Tag Info

1

In version 10 even a single Rule will produce a Dispatch object: Dispatch[ a -> 1 ] // InputForm Dispatch[{a -> 1}] Dispatch[ a -> 1 ] // AtomQ True Association is also a hash structure and provides a comparably fast alternative to Dispatch, which an interface for adding, deleting and updating rules. In many cases Associations may be ...

6

The OP's (current) definition of ncalc is unreadable and unsalvageable, so I made one up from pieces of the code. ncalc = Piecewise[{ {-21. + 294. u - 1029. u^2, u < 1/7}, {2. v (131.25 - 367.5 u + 257.25 u^2), 5/7 < u < 6/7}, {5.25, u == 6/7}, {33.8811 v^2 , u > 1/7}}, -1380.75 + 3160.5 u - 1800.75 u^2] When you set shared ...

7

It is also pretty straightforward to create your own color map. For example, the following code reads in the image, and multiplies each of the color channels by an appropriate factor, then recombines the three into a single color image. It is very fast. Change the constants (in this case, 0, 1, and 0) at will. img = ...

11

Approach As halirutan suggested in question 71310 we can create a custom, compiled color function and apply it using the trick Image[colorFunction@ImageData@img] on my computer with my custom avocado color function this is more than eight times faster than Colorize, taking only 0.035 seconds. How to create a fast custom color function In order to ...

12

Original question As noted in the comments the use of Dispatch is the easiest way to make this replacement operation much faster. However taking this as an opportunity to explore other optimizations here are some examples for you to consider: (dsp = Dispatch[soln]) // RepeatedTiming // First 0.0030 Total[vars] /. dsp // RepeatedTiming {0.0038, ...

4

