Matrix Indices Problem

조회 수: 6 (최근 30일)
mutt
mutt 2011년 8월 15일
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]

채택된 답변

Sean de Wolski
Sean de Wolski 2011년 8월 15일
[junk, idx] = max(logical(A),[],2)
idx will be you index vector.
  댓글 수: 6
Fangjun Jiang
Fangjun Jiang 2011년 8월 15일
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 2011년 8월 16일
Thanks to everyone for contributing. In practice I wouldn't use the sort approach because my real matrix is very large.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2011년 8월 15일
size(A,2)+1-sum(cumsum(A,2)~=0,2)
more
(sum(cumsum(A')==0)+1)'
  댓글 수: 2
mutt
mutt 2011년 8월 15일
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?
Andrei Bobrov
Andrei Bobrov 2011년 8월 16일
Hi Mutt! my variant:
sum(cumsum(flipud(A'))>0)'

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by