Sorting matrices

so I have two matrices:
A = [4 6 3 2 9 0 1 5 7 8]
B = [6 5 2 4 0 8 3 7 4 9]
I want to sort matrix A in ascending order, but I want B to correspond with the sorting so that the column match. so if I sort(A), I want B to look like this:
A = [0 1 2 3 4 5 6 7 8 9]
B = [8 3 4 2 6 7 5 4 9 0]
Matrix B can have more than one rows. B is not to be sorted, it just follow the sorting of matrix A. A and B can be in one matrix so as long as I can sort the first row, all the following rows will follow. I would like some ideas about doing this. Thanks.

 採用された回答

Matt Fig
Matt Fig 2011 年 4 月 6 日

3 投票

[As,I] = sort(A);
Bs = B(I);
To sort along the rows, use the dim argument to SORT.

5 件のコメント

Jason
Jason 2011 年 4 月 6 日
This only work if B have one row. I just tried with B having two rows and it combines B into one row. Is there another way to do this if B has more than one rows? like:
B = [6 5 2 4 0 8 3 7 4 9; 6 5 2 4 0 8 3 7 4 9]
Sean de Wolski
Sean de Wolski 2011 年 4 月 6 日
Bs = B(:,I);
Matt Fig
Matt Fig 2011 年 4 月 6 日
Sean de has the correct solution to this further problem. When working with matrices and sorting along dim2, I contains the column indices of the sort for each row.
Thus you must use them that way when indexing into B.
Jason
Jason 2011 年 4 月 6 日
Got it now. Thanks.
Mohamed Helmy
Mohamed Helmy 2011 年 4 月 26 日
Thanksssssssss

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

その他の回答 (1 件)

Tim Zaman
Tim Zaman 2011 年 4 月 6 日

1 投票

Append A to B so that
i believe the code is C=[A;B] so that:
C = [4 6 3 2 9 0 1 5 7 8;
6 5 2 4 0 8 3 7 4 9]
Then you say "sort(C,1)" so that the sorting is done for the first column
Have fun
PS makeup and layout in this textbox is awful

1 件のコメント

Sean de Wolski
Sean de Wolski 2011 年 4 月 6 日
What about it is awful?

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

カテゴリ

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

製品

タグ

質問済み:

2011 年 4 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by