# Tag Info

22

This is a simplification of your solution: LanguageExtendedFullDefinition[new] = LanguageExtendedFullDefinition[old] /. HoldPattern[old] :> new I believe Language`ExtendedFullDefinition is used in transferring definitions between the main kernel and subkernels. Also note the HoldPattern on the LHS of the rule which ensures that OwnValues will ...

17

Here is a hybrid recursive/StringReplaceList method. It builds a tree representing all possible splits. Now with a massive speed improvement thanks to Rojo's brilliance. elements = ToLowerCase @ Array[ElementData[#, "Symbol"] &, 112]; altelem = Alternatives @@ elements; f1[""] = Sequence[]; f1[s_String] := Block[{f1}, StringReplaceList[s, ...

13

The following seems a little more elegant. data = Import["http://www.massey.ac.nz/~pscowper/ts/cbe.dat"]; ts = TemporalData[data[[2 ;; -1, 1]], {"1958", Automatic, "Month"}]; DateListPlot[ts["Path"]] TemporalData can also store multiple paths. ts2= TemporalData[Transpose[data[[2 ;; -1]]], {"1958", Automatic, "Month"}]; DateListPlot[ts2["Paths"]]

13

Here is a fairly simple approach using only higher level functions. First, note that StringCases does almost all the work for you. István mentioned it in passing, but it is more powerful than that. It has an Overlap option that you can set to True to get all possible decompositions in one go: elements = Table[ElementData[i, "Symbol"], {i, 112}]; ...

12

Some really simple partial answers using the string patternmatcher: elements = ToLowerCase /@ Select[Table[ElementData[i, "Symbol"], {i, Length@ElementData[]}], StringLength[#] < 3 &]; StringReplace["archbishop", # -> {#} & /@ elements] /. StringExpression -> Join StringReplace["titanic", # -> {#} & /@ elements] /. ...

12

One can also go about this using integer linear programming, with an array of 0-1 variables indexed by vertices and colors. Here is one encoding of that approach. constrainedColorings2[graph[vertices_, nbrhds_], colors_List, start_List, v_] := Module[ {unassigned, nv = Length[vertices], nc = Length[colors], vars, fvars, c1, c2, c3, c4, pos1, pos2, ...

11

Well, Mike Honeychurch and Leonid Shifrin have pretty much covered the ground, but I have one thing to add, which, while based only on observed behavior, I think helps explain what's going on. Set and SetDelayed both create OwnValues is the form HoldPattern[symbol] :> code. The difference is that code is unevaluated in the case of SetDelayed. ...

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

First, I notice that you are using Real numbers such as 1. and 2. for Part indexes. While this works it would be better to use Integer indexes, 1 and 2. Your use of PregaoMC and then Table, etc., is highly inefficient. Part and Span will be better. Observe: Table[PregaoMC[x], {x, 2, n}] === CompleteMatrix[[2 ;; n, 1]] True n = 359835; ...

10

This appears to be a perfectly legitimate use of DownValues. These are often used by experienced users as a hash table. There are some ways you might improve this. First, you could use the value True directly, and it's arguably better to Scan than to Map, but I've used the latter often enough myself as it rarely matters. Scan[(both[#] = True) &, ...

9

Without reading Leonid's answer (which is probably better) I recommend something like this: fillDates[dates_] := Module[{f, all}, all = Part[DateList /@ (Range[##, 24*60^2] & @@ AbsoluteTime /@ dates[[{1, -1}, 1]]), All, {1, 2, 3}]; (f[#[[1]]] = #) & ~Scan~ dates; f[x_] := {x, 0}; f /@ all ] fillDates @ {{{2012, 1, 1}, 1}, {{2012, ...

9

First I want to say, as you mentioned in your comment that your ultimate goal is to to do it for nMax over 100, I suggest you first symbolicly calculate the correlation of the following function, treating $r_n$ ($n=-s,-s+1,\dots,s$, and $s$ is nSteps for short) as variables as $x$: \xi(x,r_{-s},r_{-s+1},\dots,r_{s})=\sum _{n=-s}^{s} r_n\, ...

9

Shotgun thoughts: You don't need the Hold/ReleaseHold pair; Unevaluated will do: Unevaluated[f] /. rules You can use direct destructuring to extract extvar: curvature[f_, range : {var_, __}] := By extracting var as above you can Block it directly, simplifying everything. You can leave the Table variable out of the main Block as it is already localized. res ...

8

Minor improvement: RandomVariate accepts a second argument with the number of elements you want to create. So your assignments to tempX, etc, are equivalent to tempX = RandomVariate[NormalDistribution[0, Sqrt[EmitX]], 2]; tempY = RandomVariate[NormalDistribution[0, Sqrt[EmitY]], 2];

8

This response will keep the basic strategy of the exhibited code, but it will show some useful Mathematica notations that can shorten the code and emphasize its key features. See the bottom of this response for the code in textual form. First, we will use ⊕ to represent XOR, just like in the Wikipedia article. This operator has no built-in meaning in ...

8

I can't find the actual code in your linked data file, but it may be worth posting my own solution for a 2D Poisson problem here. It is copied from my web page. I'm using a maximum of 100000 iterations by default. From your description, it sounds as if you could try to re-write your loops using constructs such as Fold, Nest or - as I do below - FixedPoint. ...

8

Let me offer some advice. Do not start user symbols (variable names) with capital letters. These often may conflict with built-in functions. You have a full selection of Script, Gothic, Double-struck, and Greek characters to choose from to avoid these. Look at Palettes > Special Characters to see these, and hover the mouse pointer over any one of them ...

8

The replace is unnecessary here. When I see this right, then your only issue is, that you use the slot #3 inside the inner pure function. There, it would be belong semantically to the inner function but you want it to be the parameter of the outer one. This can be solved by using only for the inner function the (#...)& syntax. For the outer one, you use ...

7

Rather than applying ToExpression and then NumberQ, perhaps you could just use StringMatchQ with NumberString in the first place. StringMatchQ["assd??asd", NumberString] (* Out: False *) StringMatchQ["123.3", NumberString] (* True *)

7

I don't know why no one thought to use ArrayFlatten: wizard1[l1_, l2_] := ArrayFlatten @ MapThread[Append, {l1, l2}] wizard2[l1_, l2_] := ArrayFlatten @ Join[l1, List /@ l2, 2] Test: wizard1[l1, l2] wizard1[l1, l2] === wizard2[l1, l2] {{a1, a2, 1, 2, 3}, {a1, a2, 4, 5, 6}, {b1, b2, 10, 11, 12}, {b1, b2, 13, 14, 15}, {b1, b2, 16, 17, 18}, {c1, c2, ...

7

As you expect, it's much faster to call RandomVariate fewer times. In fact, it'd be much much faster to call it only once at the beginning, generating large arrays and then operating on them: In[20]:= Bunch = {}; Timing[Do[ Particle = {RandomVariate[NormalDistribution[0, 1]], RandomVariate[NormalDistribution[0, 1]], ...

7

Here are two things you can do to speed up this code. 1. Do the convolution with symbolic y Because you have defined corr using SetDelayed, the table of Convolve expressions will be re-evaluated every time you evaluate corr[number]. The normalisation term with y=0 is causing a particular slow down, though I'm not sure why exactly. If you instead use Set ...

7

Your best bet is to remove the procedural programming Do, While and Append Statements, building lists with Append is not quick. Then embrace a functional programming approach on which Mathematica thrives. Making use of constructs like Transpose, Part, Nest, Map, Table and Fold. These are generally much faster and lead to eventually to less buggy code. If ...

7

You can implement list functionality with string operations, so it's straightforward to make the output of Mr.Wizard's elegant solution more readable while retaining the focus on string operations. Let's begin with a modified version of his solution (altelem is the same as before): f1[""] = ","; f1[s_String] := StringJoin[ StringReplaceList[s, ...

6

Here's a version that uses plain (not string) pattern matching and rule replacement, as well as recursion, to generate all decompositions. EDIT to add: This approach turns out to be suprisingly efficient. I made no attempt to optimize my solution, and it doesn't make use of the string-handling functions at all, and it's about half as fast as Mr.Wizard's ...

6

Update #2 Now significantly cleaner and more efficient. This uses an arbitrary maximum pattern length of 20. This should be sufficient for most words, but it could be raised at the loss of some performance. elements = ToLowerCase @ Array[ElementData[#, "Symbol"] &, 112]; altelem = ## | EndOfString & @@ elements; pat = StartOfString ~~ ## -> ...

6

In addition to the other answers, it's generally not very efficient to create a table using Append repeatedly. This is because every time you call p = Append[p, exp], Mathematica creates a new copy of the list. A more efficient way would be to use Table instead, i.e. Bunch = Table[ code; Particle, {i, 20000}];

6

If you want to translate Matlab code into Mathematica, my advice is - don't! As programming languages, the two are very different and an idiom that works well in one is unlikely to work well in the other. A fundamental theorem theorem in discrete dynamics states that if there's an attractive orbit, then it must attract at least one critical point. Thus, ...

6

The example below indicates what I had in mind with a comment to use Join and GatherBy. It also shows that this is roughly comparable to using DownValues. Set up an example: n = 6; l1 = RandomInteger[10^n, {7*10^(n - 1), 2}]; l2 = RandomInteger[10^n, {7*10^(n - 1), 2}]; l1b = Map[First, GatherBy[l1, First]]; l2b = Map[First, GatherBy[l2, First]]; Using ...

6

The main problem, as I see it: your formula for the curvature is incorrect. Here is a derivation of the curvature using Mathematica: Clear[x, y, t, vec, velocity, tangent, speed, curvature] tangent[t_] = Simplify[velocity[t]/speed[t]]; curvature[t_] = Sqrt[#.#] &@FullSimplify[D[tangent[t], t]/speed[t], speed[t] > 0]; vec[t_] = Through[{x, ...

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