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

五迷三道 提交于 2019-11-26 08:56:29

问题


I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently.

For example, if my matrix data is:

 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:

-1     3
 1     4
 5     7

How can I sort this matrix by the first column?


回答1:


I think the sortrows function is what you're looking for.

>> sortrows(data,1)

ans =

    -1     4
     1     3
     5     7



回答2:


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

  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,:)
    


来源:https://stackoverflow.com/questions/134712/how-can-i-sort-a-2-d-array-in-matlab-with-respect-to-one-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!