如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:39:14  来源:igfitidea点击:

How can I sort a 2-D array in MATLAB with respect to one column?

matlabsortingmatrixoctave

提问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

I think the sortrowsfunction is what you're looking for.

我认为sortrows功能正是您要寻找的。

>> sortrows(data,1)

ans =

    -1     4
     1     3
     5     7

回答by AlessioX

An alternative to sortrows(), which can be applied to broader scenarios.

的替代方案sortrows(),可应用于更广泛的场景。

  1. save the sorting indices of the row/column you want to order by:

    [~,idx]=sort(data(:,1));
    
  2. reorder all the rows/columns according to the previous sorted indices

    data=data(idx,:)
    
  1. 保存要排序的行/列的排序索引:

    [~,idx]=sort(data(:,1));
    
  2. 根据之前的排序索引对所有行/列重新排序

    data=data(idx,:)