How to sort a matrix based on two columns

Assume matrix A as follows:
A = [
1 1 20
1 2 32
1 3 10
2 1 45
2 2 10
2 3 15
3 1 43
3 2 90
];
I want to sort matrix A based on the third column. However, I want to keep the first column also sorted. Whenever the ID changed, then column 3 is sorted. The output should be something likes:
B = [
1 3 10
1 1 20
1 2 32
2 2 10
2 3 15
2 1 45
3 1 43
3 2 90
];

1 Kommentar

Stephen23
Stephen23 am 22 Mai 2017
@Zhan: you keep asking questions, but you have not accepted any of the answers to any of your questions. Accepting answers shows which answer solved your question, and is also an easy way for you to say "thank you" for our volunteer effort helping you.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

dpb
dpb am 21 Mai 2017

9 Stimmen

>> sortrows(A,[1 3 2]) % doc sortrows for details...
ans =
1 3 10
1 1 20
1 2 32
2 2 10
2 3 15
2 1 45
3 1 43
3 2 90
>>

3 Kommentare

pepijn schrage
pepijn schrage am 26 Jun. 2019
Sweet! I hoped it would be something this elegant. Thanks for the answer!
Muhammad Bilal
Muhammad Bilal am 23 Dez. 2020
plz anyone can explain sortrows(A,[1 3 2]) ?
thanks
>> help sortrows
sortrows Sort rows of a matrix.
B = sortrows(A) sorts the rows of matrix A in ascending order as a
group. B has the same size and type as A. A must be a 2-D matrix.
B = sortrows(A,COL) sorts the matrix according to the columns specified
by the vector COL. If an element of COL is positive, the corresponding
column in A is sorted in ascending order; if an element of COL is
negative, the corresponding column in A is sorted in descending order.
For example, sortrows(A,[2 -3]) first sorts the rows in ascending order
according to column 2; then, rows with equal entries in column 2 get
sorted in descending order according to column 3.
...
So,
sortrows(A,[1 3 2]) % doc sortrows for details...
sorts A in ascending order by column order of first, third, second. This can be seen to be so by inspection of the output.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Gefragt:

am 21 Mai 2017

Kommentiert:

dpb
am 23 Dez. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by