# Tag Info

32

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

25

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

22

After some sleuthing through the xkcdConvert code I found the routine that is causing the execution slow down. The function containing the problem is the xkcdDistort function. See the following code: xkcdDistort[p_] := Module[{r, t, ix, iy}, r = ImagePad[Rasterize@p, 10, Padding -> White]; {ix, iy} = Table[RandomImage[{-1, 1}, ...

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

20

You can implement an imperative-style circular buffer. big = Range@1*^7; size = Length@big; pointer = size; updateElement[new_Integer] := (pointer = 1 + Mod[pointer, size]; big[[pointer]] = new) Do[updateElement[RandomInteger@99], {100}] // AbsoluteTiming {0.000374, Null} To bring the buffer back to the normal form use big = RotateLeft[big, ...

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

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

15

You can take advantage of listability. As a rule if a function has the Listable attribute listable operations will be faster than other alternatives such as mapping. {a, b, c} = Transpose[{a, b, c}]; Apply[Plus, x^a*y^b*z^c] or {a, b, c} = Transpose[{a, b, c}]; Total[x^a*y^b*z^c]

15

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

13

I had a look at an evaluation copy of v9 today, and did some digging around in ImageValue. It looks like the main cause of the slowdown is the handling of Span notation in the position specification. ImageValue calls ImageImageDumpextractCoordinates with the requested position and the image dimensions as arguments. This function then does various checks ...

13

Looks like a computation that rightfully should be slow, you end up with close to 5 million sequences, and I suppose it's checking each constantly throughout to see if the products of the squares lead to square-able numbers. Why is Maple and Mupad faster? I can't say, but looking at the timing I would suspect they are just using approximate floats, leading ...

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

12

I think it might be a good example for FindMinimum with the "PrincipalAxis" method. First define the summation function myfunc: Clear[myfunc] myfunc[n_?NumericQ] := NSum[1/(i + Sqrt[i]), {i, n // Round}] myfunc[n_?(# <= 0 &)] := 0 then the original problem can be solved by minimizing Abs[myfunc[n]-15]: sol = FindMinimum[Abs[myfunc[n] - 15], {n, ...

12

This seems to give a rather decent performance (final version with improvements by jVincent): Clear[getSubset]; getSubset[input_List,sub_List]:= Module[{inSubQ,sowMatches}, Scan[(inSubQ[#] := True)&,sub]; sowMatches[x_/;inSubQ@First@x] := Sow[x,First@x]; Apply[Sequence, Last@Reap[Scan[sowMatches, input], sub], {2}] ]; Benchmarks: n = ...

12

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

12

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

11

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

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

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

10

I compiled your exact algorithm, and it seems to work OK. I get 15 times speed up when using WVM as target, and 60 times when using C (CompilationTarget->"C"). The output is: {{e, vir, 0}, f} test = Compile[{{nparticle, _Integer, 0}, {rho, _Real, 0}, {rc, _Real, 0}, {r, _Real, 2}, {f, _Real, 2}}, Module[{vir = 0., e = 0., dr = {0., 0., 0.}, ...

10

We can substantially speed up the calculation for large primes by making some elementary observations about the Fibonacci series. There are two motivating ideas behind them: Almost all the properties of the Fibonacci series rely only on the field axioms, so that the theory of Fibonacci series (and linear recurrences in general) holds practically without ...

10

Inspired in this solution from @Mr.Wizard. That is the function that I made in order to simulate Excel vLookup: vLookup[data1_, data2_, pk1_:1, pk2_:1,null_:Null] := Module[{index,pickList}, pickList=Complement[Range[Length[data2[[1]]]],{pk2}]; SetAttributes[index,Listable]; (index[#[[pk2]]]=#[[pickList]])&/@data2; ...

10

One potential problem with directly testing the complete list using DeveloperPackedArray[arr_, type_] is that this test may fail if the whole array is not packed, but sub-arrays are. As a result, one can too easily fall through to the more general test using FreeQ (or MemberQ) and end up unpacking anyway. This can be avoided by using ReplaceAll to remove ...

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] - CompileGetElement[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

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

10

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

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