Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of the last non-zero element in each row of a given matrix?

For an arbitrary sized matrix x, how do I find the index of the last non-zero element in each row of a given matrix?

For example, for the matrix

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ]

the vector [ 3 6 0 5 ] should be obtained.

like image 923
Jack Lu Avatar asked Oct 11 '10 22:10

Jack Lu


1 Answers

Here's a shorter version, combining find and accumarray

x = [ 0 9 7 0 0 0; 5 0 0 6 0 3; 0 0 0 0 0 0; 8 0 4 2 1 0 ];
%# get the row and column indices for x
[rowIdx,colIdx] = find(x);
%# with accumarray take the maximum column index for every row
v = accumarray(rowIdx,colIdx,[],@max)'
v =
     3   6   0   5
like image 164
Jonas Avatar answered Oct 04 '22 17:10

Jonas