0

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]  
Suever
  • 64,497
  • 14
  • 82
  • 101
well
  • 47
  • 3
  • Seeing [double](http://stackoverflow.com/q/5347377/958580) ? Use the search ! Double agents don't get badges :P (Though being SO they probably will, dual horned unicorns are not uncommon) – Carel Apr 15 '16 at 09:14

2 Answers2

2

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.

Carel
  • 3,289
  • 2
  • 27
  • 44
1

You can just sort the 1st two columns and update the matrix accordingly:

edit: updated dimension

A(:,1:2) = sort(A(:,1:2),2);
matlabgui
  • 5,642
  • 1
  • 12
  • 15
  • I think you'll want to specify the dimension to be 2. The OP wants to sort along the rows without affecting the last column. – rayryeng Apr 15 '16 at 08:48
  • 1
    yes sir, you're right, i just want to make the rows in ascending order but 3rd column should not be affected. – well Apr 15 '16 at 08:54