필터 지우기
필터 지우기

How to concatenate cell array without causing nested cell array

조회 수: 3 (최근 30일)
Nhut Ngo
Nhut Ngo 2019년 11월 22일
댓글: Adam Danz 2019년 11월 22일
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