Hot answers tagged

62

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


34

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


31

Update It turns out that the correct way is to use ExtendedDefinition, not ExtendedFullDefinition. Please see the answer by @jkuczm for a detailed explanation. This is a simplification of your solution: Language`ExtendedFullDefinition[new] = Language`ExtendedFullDefinition[old] /. HoldPattern[old] :> new I believe Language`ExtendedFullDefinition ...


26

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


21

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


20

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


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


17

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


16

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


16

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 = {}; ...


15

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["()[]{}"]] ..) :&...


15

As is demonstrated very well in this post you can use a criteria for your pattern, thereby only applying your function as long as you are searching and not to all elements. Also there is a specific FirstPosition function. f[x_] := Module[{}, Pause[0.5]; 2 x] AbsoluteTiming[ Position[f /@ Range[10], 10, 1, 1] ] AbsoluteTiming[ FirstPosition[f /@ Range[...


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


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

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

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


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


13

Well I decided to give it a bit of a go...First import the image and convert to grayscale, then crop to focus on the area of interest. Then I used a LaplacianGaussianFilter, which is often used in blob detection. img = ImageAdjust@ColorConvert[Import["http://i.imgur.com/4lDwE33.jpg"], "Grayscale"]; smallimg = ImageAdjust@ImageTake[img, {200, 500}, {200, 600}...


13

Implementation This is indeed an important problem. It is usually best to have a separate function testing various options. Here is the solution I propose: a wrapper that would factor out the testing functionality from the main function. Here is the code: ClearAll[OptionCheck]; OptionCheck::invldopt = "Option `1` for function `2` received invalid value `3`"...


13

SelectFirst would work: SelectFirst[Range[10], f[#] == 10 &] You can tell that it only executes f on indexes 1-5 if you add a Print statement to the definition: f[x_] := (Print[x]; 2 x)


12

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


12

I think you'll find this much faster than answers so far... strnumsrt = Module[{tc = ToCharacterCode[#], tcc, tcr}, tcc = Unitize@Clip[tc, {48, 57}, {0, 0}]; tcr = Pick[Range@Length@tcc, tcc, 1]; tc[[tcr]] = Sort[tc[[tcr]]]; FromCharacterCode[tc]] &;


12

I remember reading somewhere that everytime I use =, Mathematica copies an expression in the memory (which may be slow and inefficient). This is not quite true, as written here. Mathematica uses a copy-on-write behaviour, i.e. it will only create an actual copy of a datastructure if you modify it. Example: a = {1,2,3}; As this is evaluated, first the ...


12

It's hard to know quite where to start with this, but I'd start with the answers to this question for some initial guidance. As a general guide, nested For loops are almost never necessary and using list-based operations is much more efficient, as well as readable and less prone to error. Let's take the inner loop first. For[h = 1, h <= 3, h = h + 1,...


12

The trick here is to use the plotting function to generate the mesh lines, but there is no way to apply a ColorFunction for a MeshStyle - mesh lines need to have a single color. So we extract the mesh lines, break them up into pieces, and then apply the color function to them. This could be more efficient if I didn't use Normal but the code would be much ...


12

First let me observe that your coding style makes debugging difficult, I highly recommend breaking giant expressions into manageable pieces. Second, in the code below I have used a different definition for the segments. Your version: $y=(x-x_1)^{curvature}\frac{y_2-y_1}{x_2-x_1}+y_1$ does not give an amplitude of $y_2$ at $x=x_2$ if $curvature\neq1$. I ...


11

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


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

You have good answers already, but as I was nitpicking about your terminology I wanted to explain why. The strength of Mathematica compared to e.g. a pocket calculator is that it provides a powerful programming language and what you actually do when making good use of it is writing programs -- and for doing that it is in general very helpful to be precise ...



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