You should preallocate the `cs` cell array: [v,x] = find(diff(a)>1); %find "jumps" xx = [0 x length(a)]; cs = cell(length(a)+1,1); for ii = 1:length(xx)-1 cs{ii} = a(xx(ii)+1:xx(ii+1)); end Style comments: - Try to keep consistent formatting, either put spaces around all equal signs, or around none. - Terminate statements with a semicolon to prevent your function producing output to the command window.