Hot answers tagged

38

I think there is a neat solution. We have curios function ListCurvePathPlot: pic = Thinning@Binarize[GradientFilter[Rasterize[Style["\[Euro]", FontFamily -> "Times"], ImageSize -> 200] // Image, 1]]; pdata = Position[ImageData[pic], 1]; lcp = ListCurvePathPlot[pdata] Now this is of course Graphics containing Line with set of points lcp[[1, 1, 3, ...


35

You can use combination of Part and Ordering as list1[[ Ordering @ list2 ]] to sort list1 in the order of list2. Examples: {list1, list2, list3} = {{1, 3, 2}, {a, b, c}, {x, y, z}}; list2[[ Ordering @ list1 ]] gives {a, c, b} and list3[[ Ordering @ list1 ]] gives {x, z, y} EDIT: Using with lists of lists, to sort the entire array based on the ...


35

If you're looking for a way to sort the colors in such a way as to make them seem the least discontinuous, then one way to think of it is that each color is a point in a space endowed with a distance metric (either the CIELAB 1976 or the CIELAB2000 perceptual metrics), and you are trying to find a shortest tour that visits each point. We can do that with ...


33

Caveat lector: Incorrect results are generated by this solution, e.g., sortByColumn[{{"a", 1, 1}, {"b", 2, 3}, {"a", 3, 2}}, {1, 1, -1}] returns {{"a", 1, 1}, {"b", 2, 3}, {"a", 3, 2}} when the correct result is obviously {{"a", 1, 1}, {"a", 3, 2}, {"b", 2, 3}} I've commented on the answer to bring it to the attention of the ...


32

This is probably because by default Sort doesn't just use numerical values, it includes structure information as well. From the doc: Numeric expressions are sorted by structure as well as numerical value: In[1]:= Sort[{Sqrt[2], 1, 2, 1/Sqrt[2]}] Out[1]= {1, 2, 1/Sqrt[2], Sqrt[2]} Sort by numerical value only: In[2]:= Sort[{Sqrt[2], 1, 2, 1/Sqrt[2]}, ...


29

If you want to keep the rows and your preferences of ordering is first ascending, second descending and third ascending, you can use SortBy: SortBy[data, {#[[1]],-#[[2]],#[[3]]}&]


29

lists = {list1, list2, list3} = {{1, 3, 2}, {a, b, c}, {x, y, z}}; Another option SortBy[lists\[Transpose], First]\[Transpose] {{1, 2, 3}, {a, c, b}, {x, z, y}}


28

This is implemented in SortBy: Because this function does not perform a pairwise compare, you would need to be able to recast your sort function to produce a canonical ordering. On the upside, if you are able to do so it will be far more efficient than Sort. f1 = Mod[#, 4] &; f2 = Mod[#, 7] &; SortBy[Range@10, {f1, f2}] {#, f1@#, f2@#} & /@ %...


28

n = 100; (*number of points*) s = RandomSample@Range@n; (*the initial set*) (*some aux functions*) head[{x_, xs___}] := Select[{xs}, # <= x &]; tail[{x_, xs___}] := Select[{xs}, # > x &]; (*qsort function modified for sowing the information needed*) qsort[{}] = {}; qsort[l : {x_, ___}] := Module[{lh, lt}, (Sow@{l, lh = head@l, x, lt = tail@l}; ...


27

With: dat = {{10, b, 30}, {100, a, 40}, {1000, b, 10}, {1000, b, 70}, {100, b, 20}, {10, b, 70}}; Perhaps most directly: Cases[dat, {_, _, Max@dat[[All, 3]]}] More approaches: Last @ SplitBy[SortBy[dat, {#[[3]] &}], #[[3]] &] Pick[dat, #, Max@#] &@dat[[All, 3]] Reap[Fold[(If[#2[[3]] >= #, Sow@#2]; #2[[3]]) &, dat]][[2, 1]] Of these ...


25

Possible answer using ClusteringComponents: image=Rasterize[ Style["Sjoerd!",Italic,FontSize->24,FontFamily->"Times"], "Image",ImageSize->200] cluster=ClusteringComponents[ImageReflect[image,Left->Right]]; ListPlot3D[cluster,Mesh->False,BoxRatios->{3,1,1},Boxed->False, Axes->False,Lighting->"Neutral", ViewPoint->{-0....


25

In general SortBy can do pretty much anything that Sort does; in some cases, possibly better or faster. You can find many comparisons on this site if you just search for both function names. I also disagree with @user21382 that his task could not be expressed elegantly in SortBy form: not only can it be done, I would actually argue that it could be done ...


24

You can recast this to a problem of finding a Hamiltonian cycle in a graph constructed in a certain way from your points (distance graph). First, compute mutual distances: distances = With[{tr = Transpose[N@pdata]}, Function[point, Sqrt[Total[(point - tr)^2]]] /@ N[pdata]]; Now, construct an adjacency matrix by stating that two vertices (points) are ...


23

Ordering and Part is more efficient than SortBy and Transpose and it can also be done in one pass as I will demonstrate. I create three lists of different type as described in the question: a = RandomInteger[999, 500]; b = RandomReal[1, 500]; c = CharacterRange["a", "z"] ~RandomChoice~ 500; I use the timeAvg function for testing: SortBy[{a, b, c}\[...


22

I tried FindCurvePath and FindShortestTour, but didn't succeed. The latter is too slow to finish on my machine, except when using the "Greedy" method, which does not give a perfect solution. Here's something different: matrix = Rasterize[ Style["\[Euro]", FontFamily -> "Times", Antialiasing -> False], "Data", ImageSize -> 200][[All, All, ...


22

Yes, there is! Szabolcs showed a use of GatherBy in an inverted fashion as a substitute for a conventional decorate-and-sort. It proved both syntactically and computationally efficient. By using that method in place of the decorate-and-sort in this application we can use Ordering directly, and also eliminate Part which was needed to strip the decoration: ...


22

arr = {29400., 28200., 22300., 20900., 20300., 19800., 17400., 16600., 16300., 16100., 15500., 15300., 15300., 15200., 15100., 14900., 14700., 14700., 14400., 13900.} From here RANK gives duplicate numbers the same rank. However, the presence of duplicate numbers affects the ranks of subsequent numbers. For example, in a list of integers sorted in ...


22

This is not simplification. It is canonicalization. Bringing expressions to canonical form is very useful because then two expressions can be compared for equality by simply checking that they have the same structure. Checking equality is a very common operation during symbolic manipulations. a+b and b+a are structurally different, but mathematically ...


21

Something like this might be helpful. It replaces the unsorted list of symbols with a sorted list, lets Mathematica rearrange the expression in the normal way, and then applies a HoldForm before replacing the symbols back again. reorderSymbols[expr_, symbols_List] := With[{s = symbols}, HoldForm[Evaluate[expr /. Thread[s -> Sort@s]]] /. Thread[Sort@s -...


21

This is short: Last /@ Sort[{Characters@#, #} & /@ names] {"~/Hex_6.dat", "~/Hex_12.dat", "~/Hex_24.dat", "~/Hex_48.dat", "~/Hex_96.dat", "~/Hex_192.dat"} Alternatively: Last /@ Sort[{ToExpression[StringJoin[Select[Characters@#, DigitQ]]], #} & /@ names]


21

This is a great use for the Association data structure, which makes so many tasks in Mathematica that much more pleasant. First, we can just write out a ranking of grades: ranking = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "W"}; Then we take your grades and count how many of each there are into an association with ...


20

A bit simpler: Permute[lst, SparseArray[order]] Example: lst = {"e", "c", "a", "d", "b"}; order = {1 -> 5, 2 -> 3, 3 -> 1, 4 -> 4, 5 -> 2}; Permute[lst, SparseArray[order]] {"a", "b", "c", "d", "e"}


18

Maybe Partition[Sort@list, 2, 1] giving {{1, 3}, {3, 4}, {4, 5}, {5, 7}}


18

A year late, but here are my thoughts: As Szabolcs showed, extracting the Line primitives from a RegionPlot provides a convenient way to produce a polygon from an image. The function imgToPolys below does just that - it's essentially the same as Szabolcs' code but I use ImageValue instead of creating an interpolating function from the image data. Of course,...


18

I also got angry about those randomly picked and ill-implemented benchmarks by the Julia team. I appreciate their efforts (jit compilers are useful), but the Fibonacci example was straight away ridiculous. Here is a compiled quick sort implementation that employs a stack in order to avoid recursive calls. The problem with recursion in CompiledFunctions is ...


17

So I think the docs are mostly clear, if hard to visualize. Here's my version of such a table: { "Numerics" -> { "Negative Integer" -> -1, "Zero" -> 0, "Positive Integer" -> 1, "Negative Float" -> N@-\[Pi], "Positive Float" -> N@\[Pi], "Symbolic Constant (Pi)" -> \[Pi], "...


17

How about: Module[{tmp = test}, With[{ord=Ordering[tmp]}, tmp[[ord]] = Reverse @ tmp[[ord]]]; tmp ] {56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}


16

From the sublime to the ridiculous. By way of contrast, here's another approach to 3D text rendering: sjoerd = Image[ Rasterize[" sjoerd ", RasterSize -> 900, ImageSize -> 900]]; Manipulate[ ImagePerspectiveTransformation[sjoerd, ScalingMatrix[s, {v1, v2, v3}], Padding -> "Periodic", Resampling -> "Bicubic"], {{s, .2}, 0....


16

No, this is not a bug, and Ordering does not give a wrong answer. Quoting the documentation of Sort, Sort[list,p] applies the function p to pairs of elements in list to determine whether they are in order. The default function p is OrderedQ[{#1, #2}] &. As you can see, Sort (and Ordering) compares using OrderedQ, not Less. OrderedQ uses a ...


16

As you said in your comment that you just want a well displayed formula, I suggest using Row to force specific orders. A rough example will look like following, you might want to adjust the priority level according to your needs: expr = A^2 e^2 SuperMinus[\[Phi]] SuperPlus[\[Phi]] + A e SuperMinus[\[Phi]] SuperPlus[\[Phi]] Subscript[c, 2 w] Subscript[g, ...


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