Reputation: 1144
I have a matrix of zeros and ones. Any given column of the matrix is either full of zeros or has a single one.
E.g.:
A = [0 0 0 0 0;
1 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 1];
I want to get vector B
that gives me the line position of each 1. If there is no 1 on the column it should give me the maximum number of rows. Eg:
B = [2 5 4 5 5];
Any easy way of getting this?
Upvotes: 1
Views: 49
Reputation: 112749
You can use the two-output version of max
, which gives the position of each maximum. For columns consisting of only zeros the maximum will be in the first row, so you need to correct this by checking if the found maximum was 0
or 1
[m, result] = max(A, [], 1); % maximum of each column, and its row index
result(~m) = size(A, 1); % if the maximum was 0: modify result
Upvotes: 0
Reputation: 15867
A possible solution with matrix multiplication:
A = [0 0 0 0 0;
1 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 1];
[r ,~] = size(A);
B = (1:r) * A;
B(B==0)=r;
comparison with other method:
n = 9000;
ro = randperm(n,4000);
co = randperm(n , 4000);
A = accumarray([ro(:) co(:)],1);
disp('------matrix multiplication---------:')
tic
[r ,~] = size(A);
B = (1:r) * A;
B(B==0)=r;
toc
disp('------find---------:')
tic
[r,~]=find(A);
B = double(any(A));
B(B==1)= r; B(B==0)=n;
toc
result:
------matrix multiplication---------:
Elapsed time is 0.0569789 seconds.
------find---------:
Elapsed time is 0.252345 seconds.
Upvotes: 1