1

I think I can illustrate this best with an example: Suppose I have A = [ 1, 4, 2, 3; 0,-1, 2, -1]

I want to turn it into [1, 2, 3, 4; 0, 2, -1, -1]

i.e. keep columns intact, sort by entries in first row. How do I do this?

Viktor
  • 141
  • 3
  • 5
  • Often duplicated: [How can I sort a 2-D array in MATLAB with respect to one column?](http://stackoverflow.com/questions/134712/how-can-i-sort-a-2-d-array-in-matlab-with-respect-to-one-column), [How do I maintain rows when sorting a matrix in MATLAB?](http://stackoverflow.com/questions/2923118/how-do-i-maintain-rows-when-sorting-a-matrix-in-matlab), [How can I sort a 2-D array in MATLAB with respect to 2nd row?](http://stackoverflow.com/questions/3482958/how-can-i-sort-a-2-d-array-in-matlab-with-respect-to-2nd-row) – gnovice Mar 18 '11 at 04:42

1 Answers1

2

The sortrows command does what you want:

>> A = [ 1, 4, 2, 3; 0,-1, 2, -1];
>> sortrows(A.').'   

ans =

     1     2     3     4
     0     2    -1    -1

You can also use the second return value from sort to get the column permutation necessary to turn your matrix into the one you want:

>> [~,ii] = sort(A(1,:))

ii =

     1     3     4     2

>> A(:,ii)

ans =

     1     2     3     4
     0     2    -1    -1
nibot
  • 14,428
  • 8
  • 54
  • 58