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

后端 未结 4 1925
后悔当初
后悔当初 2020-12-06 02:59

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 answe

相关标签:
4条回答
  • 2020-12-06 03:21

    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.

    0 讨论(0)
  • 2020-12-06 03:25

    Try this:

    max( diff( [0 (find( ~ (x > 0) ) ) numel(x) + 1] ) - 1)
    
    0 讨论(0)
  • 2020-12-06 03:27

    Cody Problem 15 is find maximum consecutive ones in a 'binary' string. This works quite nicely. As you can tell I'm quite pleased with it! Cody size 19

    max(cellfun(@numel,strsplit(x,'0')));
    
    0 讨论(0)
  • 2020-12-06 03:37

    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 an answer to a somewhat similar question...

    0 讨论(0)
提交回复
热议问题