Sort a table with different orders for different columns

Assume table A:
A = [
'k' 2 4
'a' 3 8
'a' 4 5
'k' 2 2
'a' 3 16
'k' 9 3
'k' 9 8
'a' 4 6
]
If i use sortrows(A) every column is sorted with ascending order:
A = [
'a' 3 8
'a' 3 16
'a' 4 5
'a' 4 6
'k' 2 2
'k' 2 4
'k' 9 3
'k' 9 8
]
Is there a way to sort rows, so first and second column is sorted with ascending order, but third one with descending? I want to get something like this:
A = [
'a' 3 16
'a' 3 8
'a' 4 6
'a' 4 5
'k' 2 4
'k' 2 2
'k' 9 8
'k' 9 3
]

댓글 수: 3

Do you want the columns sorted indepently? Or do you want to sort first by column 1, then column 2, then column 3?
I want to sort by first column in ascending order, then second in ascending order, then third in descending, so like in example, sortrows is sorting first column, so 'a's are before the 'k's, then for every 'a' it sorts second column, so 'a' 3 is before 'a' 4 etc. My problem is sortrows sorts it by (asc,asc,asc) and I want it sorted by (asc,asc,desc).
It would likely be necessary to sort each column independently, then concatenate the results into a new matrix.

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

 채택된 답변

Stephen23
Stephen23 2021년 3월 31일
Where T is your table:
sortrows(T,[1,2,-3])

추가 답변 (1개)

David Hill
David Hill 2021년 3월 31일
You can't have a matrix with characters and numbers. But if you convert the characters to double, then:
A=[sort(A(:,1)),sort(A(:,2)),sort(A(:,3),'descend')];

댓글 수: 1

I'm sorry, it is actually a table, not a matrix. I've corrected my question accordingly.

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

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

2021년 3월 31일

댓글:

2021년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by