Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: First Non-zero element of each row or column

For example,

A = [ -1   0  -2   0   0
   2   8   0   1   0
   0   0   3   0  -2
   0  -3   2   0   0
   1   2   0   0  -4];

how can I get a vector of the first nonzero elements of each row?

like image 600
user2913990 Avatar asked Oct 27 '13 23:10

user2913990


1 Answers

You can use max:

>> [sel, c] = max( A ~=0, [], 2 );

Rows for which sel equalse zero - are all zeros and the corresponding column in c should be ignored.

Result:

>> [sel c]= max( A~=0, [], 2 )

sel =
 1
 1
 1
 1
 1
c =
 1
 1
 3
 2
 1

In order to find the first non-zero row index (for each column) you just need to apply max on the first dimension:

>> [sel r] = max( A~=0, [], 1 );
like image 84
Shai Avatar answered Sep 20 '22 04:09

Shai