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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With