Search code examples
matlabrun-length-encoding

Count lengths of sequences of consecutive integers in MATLAB


I want to count all lengths of sequences of consecutive integers and return those as a vector. For example, consider the vector: x = [1 2 3 4 6 8 9 10 12 13];

The lengths will be:

length([1 2 3 4]) = 4;
length([6]) = 1;
length([8 9 10]) = 3;
length([12 13]) = 2;  

So, the result I want to generate is:

y = [4 1 3 2] 

How can I achieve this?


Solution

  • This should do the trick:

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

    The inner diff looks for steps that are not +1 (sequence breaks), the find determines the corresponding positions (indices), the outer diff computes sequence lengths as differences between sequence break positions. The nans are there to make sure that the sequence at the beginning and the sequence at the end of the vector are found, by inducing diff values different from 1.