Tag Info

Hot answers tagged

52

In this response, I will focus upon the programming paradigm change when moving from Java to Mathematica. I will emphasize two differences between the languages. The first concerns the "feel" of writing Mathematica code. The second is about how iteration is expressed. The "Feel" of Mathematica Java is a reasonably conventional programming language, ...


27

This is a simplification of your solution: Language`ExtendedFullDefinition[new] = Language`ExtendedFullDefinition[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 ...


23

This is not the full answer but I've solved most of the problems. The hardest one, with sound, remains. Embedded version without music bobthechemist's points Quality is not a problem anymore since here nothing is rasterized. White edges are due to "features" with Texture, I've fixed that using strange VertexTextureCoordinates. I can't handle this ...


22

StringReplace method After reading other answers I was inspired to write a new method. I place it first because it is almost as concise as the method below yet it is more robust (and safe) because it preserves strings as strings. str = "[can {and it(it (mix) up)} look silly]"; StringReplace[str, {"["|"{"|"(" -> -1, "]"|"}"|")" -> 1, " " -> 0}] ...


19

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


19

str = "[can {and it(it (mix) up)} look silly]"; i = 10; StringJoin @@ Last[Replace[Characters@str, {"[" | "(" | "{" :> Sow[" ", --i], "]" | ")" | "}" :> Sow["", ++i], c_ :> Sow[c, i]} , 1] ~Reap~ Range@10] (* " mix it up and it can look silly" *) This just scans through the characters one at a time and Sows them with an integer tag. ...


18

What is wrong: a) you're using exact arithmetic. b) You keep iterating even if the point seems to be escaping. Try this ClearAll@prodOrb; prodOrb[c_, maxIters_: 100, escapeRadius_: 1] := NestWhileList[#^2 + c &, 0., Abs[#] < escapeRadius &, 1, maxIters ] prodOrb[0. + 10. I] prodOrb[0. + .1 I] (if you don't need the entire list but ...


15

Just a bit of fun with @acl's code: ArrayPlot[Table[ NestWhile[#^2 - (0. - 1 I) & , r + i I, Abs[#] < 2.0 &, 1, 10], {r, -2, 2, 0.005}, {i, -2, 2, 0.005}]]


14

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


14

This is a straightforward attempt at a recursive descent parser, favoring readability over brevity. First, the tokenizer: tokenize[str_] := DeleteCases[StringCases[str, { "(" -> open[1], "[" -> open[2], "{" -> open[3], ")" -> close[1], "]" -> close[2], "}" -> close[3], x : (Except[Characters["()[]{}"]] ..) ...


14

As no one gave a FixedPoint answer, here is one: preparedStr = StringReplace[ "((your[drink {remember to}]) ovaltine)", { RegularExpression["[{[(]"] -> "{", RegularExpression["[)\]}]"] -> "}" }] "{{your{drink {remember to}}} ovaltine}" lst = {}; ...


13

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


13

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


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

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


13

Reset the kernel first. str = "[can {and it(it (mix) up)} look silly]" new = StringReplace[ StringReplace[str, {"(" | "[" -> "{", ")" | "]" -> "}"}], {(a : WordCharacter ~~ " " | "" ~~ "{") :> a <> ",{", (a : WordCharacter ~~ " " ~~ b : WordCharacter) :> a <> "," <> b, ("}" ~~ " " | "" ~~ b : ...


12

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


11

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


11

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


11

I worked on Interpreter. As far as the implentation is now, the DelimitedSequence parser does not support quoting, so what you want can't be done. We'll try to add it in a future version.


10

A similar alternative MapThread[Flatten /@ Tuples[{{#1}, #2}] &, {l1, l2}]~Flatten~1 {{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, 19, 20, 21}}


10

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


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


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

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


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


9

This will give you an idea to start with I think: target = "[racket for {brackets (matching) is a} computers]" Rest@Reap[ Nest[With[{s = StringPosition[#, {"{", "(", "["}][[-1, 1]], e = StringPosition[#, {"}", ")", "]"}][[1, 1]]}, Sow[StringTake[#, {s + 1, e - 1}]]; StringDrop[#, {s, e}]] &, target, Length@StringPosition[target, ...


9

str = "[to {quite similar(answer (My) is)} Kuba's answer]"; mid = StringReplace[ StringReplace[ "Hold@" <> str, {"[" | "(" -> "{", "]" | ")" -> "}"}] // ToExpression // InputForm // ToString, "*" -> ","] // ToExpression // ReleaseHold {to, {quite, similar, {answer, {My}, is}}, Derivative[1][Kuba], s, answer} ...


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

For reference there is a built-in function CholeskyDecomposition. For improving your existing code Array may be a minor subjective improvement: HalfFunctionalCholesky2[matrin_List?PositiveDefiniteMatrixQ] := Module[{dimens, uu}, dimens = Length[matrin]; uu = ConstantArray[0, {dimens, dimens}]; Array[(uu[[#]] = makerow[matrin, #, uu, dimens]) ...



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