计算连续数字岛的长度和频率



我有一个 1 和 0 的序列,我想计算连续孤岛出现的频率。

鉴于:S = [1 1 0 0 1 1 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 1 0 1]

通过计算连续岛屿,我的意思是:R = [4 3 1]...因为有四个单一,三个双一和一个单三重一。

这样当乘以岛屿的长度时[1 2 3]。

[4 3 1] * [1 2 3]’ = 13

这对应于sum(S),因为有十三个。

我希望对解决方案进行矢量化,而不是循环播放某些内容。

我想出了这样的东西:R = histcounts(diff( [0 (find( ~ (S > 0) ) ) numel(S)+1] ))

但结果没有多大意义。它计算了太多的三胞胎。 我在互联网上找到的所有代码都围绕着diff([0 something numel(S)])但问题总是略有不同,并没有真正帮助我

感谢任何建议!

以下应该可以做到。 希望评论是明确的。

S = [1 1 0 0 1 1 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 1 0 1];
% use diff to find the rising and falling edges, padding the start and end with 0
edges = diff([0,S,0]); 
% get a list of the rising edges
rising = find(edges==1);
% and falling edges
falling = find(edges==-1);
% and thereby get the lengths of all the runs
SRuns = falling - rising;
% The longest run
maxRun = max(SRuns);
% Finally make a histogram, putting the bin centres 
R = hist(SRuns,1:maxRun);

您也可以通过以下方式获得相同的结果:

x = find(S==1)-(1:sum(S)) %give a specific value to each group of 1
h = histc(x,x)            %compute the length of each group, you can also use histc(x,unique(x))
r = histc(h,1:max(h))     %count the occurence of each length   

结果:

r = 
4,3,1

最新更新