user3519893
user3519893

Reputation: 33

MATLAB-How to count 0s and 1s in a vector

Let a vector v with length n be v = randi([0 1],1,n), containing 0s or 1s randomly.

What is the effective way to get a vector indicating how many 0s or 1s there are in each 0-segment or 1-segment alternatively?

Example:

v = [1 0 0 0 1 1 0 0 1]   ----> 
    counts = [0 1 3 2 2 1]  (*0* zero, *1* one, *3* zeros, ....)

v = [0 0 1 0 0 0]   ---->
    counts = [2 1 3]

P.S. Always count 0s first, if the vector starts with a 1, then the first entry of the result vector, i.e. counts(1), should be a 0.

Upvotes: 3

Views: 320

Answers (2)

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

You can do it like this (it always counts zeros first, even if they don't exist):

aux = cumsum(abs(diff([0 v])));
counts = histc(aux, 0:max(aux));
clear aux;

Upvotes: 1

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

This is a fairly simple way to do it:

diff(find(diff([inf v inf])))

It should not be hard to expand if you also want to know which value correspond to each segment.

Upvotes: 5

Related Questions