フィルターのクリア

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 Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by