计算连续数字岛的长度和频率
Count length and frequency of island of consecutive numbers
我有一个 1 和 0 的序列,我想计算连续 1 的孤岛出现的频率。
鉴于:
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
我有一个 1 和 0 的序列,我想计算连续 1 的孤岛出现的频率。
鉴于:
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