0

Is there any command in GNU Octave that allows me to count the zero (without counting the nonzero) entries in a matrix?

Mr. Duhart
  • 927
  • 12
  • 11
  • 1
    possible duplicate of [How can I count the number of elements of a given value in a matrix?](http://stackoverflow.com/questions/2880933/how-can-i-count-the-number-of-elements-of-a-given-value-in-a-matrix) – Paul R Dec 10 '14 at 02:06
  • 1
    That link helped, thanks. Specifically, sum(your_matrix == 5), was the example that helped. – user2780341 Dec 10 '14 at 04:24
  • 1
    @user2780341, Your question header and question body **mismatches**. In header you are asking about counting **non**zero entries. In body you are asking about counting **zero** entries. Would you mind editing it? – Md. Abu Nafee Ibna Zahid Feb 07 '18 at 14:21

1 Answers1

3

There are may ways, I'll show you two below.

a = rand (5,5) > 0.5
a =

   0   0   0   1   1
   1   1   0   1   0
   0   1   0   1   1
   0   0   0   1   0
   1   1   0   1   1

numel (find (a==0))
ans =  12

This is faster for very large matrices (see below)

numel (a) - nnz (a)
ans =  12

Speed test for large matrices:

a = rand (1e6, 1e6) > 0.5;
tic
numel (find (a==0))
toc
tic
numel (a) - nnz (a)
toc

which gives

ans =  499566
Elapsed time is 0.060837 seconds.
ans =  499566
Elapsed time is 0.0187149 seconds.
Andy
  • 7,931
  • 4
  • 25
  • 45