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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by