tags:

views:

60

answers:

3

Some MATLAB help needed !

I have an set of 1s and 0s, I need to find how many 1s and how many 0s.

(i.e. x = [ 1 1 0 0 0 0 0 1 0 0 1 1 ....] ) . I was looking at some search and count inbuilt function, however I have not been successful.

+3  A: 

What about the built-in sum and length functions, i.e.

numOfOnes = sum(x);
numOfZeros = length(x)-numOfOnes;

This assumes that you really only have 0s and 1s in your vector. If you can have different values but want to count the 0s and 1s only, you can preprocess the vector and count the 1s in a logical vector:

numOfOnes = sum(x==1);
numOfZeros = sum(x==0);
groovingandi
@groovingandi : Thanks ! .... this is what happens if one has been using programming languages (the scripting ones) too often ..... one forgets simple and easy MATLAB ! ...:)
Arkapravo
+3  A: 

You can just do

onesInList = sum(x == 1);
zerosInList = sum(x == 0);

This extends to any values you have in the list (i.e., if you wanted to find all of the sevens, you could just do sevensInList = sum(x == 7);).

Daniel G
-1 for overshadowing builtin "ones" and "zeros" functions with variables of those names... choose better variable names! It's almost as bad as using "i" in a for-loop and then not being able to use i to mean sqrt(-1).
Michael Aaron Safyan
@Daniel G: Thanks, voted up !
Arkapravo
@Michael *doh!* Sorry, haven't programmed MATLAB for awhile!
Daniel G
@Daniel, ok, I've upvoted since the fix.
Michael Aaron Safyan
+1  A: 

A nice simple option is to use the function NNZ:

nOnes = nnz(x);
nZeroes = nnz(~x);
gnovice