如何根据第一行在 MATLAB 中重新排列矩阵?

How can I rearrange a matrix in MATLAB according to its first row?

我想做的是制作一个矩阵,例如'A = [8,9,5;15,10,17];',然后将第一行按升序排列。但是,我也希望第二行以相同的顺序排列。所以我想要 'A = [5,8,9;17,10,15];' 的输出。我如何在 MATLAB 中执行此操作?提前致谢。

您希望使用 sort 函数的功能。

来自MathWorks website

B = sort(A)
B = sort(A,dim)
B = sort(___,direction)
B = sort(___,Name,Value)
[B,I] = sort(___)

第一个return参数是排序列表,第二个参数是排序列表的索引。这些可用于以与原始输入排序相同的方式洗牌另一个列表。这将在第一行排序后应用到第二行。

A = [8,9,5;15,10,17];

[B, I] = sort(A(1, :)); % defaults to ascending order

A(1, :) = B;
A(2, :) = A(2, I); % "shuffle" the second row to match the sorting order