如何在 MATLAB 中根据一列对二维数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/134712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort a 2-D array in MATLAB with respect to one column?
提问by Midhat
I would like to sort a matrix according to a particular column. There is a sortfunction, but it sorts all columns independently.
我想根据特定列对矩阵进行排序。有一个sort函数,但它独立地对所有列进行排序。
For example, if my matrix datais:
例如,如果我的矩阵data是:
1 3
5 7
-1 4
Then the desired output (sorting by the first column) would be:
然后所需的输出(按第一列排序)将是:
-1 4
1 3
5 7
But the output of sort(data)is:
但输出sort(data)是:
-1 3
1 4
5 7
How can I sort this matrix by the first column?
如何按第一列对这个矩阵进行排序?
回答by Kena
回答by AlessioX
An alternative to sortrows(), which can be applied to broader scenarios.
的替代方案sortrows(),可应用于更广泛的场景。
save the sorting indices of the row/column you want to order by:
[~,idx]=sort(data(:,1));reorder all the rows/columns according to the previous sorted indices
data=data(idx,:)
保存要排序的行/列的排序索引:
[~,idx]=sort(data(:,1));根据之前的排序索引对所有行/列重新排序
data=data(idx,:)

