开发者

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.


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


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


A nice simple option is to use the function NNZ:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