Sorting a Cell Array

조회 수: 143 (최근 30일)
Matthew
Matthew 2011년 12월 23일
댓글: Ananya 2024년 4월 26일
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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2011년 12월 23일
Array = {'B' 'C' 'A';1 3 2; 'D' 'E' 'F'}
out = sortrows(Array',1)';
OR
[id id] = sort(Array(1,:))
out = Array(:,id)
  댓글 수: 3
NALLARASU KRISH
NALLARASU KRISH 2022년 3월 10일
What is the syntax for sorting cell arrays in descending order? Thank You!
Ananya
Ananya 2024년 4월 26일
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')'

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Andreas Goser
Andreas Goser 2011년 12월 23일
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 2011년 12월 23일
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 2011년 12월 23일
Apologies again!
Thanks to Andrei, works perfectly!

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by