在MATLAB中计算连续整数序列的长度

时间:2015-01-21 15:21:16

标签: matlab run-length-encoding

我想计算连续整数序列的所有长度,并将它们作为向量返回。 例如,考虑向量: 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] 

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

y = diff(find(diff([nan ; x(:) ; nan]) ~= 1))

内部diff查找 +1(序列中断)的步骤,find确定相应的位置(索引),外部diff计算序列长度作为序列中断位置之间的差异。 nan用于确保通过引入不同于1的diff值来确定向量的开始处和序列结尾处的序列。

答案 1 :(得分:2)

A. Donda's answer的一小部分变种:

  1. 使用diff检测大于1的差异。这会在每次运行的 end 处显示1值。
  2. 向后累积(使用cumsum)为每次运行分配不同的数字标签。积累是向后完成的,因为步骤1中的1值是在每次运行结束时,而不是在开始时。
  3. 使用histc计算游程长度。
  4. 代码:

    y = [diff(x)>1 1];               %// step 1
    y = cumsum(fliplr(y));           %// step 2
    y = fliplr(histc(y, 1:y(end)));  %// step 3
    

答案 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)

这是经过测试的,可行。