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
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.
采纳的回答
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
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 个评论
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!