Matrix Indices Problem

Given a matrix e.g. A = [0 1 2 0 0; 0 3 4 5 0; 6 7 8 9 10; 0 0 0 11 0]
what MATLAB code will generate a vector of the column numbers of the first non-zero element in each row?
For this example the vector returned should be: [2;2;1;4]

 Accepted Answer

[junk, idx] = max(logical(A),[],2)
idx will be you index vector.

6 Comments

Nice.
+1
mutt
mutt on 15 Aug 2011
Very neat trick. But how about the last non-zero element in each row? [3;4;5;4]
A=[0 1 2 0 0; 0 3 4 5 0; 6 7 8 9 10; 0 0 0 11 0]
[junk, idx] = max(logical(fliplr(A)),[],2)
idx=size(A,2)+1-idx
Use sort().
A = [0 1 2 0 0; 0 3 4 5 0; 6 7 8 9 10; 0 0 0 11 0];
[dummy,Ind]=sort(A~=0,2)
Ind=Ind(:,end)
To find first non-zero,
A = [0 1 2 0 0; 0 3 4 5 0; 6 7 8 9 10; 0 0 0 11 0];
[dummy,Ind]=sort(A~=0,2,'descend')
Ind=Ind(:,1)
mutt
mutt on 16 Aug 2011
Thanks to everyone for contributing. In practice I wouldn't use the sort approach because my real matrix is very large.

Sign in to comment.

More Answers (1)

size(A,2)+1-sum(cumsum(A,2)~=0,2)
more
(sum(cumsum(A')==0)+1)'

2 Comments

mutt
mutt on 15 Aug 2011
Very good. And re-using that logic I have for the last non-zero elements:
size(A,2)+1-sum(not(logical(cumsum(A,2)-repmat(max(cumsum(A,2),[],2),1,size(A,2))))~=0,2)
Could this be simplified?
Hi Mutt! my variant:
sum(cumsum(flipud(A'))>0)'

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!