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 :-)
This does work:
SortBy[a,#[[2]]&]
Alternatively,
a[[Ordering[a[[All, 2]]]]]
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 *)
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With