MATLAB: How to combine series of consecutive numbers in Matlab

MATLAB

I have following data:
s{1} = 1:10;
s{2} = 19:27;
s{3} = 29:41;
s{4} = 59:67;
s{5} = 71:89;
s{6} = 91:110;
s{7} = 119:210;
s{8} = 214:290;
and I want to combine sets with difference less than 4
diff = s{2}(1)-s{1}(end)
if diff <4
combine s{1}and s{2}
My out should be:
s{1} = 1:10;
s{2} = 19:41;
s{3} = 59:67;
s{4} = 71:110;
s{5} = 119:210;
s{6} = 214:290;

Best Answer

Bs = cellfun(@(v)v(1),s);
Es = cellfun(@(v)v(end),s);
D = Bs(2:end)-Es(1:end-1);
X = cumsum([1,D>=4]);
Bz = accumarray(X(:),Bs(:),[],@min);
Ez = accumarray(X(:),Es(:),[],@max);
Z = arrayfun(@(b,e)b:e,Bz,Ez,'uni',0);
Giving:
>> Z{:}
ans =
1 2 3 4 5 6 7 8 9 10
ans =
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
ans =
59 60 61 62 63 64 65 66 67
ans =
71 72 73 74 ... 106 107 108 109 110
ans =
119 120 121 122 ... 205 206 207 208 209 210
ans =
214 215 216 217 ... 286 287 288 289 290