Matlab: Find row indice of first occurrence for each column of matrix (without using loops)

MikeSchneeberger picture MikeSchneeberger · Mar 30, 2013 · Viewed 7.3k times · Source

For each column of a matrix A consisting of '0' and '1', I would like to find the column indices of the first occurrence of '1' if 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 would be:

b=[5 6 2]

I'm searching for a solution without any 'for' or 'while' loops.

One solution I came up with:

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

Is there a more elegant way to do this?

Answer

Alexey picture Alexey · Mar 30, 2013

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

[I,J] = find(A==1);
[~,m] = unique(J, 'first');
I(m)

ans =    
     5
     6
     2