Tag Info

Hot answers tagged

27

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


20

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


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

When experimenting with Map (do check the examples under this link), it's better not to define the function you're mapping. If it's not defined, it won't evaluate and it's easier to see what's going on. Map[f, 1+x] is Map[f, Plus[1,x]] with a different notation. So you get Plus[f[1], f[x]], i.e. f[1]+f[2]. Map[f, x] returns x because x is an atomic ...


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

What you have is a so called linked list, and such lists are usually traversed through recursion like this: applyFunc[f_, {el_, rest_}, level_: {1}] := {f[el, level], applyFunc[f, rest, Prepend[level, 2]]} applyFunc[f_, {el_}, level_] := {f[el, level]} applyFunc[h, expr] {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2,1}]}}}} But ...


10

Interesting question. Here is my proposal: fn[f_, expr_] := Module[{h}, h[x_List, _] := x; h[o_[x__h], i_] := h[o @@ {x}[[All, 1]], i]; MapIndexed[h, expr, {1, -1}] /. h -> f ] Test: fn[h, {a, q Sqrt[r], {{{e + f g h}, c^d}, b}}] {h[a, {1}], h[q Sqrt[r], {2}], {{{h[e + f g h, {3, 1, 1, 1}]}, h[c^d, {3, 1, 2}]}, h[b, {3, 2}]}} I ...


9

