Search code examples
matlabsequences

Dividing an array into unbroken increasing sequences


I have an array of the non-zero columns of an array, which in strictly increasing, but punctuated by gaps. I need to take the average of the non-zero columns, but with respect to the breaks.

For example, if the array was

a = [2,3,4,5,6,8,9,10]

I would need to average columns [1,2,3,4,5,6] and [7,8,9,10] separately (the extra at the beginning is when the underlying signal changes).

This code:

output = accumarray( cumsum([0; diff(a(:))] < 0)+1, a, [], @(x) {x} )

will split up the array into increasing sequences, punctuated by decreases.

How do I split up the array into increasing sequences punctuated by gaps?


Solution

  • Figured it out!

    output = accumarray( cumsum([0; diff(a(:))] > 1)+1, a, [], @(x) {x} )
    

    does the job.

    I just needed to check when diff(a(:)) was greater than 1!