0

I have a matrix that is:

matrix = [1, 0, 0;  
          0, 1, 1;
          0, 0, 1];

I want to iterate through the matrix column by column and get the row number of the first 1 occurred in that column. So, the result is supposed to be:

[1, 2, 2]

What I have idea so far is:

for i = matrix
    if i == 1
       %store the row No. to an array.
    end
end
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
Mina
  • 13
  • 1
  • If you have just zeros and ones in your matrix then `[~,r]= max(A)` will do the job. Otherwise `[~,r]=max(A==1)` Also check the linked duplicate for more ideas. – Sardar Usama Feb 14 '21 at 19:21
  • I'd use `[~,Indices] = max(matrix,[],2)` to ensure that the furthest left index is selected. – MichaelTr7 Feb 14 '21 at 19:25
  • 1
    @MichaelTr7 The OP is interested in the row subscript of first occurrence of 1 in each column i.e. `[1,2,2]`. Whereas `max(matrix,[],2)` returns the column subscript of first occurrence of 1 in each row.i.e. `[1,2,3]` – Sardar Usama Feb 14 '21 at 19:50
  • @Sandar Usama My bad, I was mistaken. Thanks for the correction. – MichaelTr7 Feb 14 '21 at 20:03
  • @MichaelTr7 @SardarUsama, you can then just transpose the matrix. `[~,Indices] = max(matrix', [], 2)` returns exactly `[1, 2, 2]`. – Matteo V Feb 15 '21 at 07:59
  • @MatteoV 1. That's a complex conjugate transpose; not transpose 2. This is an overkill. No need of taking complex conjugate transpose when you can just directly use max – Sardar Usama Feb 15 '21 at 14:16

1 Answers1

1

Try

row = zeros(size(matrix,2),1);
for column = 1:size(matrix,2)
    row(column) = find(matrix(:,column),1);
end

there might be a better way without the loop..

Till
  • 183
  • 7