Tag Info

Hot answers tagged

13

You can use ReplaceList with a helper function which has the Orderless attribute: ClearAll[f]; SetAttributes[f, Orderless]; ReplaceList[f[a, b, c], f[a___, b___, c___] :> {{a}, {b}, {c}}] // DeleteCases[#, {}, -1] & // Union // Column The DeleteCases and Union are required because the output from ReplaceList includes the empty list {} as a ...


10

SeedRandom[42]; haystack = RandomReal[1, 6300]; AbsoluteTiming[ f = Nearest[haystack -> Range@Length@haystack]; {f[.3, 1], haystack[[f[.3, 1]]]}] (* -> {0.015625, {{3123}, {0.300033}}} *) Of course in this case most of the time is expended calculating the nearest function. If your points aren't changing from one use to the next, the time for ...


10

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


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

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.


8

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


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


5

You can call the windows function that does the sorting directly. The function is StrCmpLogicalW. Note that this is not a cross-platform solution:) Here is a short example: Needs["NETLink`"]; naturalOrder = DefineDLLFunction["StrCmpLogicalW", "Shlwapi.dll", "int", {"string", "string"}, MarshalStringsAs -> "Unicode"]; strings = {"Ie501sp2", ...


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

You can do this in many ways. For example: SortBy[filenames, ToExpression@FileBaseName[#] &] Before @Leonid's comment I used StringDrop[FileNameTake[#], 4]& to get rid of ".tif". Now it is more general FileBaseName.


5

I would use this: Reverse @ SortBy[list, Reverse]


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


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

note see bottom of answer for a required fix for version 10+ A 2D example of what i suggested in my comment: Based on Belisarius example..we get three lines obviously not connected properly: m = SparseArray[{i_, j_} -> Sin[i j 9 /10 y], {3, 3}]; alle = Table[Eigenvalues[m], {y, 0, 1, .1}]; original = Show[ MapIndexed[ListPlot[Flatten[Take[alle, ...


4

m = {"computer", "экзамен", "elephant", "стол", "bread", "телефон", "exception", "desktop", "best", "колонка", "zoom", "saphire", "ярость"}; First Sort it: sortedm = SortBy[m, First@ToCharacterCode@# &] {"best", "bread", "computer", "desktop", "elephant", "exception", "saphire", "zoom", "колонка", "стол", "телефон", "экзамен", "ярость"} ...


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

I briefly closed this question, then realized I had more to say than easily fits into the comments. This is documented behavior so in a way you have to learn to live with it, but the work-around is very simple: use SortBy SortBy[{13, Sqrt[157], Sqrt[163]}, N] {Sqrt[157], Sqrt[163], 13} This is far superior to using Sort with a second argument as it ...


3

[Warning: There could be issues with the averaging procedure. At least one should pay attention to allPossibleOrderings; its definition probably needs to be improved. See other two *edit*s in text below.] I'm probably doing something nasty here but if RAM is really not a problem for you, then… here you go, a blunt brute-force approach: KemenyDistance = ...


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


3

l1 = {{"a", a1}, {"b", a2}, {"c", a3}} l2 = {{"c", b3}, {"b", b2}, {"a", b1}} {#, # /. Rule @@@ l2} &[l1[[All, 1]]] // Transpose (* {{"a", b1}, {"b", b2}, {"c", b3}} *)


3

This is ugly ;), but I think it is what you are after. Composition[ Row[#[[;; , 1]], " < "] &, SortBy[#, N[#[[2]]] &] &, ReleaseHold, MapAt[HoldForm, #, {1, ;; , 1}] &, # /. s_Subscript :> RuleCondition@{HoldForm[s], s /. k -> 1 /. m -> 1} & ]@Hold[{Subscript[ω, 1], Subscript[ω, 2], Subscript[ω, 11], Subscript[ω, ...


3

Using belisarius's test setup and a modification of the Ordering-based method: c = Transpose[{StringJoin /@ Permutations@Characters["123456789"], Range[9!]}]; M = Join[c, c, c]; ClearSystemCache[]; Print@Timing[l1=Reverse@SortBy[Most@M, Last]~Join~{Last@M};]; ClearSystemCache[]; Print@Timing[l2= M[[Ordering[M[[;; -2, 2]], All, Greater]]]~Join~{Last@M};]; ...


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

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


3

Update: Still 4X slower than @Mr.W' method, but much faster than ones in the original post is invF5 = With[{ss = Subtract @@ Transpose[Subsets[#, {2}]]}, Total@UnitStep[ss]] & invF = Total@(1 - UnitStep[Order @@@ Subsets[#, {2}]]) & or invF2 = Count[Subsets[#, {2}], _?(Greater @@ # &)] &; or, variations on george2079's approach ...



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