Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
MikeSchneeberger Avatar asked Mar 30 '13 09:03

MikeSchneeberger


People also ask

How do you find the index of a matrix in MATLAB?

To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.

How do I index a specific row in MATLAB?

The most common way is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A .

How do you find the index of an element in an array in MATLAB?

k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.

How do you find the number of rows and columns in a matrix in MATLAB?

If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns. Also there are some other ways like : length ( A(:,1) ) for number of rows.


2 Answers

This is shorter than anything posted and it's a one liner. Code:

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

Output:

idx =

     5     6     2

EDIT: Just realized you can do:

[~,idx] = max(A(:,any(A)))
like image 95
JustinBlaber Avatar answered Nov 15 '22 06:11

JustinBlaber


@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
like image 39
Alexey Avatar answered Nov 15 '22 06:11

Alexey