Borrar filtros
Borrar filtros

How to concatenate cell array without causing nested cell array

5 visualizaciones (últimos 30 días)
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 comentarios
the cyclist
the cyclist el 22 de Nov. de 2019
Editada: the cyclist el 22 de Nov. de 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 el 22 de Nov. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

the cyclist
the cyclist el 22 de Nov. de 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

Más respuestas (1)

Adam Danz
Adam Danz el 22 de Nov. de 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 comentarios
Nhut Ngo
Nhut Ngo el 22 de Nov. de 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 el 22 de Nov. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by