MATLAB Answers

0

Calculate the number of nonzero rows

Asked by muhammad muda on 29 Aug 2019
Latest activity Commented on by muhammad muda on 29 Aug 2019
Hi,
How can I calculate the number of nonzero rows in a matrix?
I have
B =
3 4
5 0
0 0
and the number of nonzero rows (that I need) is 2. (because the 2nd row has the element of '5')
I tried sum( all( B ~= 0, 2 ) ); but the answer is 1.

  1 Comment

B =[3 4;5 0;0 0];
result=sum(~(all(B==0,2)))

Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 29 Aug 2019
 Accepted Answer

>> nnz(any(B,2))
ans = 2

  2 Comments

the way to go, but if you insist on using ALL, try
nnz(~all(B,2))
yes it works! Thanks!

Sign in to comment.


Answer by the cyclist
on 29 Aug 2019
Edited by the cyclist
on 29 Aug 2019

Use any instead of all. Your code is counting rows in which all entries are non-zero.

  1 Comment

Thanks, i'll use any then :)

Sign in to comment.