Sorting a Cell Array

166 visualizzazioni (ultimi 30 giorni)
Matthew
Matthew il 23 Dic 2011
Commentato: Ananya il 26 Apr 2024
Hi,
Sorry if this has been asked / answered many times or very simple etc. etc!
If I have a cell array say Array = {B C A;1 3 2; D E F}
Is it possible to sort the first row in order, so its A B C, with the second and third rows changing corresponding to to this initial sort?
Final answer being {A B C;2 1 3;F D E}
Thanks in advance Matthew

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 23 Dic 2011
Array = {'B' 'C' 'A';1 3 2; 'D' 'E' 'F'}
out = sortrows(Array',1)';
OR
[id id] = sort(Array(1,:))
out = Array(:,id)
  3 Commenti
NALLARASU KRISH
NALLARASU KRISH il 10 Mar 2022
What is the syntax for sorting cell arrays in descending order? Thank You!
Ananya
Ananya il 26 Apr 2024
sortrows(Array',1)':: here since sortrows works for columns ,(sorting elements in a column of a matrix...)
you needed the row to be sorted here , so Array' is the transpose of it and then doing a retranspose of the result by doing sortrows(Array',1)'<-- to get the original matrix
for descending its simple, just add 'descend' at the end of these arguments (Array',1,'descend')'

Accedi per commentare.

Più risposte (3)

Andreas Goser
Andreas Goser il 23 Dic 2011
It is not clear to me what your cell array really looks like, as your example is not valid, but the SORTROWS command should work.

Matthew
Matthew il 23 Dic 2011
Sorry if not clear...
The array consists of both strings and numbers
so Array = {'B' 'C' 'A';1 3 2;'D' 'E' 'F'}
where the letters are strings and the numbers numbers!
i tried the sortrows and it did not work
Thanks again, matthew

Matthew
Matthew il 23 Dic 2011
Apologies again!
Thanks to Andrei, works perfectly!

Categorie

Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by