How can I sort a two-dimensional array in MATLAB with respect to a single column?

I would like to sort the matrix according to a specific column. There is a sort function, but it sorts all columns independently.

For example, if my matrix is data :

  1 3 5 7 -1 4 

Then the desired result (sorting by the first column) will be:

 -1 4 1 3 5 7 

But the output of sort(data) :

 -1 3 1 4 5 7 

How can I sort this matrix by first column?

+44
sorting matrix matlab octave
Sep 25 '08 at 17:30
source share
2 answers

I think the sortrows function is what you are looking for.

 >> sortrows(data,1) ans = -1 4 1 3 5 7 
+74
Sep 25 '08 at 18:34
source share

An alternative to sortrows() , which can be applied to wider scripts.

  • save the sort indexes of the row / column you want to order:

     [~,idx]=sort(data(:,1)); 
  • reorder all rows / columns according to previous sorted indexes

     data=data(idx,:) 
+3
Mar 06 '16 at 21:27
source share



All Articles