Matlab: find the row index of the first occurrence for each column of the matrix (without using loops)

For each column of matrix A consisting of "0" and "1", I would like to find the column indices of the first occurrence of "1" if one exists. For example, if A is defined as:

A=[0 0 0 0; 0 0 0 1; 0 0 0 0; 0 0 0 1; 1 0 0 0; 0 1 0 1; 1 1 0 0] 

then the result will be:

 b=[5 6 2] 

I am looking for a solution without any 'for' or 'while' loops.

In one solution, I came up with:

  [b,~]=find(cumsum(cumsum(A))==1) 

Is there a more elegant way to do this?

+4
source share
2 answers

It is smaller than anything and it is one liner. Code:

 [~,idx] = max(A(:,sum(A)>0)); 

Output:

 idx = 5 6 2 

EDIT: Just realized what you can do:

 [~,idx] = max(A(:,any(A))) 
+4
source

@Nacer is a good answer. By default, [a, m, c] = unique (J) returns the vector m to index the last occurrence of each unique value in J. Instead, use [~,m] = unique(J, 'first'); .

 [I,J] = find(A==1); [~,m] = unique(J, 'first'); I(m) ans = 5 6 2 
+5
source

All Articles