Reputation: 141
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?
Upvotes: 1
Views: 301
Reputation: 14958
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
Upvotes: 2