trying to accounting the number of zeros in random script

조회 수: 1 (최근 30일)
itsik
itsik 2011년 6월 12일
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
Paulo Silva 2011년 6월 12일
a=randint(1000,1);
numel(a(a==0))
or
sum(a==0)
or
numel(a)-nnz(a)
  댓글 수: 3
Matt Fig
Matt Fig 2011년 6월 14일
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
Matt Tearle 2011년 6월 14일
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))

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Yella
Yella 2011년 6월 14일
[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
Matt Fig
Matt Fig 2011년 6월 14일
Yella, you have an error. The correct comparison operator is '=='.
if f(i)==0
This could be replaced by:
if ~f(i)
Yella
Yella 2011년 6월 14일
Thanks matt

댓글을 달려면 로그인하십시오.


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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by