matlabuniquebinary-matrix

Columnwise removal of first ones from binary matrix. MATLAB


I have some binary matrix. I want to remove all first ones from each column, but keep one if this value is alone in column. I have some code, which produces correct result, but it looks ugly- I should iterate through all columns.

Could You give me a piece of advice how to improve my code?

Non-vectorised code:

% Dummy matrix for SE
M = 10^3;
N = 10^2;
ExampleMatrix = (rand(M,N)>0.9);
ExampleMatrix1=ExampleMatrix;
% Iterate columns
for iColumn = 1:size(ExampleMatrix,2)
    idx = find(ExampleMatrix(:,iColumn)); % all nonzeroes elements
    if numel(idx) > 1
        % remove all ones except first
        ExampleMatrix(idx(1),iColumn) = 0;
    end
end

Solution

  • I think this does what you want:

    ind_col = find(sum(ExampleMatrix, 1)>1); % index of relevant columns
    [~, ind_row] = max(ExampleMatrix(:,ind_col), [], 1); % index of first max of each column
    ExampleMatrix(ind_row + (ind_col-1)*size(ExampleMatrix,1)) = 0; % linear indexing
    

    The code uses: