Wednesday, June 10, 2009

Matlab: break consecutive numbers into cells

OP here.


Q:

Suppose I have a sorted array like

[1 2 3 4 5 10 11 17 18 19]


I want to break consecutive blocks into separate arrays:

[1 2 3 4 5]
[10 11]
[17 18 19]


A:

mat2cell(x,1,diff([0,find(diff(x) ~= 1),length(x)]))

3 comments:

BuoyantOne said...

Very neat - thank you!!

Unknown said...

Hi Siyi,
very nice code, just have one question, if I want to allow one missing spot between consecutive number, what will you do it?
for example:
v=[1 2 3 5 6 7 11 12 13 15 16 18 19 21]
want to break down to [1 2 3 4 6 7],[11 12 13 15 16 18 19 21].
Thanks. TY

Unknown said...

find a typo here, it is actually [1 2 3 5 6 7] and [11 12 13 15 16 18 19 21].