Tag Info

Hot answers tagged

24

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


13

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


13

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]


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[___] ...


12

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


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

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]


10

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


10

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


9

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


9

If I understand the statement, you wish to do this: Table[If[time[[i]] == 0, x[[i]] y[[i]], z[[i]]], {i, 1, Length[time]}] but you wish to do it without Table or Do. One way to accomplish this is quite straightforward: (1 - time) x y + time z which gives the same result as above, though this assumes that the time variable is either zero (when you wish ...


8

Just playing around Normal@SparseArray[{i_ /; sel[[i]] :> f[list[[i]]], i_ :> list[[i]]}, Dimensions@list] Another playful one Total[{#~BitXor~1, #} &@Boole@sel {list, f /@ list}] An almost similar solution to @Artes and @ruebenko's that I find neater could be If[#1, f[#2], #2] & ~ MapThread ~ {sel, list} The function on the lhs of ...


8

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


8

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


8

This is an interesting puzzle. I think, though, you should restrict yourself to only words of length 4, to save processing time, as follows: words = DictionaryLookup[Repeated[CharacterRange["a", "z"], {4}]]; where I used CharacterRange to eliminate proper names and contractions. This has the side effect that all accent marks, umlauts, etc. are also ...


8

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]


7

If your elements are in lists the fastest way is to use array operations. In the present case of an outer product one index, let's say "i", will not be expanded, on the other you want to thread. To operate on a list the function needs the attribute Listable. The Times function, as many other internal ones, is already listable, that is Times[{1,2,3},x] = ...


7

You may use map with a pure function: f[#,10,100]& /@ xVals {f[1, 10, 100], f[2, 10, 100], f[3, 10, 100], f[4, 10, 100]} Table will also work: Table[f[x, 10, 100], {x, xVals}] {f[1, 10, 100], f[2, 10, 100], f[3, 10, 100], f[4, 10, 100]} Multiple iterator form: Table[f[x, y, 100], {x, {1, 2, 3, 4}}, {y, {5, 6, 7, 8}}]


7

I like the following very much {x, y} = {{1, 2, 4}, {3, 4, 6}}; (#1^2 + #2^2) & @@@ Tranpose[{x,y}] Another thing which is highly unused is to attach Attributes to pure Functions Function[{a, b}, a^2 + b^2, {Listable}][x, y] You can stick with the Slot notation too, but you have to tell then that the variables in Function is a Null list which might ...


7

Another way, using MapIndexed's functionality, like rm-rf's: mapAtIndexed[f_, expr_, pos_, levelspec_: 1, opts : OptionsPattern[MapIndexed]] := Module[{f0}, f0[x_, p : Alternatives @@ pos] := f[x, p]; f0[x_, _] := x; MapIndexed[f0, expr, levelspec, opts] ] OP's example: mapAtIndexed[g, list, {{2}, {3}}] (* {10, g[20, {2}], g[30, {3}], 40} *) ...


6

I quite like the following myself: list = {1, 10, 100}; sel = {True, False, True}; MapIndexed[If[sel[[Sequence @@ #2]], f[#1], #1] &, list] {f[1], 10, f[100]} Here, we leverage the fact that MapIndexed[] conveniently produces the position of the objects its first argument is being mapped at. For the positions to be usable by Part[], one has to ...


6

vertices = Range[10]; pairs = Tuples[vertices, 2]; func[x__] := First@x <= Last@x; edges = Pick[pairs, func[#] & /@ pairs]; (* or *) edges = Pick[pairs, Boole[func[#]] & /@ pairs, 1]; Graph[DirectedEdge @@@ edges, VertexLabels -> "Name", ImagePadding -> 20] Graph[DirectedEdge @@@ edges, VertexLabels -> "Name", ImagePadding -> 20] ...


6

For educational purposes, here's a couple other ways to do this: Power @@@ {{1, 2}, {2, 2}, {3, 2}} Power[Sequence @@ #] & /@ {{1, 2}, {2, 2}, {3, 2}} Cases[{{1, 2}, {2, 2}, {3, 2}}, List[x__] :> Power[x]] # /. List -> Power & /@ {{1, 2}, {2, 2}, {3, 2}} Replace[{{1, 2}, {2, 2}, {3, 2}}, List -> Power, {2}, Heads -> True] ...


6

Generic element-grouping function Several years ago, I wrote a simplistic HTML parser, for which I wrote a generalization of the function you request, that works on different levels of expression, and groups elements at specified start and end positions in specified heads. Implementation Here is the code (I made no effort to improve it, so it may not be ...


6

Consider this: fn[img_Image][t_] := ImageApply[Evaluate[# (1 + Sin[2 Pi*t])] &, img] times = Table[i, {i, 0, 1, 0.1}]; fn[lena] /@ times I used SubValues notation for flexibility (direct mapping onto times) but it is not required. You can also use the function like this: Table[fn[lena][i], {i, 0, 1, 0.1}] I pre-evaluated the body of the ...


6

Very similar to ssch's second answer, but sometimes Thread feels more natural than Transpose: Thread /@ Thread @ {lst2, lst1} Less clear, but more interesting, is to make a Listable version of List: Function[, {##}, Listable][lst2, lst1] You could also use my smartThread function: smartThread @ {lst2, lst1}


5

Simply you could use: Thread @ h[{1, 2}, a, b] {h[1, a, b], h[2, a, b]} If you can demonstrate how that fails in your application I will give other methods. It was suggested that I use Sequence @@ {a, b} so as to keep {a, b} in the given form. I did not, because I was not clear as to the expected input format and because I felt that it would ...


5

One option is to separate the slots by using an explicit Function for the second argument Map[Function[arg, Apply[{h[arg, ##]} &, {a, b}]], {1, 2}] Regarding your updated question. The approach is the same Map[Function[arg, Apply[{h1[arg, ##], h2[arg, ##]} &, {RandomReal[], RandomReal[]}]], {1, 2}]


5

Yes, there are definitely shorter, non-loop ways to do this. Define your link-defining function like this (with whatever test you need as the first argument to If: islinked[a_Integer?Positive, b_Integer?Positive] := If[Mod[a, 3] == 0 && Mod[b, 2] == 1, a -> b, {}] You can then Apply this at the level of each row using the @@@ shorthand. I ...



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