Tag Info

Hot answers tagged

12

Here's another way you might approach this kind of thing -- instead of assigning values to the variables using =, you can make them into rules. For example, here is a collection of "variable names" and values for those variables, and a rule to make the assignment explicit: vars = {a, b, c, d, e}; vals = {5, 4, 3, 2, 1.1}; Thread[Rule[vars, vals]] {a -> ...


11

I do not believe that this behaviour is a bug. The correct usage would be SortBy[#age&] or SortBy[Key@"age"]. The rest of this response will explain these assertions. The crucial point is that the "age" argument in SortBy["age"] is not conferred with any special meaning on account of SortBy being used as a Dataset operator. In the absence of such ...


10

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]] &]


9

You have to use a pure function also for SortBy titanic[Select[#age > 65 &] /* SortBy[#age &]] Since #age will pick out the values of the key "age" in the association.


9

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])}, ...


9

Unless you use := for varList definition. a,b... are lost. Here's more about that, in related Q&A: Generate list of strings from a list of assigned variables. So: a = 5; b = 4; c = 3; d = 2; e = 1; varList := {a, b, c, d, e}; (Defer[varList] /. OwnValues[varList])[[{1}, Ordering[varList]]] {e, d, c, b, a}


8

Likely something like the following: Import[#, "PNG"] & /@ SortBy[FileNames[importString], FileDate[#,"Creation"]&] although I suspect there might be a more terse approach.


8

Using Mathematica 7: Needs["Combinatorica`"] Partition[Flatten@ExtractCycles@FromUnorderedPairs@list, 2, 1] => {{140, 1}, {1, 2}, {2, 43}, {43, 10}, {10, 140}} Edit testLalmei = RandomSample /@ (RandomSample@ Partition[RandomInteger[{1, 1000}, 100], 2, 1, -1]); ExtractCycles@FromUnorderedPairs@testLalmei => { {643, 115, 518, 238, ...


8

If your operation can be converted to a canonical ranking rather than a pairwise comparison then you can use MaximalBy introduced in version 10. If not a good approach to a single pass through a list is Fold. Here is a function using that: foldMax[list_, p_] := Fold[If[p[##], ##] &, list] This proves to be faster in some cases than using Ordering ...


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 @@ # &, ...


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, ...


6

dateOrdered = ((names = FileNames["*.dat"])[[Ordering[ FileDate[#, "Modification"] & /@ names]]]); data = Import[#, "Table"] & /@ dateOrdered; This will import with oldest modification date first, most recent last.


6

In your particular case, the following does the job: lst = {{1, 2}, {10, 140}, {43, 10}, {1, 140}, {43, 2}}; List @@@ If[# === {}, {}, First[#]] &[FindHamiltonianCycle[Graph[UndirectedEdge @@@ lst]]] (* {{1, 2}, {2, 43}, {43, 10}, {10, 140}, {140, 1}} *) To work for your larger test, it should be generated by a variation of your code: test = ...


6

As L.S. said, using MMA like C is a path to poor performance. Based on the OP content, I took the liberty of assuming you want the Mean of remaining tuple values appended to the first: d = {{1, 2}, {1, 3}, {3, 4}, {5, 1}, {6, 9}, {6, 8}, {6, 1}}; Map[{#[[1, 1]], Mean[#[[All, 2]]]} &, GatherBy[d, First]] test = RandomInteger[{1, 20}, {100000, 2}]; ...


6

I think this does what you want: Less @@ SortBy[Defer[Subscript[ω, #]] & /@ {1, 2, 11, 22}, N @@ # &]


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}} *) ...


6

As a followup to the answer by bill s, as of version 10, you should consider using Association instead of lists of rules. In this case, you could do the following: Sort[AssociationThread[{a, b, c, d, e}, {5, 4, 3, 2, 1.1}]] (* <|e -> 1.1, d -> 2, c -> 3, b -> 4, a -> 5|> *) and then Keys@% (* {e, d, c, b, a} *)


5

The function Less is what you can use. list = {2 Pi - 2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 Pi + 2 ArcTan[Sqrt[2 + Sqrt[5]]]}; Sort[list, Less] Or, Sort[list, #1 < #2 &] Or you could use: SortBy[list, N@# &]


5

Don't compare values that are likely to be infinities. Instead, compute Limit on ratios of arguments to be sorted: Sort[v, Limit[#1 / #2, n -> Infinity] < 1 &] You need to use valid functions, though; whatever Iteratedlog is, it's going to be nonsensical on this comparison as it's not defined. Mathematica silently skips complaining about it, ...


5

The sorting (ordering) done by Union is different for different forms of expressions, e.g., analytic versus numeric expressions for a number. Union[{2., (Sqrt[5] + 1)/2}] {2., 1/2 (1 + Sqrt[5])} % // N {2., 1.61803} Union[{2., (Sqrt[5] + 1.0)/2}] {1.61803, 2.} SortBy[{2., (Sqrt[5] + 1)/2}, N] {1/2 (1 + Sqrt[5]), 2.}


5

I am not familiar with the specific output format you need but I think I can show you how to proceed. dat = Import["ExampleData/caffeine.xyz", {{"VertexTypes", "VertexCoordinates"}}]; dat2 = {#[[1, 1]], #[[All, 2]]} & /@ GatherBy[dat\[Transpose], First]; dat3 = {#, Length@#2, #2} & @@@ dat2; dat3 has this format: dat3 // TableForm $\left( ...


5

Ordering[Ordering[data]] (* {3,1,2} *)


4

Edit: This question closely related to one asked on Stack Overflow before the existence of Mathematica.SE. Please see this link for the history and examples: Unsort: remembering a permutation and undoing it See also: Ordering@Ordering and Ranking Permutations The first Q&A references a use of the Ordering method shown below from 2007 on ...


4

I think that it can be done, without loading all the data into memory. The main idea would be to load only the data necessary to do the sorting and then take advantage of Stream Let's first create a a fake log file with random data: strW = OpenWrite["UnSorted.txt"] Do[ WriteString[strW, FromCharacterCode[RandomInteger[{65, 90}, 10]], "\t" , ...


4

{ First @ First @ #, Mean @ Last @ Transpose @ #}& /@ GatherBy[ M, First] {{1, 5/2}, {3, 4}, {5, 1}, {6, 6}} or {First @ #1, Mean @ #2}& @@@ Transpose /@ GatherBy[ M, First] See (Apply (at the first level) - @@@, Map - /@, Slot - #)


4

Something like this? myinversions[list_] := Select[ Subsets[Range[Length[list]], {2}] , list[[#[[1]]]] > list[[#[[2]]]] & ] // Length Verify the same result as builtin Inversions for a permutation Needs["Combinatorica`"] And @@ (Inversions[#] == myinversions[#] & /@ Permutations[Range[5]]) True myinversions[{1, 4, 2, ...


4

In version 10, you can use MeshCoordinates[ConvexHullMesh[...]] as in RunnyKine's answer, but you need to re-order them using MeshCells: pentagon=N@Table[{Cos[2 Pi k /5], Sin[2 Pi k /5]}, {k, 5}] points = N@RandomSample[Join[pentagon, {{0, 0}}]] chm=ConvexHullMesh[points]; ordering=MeshCells[chm,2][[1,1]] out=MeshCoordinates[chm][[ordering]] ...


3

An approach using Reap and Sow: Last@Reap[Sow@@@(Reverse/@M),_, {#1,Mean@#2}&] Thank you rasher for correcting my initial post (see comments)


3

Mathematica 9 has no Sort implementation geared for out-of-core (~ does not fit in RAM) data. As Szabolcs suggested, you can use GNU sort command (possibly directly from Mma), unless you want to specifically implement some external sorting algorithm with Mathematica. For further information on external sorting with GNU sort, see this stackoverflow thread. ...


3

L1 = {{"Australia", a1}, {"USA", a2}, {"Norway", a3}}; L2 = {{"USA", b1}, {"Norway", b2}, {"Australia", b3}}; L2[[Flatten[Position[First /@ L2, #] & /@ First /@ L1]]] {{"Australia", b3}, {"USA", b1}, {"Norway", b2}} Or (revised as per Mr. Wizard's comments) Sort[L2][[Ordering @ Ordering @ L1]] {{"Australia", b3}, {"USA", b1}, {"Norway", ...



Only top voted, non community-wiki answers of a minimum length are eligible