MATLAB: Split cell array taking into account difference between elements

split

Hello! I have a cell array which contains indices from another cell array.Lets say for example
TES={[1;2;3;4;5];[12;13;14];[1;2;3;4;8;9;10;22;23;24];[4;5;6;8;9];[5;6;7]};
Where the indices have no jump at their sequence (cases 1,2 & 5) I want to keep the cell as it is. Where the jump is smaller than 2 I also want to keep the cell as it is(cell 4) But where there is a jump(or more) greater than 2 I need to split each cell into other cells.Their Number should be (jumbs+1).
The desirable result is
TES_new={[1;2;3;4;5];[12;13;14];[1;2;3;4];[8;9;10];[22;23;24];[4;5;6;8;9];[5;6;7]};

Best Answer

A fairly simple way of doing it:
TES={[1;2;3;4;5];[12;13;14];[1;2;3;4;8;9;10;22;23;24];[4;5;6;8;9];[5;6;7]};
runlengths = cellfun(@(m) diff([0; find(diff(m) > 2); numel(m)]), TES, 'UniformOutput', false);
splits = cellfun(@(m, runs) mat2cell(m, runs), TES, runlengths, 'UniformOutput', false);
TES_new = vertcat(splits{:})
You can combine both cellfun for a little bit more speed at the expense of readability:
splits = cellfun(@(m) mat2cell(m, diff([0; find(diff(m) > 2); numel(m)])), TES, 'UniformOutput', false);
TES_new = vertcat(splits{:})