How to arrange rows of a matrix to get a specific column in order?

are there any built-in function for this, or I have to extract that column, order it, and arrange the matrix separately?

1 件のコメント

RAGHAVENDRA
RAGHAVENDRA 2015 年 2 月 25 日
編集済み: Guillaume 2015 年 2 月 25 日
You can do the following way:
let us say i want to sort X according to 5th column, then:
X=randi(5,[10 10]);% 10X10 random matrix with elements <= 5
[S,I]=sort(X(:,5),'ascend');
Y=X(I,:);

サインインしてコメントする。

回答 (2 件)

Jos (10584)
Jos (10584) 2015 年 2 月 25 日
編集済み: Jos (10584) 2015 年 2 月 25 日

1 投票

Yes, there is! Take a look at SORTROWS
M = [1 2 3 ; 2 3 1 ; 3 1 2]
sortrows(M,2)

3 件のコメント

RAGHAVENDRA
RAGHAVENDRA 2015 年 2 月 25 日
Hi Jos,
But this will sort rows in ascending order, what if we want to sort the matrix such that column 3 of M is to be in ascending order
Jos (10584)
Jos (10584) 2015 年 2 月 25 日
Oh, I misunderstood. You only want to sort column 3, leaving the other columns as they are?
M(:,3) = sort(M(:,3))
Guillaume
Guillaume 2015 年 2 月 25 日
Jos, you didn't misunderstand the question and your answer was actually correct. Raghavendra should actually have tested the posted code, which sorted the rows according to the second column.
To be very clear:
sortrows(M, cols)
sorts the rows of M according the columns defined in cols, so
sortrows(M, 3)
sorts the rows of M so that values in column 3 are ascending
sortrow(M, [3 -2])
sort the rows of M, first according to column 3 in ascending order. For identical values in column 3 it then uses column 2 in descending order.
It's all explained in the doc.

サインインしてコメントする。

RAGHAVENDRA
RAGHAVENDRA 2015 年 2 月 25 日

0 投票

You can do the following way:
let us say i want to sort X according to 5th column, then:
X=randi(5,[10 10]);% 10X10 random matrix with elements <= 5
[S,I]=sort(X(:,5),'ascend');
Y=X(I,:);

3 件のコメント

RAGHAVENDRA
RAGHAVENDRA 2015 年 2 月 25 日
You can also use X=sort(X,I), as an alternate to Y=X(I,:) in the above code
Guillaume
Guillaume 2015 年 2 月 25 日
Raghavendra, as mentioned in another of your answer, please use the code formatting tool when you answer, so that it is easily readable.
It's not that hard, just add two spaces before writing the line of code, or select the code and click the {} Code button.
People answering questions should know how to use the forum tools.
RAGHAVENDRA
RAGHAVENDRA 2015 年 2 月 26 日
Hi Guillaume
I didn't know this. Thank you very much, for the suggestion.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

質問済み:

2015 年 2 月 25 日

コメント済み:

2015 年 2 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by