MATLAB: How to concatenate cell array without causing nested cell array

I have a matrix years = [2007 2008 2005 2006 2007 2008 2005 2006 2007 2008]. I want to make it a cell array like this years_cell = { [2007 2008] ; [2005 2006 2007 2008] ; [[2005 2006 2007 2008] }. But what I got was 2×1 nested cell array with the first cell as another 2×1 cell array. Thank you for the help in advance guys. Here is my code:

Best Answer

% Input data
years = [2007 2008 2005 2006 2007 2008 2005 2006 2007 2008];
% Initialize the first cell with the first year
ci = 1;
years_cell = {years(1)};
% Loop over the years
for i = 2:numel(years)
% If the year is a later one, append to vector in current cell
if years(i) > years(i-1)
years_cell{ci} = [years_cell{ci} years(i)];
else % else increment to next cell and initialize vector with the year
ci = ci+1;
years_cell{ci} = years(i);
end
end
Related Question