Hot answers tagged

38

Preamble This is a very good question, because answering it will make it very clear what immutability means, both in general and in the context of Associations. General A few general words on immutability Associations are immutable data structures. This means that they carry no state, and a copy of an Association is another completely independent ...


36

These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, ...


29

Updated with new functions and additional timings Since this question inspired so many answers I think there is as need to compare them. I have included two of my own functions, freely borrowing from previous answers: wizard1[] := Inner[Compose, sel /. {True -> f, False -> Identity}, list, List] wizard2[] := Module[{x = list}, x[[#]] = f /@ ...


22

I hesitate to add anything after @Leonid's comprehensive answer, but I'd like to point out that an easy way to achieve the stated goal is to define f like this: f[x_] := <| x, "isFirstValueTrue" -> x@"firstValue" |> ... which yields the desired result when mapped across the associations in x: f /@ x (* { <|"firstValue" -> True, ...


22

Well, transposing, subtracting, transposing... Transpose[Transpose[mat] - Mean[mat]]


19

It is there: Standardize[mat, Mean, 1 &]


17

Please see the Utility function section for a concise summary. An arbitrary density plot for the example: den = DensityPlot[Sin[x] Sin[y], {x, -180, 180}, {y, -90, 90}] : Extract the graphics primitives from the density plot: prim = First @ Cases[den, Graphics[a_, ___] :> a, {0, -1}, 1]; Plot them directly with GeoGraphics while setting the ...


15

For Mean you don't have to do any transformation to the input array data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Mean[data] (* {4, 5, 6} *) because (from docs Mean >> More Information) that is, Mean "threads" over its input when it is fed an array. In general, in addition to func/@Transpose[data] (as in @m_goldberg's answer) you can also use ...


15

A little "secret" of level specifications is that they can be negative. -1 refers to the atomic leaves, -2 refers to all Depth 2 subexpressions, generally -k refers to all depth k subexpressions. Thus the behaviour of negative levels is somewhat different from that of positive ones. You can read more here: Levels: how do they work? ...


14

If[ #[[2]], f[#[[1]]], #[[1]]] & /@ Transpose[{list, sel}] {f[1], 10, f[100]} this should be a bit faster : If[ Last @ #, f @ First @ #, First @ #] & /@ Transpose[{list, sel}] or using Inner : Inner[ If[#2, f, Identity][#1] &, list, sel, List]


14

mat - ConstantArray[Mean[mat], 3] or more generally: mat - ConstantArray[Mean[mat], Length[mat]]


13

Summary: undocumented HashTable is a bit faster (at least in version 9) both in storage and in retrieval than DownValues. DownValues list = RandomInteger[{-10^9, 10^9}, 10^6]; ret = RandomInteger[{-10^9, 10^9}, 10^6]; isGood[___] = False; Scan[(isGood[#] = True) &, list]; // AbsoluteTiming (* ==> {3.240005, Null} *) ClearAll[isGood]; isGood[___] ...


13

This version seems to be about twice faster than the fastest so far (generally, as much faster as small is a fraction of selected elements), and about an order of magintude faster when Listable functions are mapped on a numerical list - since it automatically utilizes Map auto-compilation in such cases: ClearAll[conditionalMap]; conditionalMap[f_, lst_, ...


13

This is because of the compilation that kicks in automatically if the list in Map exceeds a certain number of elements. "MapCompileLength" /. ("CompileOptions" /. SystemOptions["CompileOptions"]) (* Out: 100 *) shows that the default setting is that if the list contains more than 100 elements then Map will be compiled. MapThread on the other hand does not ...


13

To my knowledge, there aren't built-in versions for comparison operators that would be automatically threaded over lists. One reason for that is that Mathematica is a symbolic system, and every auto-simplification has a cost, because there may be cases when this isn't desirable. It is relatively easy however to construct the behavior you want: ClearAll[l]; ...


12

There are two built-in functions to generate pairs, either with (Tuples) or without (Subsets) duplication. Since your question states the number of iterations as $n*(n-1)/2$ I believe you want the latter: set = {1, 2, 3, 4}; Subsets[set, {2}] {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}} The short notation for Apply at level 1 is @@@, so this ...


12

This is a good example where Internal`PartitionRagged (IPR) can be used very effectively. First, observe the following: list = {10, 20, 30, 40, 50, 60, 70}; (* 3 continuous elements in the middle *) Internal`PartitionRagged[list, {2, 3, 2}] (* {{10, 20}, {30, 40, 50}, {60, 70}} *) (* 3 continuous elements from the start *) Internal`PartitionRagged[list, ...


12

Use Map with a levelspec of {-1}: Map[g, {a, b, {c, d}, {{e}}}, {-1}] {g[a],g[b],{g[c],g[d]},{{g[e]}}}


12

Map is automatically compiled. Yes, even with RandomChoice. Try it: f = Compile[{{p, _Real, 0}, {t, _Integer, 1}}, Map[# RandomChoice[{p, 1 - p} -> {1, 0}] &, t] ]; f // InputForm (* -> clean bytecode *) Check its performance: p = 0.1; t = Table[1, {10^6}]; SeedRandom[1000]; AbsoluteTiming[a = Map[# RandomChoice[{p, 1 - p} -> {1, 0}] ...


12

There are many closely related topics but I've failed to find a duplicate. MapThread[Thread @* f, {First @ list1, list2}] MapThread[f, {list2, list3}] {{f[a, 1], f[a, 2]}, {f[b, 3], f[b, 4]}} {f[{1, 2}, {x, y}], f[{3, 4}, {z, w}]}


11

Transpose followed by mapping Mean over the array should do the job. data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Mean /@ Transpose[data] (* ==> {4, 5, 6} *)


11

How about something unconventional? Transpose[{list, sel}] /. {x_, y_} :> (f^Boole[y])[x] /. 1[x_] :> x (* {f[1], 10, f[100]} *) Again, another unconventional solution: Transpose[{list, sel}] /. {x_, y_} :> (y /. {True -> f, False -> Identity})[x]


11

I believe I have a solution for you, assuming we've worked out all the discrepancies in the original question. You will need my dynamicPartition function or one of its "core function" equivalents. process[data_List] := Module[{f, s1, s2}, f[_, {1, ___, 1}] = 1; f[_, {___, 0}] = 0; f[x_, _] := x; s1 = Split @ Rest @ FoldList[f, 0, data]; ...


11

MapThread[Thread[{##}] &, {lst2, lst1}] Map[Thread, {lst2, lst1}\[Transpose]] ## is used so Thread gets called like Thread[{1, {a, b, c}}] As MapThread gives two arguments in this case it is equivalent to Thread[{#1, #2}]& and Composition[Thread, List]


11

This perhaps: Function[{a, b}, a[#]/b[#] &] @@@ {{a, b}, {c, d}, {e, f}} (* Out: {a[#1]/b[#1] &, c[#1]/d[#1] &, e[#1]/f[#1] &} *) Mr.Wizard's way of writing it (see comment) looks like this in the frontend:


11

# - Mean@mat & /@ mat // MatrixForm


10

Are you sure you want to use UpValues? You can use Dispatch which is pretty fast when generating the lookup table and is equally fast when accessing values: n = 6; list = RandomInteger[{0, 10^(n + 1)}, {10^n}]; AbsoluteTiming[disp = Dispatch@Thread[list -> True];] {1.6220927, Null} Remove[isGood]; AbsoluteTiming[isGood[___] = False; ...


10

If you want to use Map[] that is possible too: #[[1]]^#[[2]] & /@ {{1, 2}, {2, 2}, {3, 2}}


10

First of all, let's clarify that if you define h as `h[{x_, y_}] := ...` then it takes a single argument which is a list of two items. If you define it as `h[x_, y_] := ...` then it takes two separate arguments. #n denotes the nth argument in a pure function. In the function call (#1^#2)& [{2,3}] you are passing the pure function a single ...



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