views:

75

answers:

2

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');
+5  A: 

The SORTROWS function can handle that for you:

B = sortrows(A);
gnovice
Thanks that works! :)
Jessy
How can I save the sorted data back to the same txt file?
Jessy
@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
gnovice@ thanks..I have problem, it doesnt printed in the txt file as excatly shown in the output of B=sortrows(A)
Jessy
@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
@gnovice ...Thanks very much, you're great!! :) I forgot to add B with .' ...
Jessy
+3  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);
Doresoom