Using the option Evaluated->True or wrapping the first argument of Plot with Evaluated gives a 100x speed-up: ls1[t_] := Quantity[10, "Nanometers"]/t Plot[ls1[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"], {t, 0, 10}] // Timing ls2[t_] := Quantity[10, "Nanometers"]/t Plot[ls2[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"], {t, 0, 10}, ...

6

It is possible to Compile Position itself for machine types (e.g. Integer or Real): posmax = Compile[{{list, _Integer, 1}}, Position[list, Max@list] ]; Performance: x = RandomInteger[{1, 100}, 10^7]; Position[x, Max@x] // Timing // First posmax[x] // Timing // First 0.44754 0.0736 With a C compiler this should be faster still; I'll find out in a ...

5

My proposal: Nearest[list -> Automatic, Max[list], {All, 0.5}] Among non-C solutions, it's slightly faster than Pickett's, but slower than Simon Woods's. list = RandomInteger[{1, 100}, 10^7]; Needs["GeneralUtilities"]; Nearest[list -> Automatic, Max[list], {All, 0.5}] // AccurateTiming SparseArray[Unitize[list - Max[list]] - ...

13

For a 1D list you can also use Pick[Range@Length@list, list, Max@list]

14

A fast uncompiled alternative without pattern matching is to use the NonzeroPositions property of SparseArray, as long as you're dealing with numerical data. list = RandomInteger[{1, 100}, 10^7]; Needs["GeneralUtilities"] SparseArray[Unitize[list - Max[list]] - 1]["NonzeroPositions"] // AccurateTiming (* 0.120459 *) Position[list, Max[list]] // ...

2

I think this works Ordering[dat, -Count[dat, Max[dat]]] but it is actually slower than Position[dat,Max[dat]] This also works, but again, it's still slower pos1[list_, max_] := Block[{i = 1, l = Length[list]}, Last[Reap[While[i <= l, If[list[[i]] == max, CompoundExpression[Sow[i], i++], i++]]]]] ... unfortunately so is this more compact solution ...

9

For a one-dimensional list: compPos = Compile[{{list, _Integer, 1}, {max, _Integer}}, Block[{copy = list, i = 1}, Do[ If[ list[[j]] == max, copy[[i++]] = j], {j, Length[list]}]; copy[[1 ;; i - 1]] ], CompilationTarget -> "C" ]; Though I think Position is a good non-compiled alternative in this case, since the "pattern" ...

2

Edit: revised to perform the correct operation this time! In many cases this code appears to be faster than either your own SparseArray formulation or kguler's Internal`DeleteTrailingZeros methods: unPad = MinMax /@ SparseArray[#]["AdjacencyLists"] /. pos_ :> Take @@@ Pick[{#, pos}\[Transpose], UnitStep @ pos[[All, 1]], 1] &; A few ...

0

OK, I found a simple solution, at least if grep or the like is available. Here are the timing results when I apply to the file I used in my original post: rows = ReadList["!grep -iv nan " <> pathToTSV, types, RecordSeparators -> {tab, nl}] // printTime; 3.72033 s ReadList[!grep -v nan <> pathToTSV, types, RecordSeparators -> ...

1

I would do this line by line, using the ability of ReadList to read a single record via its third argument. You can then check whether you want to keep that record, and Sow it if you do. Thus, I would use something like this: importFunction[path_, columns_, maxRows_:∞] := Block[ {inputstream, record, i = 1}, inputstream = OpenRead[path]; Reap[ ...

3

Select[listoffuns, Resolve[Exists[t, # == 0], Reals] &] Constructs list1 for you and Select[listoffuns, !Resolve[Exists[t, # == 0], Reals] &] constructs lists2. However the test Resolve[Exists[t, # == 0], Reals] & is computationally so expensive, that the For loop does not add any significant overhead. You'd be best off performing a refined ...

1

One way to improve the performance of your code is to remove definitions of auxiliary functions from the bodies of function definitions. Such auxiliary functions are redefined every time the function is called. This is demonstrated by f[] := Module[{g}, g[] := SymbolName[g]; g[]] Table[f[], {4}] {"g$11401", "g$11402", "g$11403", "g$11404"} In your ...

7

My guess is that Tally preallocates a number of bins equal to 10% of the length of the list. If the need exceeds that, then it probably has to reallocate the bins, apparently in a time-consuming manner. Table[ l1 = l2 = RandomInteger[{1, max}, 10 max]; l2[[-1]] = -1; {First@Timing@Tally[l1], First@Timing@Tally[l2]}, {max, 2^Range[12, 21]}] // ...

8

This is more of a comment than an answer but it's too long for a comment box and I hope to extend it as I learn more. My first thought was that the negative value might be preventing some optimization so I looked for a counterexample and found something surprising: Table[ With[{a = RandomInteger[{1, 100000}, 1000000 + x]}, First @ Timing @ Do[Tally[a], ...

0

I have tuned your code a bit and it now works reasonably on v.10. 7 locators are ok, 10 gets terrible, but nothing crashes. This is the integral of your function. You can compare it to Integrate[dp[w, z], w]: p[w_, n_Integer, z__] := Sum[Total@(((-1)^n w^(n - i + 1))/(n - i + 1) Times @@@ Subsets[-(Complex @@@ {z}), {i}]), {i, 0, n}]/ ...

5

I propose: errorOps[n_, w_] := Module[{masks, tup}, masks = Permutations[Join @@ ConstantArray @@@ {{1, w}, {0, n - w}}]; tup = ArrayPad[{"X", "Y", "Z"} ~Tuples~ {w}, {0, {1, 0}}, "U"]; Join @@ Map[tup[[All, #]] &, 1 + masks (Accumulate /@ masks)] ] errorOps[10, 7] // Length // AbsoluteTiming {0.0406705, 262440} An alternate ...

4

Is this faster than the fastest of yours? xyz = {"X", "Y", "Z"}; ErrorOps[n_, w_] := Flatten[With[{tups = Tuples[xyz, w], R = Range[n]}, Table[R /. Join[Thread[Complement[R, i] -> j], Thread[i -> "U"]], {i, Subsets[R, {n - w}]}, {j, tups}]], 1]

2

According to a comment by @ilian, this has been fixed as of version 10.0.0. It certainly works in version 10.1, as we can see below: \$Version (* 10.1.0 for Linux x86 (64-bit) (March 24, 2015) *) fC[randomdata] == (fC /@ randomdata) (* True *) totalC /@ randomdata totalC[randomdata]

5

The main reason for the slowness of the magicSquare is that your failed to insist on vecterization. (you're already aware of its importance, right? ) Making use of the internal functions owning Listable attribute and treating lists as a whole as much as possible, it's not hard to come to the following: magicSquare2[n_] /; Mod[n, 4] == 0 := Module[{mat, ...

3

NIntegrate does each integral separately This has been observed before: NIntegrate piecewise vector function, Nested NIntegrate of vector function. It is also clear from the following BenchmarkPlot: int[n_] := Block[{shaxis}, shaxis = Table[1.0*i, {i, 1, n}]; NIntegrate[shaxis/(x^3 + 10), {x, 0, Infinity}, Method -> {"GlobalAdaptive", Method ...

0

This is similar, but perhaps a bit more readable than yours: exMag=Total@Map[ EFieldxComponent[#["alignType"], \[CurlyEpsilon]r, testPtx, testPty, testPtz, #["x1"], #["x2"], #["y1"], #["y2"], #["z1"], #["z2"], \[Rho]\[ScriptL]] &, activeSegments] alternately you might use the Dataset built in map functionality: ...

1

There may be better approaches, but this is what I found to work. I replaced: segmentMapEFieldx[testPtx_, testPty_, testPtz_, \[CurlyEpsilon]r_, \[Rho]\[ScriptL]_]:= Module[ {segmentIndex, segmentCount, exMag}, exMag = 0.0; segmentCount = Length[activeSegments]; For[segmentIndex = 1, segmentIndex<=segmentCount,segmentIndex+=1, ...

Top 50 recent answers are included