How to concatenate cell array without causing nested cell array

5 次查看(过去 30 天)
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 个评论
the cyclist
the cyclist 2019-11-22
编辑:the cyclist 2019-11-22
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 2019-11-22
well, I'm working on a project, the variable years changes everytimes. It's not always like that. It depends on the input file.

请先登录,再进行评论。

采纳的回答

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

更多回答(1 个)

Adam Danz
Adam Danz 2019-11-22
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 个评论
Nhut Ngo
Nhut Ngo 2019-11-22
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 2019-11-22
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by