I have a set of 1s and 0s. How do I count the maximum number of consecutive 1s?
(For example, x = [ 1 1 0 0 1 1 0 0 0 1 0 0 1 1 1 ....]
). Here the answer is 3 because the maximum number of times 1 occurs consecutively is 3.
I was looking at some search and count inbuilt function, however I have not been successful.
A = count( str , pat ) returns the number of occurrences of pat in str . If pat is an array containing multiple patterns, then count returns the sum of the occurrences of all elements of pat in str . count matches elements of pat in order, from left to right.
n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .
Try this:
max( diff( [0 (find( ~ (x > 0) ) ) numel(x) + 1] ) - 1)
Here's a solution but it might be overkill:
L = bwlabel(x);
L(L==0) = [];
[~,n] = mode(L)
Sometimes it's better to write your own function with loops ; most of the time it's cleaner and faster.
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