# Tag Info

33

You can use GatherBy for this. You can map List onto Range[...] first if you wish to have exactly the same output you showed. positionDuplicates[list_] := GatherBy[Range@Length[list], list[[#]] &] list = {3, 3, 6, 11, 13, 13, 11, 1, 2, 3, 12, 8, 9, 9, 4, 15, 5, 6, 9, 12} positionDuplicates[list] (* ==> {{1, 2, 10}, {3, 18}, {4, 7}, {5, 6}, {8}, ...

27

RPi configuration options The RPi has two easily accessible features that may influence the performance of M/RPi. The first is overclocking. The default is 700 MHz but the configuration software allows for 4 levels of overclocking: modest, medium, fast and turbo. The second option is the memory split. The Model B RPi comes with 512 Mb of RAM which is ...

26

Using Outer is here one of the worst methods, and not just because it computes the distance twice, but because you can't leverage vectorization in this approach. This is actually a common issue and an important point to stress: Outer works pairwise and is unable to utilize the possible vectorized nature of the operation it is performing on an ...

24

Simple solution Why not just dropWhile[list_, test_] := Drop[list, LengthWhile[list, test]] ? Fast JIT-based solution with automatic type identification / dispatch Here I will show a solution that is potentially much faster on packed arrays. The code is directly modeled after this answer, so I refer to some additional details there. JIT version with ...

21

By the power of CUDALink and a CUDA-enabled GPU, this code drastically increases the speed of xkcdDistort by almost 120x. It takes circa 60s to transform a 400 × 400 image using xkcdDistort on my laptop (i5-2410M + NVIDIA GT540M + 4GB memory), and CUDAxkcdDistort can do the same in just 0.5s. Distortion of a 1000 × 1000 image takes just 2.5s. ...

18

Maybe two advises for the start: Use the fact that Sin is Listable and you can call Sin[{1,2,3,4,..}] to get a list of results. Don't calculate the sum twice. Calculate the sine part only once and make the multiplication with i in the first sum as vectorized multiplication. Taking this into account give in a first try something like fHal = Compile[{{n, ...

17

Regarding your 1. question A density plot is clearly not recommended for your problem. Firstly, a density is AFAIK per definition not complex, but let's ignore this for a moment. The real neck-breaker here is, that ListDensisityPlot interpolates the values if you don't turn it explicitly off. And even if you turn it off, a ListDensityPlot will create a ...

16

Here is another compiled implementation: hammingDistanceCompiled = Compile[{{nums, _Integer, 1}}, Block[{x = BitXor[nums[[1]], nums[[2]]], n = 0}, While[x > 0, x = BitAnd[x, x - 1]; n++]; n ], RuntimeAttributes -> Listable, Parallelization -> True, CompilationTarget -> "C", RuntimeOptions -> "Speed" ]; This appears to ...

16

Well, you can trade memory for speed and use Compile, as follows: accumC = Compile[{{l, _Integer, 1}, {max, _Integer}}, Module[{accum = Table[0, {max}], res = Table[0, {Length[l]}]}, Do[res[[i]] = ++accum[[l[[i]]]], {i, Length[l]}]; res ] ] ClearAll[occurrences]; occurrences[lst_List] := With[{rules = Thread[# -> ...

15

This is an incomplete answer; I will continue it tomorrow. Work In Progress: errors may abound. Preamble hat-tip to Leonid For the variations with custom test or ordering functions we can snoop on applications of that function to deduce the algorithm that is used. In the case of the default methods we must rely on observed complexity and guesswork ...

15

I have found that my approach with textures has different applications: How to plot contours in the faces of a cube? How to plot ternary density plots? Now I want to use it for the enhancement of the DensityPlot: Options[fastDensityPlot] = Append[Options[DensityPlot], Subpoints -> 30]; SyntaxInformation[fastDensityPlot] = ...

14

Another problem is that the Table[..., {x, -L1, L1, δ}, {y, -L2, L2, δ}] produces unpacked array. f = With[{fun = Evaluate[ Sum[Exp[ω I Sqrt[(#1 - 1.0 Cos[θ])^2 + (#2 - 1.0 Sin[θ])^2]], {θ, 2 Pi/n, 2 Pi, 2 Pi/n}]] &}, Compile[{{x, _Real}, {y, _Real}}, {Mod[Arg[#]/(2.0 Pi), 1], 1.0, Abs[#/2]} &@fun[x, y], ...

13

edit: this doesn't really answer the question but merely provides some other alternatives, you should probably up-vote other more useful answers. There are also faster ways to do this using Pick or by compiling Select. Timing comparison done on a Macbook Air OS X 10.8.3 w/ 1.7 GHz Intel Core i5 with Mathematica 9.0.0.0. t = RandomInteger[100, 10^7]; ...

13

Obviously, for large negative inputs, Exp will produce very small numbers. While this isn't intrinsically problematic, it so happens that, by default, Mathematica deals with machine underflow by converting the affected values to an arbitrary precision representation in order to avoid catastrophic loss of precision. However, sometimes one would rather ...

12

A more efficient use of Select If the likely bound of the problem is easily stored in memory it is practical to generate a Range, which is fast, and then Select from that. Since the Range will be unpacked by Select you must consider the unpacked size. For example: ByteCount @ DeveloperFromPackedArray @ Range@1*^7 240 000 032 This is a reasonable ...

12

For unknown reasons, TensorProduct produces unpacked array (see packed arrays here). You can use Outer[Times, a, b] instead: \$HistoryLength = 0; L = 2000; a = RandomReal[{-10^6, 10^6}, {L, L}]; b = RandomReal[{-10^6, 10^6}, 3]; c = TensorProduct[a, b]; c2 = Outer[Times, a, b]; d = RandomReal[{-10^6, 10^6}, {L, L, 3}]; ByteCount /@ {a, b, c, c2, d} // Column ...

11

Here's a version with decent performance without Compile. The idea is to Transpose the data so that the vertex lists {{a,b},{b,c},{a,c}} can be created in one go instead of mapping over the list. The posh version of Flatten is used to reshape the list afterwards. trianglesToLinesSW[t_] := Union@Flatten[{{#1, #2}, {#2, #3}, {#1, #3}} & @@ ...

11

(Update, added more points, and more timings) Using MATLAB's help standard example for meshgrid: Mathematica implementation meshgrid[x_List, y_List]:={ConstantArray[x,Length[x]],Transpose@ConstantArray[y,Length[y]]} {xx, yy} = meshgrid[Range[-2, 2, .1], Range[-4, 4, .2]]; c = xx*Exp[-xx^2 - yy^2]; pts = Flatten[{xx, yy, c}, {2, 3}]; ListPlot3D[pts, ...

11

Try this: n = 1000; coeffs = RandomVariate[NormalDistribution[], n]; f[x_] := Sum[coeffs[[k]] Sin[k x]/k, {k, 1, n}]; Plot[Evaluate@f[x], {x, 0, 2. Pi}, PlotPoints -> n, MaxRecursion -> 0, Mesh -> All] // Timing With[{n = 1000}, First@Timing[Table[Evaluate@f[x], {x, 0, 2. Pi, 2. Pi/n}]] ] 2 times as fast as plot. I remembered my own ...

11

As halirutan comments Dispatch will speed the application of long lists of rules: SetAttributes[timeAvg, HoldFirst] timeAvg[func_] := Do[If[# > 0.3, Return[#/5^i]] & @@ Timing@Do[func, {5^i}], {i, 0, 15}] n = 1500; big = Sum[Expand[(RandomInteger[99] + a[i])^RandomInteger[9]], {i, n}]; vals = RandomInteger[9999, n]; rules = Thread[Array[a, n] -> ...

11

Here's a faster way: Clear[f] Timing[MapIndexed[If[Not@IntegerQ@f[#1], f[#1] = First[#2]] &, list];] Now f[elem] will tell you the position of the first occurrence of elem. On my machine this is approximately 8-10 times faster than your approach for a list of 10000 elements. The timing for a=5000, b=100 is 1.3 s on my machine. In general I expect ...

10

Here is a little procedural implementation using Bag compiled to C: distmatrix = Compile[{{pts, _Real, 2}}, Block[{x, y, list = InternalBag[Most[{0.}]]}, For[x = 1, x <= Length[pts], x++, For[y = x + 1, y <= Length[pts], y++, InternalStuffBag[list, Abs[CompileGetElement[pts, x, 1] - Compile`GetElement[pts, ...

10

In the first example, the list r1 is getting shorter each iteration, resulting in much fewer iterations overall: max = 10^5; r1 = Range[max]; c1 = 0; Timing[ For[i = 2, i <= Length[r1], i++, c1++; r1 = del[r1, i]]; c1] (* ==> {0.012426, 356} *) r2 = Range[max]; c2 = 0; Timing[Do[c2++; r2 = del[r2, i], {i, 2, Length@r2}]; c2] (* ==> ...

10

A print statement shows that this will overflow on platforms where Mathematica machine integers are 32 bits. pe14 = Compile[{}, Module[{n1, len, maxLen = 0, res = 0, print = 0}, Do[n1 = n; len = 1; While[n1 != 1, n1 = If[EvenQ@n1, n1~Quotient~2, 3 n1 + 1]; If[n1 > 10^4*n && print < 10, print++; Print[{n, n1}]]; ...

10

You can use Mod to create a periodic distance function, with a period of, say, d0 (in each coordinate direction). This approach could be altered to have different periods in different directions. Then Nearest will create a NearestFunction that will return the nearest points modulo the period. In the animation below, the square on the left shows the points ...

10

This is what I do. I have been using this method for long time. The idea is simple. Use the second argument of Dynamics. In there, make any changes to the state of the program you want, that only relates to the change of the current control variable being changed. In your case, in the second argument of a and b, you can make your heavy computations. In t, ...

9

Here is a version based on sorting, and using Mr. Wizard's dynP function: dynP[l_, p_] := MapThread[l[[# ;; #2]] &, {{0}~Join~Most@# + 1, #} &@Accumulate@p] positionOfDuplicates[list_] := With[{ord = Ordering[list]}, SortBy[dynP[ord, Length /@ Split[list[[ord]]]], First] ] so that positionOfDuplicates[list] (* ...

9

Mathematica does not do well with code that relies on mutable state (i.e. an explicit variable whose value is changing during the run of the program). Let's look at your For code: For[i=0, i < Length[t], i++, If[ t[[i]] > 50, r=Append[r, t[[i]]]] ] Notice that for every iteration, it needs to evaluate the following by interpreting high level ...

9

You can get about 100 times faster by using Java, without any particular tuning, but you will have to provide the date format explicitly. Here is the solution based on Java reloader. Implementation Load the Java reloader Compile the following class: JCompileLoad@ " import java.text.ParseException; import java.text.SimpleDateFormat; import ...

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