4

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');
gnovice
  • 125,304
  • 15
  • 256
  • 359
Jessy
  • 15,321
  • 31
  • 83
  • 100
  • 1
    Although it doesn't show up on the Related sidebar, I found a *very* old duplicate: http://stackoverflow.com/questions/134712/sorting-2-d-array-in-matlab-w-r-t-one-column . I'm going to try and retag these two so they are more likely to show up in searches. – gnovice May 27 '10 at 20:39

2 Answers2

7

The SORTROWS function can handle that for you:

B = sortrows(A);
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • How can I save the sorted data back to the same txt file? – Jessy May 27 '10 at 18:36
  • @Jessy: To write the sorted data back to a file, you can use FPRINTF (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html). Here's an example: `fid = fopen('newdata1.txt','w'); fprintf(fid,'%f %f\n',B.'); fclose(fid);` – gnovice May 27 '10 at 19:08
  • gnovice@ thanks..I have problem, it doesnt printed in the txt file as excatly shown in the output of B=sortrows(A) – Jessy May 27 '10 at 19:14
  • @Jessy: Two possible solutions: 1) Make sure you are transposing `B` with `.'` before writing it out. 2) You may have to have `\r\n` instead of `\n` in the format string for FPRINTF. – gnovice May 27 '10 at 19:21
3

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);
Doresoom
  • 7,398
  • 14
  • 47
  • 61