Count the appearance of consecutive 1s in 0-1 data in MATLAB

I have a set of 1s and 0s. How to 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, since the maximum number of times 1 is 3.

I was looking for some search functions and counting the built-in functions, however I was not successful.

+8
matlab
source share
4 answers

Try the following:

 max( diff( [0 (find( ~ (x > 0) ) ) numel(x) + 1] ) - 1) 
+13
source share

Here's a solution, but it might be redundant:

 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 is cleaner and faster.

+3
source share

Another possibility:

 x = randi([0 1], [1 100]); %# random 0/1 vector d = diff([0 x 0]); maxOccurence = max( find(d<0)-find(d>0) ) 

which is inspired by the answer to a somewhat similar question ...

+1
source share

The goal of Cody 15 is to find the maximum consecutive in a binary string. It works very well. How can you say, I am pleased with this! Cody size 19

 max(cellfun(@numel,strsplit(x,'0'))); 
0
source share

All Articles