Arkapravo
Arkapravo

Reputation: 4094

MATLAB : search and count (?)

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.

Upvotes: 2

Views: 226

Answers (3)

gnovice
gnovice

Reputation: 125874

A nice simple option is to use the function NNZ:

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

Upvotes: 2

Daniel G
Daniel G

Reputation: 69692

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);).

Upvotes: 3

groovingandi
groovingandi

Reputation: 2006

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);

Upvotes: 3

Related Questions