Subsections

99 How to sort a matrix based on specific column?

Given matrix $ A$ as follows


   300    48     2
   500    23     5
   120    55     7
    40    32     1
Need to sort it based on entries in the second column.

99.1 Matlab solution

EDU>> [v,I]=sort(A(:,2));
EDU>> B=A(I,:)

B =

   500    23     5
    40    32     1
   300    48     2
   120    55     7

99.2 Mathematica solution

a={{300,48,2},{500,23,5},{120,55,7},{40,32,1}};
b=SortBy[a, #[[2]]&]

Out[9]= {{500,23,5},{40,32,1},{300,48,2},{120,55,7}}



Nasser M. Abbasi
http://12000.org