Clear Filters
Clear Filters

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

9 views (last 30 days)
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.

Accepted Answer

KSSV
KSSV on 27 Feb 2019
Edited: KSSV on 27 Feb 2019
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

More Answers (1)

madhan ravi
madhan ravi on 27 Feb 2019
No loops needed:
sum(A~=0,2)

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!