How do I find the indices of non-zero rows in a matrix?

How do I find the indices of non-zero rows in a matrix?

Example:

A = [
       14  0  6  9  8  17
       85 14  1  3  0  99
       0   0  0  0  0   0 
       29  4  5  8  7  46
       0   0  0  0  0   0
       17  0  5  0  0  49
]

      

desired result:

   V =[1 2 4 6]

      

+3


source to share


3 answers


you can use

   ix = any(x,2);

      

any

check if there is any element that is not null. The second argument means "for each line" calculation.

If you want to get the numeric index, you can use the function find

:



   numIx = find(ix);

      


Another method:

  ix = sum(abs(x),2)~=0;

      

+3


source


Using

[i,~] = ind2sub(size(A),find(A));

v = unique(i);

      



Result for the above matrix:

v = unique(i')

v =

     1     2     4     6

      

+2


source


Here where ab (uses) - fast matrix multiplication in MATLAB

idx = find(abs(A)*ones(size(A,2),1))

      

+1


source







All Articles