Tag Info

New answers tagged

7

If this is a bug it runs far deeper than SortBy. Since no one has yet been able to provide a reference for the intended ordering of Sort etc. it is hard to say with certainty. I can demonstrate that Sort, Ordering and Order all agree, even if I can't justify that result. x = {6/13 (4 - Sqrt[3]), 6/13 (4 + Sqrt[3])}; Outer[#@#2 &, {Order @@ # &, ...


10

I don't know exactly why Mathematica is giving a wrong result, but here's a workaround: SortBy[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, {4/13 (-9 + Sqrt[3]), 6/13 (4 + Sqrt[3])}}, -N @ #[[2]] &] That is, force Mathematica to sort by their numerical value. OR you can use Sort instead: Sort[{{4/13 (-9 - Sqrt[3]), 6/13 (4 - Sqrt[3])}, ...


1

Operator form of SortBy a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}}; a // SortBy[Last] {{10, 7, 1}, {1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {12, 4, 8}} SortBy[#[[2]] &] @ a {7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}}


6

There is also ... Ordering ClearAll[sortBy]; sortBy[list_, column_, ord_: Less] := list[[Ordering[list[[All, column]], All, ord]]] Examples: a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}}; sortBy[a, 2] (* {{7,1,4},{1,2,3},{12,4,8},{3,5,6},{10,7,1}} *) sortBy[a, 2, Greater] (* {{10,7,1},{3,5,6},{12,4,8},{1,2,3},{7,1,4}} *) ...


11

To sort by a specific element use a pure function with the number in question. For your case (the second element) just do: SortBy[a, #[[2]] &] {{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}} You can also use Sort like this: Sort[a, #1[[2]] < #2[[2]] &]


7

Edit: 4x faster after refactoring and using {# - #2, +##} &[+##, Abs[# - #2]] & instead of Sort/@. Let we have the following 1D intervals $$ [a_1,b_1], [a_2,b_2], [a_3, b_3]. $$ Then we can take all these edges of intervals and sort them. For example, ...



Top 50 recent answers are included