필터 지우기
필터 지우기

How to find the last nonzero entry in all rows of a sparse matrix?

조회 수: 1 (최근 30일)
Benson Gou
Benson Gou 2019년 4월 8일
댓글: Benson Gou 2019년 4월 8일
Dear All,
I need to find out the last nonzero entry in each row of a sparase matrix A. Say A=[1 3 0 0 0 0;0 4 2 3 0 0;5 0 0 1 4 0]. The location of last nonzero entry in all rows of A are [2 4 5].
Thanks a lot in advance.
Benson

채택된 답변

Akira Agata
Akira Agata 2019년 4월 8일
How about the following?
[Solution 1]
A = [1 3 0 0 0 0;0 4 2 3 0 0;5 0 0 1 4 0];
pos = nan(size(A,1),1);
for kk = 1:size(A,1)
pos(kk) = find(A(kk,:),1,'last');
end
[Solution 2]
A = [1 3 0 0 0 0;0 4 2 3 0 0;5 0 0 1 4 0];
C = mat2cell(A,ones(1,size(A,1)));
pos = cellfun(@(x) find(x,1,'last'),C);
  댓글 수: 1
Benson Gou
Benson Gou 2019년 4월 8일
@Akira, Thanks a lot for your valuable suggestions. Your methods work very well. Benson.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by