开发者

How do I maintain rows when sorting a matrix in MATLAB?

开发者 https://www.devze.com 2023-01-01 02:11 出处:网络
I have a 2-by-3 matrix, and I want to sort it according to the first column. Here\'s an example: datawill change 开发者_如何学运维to -->new data

I have a 2-by-3 matrix, and I want to sort it according to the first column. Here's an example:

data   will change 开发者_如何学运维to -->  new data
11 33                      10 22
22 44                      11 33 
10 22                      22 44 

I have this code for sorting a matrix A but it doesn't work well:

sort(A,1,'ascend');


The SORTROWS function can handle that for you:

B = sortrows(A);


As @gnovice suggests, sortrows is the best solution here. You can also specify more than one output for the sort and sortrowscommands, which will return the sort index. You can use this to modify your other columns as well or just to keep track of the permutation. For example:

A=rand(10,2);
[B, idx]=sortrows(A);
0

精彩评论

暂无评论...
验证码 换一张
取 消