在MATLAB中计算0-1数据中连续1的出现次数

时间:2011-06-13 12:47:37

标签: matlab

我有一组1和0。如何计算连续1的最大数量?

(例如,x = [ 1 1 0 0 1 1 0 0 0 1 0 0 1 1 1 ....])。答案是3,因为连续发生的最大次数是3次。

我正在查看一些搜索并计算内置功能,但是我没有成功。

4 个答案:

答案 0 :(得分:13)

试试这个:

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

答案 1 :(得分:3)

这是一个解决方案,但它可能有点过分:

L = bwlabel(x);
L(L==0) = [];
[~,n] = mode(L)

有时用循环编写自己的函数会更好;大多数时候它更清洁,更快。

答案 2 :(得分:1)

另一种可能性:

x = randi([0 1], [1 100]);                %# random 0/1 vector

d = diff([0 x 0]);
maxOccurence = max( find(d<0)-find(d>0) )

受到an answer的启发,有点类似的问题...

答案 3 :(得分:0)

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')));