Monday, May 04, 2009

Matlab: Split a vector into continuous chunks.

Original post here.


Q:

Suppose I have [1 2 3 4 8 9 16 17 18], how do I get [1 2 3 4], [8 9], [16 17 18] in a vectorized way?

A:

a = [1 2 3 4 8 9 16 17 18];

b=a-(1:length(a));
b = [true; diff(b(:)) ~= 0; true];
split = mat2cell(a(:).', 1, diff(find(b)));

split{:}

1 comment:

Martin Isoz said...

Thanks, this actually helped me. A lot:-).