我想计算连续整数序列的所有长度,并将它们作为向量返回。
例如,考虑向量:
x = [1 2 3 4 6 8 9 10 12 13];
长度将是:
length([1 2 3 4]) = 4;
length([6]) = 1;
length([8 9 10]) = 3;
length([12 13]) = 2;
所以,我想要生成的结果是:
y = [4 1 3 2]
我怎样才能做到这一点?
答案 0 :(得分:3)
这应该可以解决问题:
y = diff(find(diff([nan ; x(:) ; nan]) ~= 1))
内部diff
查找不 +1(序列中断)的步骤,find
确定相应的位置(索引),外部diff
计算序列长度作为序列中断位置之间的差异。 nan
用于确保通过引入不同于1的diff
值来确定向量的开始处和序列结尾处的序列。
答案 1 :(得分:2)
A. Donda's answer的一小部分变种:
答案 2 :(得分:1)
这等于x - (1:length(x))
的 run lengths 。因此,您可以使用:
runLengths = @(x) diff([0, reshape(find(x(1:end-1)~=x(2:end)),1,[]), numel(x)]);
sequenceCounts = @(x) runLengths(x(:)-(1:numel(x)).');
result = sequenceCounts(x);
答案 3 :(得分:0)
x = [1 2 3 4 6 8 9 10 12 13];
consecs = []; % empty vector to store answers
consec = 1; % initialize
for I=2:length(x)
if x(I)==x(I-1)+1 % this one is consecutive with previous
consec = consec+1;
else % this one starts a new set of consecutives
consecs(end+1) = consec;
consec = 1;
end
end
consecs(end+1)=consec; % remember to include the last consecutives
display(consecs)
这是经过测试的,可行。