3

How to find the indices of nonzero 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
]

the desired result :

   V =[1 2 4 6]
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
bzak
  • 563
  • 1
  • 8
  • 21

3 Answers3

4

You can use

   ix = any(x,2);

any check whether there is any element that is not a zero. The second argument stands for "per-row" computation.

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

   numIx = find(ix);

Another method:

  ix = sum(abs(x),2)~=0;
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
2

Use

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

v = unique(i);

Result for the matrix given above:

v = unique(i')

v =

     1     2     4     6
Nemesis
  • 2,324
  • 13
  • 23
  • my 2009 version of matlab gives me the error: ??? [i,~] = ind2sub(size(A),find(A)) | Error: Unbalanced or unexpected parenthesis or bracket. – bzak Nov 09 '14 at 12:28
  • 2
    I guess it is due to `~` which was not implemented in this version (I guess). Try `[i,j] = ind2sub(size(A),find(A));` – Nemesis Nov 09 '14 at 12:29
  • Strange, for me it does. – Nemesis Nov 09 '14 at 12:39
  • [i,j] = ind2sub(size(A),find(A)) i = 1 2 4 6 2 4 1 2 4 6 1 2 4 1 4 1 2 4 6 j = 1 1 1 1 2 2 3 3 3 3 4 4 4 5 5 6 6 6 6 – bzak Nov 09 '14 at 12:40
1

Here's one that ab(uses) the fast matrix multiplication in MATLAB -

idx = find(abs(A)*ones(size(A,2),1))
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358