How to count the number of nonzero numbers in a row.

14 ビュー (過去 30 日間)
jaah navi
jaah navi 2019 年 2 月 27 日
コメント済み: madhan ravi 2019 年 2 月 27 日
I having a matrix A=[ 0 0 0 0 0.4 0 0 0.3;
0.1 0 0 0.7 0 0.2 0 0 0;
0 0 0.6 0 0 0 0 0.9]
I want to count the number of elements which is not equal to zero present in each row
the answer will be A=[2;
3;
2]
I tried with the command
D=(numel(A~=0),1)
But unable to get the result.Could anyone please help me on this.

採用された回答

KSSV
KSSV 2019 年 2 月 27 日
編集済み: KSSV 2019 年 2 月 27 日
Read about nnz
A=[ 0 0 0 0 0.4 0 0 0.3;
0.1 0 0 0.7 0 0.2 0 0 ;
0 0 0.6 0 0 0 0 0.9] ;
[m,n] = size(A) ;
iwant = zeros(m,1) ;
for i = 1:m
iwant(i) = nnz(A(i,:)) ;
end
iwant

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 2 月 27 日
No loops needed:
sum(A~=0,2)
  2 件のコメント
Jan
Jan 2019 年 2 月 27 日
+1. Most efficient solution.
madhan ravi
madhan ravi 2019 年 2 月 27 日
@Jan: Thank you!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by