MATLAB Answers

trying to accounting the number of zeros in random script

1 view (last 30 days)
itsik
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!!

Accepted Answer

Paulo Silva
Paulo Silva on 12 Jun 2011
a=randint(1000,1);
numel(a(a==0))
or
sum(a==0)
or
numel(a)-nnz(a)
  3 Comments
Matt Tearle
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))

Sign in to comment.

More Answers (2)

Yella
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
  2 Comments

Sign in to comment.


itsik
itsik on 14 Jun 2011
thanks all of u but i used this code: a=randint(1000,1); numel(a(a==0)) and it helped me!!!

Community Treasure Hunt

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

Start Hunting!