Reputation: 47
I would like to sort a matrix in ascending order, however I do not want to affect the third column. For example, the sorted version of
A= [ 2 1 3;
5 4 1;
4 3 2]
Would be
B= [1 2 3;
4 5 1;
3 4 2]
Upvotes: 0
Views: 349
Reputation: 5672
You can just sort the 1st two columns and update the matrix accordingly:
edit: updated dimension
A(:,1:2) = sort(A(:,1:2),2);
Upvotes: 1
Reputation: 3397
Matlab provides quite a bit of inhouse help so using help FUNCTION/CLASS
would have provided you with the below information. If you don't know the FUNCTION\CLASS
name use lookfor TERM
for a list of matches or alternately docsearch TERM
.
Stock matlab provides both sort
and sortrows
. You'll be needing the latter.
sortrows(X,C)
Where C is a list of column indices to sort by whose sign may be positive corresponding for ascending order or negative for descending order.
In your example you'll want this :
sortrows(A',[1,2])'
The '
indicates to matlab that you need the matrix transposed, which basically swaps rows and columns before and after sortrows
is called.
Upvotes: 2