# trying to accounting the number of zeros in random script

1 view (last 30 days)
itsik on 12 Jun 2011
hello lets say i have this random script w=randint(1000,1) and i want to know how many 'zeros' there are in this script what should i do to account the 'zeros'? thanks!!

Paulo Silva on 12 Jun 2011
a=randint(1000,1);
numel(a(a==0))
or
sum(a==0)
or
numel(a)-nnz(a)

Matt Fig on 14 Jun 2011
itsik says,
thank u for your answer but my problem is i want to know how MANY zeros there are all over the matrix lets say i have a=0 1 0 0 0 0 0 0 1 1 1 1 1 0 0
so im trying to make a code that accounting the numbers of zeros and will give me a=8 like there is 8 zeros thanks!
Matt Fig on 14 Jun 2011
I wonder if you tried Paulo's answer. The solutions he gives are standard solutions to this problem and return the number of zeros in the array... Did you try them???
a = [0 1 0 0 0 0 0 0 1 1 1 1 1 0 0] % 9 zeros, not 8!
sum(a(:)==0) % This DOES count the zeros!
ans =
9
Matt Tearle on 14 Jun 2011
Minor quibbles.
randint is deprecated. To make a random vector of 0s and 1s you can do
a = randi(2,10000,1)-1;
On my machine, running 11a, the most efficient approach is
nnz(a==0)
followed by
sum(a==0)
and then
numel(a(a==0))

Yella on 14 Jun 2011
[EDIT: Tue Jun 14 05:17:56 UTC 2011 - Reformat - MKF]
Its simple make a for loop and use and conditional loop like "if else" when ever value is '0' in the matrix increment a variable if not continue the loop.
k=0;
for i= 1:1:n
if (f(i)=0)
k=k+1;
else continue
end
end

Matt Fig on 14 Jun 2011
Yella, you have an error. The correct comparison operator is '=='.
if f(i)==0
This could be replaced by:
if ~f(i)
Yella on 14 Jun 2011
Thanks matt