1
votes

I have this problem that I need to sort a matrix in MATLAB.

Input:

[20    10    0    50    0; 
 300   100   50   50    100]

And I'd like the output to be:

[0    0    10    20    50;

 50   100  100   300   50] 

So I'd like it to sort the first column but the rows remain unchanged. Help is needed!

2

2 Answers

3
votes

You did write the answer yourself, try sort

A = [20    10    0    50    0;  300   100   50   50    100];
[A(1,:) idx] = sort(A(1,:),2);
A(2,:) = A(2,idx);
2
votes

You could also use sortrows and get the desired result in one line:

result = sortrows(A.',1).';