May be this is not the smarter way to do it but here is what I got: l = {a, {b, {c^d, {e + f g}}}}; pos = ReplaceAll[(Position[l, List]), 0 -> 1]; h[l[[Sequence @@ #]], #] & /@ pos (*{h[a, {1}], h[b, {2, 1}], h[c^d, {2, 2, 1}], h[e + f g, {2, 2, 2, 1}]}*) If you want to keep the levels as they are then: rule = Rule[#, h[l[[Sequence @@ #]], #]] ...


8

If you look at SystemOptions[], like so, Column[ OpenerView /@ (Replace[SystemOptions[], Rule[x_, y_] -> List[x, y], 1]) ] you see that under CompileOptions, if you click on the triangle to open it, there is an option "MapCompileLength" -> 100. Set it to eg 10 and see it it helps (do SetSystemOptions["CompileOptions" -> ...


7

I would use the following, Quiet[ Check[ PowerMod[#, -1, 126] + #, ##&[], PowerMod::ninv ]& /@ Range[125], PowerMod::ninv ] (* {2, 106, 34, 110, 106, 92, 34, 146, 142, 92, 146, 124, 128, 106, 160, 110, 106, 92, 160, 146, 142, 92, 146, 124, 128, 106, 160, 110, 106, 218, 160, 146, 142, 218, 146, 250} *) where ##&[] inserts a ...


7

Here is one way: movingMapCircular[f_, l_List] := MapThread[f@* List, {l, RotateLeft[l]}]; For example: movingMapCircular[f, {1, 2, 3, 4}] (* {f[{1, 2}], f[{2, 3}], f[{3, 4}], f[{4, 1}]} *) A generalization of this approach for arbitrary window size may look like: ClearAll[movingMapCircular]; movingMapCircular[f_, l_List, {n_Integer}] := MapThread[ ...


7

"Reflected" padding works as desired but "Periodic" padding is missed. There is corresponding definition for "Reflected" RandomProcesses`TemporalDataUtilitiesDump`toCannonicalPadding[ RandomProcesses`TemporalDataUtilitiesDump`td_, "Reflected", RandomProcesses`TemporalDataUtilitiesDump`w_, RandomProcesses`TemporalDataUtilitiesDump`Caller_] := ...


7

This duplicates the behavior of yours (no effect on zeroes at ends): smoothee=ReplacePart[#, i_ /; i > 1 && i < Length@# && #[[i]] == 0 :> Mean[{#[[i - 1]], #[[i + 1]]}]] &; smoothee[{0, 1, 3, 4, 6, 8, 0, 11, 12, 0, 13, 0}] (* {0, 1, 3, 4, 6, 8, 19/2, 11, 12, 25/2, 13, 0} *) Here's a goofy ...


7

MovingMap is doing, what it is supposed to do. Evaluating AbsoluteTime /@ (Data[[1 ;; 5]][[All, 1]]) {3439843200, 3440102400, 3440188800, 3440275200, 3440361600} gives the timestamps for the first five data points in absolute time. The output of MovingMap[foo[#] &, Data, 5] or simpler MovingMap[foo[#] &, Data[[1 ;; 5]], 5] ...


6

molekyla777's answer can be very helpful but it is not technically correct. The question specifies "every element of a list" but using a levelspec of {-1} will apply the function to every atomic element regardless of its head: Map[f, 1 + 5 x + 10 x^2 + 10 x^3, {-1}] f[1] + f[5] f[x] + f[10] f[x]^f[2] + f[10] f[x]^f[3] Of course this can be very ...


6

ReplacePart If one is willing to bend on the requirement to use MapIndexed, ReplacePart can generate the desired output directly: $list = {a, {b, {c^d, {e + f g}}}}; ReplacePart[$list, {i:PatternSequence[2..., 1]} :> h[$list[[i]], {i}]] (* {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}} *) MapIndexed Alternatively, we ...


6

Here is a way to use MapThread: MapThread[Function[{r, s}, r + # & /@ s], {tensorR, tensorS}, 2] For numeric tensors, it can be compiled to squeeze out a little more performance: Compile[{{tensorR, _Real, 3}, {tensorS, _Real, 4}} , MapThread[Function[{r, s}, r + # & /@ s], {tensorR, tensorS}, 2] ] Performance Measurements @kguler's solution ...


6

First, your construction of f is a bit malformed. You are using the operator form of Select, therefore the Select expression itself acts as a function; you do not need to add @# & to it. Use instead: f = Select[#[[2]] >= 10 &]; The reason that your operations are not the same can be seen by mapping a dummy function foo: foo /@ a <|1 ...


6

Since version 9 you do not need to do anything extra. tab1 = {{a1, a1 + a2}, {b1, b2*b2}} tab2 = {{2, 5}, {5, 2}} Solve[tab1 == tab2] {{a2 -> 3, b1 -> 5, a1 -> 2, b2 -> -Sqrt[2]}, {a2 -> 3, b1 -> 5, a1 -> 2, b2 -> Sqrt[2]}}


6

ds[MapIndexed[Append[#1, "age" -> ages[[First@#2]]] &]] {<|"name" -> "bob", "age" -> 1|>, <|"name" -> "joe", "age" -> 2|>} Note 10.0.2 throws a warning - who knows what's going on in that private type system: First::normal: Nonatomic expression expected at position 1 in \ First[TypeSystem`ZSignatures`PackagePrivate`i] ...


6

Here are two possibilities. First, use MovingMap: ClearAll[av]; av[{l_, 0, r_}] := (l + r)/2; av[{_, m_, _}] := m; and then smoothMM[list_] := Join[{First@list}, MovingMap[av, list, 3], {Last@list}] or, you can use in-place assignments: smooth2[list_] := Module[{copy = list, pos = Flatten[Position[list[[2 ;; -2]], 0]] + 1 }, copy[[pos]] = ...


5

Another method with a single plot: ClearAll[myFunc2]; yvalues = {0.1`, 0.5`, 1.`, 2.`, 3.`}; myFunc2[x_?NumericQ, y_?NumericQ] := ConditionalExpression[Sin[x y], IntervalMemberQ[Interval[{0, Cos[y]}], x]]; {min, max} = Through[{Min, Max}[Cos[yvalues]]]; Plot[myFunc2[x, #] & /@ yvalues, {x, min, max}, Evaluated -> True, BaseStyle -> ...


5

A method using a single Plot expression: myFunc[x_, y_] := Sin[x y] yvalues = {0.1, 0.5, 1.0, 2.0, 3.0}; Block[{x}, Plot[#, {x, -5, 5}, PlotRange -> All, PlotLegends -> Automatic] &[ If[Cos[#] <= x <= 0 || 0 <= x <= Cos[#], myFunc[x, #]] & /@ yvalues ] ] Notes: I use Block to keep x localized. I did not programmatically ...


5

You can almost always turn to replacement patterns when you need to transform expressions: Cases[ {{a, b}, {c, d}, {e, f}}, {x_, y_} :> (x[#]/y[#] &) ] {a[#1]/b[#1] &, c[#1]/d[#1] &, e[#1]/f[#1] &} Cases defaults to levelspec {1} so this is safer than using /..


5

In your first example, Map maps the function f over Plus, applying f to each argument. In the second case this is not possible, because there is just an x. What is your expected result? Maybe this? Map[f, {x}] (* {2 x} *)


5

fileNames = "file" <> # & /@ RandomSample[CharacterRange["A", "Z"], 4] (* {"fileS","fileU","fileJ","fileO"} *) sheetNames = "sheet" <> # & /@ # & /@ (RandomSample[CharacterRange["A", "Z"], RandomInteger[{1, 3}]] & /@ Range[4]) (* ...


5

Update Well I guess I should retire for the evening to a less brain-intensive activity as apparently I can't think clearly. One could of course use Outer: Outer[Compose, {f, g}, {a, b, c}] {{f[a], f[b], f[c]}, {g[a], g[b], g[c]}} However I recommend that you do not do this as you will not gain the auto-compilation of Map, meaning this method will ...


5

It's a rounding problem. You can see it from: numbers = Rationalize@{0., 0.6, 0.8, 1., 1.2, 1.4, 1.8} midpoints = MovingAverage[numbers, 2] Nearest[numbers, #] & /@ midpoints (* {{0, 3/5}, {3/5, 4/5}, {4/5, 1}, {1, 6/5}, {6/5, 7/5}, {7/5, 9/5}} *) BTW, for long lists and reusable results use Nearest this way: f = Nearest[numbers]; f /@ midpoints


5

Map[f, Unevaluated@{x, y, z}] (* {True, True, True} *) Update: ClearAll[f, x, y, z, q, w, e, r, t] f[vars : {(_) ..}] := Map[ValueQ, Unevaluated@vars]; SetAttributes[f, HoldAllComplete]; f[{x}] (* {False} *) x = 10; f[{x}] (* {True} *) f[{x, y}] (* {True, False} *) f[{x, y, z, q, w, e, r, t}] (* {True, False, False, False, False, False, False, False} ...


5

Since c is common to all the entries, I would do this: MapThread[f[##, c] &, {{a1, a2}, {b1, b2}}] (* ==> {f[a1, b1, c] , f[a2, b2, c]} *) Here the ## stands for SlotSequence and accepts the pair of arguments fed into it by Inner, taken from the two Lists. This is based on constructing a pure function (identified by the & at the end) that is ...



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