Alex Rivera | Logout

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

Asked 2011-11-22T20:09:51.710
10

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 :-)

Edit
Report

1 Answer

9

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 *)
answered 2011-11-22T20:57:39.120

Your Answer