Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order a matrix in Mathematica by its second column?

Imagine you have:

a = {{5, 1, 1}, {2, 0, 7}, {3, -4, 6}}

and you want to order it by the second column, to get

b = {{3, -4, 6}, {2, 0, 7}, {5, 1, 1}}

I have tried with SortBy[a, Last] and works for the last column, but I can't get it to work for the second column.

Thanks in advance :-)

like image 550
ninescita Avatar asked Nov 22 '11 20:11

ninescita


4 Answers

This does work:

SortBy[a,#[[2]]&]
like image 59
Dr. belisarius Avatar answered Nov 12 '22 09:11

Dr. belisarius


Alternatively,

a[[Ordering[a[[All, 2]]]]]
like image 13
Chris Degnen Avatar answered Nov 12 '22 07:11

Chris Degnen


And here, for the obligatory timing (I added the basic Sort to the methods):

a = RandomReal[{0, 10}, {1000000, 3}];

Sort[a, #2[[2]] < #1[[2]] &]; // Timing

(* ==> {34.367, Null} *)

SortBy[a, #[[2]] &]; // Timing

(* ==> {0.436, Null} *)

 a[[Ordering[a[[All, 2]]]]]; // Timing

(* ==> {0.234, Null}, Chris wins *)
like image 9
Sjoerd C. de Vries Avatar answered Nov 12 '22 07:11

Sjoerd C. de Vries


Maybe you can use this url: http://12000.org/my_notes/mma_matlab_control/KERNEL/node99.htm

Code you can use:

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

Result:

Out[9]= {{500,23,5},{40,32,1},{300,48,2},{120,55,7}}
like image 5
Niels Avatar answered Nov 12 '22 08:11

Niels