I have a cell array that looks like:
a={apples} {1}
{orange} {2}
{apples} {3}
{Pear} {4}
{apples} {5}
I want to get like items together in their own matrix like:
a1= {apples} {1}
{apples} {3}
{apples} {5}
a2= {orange} {2}
a3= {pear} {4}
Thank you!

 Respuesta aceptada

Matt J
Matt J el 12 de Jul. de 2021
Editada: Matt J el 12 de Jul. de 2021

0 votos

One way:
a=sortrows(a,1)

6 comentarios

Qiana Curcuru
Qiana Curcuru el 13 de Jul. de 2021
thanks that's almost what i want.
After they are sorted, i want to set each like row to its own variable like i have above.
Matt J
Matt J el 13 de Jul. de 2021
Editada: Matt J el 13 de Jul. de 2021
That would be a bad idea:
The better thing to do would be to organize the subsets of a as fields of a struct:
a={'apples',1;...
'orange',2;...
'apples',3;...
'Pear',4;...
'apples',5};
[G,fields]=findgroups(a(:,1));
X=splitapply(@(x){x.'}, a(:,2),G);
Sa=cell2struct(X,fields)
Sa = struct with fields:
Pear: {[4]} apples: {[1] [3] [5]} orange: {[2]}
Qiana Curcuru
Qiana Curcuru el 19 de Jul. de 2021
awesome thanks! so then how would you reference items in the struct?
Like if i wanted to know what objects are under 'apples' what is the command for that?
Sa.apples
Qiana Curcuru
Qiana Curcuru el 19 de Jul. de 2021
ah okay, but what if i dont know what the categories are since i am writing them with a for loop. is there a way to refernce them using indices?
Matt J
Matt J el 19 de Jul. de 2021
Editada: Matt J el 19 de Jul. de 2021
fields=fieldnames(Sa);
for i=1:numel(fields)
Sa.(fields{i})
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Versión

R2018b

Etiquetas

Preguntada:

el 12 de Jul. de 2021

Editada:

el 19 de Jul. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by