-5

Say, I have the matrix x as

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

Hence

x =

 1     5     0     6     0
 2     6     0     3     0
 0     0     5     5     0
 0     0     0     8     9
 0     0     0     0     8

The result should be 1st col: (3,5) 2nd col: (3,5) 3rd col: (1,2) and (4,5) 4th col: (5,5) 5th col: (1,3)

OR

It will be better if I can get only the first and last indices of zeros across a column. In this case the result should be 1st col: (3,5) 2nd col: (3,5) 3rd col: (1,5) 4th col: (5,5) 5th col: (1,3).

John Dvorak
  • 26,799
  • 13
  • 69
  • 83

1 Answers1

2

One way to do this is by combining find with accumarray:

[r,c]=find(x==0)
%# identify the first and the last zero for each column
firstIdx = accumarray(c,r,[size(x,2),1],@(x)min(x),NaN)
lastIdx  = accumarray(c,r,[size(x,2),1],@(x)max(x),NaN)
Jonas
  • 74,690
  • 10
  • 137
  • 177