2.31 Sort a matrix row-wise using non-first column as key

Given

     4     2     5 
     2     7     9 
    10     1     2
 

Sort the matrix row-wise using the second column as key so that the result is

    10     1     2 
     4     2     5 
     2     7     9
 

In Matlab, the sortrows() command is used, but now we tell it to use the second column as key.

In Mathematica the SortBy[] command is now used but we tell it to use the second slot as key.

Mathematica

mat={{4, 2, 5}, 
     {2, 7, 9}, 
     {10,1, 2}}; 
(*sort by second element as key*) 
SortBy[mat,#[[2]]&]
 

{{10, 1, 2}, 
{4,  2, 5}, 
{2,  7, 9}}
 

 

Matlab

A=[4  2 5; 
   2  7 9; 
   10 1 2]; 
sortrows(A,2)
 

    10     1     2 
     4     2     5 
     2     7     9
 

 

Maple

restart; 
A:=Matrix([[4,2,5], 
           [2,7,9], 
           [10,1,2]]); 
convert(A,listlist); 
sort(%,key=(x->x[2])); 
Matrix(%)
 

 Matrix(3, 3, [[10, 1, 2], 
               [4, 2, 5], 
               [2, 7, 9]])
 

 

In Maple 2023 we can now do the following to get the same output

restart; 
A:=Matrix([[4,2,5], 
           [2,7,9], 
           [10,1,2]]); 
ArrayTools:-SortBy( A, 'column', 2 );
 

Matrix(3, 3, [[10, 1, 2], 
              [4, 2, 5], 
              [2, 7, 9]])