How to concatenate cell array without causing nested cell array

4 views (last 30 days)
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 2x1 nested cell array with the first cell as another 2x1 cell array. Thank you for the help in advance guys. Here is my code:
  2 Comments
the cyclist
the cyclist on 22 Nov 2019
Edited: the cyclist on 22 Nov 2019
Is the "rule" that you want to begin a new cell-array element each time a year is earlier than the prior one?
FYI, it's much more useful to paste code, not images of code. Then we can copy/paste into MATLAB if we want to.
Nhut Ngo
Nhut Ngo on 22 Nov 2019
well, I'm working on a project, the variable years changes everytimes. It's not always like that. It depends on the input file.

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 22 Nov 2019
% 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

More Answers (1)

Adam Danz
Adam Danz on 22 Nov 2019
This groups your vector years into groups of monotonically increasing years.
years = [2007 2008 2005 2006 2007 2008 2005 2006 2007 2008];
yGrp = cumsum([true,diff(years(:)')<1]); % group ID for increasing years
yearsGrouped = accumarray(yGrp(:),years,[],@(x){x.'});
Result
yearsGrouped =
3×1 cell array
{1×2 double}
{1×4 double}
{1×4 double}
celldisp(yearsGrouped)
yearsGrouped{1} =
2007 2008
yearsGrouped{2} =
2005 2006 2007 2008
yearsGrouped{3} =
2005 2006 2007 2008
  2 Comments
Nhut Ngo
Nhut Ngo on 22 Nov 2019
Thank you so much. I'm in an intro class, so cumsum function is something that my teacher has not mentioned yet, so I don't know if I'm allowed to use it.
Adam Danz
Adam Danz on 22 Nov 2019
No problem! the cyclist's answer may have more lines but it's actually faster. If you're eager to learn, you could copy my 2-line solution into your code and comment it out until you have time to tear it apart later.

Sign in to comment.

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!