Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

matlab

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.

like image 290
user3519893 Avatar asked Dec 09 '25 05:12

user3519893


1 Answers

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.

like image 82
Dennis Jaheruddin Avatar answered Dec 11 '25 22:12

Dennis Jaheruddin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!