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

3

8

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?

Gold answered 27/10, 2013 at 23:11 Comment(1)
what would you expect if there is an "all zeros" row?Remit
R
17

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 );
Remit answered 28/10, 2013 at 9:44 Comment(2)
This is a better solution as find can explode when working larger matrices.Peri
how do I find the values rather than the indices?Saltatory
A
9

Here is a solution based on accumarray that will work even if a row is all zeros.

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];

[r,c] = find(A);

%# for every row, take the minimum column index and put NaN if none is found
firstIndex = accumarray(r,c,[size(A,1),1],@min,NaN);
Access answered 28/10, 2013 at 9:35 Comment(1)
FYI, you may need accumarray(r,c,[size(A,1),1],@min,NaN) because accumarray requires the size be specified as [M 1] (at least in my version of MATLAB)Artel
E
1

You can do it by executing find function for each row as follows:

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];

% make cell of rows
cellOfRows = num2cell(A, 2);

% apply find function for each row
indexOfFirstNonZeroValues = cellfun(@(row) find(row, 1, 'first'), cellOfRows);


indexOfFirstNonZeroValues =

     1
     1
     3
     2
     1
Erection answered 27/10, 2013 at 23:30 Comment(1)
this will fail if there is a row of all zeros.Access

© 2022 - 2024 — McMap. All rights reserved.