title: How can I use Mathematica's graph functions to cheat at Boggle?

text: This question is inspired by a Stack Overflow question that I decided to solve using _Mathematica_. In addition to _Mathematica_ , I thought I'd use some of the new version's graph-related functionality, which I've never really explored in the past. It seemd like a natural fit, but the further I got into my program, the more awkward everything seemed. First, the board from the orginal question:               F X I E     A M L O     E W B X     A S T U      I use a mix of features to turn this into a `Graph`; with `ImportString` I was able to copy and past from my browser directly into a string literal in my notebook.               makeBoggleBoard[s_String] :=      makeBoggleBoard@ImportString[s]          makeBoggleBoard[mat : {{__String} ..}] /; MatrixQ[mat] :=      With[{dims = Dimensions@mat,        cPatt = {_Integer, _Integer},        dPatt = Alternatives[{1, 0}, {0, 1}, {1, -1}, {1, 1}]        },       With[{coords = Tuples[Range /@ dims]},        With[{          vertexRules =            Thread[coords -> Thread[{Range@Length@coords, Flatten@mat}]],          edgePattern = {c1 : cPatt, c2 : cPatt} /; MatchQ[c1 - c2, dPatt]          },         Graph@Cases[Tuples[coords, 2],           c : edgePattern :> ((UndirectedEdge @@ c) /. vertexRules)]]]]      This already seems a little bit clunky. Most of the difficulty comes about from trying to associate a letter with each vertex in my graph while keeping all the vertices distinct. However, this mostly seems to work well. Also, it will help to winnow the dictionary so it only contains valid words (they must have more than three letters and only use letters on the board). This part, at least, is pretty easy and quick:               makeBoggleDictionary[board_Graph] :=       With[{chars =           ToLowerCase@DeleteDuplicates@(VertexList@board)[[All, -1]]},        DictionaryLookup[chars ~~ chars ~~ chars ~~ (chars ...)]];      Now it's time to traverse the graph, finding all the words along the way. We need to traverse each possible path from each vertex, check to see if the path so far spells a word, and if it does, collect it. In order to keep performance reasonably in hand, we want to cull paths that can't possible spell a word as quickly as possible. Here's the function I came up with:               findWordsInBoggleBoard[graph_Graph, dict : {__String}] :=      With[{        makeWord = ToLowerCase@StringJoin[#[[All, 2]]] &,        lookup =          Function[pattern,           Flatten[StringCases[dict,             StartOfString ~~ pattern ~~ EndOfString]]]        },       Module[{extendPaths},        extendPaths[v_, {}] :=         With[{adj =             DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},          Join @@ (extendPaths[#, {{v}}] & /@ adj)];        extendPaths[v_, paths_] :=         Module[{           extended = Append[#, v] & /@ paths,           nexts,           strings,           feasible,           adj = DeleteCases[VertexList@NeighborhoodGraph[graph, v], v]},          strings = makeWord /@ extended;          Scan[           Sow,           lookup[Alternatives @@ strings]           ];               feasible =           Pick[            extended,            Function[string,              MatchQ[               Select[lookup[string ~~ __],                 StringLength@# >= 3 &], {__String}]] /@ strings];               nexts =           DeleteCases[            {#, Select[feasible, Function[path, FreeQ[path, #]]]} & /@ adj,            {{_, _}, {}}];                    extendPaths @@@ nexts          ];             Reap[Scan[extendPaths[#, {}] &, VertexList@graph]] /.         {{Null, {}} -> {}, {Null, {words : {__String}}} :> Union@words}]]      The performance is sort of acceptable (it takes about 3 seconds to find all the words in the sample board), but the entire approach I'm taking here seems very ugly. In particular, the repeated use of `NeighborhoodGraph` to find adjacent vertices in the recursion for `extendPaths` seems faintly ridiculous, and the whole approach feels quite low-level compared to some of the other graph functions. Can anyone suggest some possible ways to speed this up? **EDIT** : Part of what I'm interested in seeing is whether _Mathematica's_ graph functions are a good fit for this problem, though of course I'm happy to see the good, fast implementations that people have posted.


title: Strange behavior of CreateDialog's WindowSize option

text: Compare the two dialog windows, created by the same code except in the first `WindowSize` has a value while I omit it in the second one. Note, that `CreateDialog` (and especially its default option `WindowSize -> All`) can lead to unexpected behaviour.               DynamicModule[{switch = 1},       CreateDialog[        DocumentNotebook@TextCell@Dynamic@Switch[switch, 1, "A", 2, "B"],        WindowSize -> {200, 100}]];          DynamicModule[{switch = 1},       CreateDialog[        DocumentNotebook@TextCell@Dynamic@Switch[switch, 1, "A", 2, "B"]        ]];      ![Mathematica graphics](http://i.stack.imgur.com/MVYE8.png) While the value of the `WindowSize` option is recognized and used on the left, any explicit value prevents the evaluation of the dynamic content (be it a number, list of numbers, `Automatic`, `Full`, etc.). The same behavior is experience if `Module` is used instead of `DynamicModule`. Is it a bug? I need a workaround that works with a fullscreen window (i.e. `WindowSize -> Full`), any idea? **1\. Update** Even more strange is the workaround that I've found by eliminating part of my code, expression-by-expression. I ended up with the following stripped piece:               DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];      which correctly produces the dialog on the left, while (and this is the strangest bug I've ever experienced in _Mathematica_ so far) when I comment out **any part** of this code it results in an unevaluated `Switch` in the dialog window (on the right)! ![Mathematica graphics](http://i.stack.imgur.com/LOLnU.png) Below are some examples, that obviously should not change the output, but they do, and are producing the above right dialog. I think this behaviour has something to do with the parsing of `DynamicModule`, but I am quite clueless...               DynamicModule[{a = 1, b(*,c,d,e,f,g,h,i,j,k*)},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j(*,k*)},       b = Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       b = Plot3D[(*Join@*){x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       (*b =*)Plot3D[Join@{x, y}, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];          DynamicModule[{a = 1, b, c, d, e, f, g, h, i, j, k},       (*b=Plot3D[Join@{x,y},{x,0,1},{y,0,1}];*)       b = Plot3D[x, {x, 0, 1}, {y, 0, 1}];       CreateDialog[Dynamic@Switch[a, 1, "A"], WindowSize -> {200, 100}]       ];      Each of these were tried with a fresh kernel, without any user package loaded. **2\. Update** The following example shows that the variable `a` displayed in the dialog has **no initial value** in spite of defining it two times (note however that the `Initialization` code is not evaluated at all, you can make sure about that by putting any `Print` in it):               DynamicModule[{a = None},       Print[a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         (*Checkbox@Dynamic@a*)         }, WindowSize -> {200, 100}],       Initialization :> (a = None)       ];      > `None` ![Mathematica graphics](http://i.stack.imgur.com/Rjqvl.png) Thus `a` has a value (`None`) inside the `DynamicModule` but not inside the dialog. Uncommenting the commented line proves that the `a` displayed in the dialog is **not the same** as the `a` being locally defined in `DynamicModule`:               DynamicModule[{a = None},       Print[a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         Checkbox@Dynamic@a         }, WindowSize -> {200, 100}],       Initialization :> (a = None)       ];      > `None` ![Mathematica graphics](http://i.stack.imgur.com/qXRM8.png) that is: still printing `None` as the value of the `DynamicModule`-`a`, but displaying `False` as the dialog-`a`, which is the default value that `Checkbox` assignes to a variable without any value. **To conclude: a dialog does not necessarily inherit the variables of its enclosing`(Dynamic)Module`.** Printing `Dynamic@a` instead of simply `a` helps, as it forces the front-end to claim the dynamically displayed `a` of the wrapping module. Please correct me if I'm wrong.               DynamicModule[{a = None},       Print[Dynamic@a];       CreateDialog[{         Dynamic@a,         Dynamic@Switch[a, True, "A", False, "B", None, "C"],         Checkbox@Dynamic@a         }, WindowSize -> {200, 130}],       Initialization :> (a = None)       ];      ![Mathematica graphics](http://i.stack.imgur.com/OQqZY.png) * _3\. Update: *_ The purpose of this construction is to design a gui where the displayed content switches according to user interaction. While there might be easier ways to do this, I am now inclined to solve the underlyings of this behavior. The following example uses three "screens" as different contents (`first`, `second`, `third`). Changes made to dynamic controls in one screen should affect other screens (hence the variable `x`).               DynamicModule[{a = 1, x = .5, first, second, third},       first := Column@{"First", Row@{"x: ", Slider@Dynamic@x}, Button["Next", a = 2]};       second := Column@{"Second", Row@{"x: ", Dynamic@x}, Button["Next", a = 3]};       third := Column@{"Third", Button["Reset x", x = .5], Button["Next", a = 1]};       CreateDialog[Dynamic@Switch[a,          1, first,          2, second,          3, third          ], WindowSize -> {300, 200}]];


title: Why does MatrixForm affect calculations?

text: This is a really newbie question, but it has me confused. Why does this code **work without** `// MatrixForm` and **doesn't work with** `// MatrixForm`?               cov = {{0.02, -0.01}, {-0.01, 0.04}} // MatrixForm     W = {w1, w2}; FindMinimum[ W.cov.W, W]      The error is:               The function value ... is not a real number      Is `MatrixForm` supposed to be typesetting feature or it has other impact? * * * A similar problem appears here:               a = {{1, 0, 1, 0}, {2, 1, 1, 1}, {1, 2, 1, 0}, {0, 1, 1, 1}};     inv = Inverse[a];     b = MatrixForm@{{0}, {0}, {0}, {1}};     soln = inv.b      ![enter image description here](http://i.stack.imgur.com/Aw8jS.png)


title: Difference between matrix rapresentation

text: I've noticed different behaviour in Mathematica between matrix representation: The matrix               a={{1,2},{3,4}}     is different from      b=a // MatrixForm      Why i obtain different results using the same matrix in command like Eigensystem? What kind of definition should i use in my programs?


title: Problem with List Dimension Outer Map

text: I am currently handling a big list which has the following dimension: `{6, 3, 4, 2, 2, 1, 8}` where the last number `8` represent a number of equation that are in each sublist. If I apply solve to the 7 level               Ssols = Map[Flatten[Solve[#, vars]] &,SSEquations, {7}]      I get a list in which               Dimensions[Ssols]     Dimensions[Ssols[[1]]]      > {1}   >  {6, 3, 4, 2, 2, 1} so until now it seems fine, even if I don't understand this wrapping that comes out with another List containing the previous one. But then things get compplicated               SCSystem =        Outer[# && #2 && #3 && #4 && #5 &, Eq1, Eq4, Eq5, Eq6, Eq8, {2}]        /.SCEq1 /. SCEq4 /. SCEq5 /. SCEq6 /. SCEq8 // MatrixForm;     Dimensions[SCSystem[[1]]]      > {6, 3, 4, 2, 2, 1} where: `EqX = {IX,IIX, etc}` and `SCEqX ={IX->a+b<c,etc.}` or similar inequalities Now if I apply a `FullSimplify` to get which one of this set of inequalities is `True` and which one is not, and also geting a simplified form of the set of inequalities                SCsols = ParallelMap[FullSimplify[#] &, SCSystem, {7}] //MatrixForm      I get something really strange               Dimensions[SCsols[[1]]]     Dimensions[SCsols[[1, 1]]]      > {1}   >  {6, 3, 4, 2, 2, 1} How this is possible? Do you have any suggestions? And moreover I would like to go and substitute for each level 6 of `Ssols` the corresponding value in `SCsols` and I thought to do in the following way:               SCsolsSub =        Parallelize[Outer[#1 /. #2 &, SCsols, Ssols],{6}] // MatrixForm      but doesn't work probalby because the two list have not the same dimensions.


title: Inverting a matrix

text: > **Possible Duplicate:**   >  Why does MatrixForm affect calculations? I am facing a strange behaviour from Mathematica when asking it to invert the following matrix:               m = {{a, b, b, 0, 0, 0}, {b, a, b, 0, 0, 0}, {b, b, a, 0, 0, 0},           {0, 0, 0, c, 0, 0}, {0, 0, 0, 0, c, 0}, {0, 0, 0, 0, 0, c}} // MatrixForm          Inverse[m] // MatrixForm      It doesn't output the inverse of the matrix but just the command I entered. But, knowing that my matrix is bloc diagonal, when I enter each one of the blocs separately it does compute their inverses. Where is the trick?


title: Using functions as input for a function - won't simplify

text: I've defined a function P[k_] := 1/[Sqrt]2 (R[k] + L[k]) where R and L generate matrices. However the output of this function never full simplifies (even when I use the Simplify[%] functions). It always leaves the output at 1 over root 2 followed by each of the matrices with the binary operator. Can anyone tell me what I need to do to simplify this output?


title: Matrix multiplication involving MatrixForm

text: > **Possible Duplicate:**   >  Why does MatrixForm affect calculations? I am doing a matrix multiplication, but not getting the desired output. I am doing the matrix multiplication of $A^{-1}B$ from the following $Ax=B$. Multiplying a square matrix times a column vector, I would expect to get a column vector as so: $4\times 4 \cdot 4\times 1=4\times 1$ vector. When I do this, the kernel just spits back what $A^{-1}$ is and what $B$ is. The following code is what I did.               a = {{1, 0, 1, 0}, {2, 1, 1, 1}, {1, 2, 1, 0}, {0, 1, 1, 1}};     inv = Inverse[a];     b = MatrixForm@{{0}, {0}, {0}, {1}};     soln = inv.b      ![enter image description here](http://i.stack.imgur.com/Aw8jS.png) What seems to be the problem or slight piece that I may be missing here for full simplification?


title: Why does Eigenvalues[matrix I defined] not work?

text: This is the code I have in my mathematica notebook. I want to find the eigenvalues of the matrix I created called Hmatrix as defined below. However when I type Eigenvalues[Hmatrix] I get the Hmatrix back with an extra set of brackets preceded by "Eigenvalues" again. Essentially, I am not getting the eigenvalues of this matrix and I wish to know what sort of syntax I have to use to find the eigenvalues of my Hmatrix.               ϵs = -13.6;     ϵso = -29.1;     ϵp = -14.1;     ssσ = -7.20;     spσ = 9.46;          θ = (π - β/2);          Hmatrix :=       MatrixForm[{{ϵs, 0, ssσ,          Cos[θ]*spσ, -Sin[θ]*spσ,      0}, {0, ϵs,      ssσ, -Cos[θ]*spσ, -Sin[θ]*spσ,      0}, {ssσ, ssσ, ϵso, 0, 0,      0}, {Cos[θ]*spσ, Cos[θ]*spσ,      0, ϵp, 0,      0}, {-Sin[θ]*spσ, -Sin[θ]*spσ, 0,      0, ϵp, 0}, {0, 0, 0, 0, 0, ϵp}}]


title: I can't get Compile to work

text: I've got some problems with my code, and I try to make it faster. Some of you suggested me to split my problem, and I'm here... I post the same function with and without Compile. This is a support function and does not involve my question               r=8.314472     fug1 = Compile[{v, p, t, a, b},     Module[{y, z, vbv, vb, f1, f2, f3, f4, f},     y = b/(4 v);     z = (p v)/(r t);     vbv = Log[(v + b)/v];     vb = v + b;     f1 = (4.*y - 3.*y^2.)/(1 - y)^2.;     f2 = (4.*y - 2.*y^2.)/(1 - y)^3.;     f3 = (2.*vbv)/(r t*b)*a;     f4 = (vbv/b - 1./vb)/(r t)*a;     f = f1 + f2 - f3 + f4 - Log[z];     Exp[f]]]      g2 doesen't work and I don't know why               g2 = Compile[{p, t, a0, a1, a2, b0, b1, b2},     Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},     a = a0*Exp[a1*t + a2*t^2];     b = b0 + b1*t + b2*t^2;     csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +          b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);     vol = NSolve[csd == 0. && v > 0., v, Reals] // Quiet;     sol = v /. vol;     vliquid = Min[sol];     vvapor = Max[sol];     fl = fug1[vliquid, p, t, a, b];     fv = fug1[vvapor, p, t, a, b];     Print[{t, p, vol, Abs[fl - fv]}];     Abs[fl - fv]],     RuntimeAttributes -> {Listable}]      This works without Compile!               g[p_?NumericQ, t_?NumericQ, a0_?NumericQ, a1_?NumericQ, a2_?NumericQ,        b0_?NumericQ, b1_?NumericQ, b2_?NumericQ] :=      Module[{a, b, csd, vol, sol, vliquid, vvapor, fl, fv},     a = a0*Exp[a1*t + a2*t^2];     b = b0 + b1*t + b2*t^2;     csd = a/(r*t*(b + v)) - (-(b^3/(64.*v^3)) + b^2/(16.*v^2.0) +          b/(4.*v) + 1.)/(1 - b/(4*v))^3 + (p*v)/(r*t);     vol = NSolve[csd == 0. && v > 0., v, Reals];     sol = v /. vol;     vliquid = Min[sol];     vvapor = Max[sol];     fl = fug1[vliquid, p, t, a, b];     fv = fug1[vvapor, p, t, a, b];     Print[{t, p, vol, Abs[fl - fv]}];     Abs[fl - fv]];       g works very well and is the same of g2!               FindRoot[g[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,      7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,      34.376}] // Timing      g2 doesen't work               FindRoot[g2[p, 100, 500., -4.4627562855*10^-3, -2.7625748*10^-6,      7.30402014*10^-2, -2.2222592*10^-4, 9.42486*10^-8], {p,      34.376}] // Timing


title: Locators in Manipulate not moving properly

text: I thought a simple Mathematica kerning machine (for adjusting the space between characters) would be interesting, but I'm having trouble with the locators. (There are a number of other questions related to this, and I've read the answers, but as yet without finding a solution, or understanding them that well.)                Manipulate[       LocatorPane[Dynamic[points],        text = "Wolfram";        fonts = FE`Evaluate[FEPrivate`GetPopupList["MenuListFonts"]];        Column[{          Button["Export", Export["/tmp/t.png", g]],          g = Graphics[{               MapIndexed[               Text[Style[#1, FontSize -> fontsize, FontFamily -> font],                  points[[First[#2]]]] &, Characters[text]]}, ImageSize -> 500]          }]],       {points, {Table[{ x, 0}, {x, 1, Length[Characters[text]]}]},          ControlType -> None},       {fontsize , Table[x, {x, 96, 256, 12}]} ,       {font, fonts}      ]      (The font menu gets populated once you use it.) ![kerning machine](http://i.stack.imgur.com/T1aNl.png) I want to be able to slide the letters right or left (but not up or down), but at the moment they don't move like they're supposed to. ## The solution Thanks to the fine answers, I've got something useful working. There are some kludges and hacks too, and some problems still to be ironed out (string length needs to be dynamic, 'canvas' needs resizing, and so on), but this is excellent for now.               With[{fonts = FE`Evaluate[FEPrivate`GetPopupList["MenuListFonts"]]},      DynamicModule[{kernedText, points},       points = Table[{x, 0}, {x, 1, Length[Characters[text]] + 10}];       Column[{         (* input *)         InputField[Dynamic[text], String],         (* main panel *)         Panel@LocatorPane[           Dynamic[            points, (points = ReplacePart[#, {{_, 2} -> 0}]) &],            Dynamic[kernedText =              Graphics[{MapIndexed[                Text[Style[#1, FontSize -> fontsize, FontFamily -> font],                   points[[First[#2]]]] &, Characters[text]]},               PlotRangePadding -> 0,               PlotRange -> {{0, 1 + Length[Characters[text]]}, Automatic},               Background -> None, ImageSize -> 800]], Appearance -> None],         (* controls *)         Row[          {           PopupMenu[Dynamic[fontsize], Table[x, {x, 72, 416, 12}]],           PopupMenu[Dynamic[font], fonts],           Button["Export",             Export[FileNameJoin[{$HomeDirectory, "Desktop",                "KernedText.png"}], kernedText],             ImageSize -> {Full, Automatic}]           }]         }, Left]]]      ![final](http://i.stack.imgur.com/5DKID.png) I realised that the locator dots didn't need to be showing - just click on the characters. The result can be compared to the unkerned version:               Text[Style[text, 192, FontFamily -> "Palatino"]]      ![unkerned](http://i.stack.imgur.com/lKUuh.png) For me, this area of Mathematica (Manipulate/Dynamic) is gradually becoming less confusing (but only gradually).


title: Error changing edge thickness in a GraphPlot

text: I'm having some problems with the _Mathematica_ graphics inspector. I want to make a graph with the following code:               GraphPlot[{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}},         DirectedEdges -> True, MultiedgeStyle -> True, SelfLoopStyle -> True]      ![Mathematica graphics](http://i.stack.imgur.com/Vcgft.png) Which results in a good looking graph. But when I use Graphics Inspector to alter the weight of the edges, it gives me an error and _Mathematica_ closes. Does anyone else have ever experienced this? Or do you have another solution for me to achieve my graph with weighted edges? I'm using _Mathematica_ version 7.


title: MapThread and parallel computing

text: This time I have a very short question. Is there a deeper reason why ParallelMapThread does not exist? Regards, Frink


title: Numerically finding a derivative jump of a function

text: How would I numerically find where a function has derivative jumps? In particular, I'm working with this function:               f[k_?IntegerQ,y_?NumberQ] :=         x /. FindRoot[Nest[y/4 Sin[\[Pi] #] &, x, k] == x, {x, 1}]      ![k=1](http://i.stack.imgur.com/PgU5R.png) ![k=2](http://i.stack.imgur.com/CULAx.png)


title: Timing display of Graphics (Front End timing)

text: I want to know how much wall-time it takes to display a `Graphics` For example this one:               ballGrid[n_] := Module[{lines},       lines = Line[Flatten[Table[{            {{i, j, 0}, {i, j, 1}},            {{i, 0, j}, {i, 1, j}},            {{0, i, j}, {1, i, j}}},           {i, 0, 1, 1/n}, {j, 0, 1, 1/n}], 2]];       Graphics3D[{Sphere[Tuples[Range[0, 1, 1/n], 3], 1/(10 n)], lines},         Boxed -> False]]      First of all note that running `ballGrid[50]` and `ballGrid[50];` takes significantly different wall time to run Just using `AbsoluteTiming` does not give accurate representation (I assume it only measures kernel time):               In[]:= AbsoluteTiming[ballGrid[50];]     In[]:= AbsoluteTiming[ballGrid[50]]     Out[]:= {0.082963,Null}     Out[]:= {0.029378,<<Graphics>>}      I answered my own question, but I'd like to see other solutions too, and know why/if the `Print` workaround can be trusted


title: How to fit 3 data sets to a model of 4 differential equations?

text: I'm a biologist and a newbie in Mathematica. I want to fit three data sets to a model consisting of four differential equations and 10 parameters. I want to find the parameters best fitting to my model. I have searched the forum and found several related examples. However, I could not find anything that matched my question. Here are the details: **I have three time-series datasets: (xdata, ydata, zdata)**               time = Quantity[{0, 3, 7, 11, 18, 25, 38, 59}, "seconds"];     tend = QuantityMagnitude[Last[time]];      **xdata:**               xdata = Quantity[{0, 0.223522, 0.0393934, 0.200991, 0.786874, 1,          0.265464, 0.106174}, "milligram"];     xfitdata = QuantityMagnitude[Transpose[{time, xdata}]];      **ydata:**               ydata = Quantity[{0, 0.143397, 0.615163, 0.628621, 0.53515, 0.519805,          0.757092, 1}, "milligram"];     yfitdata = QuantityMagnitude[Transpose[{time, ydata}]];      **wdata:**               wdata = Quantity[{0.0064948, 0.221541, 1, 0.434413, 0.732392,          0.458638, 0.1484432, 0.0294298}, "milligram"];     wfitdata = QuantityMagnitude[Transpose[{time, wdata}]];      **I used`ParametricNDSolve` to solve the 4-DE model:**               pfun = {x, y, z, w} /.         ParametricNDSolve[{x'[t] ==           k1 - k10 x[t] w[t - 25] - k2 x[t] - k3 w[t] w[t],          y'[t] == -k8 y[t] + k10 x[t] w[t - 25] + k3 w[t] x[t],          z'[t] == k4 y[t] - k5 z[t],          w'[t] == (k6 x[t])/(y[t]^n + 1) - k7 w[t], x[t /; t <= 0] == 0.01,          y[t /; t <= 0] == 0.01, z[t /; t <= 0] == 0.01,          w[t /; t <= 0] == 0.01}, {x, y, z, w}, {t, 0, tend}, {k1, k2, k3,          k4, k5, k6, k7, k8, n, k10}]      Then I used `FindFit`. But I don't know how to specify that `xdata` is supposed to be fitted to `x[t]`, `zdata` to `z[t]` and `wdata` to `w[t]` via least-squares fit. For `y[t]`, there are no time-series data, but the parameter (`k8`) for `y[t]` is supposed to be determined as well. **I have tried the following, which is apparently wrong:**               fit = FindFit[xfitdata,        pfun[{k1, k2, k3, k4, k5, k6, k7, k8, n, k10}][        t], {{k1, 0.0859}, {k2, 0.0125}, {k3, 0.8541}, {k4, 0.0185}, {k5,          0.1004}, {k6, 0.5002}, {k7, 0.0511}, {k8, 0.0334}, {n, 9}, {k10,          0.8017}}, t]      **This is the error message:**               FindFit::nrlnum: The function value {0. +<<1>>[0.],-0.223522+<<1>>,-0.0393934+<<1>>,-0.200991+<<1>>,-0.786874+<<1>>[{0.0859,0.0125,0.8541,0.0185,0.1004,0.5002,0.0511,0.0334,9.,0.8017}][18.],-1.+<<1>>[25.],-0.265464+<<1>>,-0.106174+<<1>>[59.]} is not a list of real numbers with dimensions {8} at {k1,k2,k3,k4,k5,k6,k7,k8,n,k10} = {0.0859,0.0125,0.8541,0.0185,0.1004,0.5002,0.0511,0.0334,9.,0.8017}. >>      I'm lost and I would really appreciate your help!


title: How to fit data with numerical solution of system of parametric ODE?

text: I need to find the parameters (`k1,k2,k3,k4,k1r,k2r,k3r,k4r`) that fit my data (list of `[Intensity, time]`) using the function `b(t)`, solution of the following system of parametric ODE:               {a'[t] == -k1*a[t] - k2*a[t] + k1r*g[t] + k2r*p[t],      g'[t] == -k1r*g[t] - k3*g[t] + k1*a[t] + k3r*b[t],      p'[t] == -k4*p[t] - k2r*p[t] + k4r*c[t] + k2*a[t],      b'[t] == -k3r*b[t] + k3*g[t],      c'[t] == k4*p[t] - k4r*c[t]}      Initial conditions:               a[0] == 1,     c[0] == 0,     b[0] == 0,     p[0] == 0,     g[0] == 0,      The system of ODE has no analytical solution, so I tried to use `NDSolve`, but it is of course not working because the ODEs are parametric. I guess `ParametricNDSolve` would help me, but unfortunately it is not implemented in the version of Mathematica I am using (Mathematica 8). Do you have any idea about how to address this problem, avoiding the `ParametricNDSolve` function?


title: Using FindFit to fit nonlinear ODE parameters, subject to a constraint (an inverse problem)

text: Similar to this post I am finding that constraints tend to make `FindFit` poor at finding a good fit. However, unlike the previous post, the constraints are required and the success of `FindFit` seems to be very sensitive to initial values. Below I describe my particular problem in detail. Any suggestions to make the parameter fitting more robust would be appreciated. I am trying to fit the parameters `A`, `a0`, and `n` in the following nonlinear ODE               ExpODE = a'[t] == A * Exp[0.0583 * n * Sdot * t * Sqrt[a[t]]      to a set of experimental data. The primary varyiable `a[t]` is the crack length as a function of time `t`, and `a[0]=a0`. For those familiar with linear elastic fracture mechanics, this is a crack growth equation for a linearly increasing far-field stress `S = Sdot * t`. My experimental data consists of time to failure `tf` for various stress rates, `Sdot`. As an example, here is some fake experimental data               FakeData = {{100, 2.67886}, {200, 1.80317}, {300, 1.51754}, {400, 1.10085}, {500, 0.984215}, {600, 0.9044}, {700, 0.724567}, {800, 0.784177}, {900, 0.654773}, {1000, 0.627198}}      which looks like this when plotted ![FakeData](http://s11.postimg.org/khketh4r7/LEFM_calcs_page_1.jpg) The link between my ODE and my experimental data is an equation for the crack length at failure:               a[tf] == 294.295 / (Sdot^2 * tf^2)      Given values for `a0`, `A`, and `n`, I can solve `ExpODE` using `NDSolve` for `a[t]`, and solve for the time when the crack length equals the failure crack length. Here is my function for doing just that:               ExpModelFun[a0j_?NumberQ, Aj_?NumberQ, nj_?NumberQ][Sdotk_?NumberQ] :=     (Sol = NDSolve[{ExpODE /. {A -> Aj, n -> nj, Sdot -> Sdotk}, a[0] == a0j, WhenEvent[a[t] > 0.140, "StopIntegration"]}, a[t], {t, 0, 60}][[1]];     tf = t /. FindRoot[(a[t] == 294.295 / (Sdot^2 * t^2)) /. Join[Sol, {Sdot -> Sdotk}], {t, 0.01}];     ExpModelFun[a0j, Aj, nj][Sdotk] = tf)      (The `WhenEvent` clause is there to avoid having the crack run away on me. Once the crack length goes past 0.140 the ODE gets very stiff.) Of course, I do not know `a0`, `A`, and `n` a-priori, so I am using `FindFit` to iteratively solve for them. The following code               FindFit[FakeData, {ExpModelFun[a0, A, n][Sdot]}, {{A, 0.001}, {a0, 1*10^-9}, {n, 0.5}}, Sdot, StepMonitor :> Print[{A, a0, n}]]      results in               NDSolve::nrnum1: "The function value -0.140165-1.98689*10^-15 i is not a real number when the arguments are {1.010824975706311`*^-6,-0.000164548-1.9868921541309406`*^-15 i}"      a whole host of other errors, and a final fit of               {a0 -> -0.00013947, A -> -0.00290892, n -> 18.9563}      These parameters are not physical. I can fix this by adding the constraints `a0 > 0` (initial crack length is positive) and `A > 0` (cracks cannot shrink), but `FindFit` seems to get stuck, even if I set the `AccuracyGoal` to 1. The values it gets stuck at are               {a0 -> 4.58074*10^-9, A-> 0.000743962, n -> 1.37966}      The starting guesses `{a0, 1*10^-9}, {A, 0.001}, {n, 0.5}` are the parameters I used to create `FakeData`, before adding a little bit of noise, so they should be pretty good. I went ahead and changed `0.001` to `0.0005` anyways and found that               FitSol = FindFit[FakeData, {ExpModelFun[a0, A, n][Sdot], {a0 > 0, A > 0}}, {{a0, 1*10^-9}, {A, 0.0005}, {n, 0.5}}, Sdot, StepMonitor :> Print[{a0, A, n}], AccuracyGoal -> 3]      produces               {a0 -> 1.65801*10^-10, A -> 0.000756955, n -> 1.33919}      which looks like ![fit](http://s15.postimg.org/ozqhdosu3/LEFM_calcs2_page_1.jpg) This is a decent fit. What's frustrating is these values are quite close to the values `FindFit` got stuck at previously. I am guessing that `FindFit` is getting stuck in a local minimum. In my real application, I doubt I will have very good initial guesses. Am I just doomed to tweak initial values endlessly until I get right next to good fit?


title: How can I get the limit of a certain infinite product?

text: A first look at it suggests the fact the limit is precisely $1$. To check that I tried _Mathematica_ , but no output so far. Most probably it converges very slowly. Is there any way to get the limit?               Limit[1/n^n Product[(n Sqrt[n] + (n + 1) Sqrt[k])/(Sqrt[n] + Sqrt[k]), {k, 1, n}],        n -> Infinity]


title: Assigning values to a list of variable names

text: As part of a calculation I need to do something like this               Evaluate[{aaa, bbb, ccc}[[ index]]] = {1, 2, 3, 4, 5}      so if index is `1` then `{1, 2, 3, 4, 5}` will be stored into the variable `aaa`.   But if I re-evaluate this it does not work because `aaa` is now a list and not a variable. I tried various options with `Hold[]` etc but did not manage to solve this.


title: Better way to select all array indexes matching predicate?

text: I'd like to select (offset) indexes of a number of array points, that match a selection criteria. I can do this by creating a Table of all the coordinates, and then selecting all the values:               data = Array[ RandomInteger[1] &, {4, 4}]     {wx, wy} = data // Dimensions ;     t = Flatten[       Table[ {x - wx/2, y - wy/2, data[[x]][[y]]}, {x, 1, wx}, {y, 1,         wy}], 1]     Select[ t, #[[3]] == 1 &]      This resulted in the respective values:               {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 0, 0, 1}}     {{-1, -1, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 2, 1}, {0, -1, 1}, {0, 0,       0}, {0, 1, 0}, {0, 2, 1}, {1, -1, 1}, {1, 0, 0}, {1, 1, 1}, {1, 2,       0}, {2, -1, 1}, {2, 0, 0}, {2, 1, 0}, {2, 2, 1}}     {{-1, -1, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 2, 1}, {0, -1, 1}, {0, 2,       1}, {1, -1, 1}, {1, 1, 1}, {2, -1, 1}, {2, 2, 1}}      However, my real data is big (800x800) and sparse. This method creates a big data set and then throws most of it away. What is a more efficient way to do this?


title: Factoring a two variable polynomial in a special way

text: Let $$f=x^9-x^6+4x^5y+2x^3y^2-y^4$$ I would like to factorize $f$ into form: $$(y-F_1(x))\cdots(y-F_k(x))$$ over complex numbers. How can I do it with _Mathematica_?


title: How can I solve my system of differential equations?

text: I have a question pertaining to my code below: I require to find the values of the roots `E2` that will set the function `f1[E2] - f2[E2]` to zero. I know how to obtain the roots one at a time: for instance a root of `E2` lying between, say 0 and 2. But I would like to know whether it is possible to get _Mathematica_ to generate all the roots that lie within a certain interval at once, say those lying between 0 and 10. I have tried using `NSolve` and `Reduce`, but I got nothing, so any help will be most appreciated!               xmin = -6.5;      xmax = 6.5;      xmatch = 1.5;      eq1[x_, x0_, E2_] := {Derivative[2][y][x] + (E2 - x^2) y[x] == 0,                            y[x0] == 0, Derivative[1][y][x0] == 1/10^6};           y1[x_, E2_] := y[x] /. NDSolve[eq1[x, xmin, E2], y, {x, xmin, xmatch}][[1]];      f1[E2_] := Abs[D[y1[x, E2], x]/y1[x, E2] /. x -> xmatch];      y2[x_, E2_] := y[x] /. NDSolve[eq1[x, xmax, E2], y, {x, xmax, xmatch}][[1]];      f2[E2_] := Abs[D[y2[x, E2], x]/y2[x, E2] /. x -> xmatch]     f[(E2_)?NumericQ] := f1[E2] - f2[E2];      (* The following trial doesn't success *)     NSolve[f[(E2_)?NumericQ] == 0 && 0 < E2 < 10, E2]     rts = Reduce[f == 0 && 2.5 < E2 < 10., E2]     c2 = N[E2 /. {ToRules[rts]}]     Print["The value of E2   was=", c2]      * * * this is the code that i have written to numerically try to solve the DEs to obtain the roots E2. i am able to obtain the roots by plotting "exp" versus E2. however, when i try to use the erzek root finder, an error message is generated               xmin = (-8.5);          xmax = 8.5;          xmatch = 0.50;          eq[x_, x0_, E2_] := {y''[x] + (2 E2 - x^2) y[x] == 0, y[x0] == 0,         y'[x0] == 1/10^6};          exp := (# - #2) & @@ ((y'[xmatch]/y[xmatch] /.              NDSolve[eq[x, #, E2], y, {x, #, xmatch}][[1]]) & /@ {xmin,            xmax});          Plot[exp, {E2, 0, 10}]          Needs["Ersek`RootSearch`"];          rst = RootSearch[exp == 0, {E2, 0, 5}](* gives an error message  *)


title: How can I prevent Superscript from being interpreted as Power?

text: I have very strong desire to use superscript as the index of the variable. However, it looks like that the Mathematica automatically recognize the superscript as the power and I got message that my variable with superscript is 'protected'. Could you help me to make the superscript used as the index of the variable instead of power?


title: Get brief help for a set of functions

text: When we are in console mode or working with a notebook we can get brief help about a function just by shift-entering `?function` I would like to have a list like the following               {Map, Function, List, Transpose, Outer, Sequence, Apply, Tuples, \     Distribute, Thread, Equal, Fold, Slot, Reverse, Plus, Times, Total, \     MapThread, Inner, ReplaceAll, Rule, Composition, Through, Nest, \     ToExpression, ToString, Row, Part, Range, ComposeList, Compose, \     SlotSequence, Flatten, FoldList, NestList, Hold, Release}      and get a list of strings containing the corresponding help(s). `?` cannot be mapped to a list of course so i am trying to find another way. `?` works with Wildcards like `?*Plot*` so i suppose it accepts some kind of pattern matching. Any ideas ?


title: How to plot a function with variable with an open interval?

text: I want to plot this revenue function: $r=30q-0.3q^2$ I have no range, its an open interval, but when I try to plot in _Mathematica_ it requires the min and max of the plotting limits. How do I do this? *Edit: Thank you for helping, my professor gave us the revenue function mentioned up, and asked us to plot " revenue versus quantity (q) ", he did not specify any range, or max and min. My question is can i plot this without a max and min?


title: Maximum but still limited magnitude region is not plotted with ContourPlot

text: ![enter image description here](http://i.stack.imgur.com/5ZtSi.png) The function is well defined in the whole region. But it just skips plotting the center region. I've tried PlotPoints, Mesh, Contours - it didn't help. ![enter image description here](http://i.stack.imgur.com/kTbCN.png) After making more contours. White hole is still there. ![enter image description here](http://i.stack.imgur.com/8GBrC.png) After zooming in the region suddenly reveals data. How can I make it to plot central part in detail when zoomed out? Thank you in advance. UPD: Yes, thanks, that's PlotRange :)


title: How do I remove an entry from the Format > Stylesheet menu?

text: I was playing a bit with the stylesheets to make my own. In the process I have created and installed a few stylesheets but now I would like to remove some of them. First, how do I remove an entry from the Format > Stylesheet menu? Second, where are the stylesheet files kept? I have deleted the files from the `$UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets`, reloaded _Mathematica_ , even rebooted the computer, but my styles are still working! Apparently _Mathematica_ keeps a copy of my files somewhere I don't know about.


title: Implementing OCR without using TextRecognize

text: I am new to _Mathematica_ and trying to figure out whether it is a good tool for algorithmic exploration. So I had the idea of implementing a simple OCR with _Mathematica_ , just using standard algorithms. I have this picture: ![Block of text](http://i.stack.imgur.com/Ta5wf.png) I'd like to apply the following steps:   1. Finding the cells of the picture: Could one use a voronoi algorithm to recognize the grid in the picture? After having the cells I'd like to apply these steps to each:   1. Use `Thinning` to find the skeleton of the character.   2. Use `EditDistance` to compare the character to a skeletized version of every possible character and then select the character which is closest. I have seen in the documentation that _Mathematica_ has all these algorithms I am just not sure whether it would actually be feasible to do what I want. (If it's impossible to do without knowing the name of the font I used: It's "Osaka, Regular-Mono, 144 pt".)


title: Tokenize Mathematica input in a simple way

text: ## Background Usually, I give detailed descriptions when I have a question which sometimes lead to that users don't write their answers because they maybe think their answer is too simple. Therefore, I chose to just throw the direct question in the room and collect the ideas of all answers. Although it seems, that we cannot get a simple tokenizer by using functions like `TreeForm`, `MakeBoxes`, `MakeExpression`, ... I want to give some background information now: What really bothers me is, that we have here on Mathematica.SE a highlighter for Mathematica code which is far away from perfect, but which does a reasonable job. If I want to include a snippet of code into a LaTeX document on the other hand, I'm totally stuck with a b/w-pdf export from Mathematica or with the Mathematica **5.2** support of the listings package. Therefore, I hacked a simple parser of the html-output of our google-prettify plugin. This seems to work reasonable and with a little bit adjustment, one could include _styled_ Mathematica-code into a LaTeX document. It should be noted, that I don't intent to export formulas or sophisticated styled code. I want to stick with good old ascii-style code which is used in most packages. Before I used the html-output I was again having a long look at Leonids formatter but at its current state it lacks of the same issues since it relies on `MakeBoxes` as well and there are other issues. Leonid pointed out, that he want to reimplement this completely. On the other hand, we have functions like `SyntaxLength`, `SyntaxQ`, `MakeExpression`, `MakeBoxes` (and their `To` counterparts), all kind of `Forms`, we can keep expressions unevaluated and so on. Therefore, I was asking myself whether we can do the tokenizing much easier with Mathematica that it is possible with the JavaScript from google-prettify. ## Question Is it possible to implement a reliable tokenizer which takes a valid input- string of Mathematica code and returns a list of tokens without implementing the rules of the Mathematica-language itself? Although tokens usually don't contain whitespace characters, for the purpose of testing it would be nice, if **all characters stay even in the tokenized version**. Especially I want               input == StringJoin@@Tokenize[input]      to return `True`. Take for instance this function               Tokenize[str_String /; SyntaxQ[str]] :=        With[{expr = MakeExpression[str, StandardForm]},        Most[Drop[Flatten[MakeBoxes[expr] /. {             RowBox -> List, SuperscriptBox[a_, b_] :> {a, "^", b},              "\[Rule]" :> "->"}], 2]]     ];          Tokenize[     "Plot3D[{x^2+y^2,-x^2-y^2},{x,-2,2},{y,-2,2},RegionFunction->Function[{x,y,z},x^2+y^2<=4]]"     ]     (*      {"Plot3D", "[", "{", "x", "^", "2", "+", "y", "^", "2", ",",       "-", "x", "^", "2", "-", "y", "^", "2", "}", ",", "{", "x",       ",", "-", "2", ",", "2", "}", ",", "{", "y", ",", "-", "2",       ",", "2", "}", ",", "RegionFunction", "->",       "Function", "[", "{", "x", ",", "y", ",", "z", "}", ",", "x",       "^", "2", "+", "y", "^", "2", "<=", "4", "]", "]"}     *)      Although the output looks good here, inside Mathematica we have `\[LessEqual]` instead of `<=` (due to the `StandardForm` I assume). Furthermore, all different kind boxes need to be handled and I'm afraid many more things. Is there any chance to get this working really correctly? **Test examples:** In some of these cases I'm not sure whether my given output is the correct one. E.g. the handling of linebreaks may be system-dependent, `a_` seems to stay together in the box-representation (which would be ok), ...               "a\nb" (* {"a","\n","b"} *)     "a_:>a/2<=3" (* {"a_",":>","a","/","2","<=","3"} *)     "1`3+1.00`3" (* I'm not sure how this should be tokenized but my intention should be clear *)


title: How to perturb a Dynamic System?

text: I'm trying to model a basic feedback system with delayed feedback. I've done the initial setup and now want to add a few more advanced features to my system. Currently, it's just a simple delayed-differential equation with manipulatable delay to show how increasing the delay can send the system out of equilibrium. What I'd like to add, however, is the ability for the system to be perturbed at a particular point in time. For example, in the Predator-Prey model this might mean that the system acts exactly as normal at all times against the given initial condition, but suddenly at t = T, where T is the perturbation point, either the number of predators or prey is shocked. I want to model how this affects equilibrium for various parameters. Any good places to start? Thanks again! Edit: What I have initially is -               Manipulate[      HumanFaucetSystem =        NDSolve[{y'[time] + a*y[time - delay] == 0,          y[time /; time <= 0] == deviation}, y, {time, 0, 200*delay + 1}];      Plot[Evaluate[y[x] /. HumanFaucetSystem], {x, 0, 100*delay + 1},        PlotRange -> All], {{delay, 0, "Delay"}, 0,        15}, {{a, 1, "Multiplier"}, -5,        5}, {{deviation, 25, "Initial Deviation"}, 0, 100}]      I want to add another interactive parameter to the system that allows the user to schedule a specific time point at which a certain perturbation will occur. This can be positive or negative in the value of y. On this logic, I want to expand it to a two-agent delayed system that I've modeled already but add this feature.


title: Kramers-Kronig in Mathematica

text: I am trying to calculate the change of the refractive index from the change of the absorption coefficient using the Kramers-Kronig relations, in Mathematica.               c = 300000000;          daF[l_] = 500 * 0.28 Exp[-((l - 500)/90)^2];          dnFpoints = Table[         {             ln,             c/Pi NIntegrate[                 daF[li] / ((2 Pi c 10^9 /li)^2 - (2 Pi c 10^9 / ln)^2),                 {li, 800, 200},                 Method -> {"PrincipalValue"},                 Exclusions -> ((2 Pi c 10^9 /li)^2 - (2 Pi c 10^9 / ln)^2) == 0             ]         },         {ln, 300, 600}     ];      Unfortunately, Mathematica displays an error that it does not converge to prescribed accuracy and the output is junk (I would expect a smooth curve with a negative minimum first and then a positive maximum). I am using version 8, if it matters. Any ideas?


title: Solving a system of 4 logarithmic equations?

text: I would like to solve this system of 4 logarithmic equations in Mathematica.   * **a*log(b+d)=20**   * **a*log(b*30^c+d)=125**   * **a*log(b*180^c+d)=710**   * **a*log(b*360^c+d)=1350** I am looking for the values of **a** , **b** , **c** , and **d**. Thanks in advance!


title: Trying to solve a differential equation with a piecewise initial condition

text: I am trying to solve $$u_t=\frac{1}{4}u_{xx}$$ $-\infty<x<\infty,\: t>0$ With the initial condition $u(x,0)=\phi(x)$ where $$ \phi(x)= \left\\{ \begin{array}{lr} 1 & |x|<1\\\ 0 & |x|\geq 1 \end{array} \right.$$ So I initially typed in my piecewise function like this               ϕ[x_] := Piecewise[{{1, Abs[x]<1}, {0, Abs[x] >= 1}}]      But I have also tried this, (are they both valid, or is just one, or is neither?)               ϕ[x_] := Piecewise[{{1, -1 < x < 1}, {0, x >= 1 || x <= -1}}]      Then, following the mathematica examples I tried to solve the differential equation:               pde = D[u[x, t], t] - 1/4 D[u[x, t], {x, 2}] == 0     soln = DSolve[{pde, u[x, 0] == ϕ[x]}, u[x, t], {x, t}]      Which outputs a bunch of weird stuff, not the solution (I think) I was expecting. If my math is correct I think the solution to this would involve the error function. Any tips to where I might be going wrong would be aprreciated!


title: Answer when integrating by partial fractions

text: Evaluating $$\int \frac{x^2-x+5}{(x-2) (x-1) (x+3)} \, dx$$ Version 9.0.1 gives the following answer $$\frac{1}{4} (-5) \log (1-x)+\frac{7}{5} \log (2-x)+\frac{17}{20} \log (x+3)$$ It seems to me that the correct answer should be $$ \frac{1}{4} (-5) \log \color{Red}{|x-1|}+\frac{7}{5} \log \color{Red}{|x-2|}+\frac{17}{20} \log \color{Red}{|x+3|} + C $$ Am I missing something? Is there a fix? Edit:               Integrate[(x^2 - x + 5)/((x - 2)*(x - 1)*(x + 3)), x]


title: Number precision in a list

text: I have list with elements:               l = {1.000000000*10^-2076, 2.052685846*10^-1865, 7.337942425*10^-1741,      6.994455902*10^-1652, 2.007623567*10^-1582, 2.482890841*10^-1525,      8.737178026*10^-1477, 1.673592426*10^-1434, 5.183426213*10^-1397,      2.634095605*10^-1363}      I want to make a list l2, where each element i is equal to 1 - l[[i]]. So I made:               For[i = 1, i <= Length[l], i++, a = l[[i]]; b = 1 - a;        l2 = AppendTo[l2, b]];      But as a result I have :               l2 = {1.000000000, 1.000000000, 1.000000000, 1.000000000, 1.000000000,      1.000000000, 1.000000000, 1.000000000, 1.000000000, 1.000000000}      What is wrong, because if I will take the first element from l               a = 1.000000000*10^-2076      b = 1 - a = 0.99999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     999999999999999999999999999999999999999999999979473141540      what is ok. How can I convert l to l2, to have the good precision?


title: How to get the series expansion of $e^{x^a}$ at $x=0$?

text: I want to have a series expansion of $e^{x^a}$ or $e^{c_1x^a+c_2x^b}$ at $x=0$, but `Series` cannot give any useful result even if the assumption $a>0$ is specified.               Series[Exp[x^a], {x, 0, 2}]     Series[Exp[x^a], {x, 0, 2}, Assumptions -> {x > 0, a > 0}]     (* -> E^x^a *)      However, if $a$ is a number, we can get a result.               Series[Exp[x^(2/3)], {x, 0, 2}]     (* -> 1+x^(2/3)+x^(4/3)/2+x^2/6+O[x]^(8/3) *)


title: How to find the index of a square matrix in Mathematica quickly?

text: Let $A$ be an $n\times n$ complex matrix. The smallest nonnegative integer $k$ such that $\mathrm{rank}(A^{k+1})=\mathrm{rank}(A^{k})$, is the _index_ fo $A$ and denoted by $\mathrm{Ind}(A)$. I would like to compute $\mathrm{Ind}(A)$ quickly in Mathematica (I am using V8). Let us as a very simple example consider $$A=\left(\begin{array}{rrrrrr} 1 & -1 & 0 & 0 & 0 & 0 \\\ -1 & 1 & 0 & 0 & 0 & 0 \\\ -1 & -1 & 1 & -1 & 0 & 0 \\\ -1 & -1 & -1 & 1 & 0 & 0 \\\ -1 & -1 & -1 & 0 & 2 & -1 \\\ -1 & -1 & 0 & -1 & -1 & 2 \end{array}\right) $$ then it is clear that $\mathrm{Ind}(A)=2$. For computing this in _Mathematica_ , I used               Solve[MatrixRank[MatrixPower[A, k + 1]] == MatrixRank[MatrixPower[A, k]] && k > 0,         k, Integers]      But unfortunately, I cannot get the result. I will be grateful if anyone could design a way to compute $\mathrm{Ind}(A)$ for random matrices of the size $n\times n=200\times 200$ in _Mathematica_.


title: Proving a recurrence in Mathematica

text: I have $$j_n=\int_0^1 x^{2n} \sin(\pi x)dx.$$ How do I show that $$j_{n+1}= \frac{1}{\pi^2}(\pi- (2n+1)(2n+2)j_n)\, ?$$ I keep getting a recurring integration by parts and I can't simplify it. Please tell me where I'm going wrong.


title: What kind of object results from RegionIntersection function?

text: I'm trying to use RegionIntersection in a couple of Polygons. The polygons are the following:               p1=Polygon[{{-102.251, 21.8628}, {-102.252, 21.8628}, {-102.252, 21.8631}, {-102.251, 21.8631}, {-102.251, 21.8628}}]      and               p2=Polygon[{{-102.253, 21.8671}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8681}, {-102.252, 21.868}, {-102.252, 21.8678}, {-102.252, 21.8673}, {-102.253, 21.8672}, {-102.253, 21.8671}}]      When I run `r = RegionIntersection[p1, p2]` I was expecting that the resulting object was a "Region", however it is something like `RegionIntersection[Polygon{{...}},Polygon{{...}}]`. When I try to compute the Area of the resulting region it gives me:               Area::reg: "RegionIntersection[Polygon[{{-102.253,21.8671},{-102.253,21.8682},{-102.253,21.8682},{-102.253,21.8682},<<3>>,{-102.252,21.8673},{-102.253,21.8672},{-102.253,21.8671}}],<<1>>] is not a correctly specified region.      And if I test for a region with `RegionQ[r]` I obtain `true Also if I try to plot the region discretizing with `DiscretizeRegion[r]` I obtain:               DiscretizeRegion[RegionIntersection[Polygon[{{-102.251, 21.8628}, {-102.252, 21.8628}, {-102.252, 21.8631}, {-102.251, 21.8631}, {-102.251, 21.8628}}],Polygon[{{-102.253, 21.8671}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8681}, {-102.252, 21.868}, {-102.252, 21.8678}, {-102.252, 21.8673}, {-102.253, 21.8672}, {-102.253, 21.8671}}]]]      So it seems that the resulting object from the Intersection is a region but it is not possible to compute anything on it. Following the examples on the Documentation I notice that using circles it behaves correctly and it is possible to compute on the intersection, however if the intersection is nothing (i.e. the two regions don't intersect) the object is still a region. I was wondering if there is a way of knowing that I have a null region. Of curse my first guess was computing the Area on it but for my polygons it is apparently impossible. Any thoughts on why regions behave like that? and on how to know if the Intersection region is a null region?


title: Loop integrals (quantum field theory)

text: I am attempting to compute the one loop contribution to the Higgs mass, and the one loop integral is somewhat difficult. I decided to try and get Mathematica to do it, to see if the answer can point me in the right direction. I inputted,               Integrate [(k^(d - 1)*(k^2 + p*k + m^2))/(((k - (x - 1) p)^2 +        p^2 (x - x^2 - 1))^2), {k, 0, Infinity}]      where the integration variable is $k$, and the rest are constants. Mathematica outputted, ![enter image description here](http://i.stack.imgur.com/Mfrqc.png) i.e. it simply wrote out the integral, and did not even attempt to compute it. Can someone tell me why it behaved like this; it's happened with other integrals in the past? How can I make it perform the integral (if it can)? It didn't even output an error message. PS: Please feel free to edit/improve the tags, the closest I found to integration was 'numerical integration.'


title: Deep Pattern matching with repeating arguments

text: I have a function that accepts a single argument that is described by the following grammar:               term := (Less | Greater | Equal | LessEqual | GreaterEqual)[Symbol,Number]      argument := term | Or[term,term,...]      The expressions are generated from operations like:               Reduce[x^2 -x -6x == 0, x, Reals] // FullForm     (* Or[Equal[x,-2],Equal[x,3]] *)      I want to use a pattern in the function definition to ensure that the argument is of the correct form and I want to convert the argument into the following form for use within the function:               List[term,...]      I am currently bogged down in pattern purgatory. I have tried all of the following and am confused by the results.               (* Test data *)     s = Or[Equal[x,-2],GreaterEqual[x,3]]      This pattern matched the test case. So far so good.               (* case 1 *)     s /. Or[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {2}     (* {2} V {2} *)      Let's see if we can capture the head in a variable. Yes, we can. I've got this figured out.               (* case 2 *)     s /. f_Symbol[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {Or} *)      Let's limit the pattern to a specific head instead of any symbol. This didn't match. I'm not clear on why.               (* case 3 *)     s /. f_Or[(Less | Greater | Equal | LessEqual | GreaterEqual)          [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* No Match *)      Maybe a different syntax will work. And it does, but I expected `{Or}` as a result.               (* case 4 *)     s /. f : (Or)[(Less | Greater | Equal | LessEqual | GreaterEqual)          [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {x == -2} V {x >= 3} *)      **Edit** : Some appropriately placed parens make a difference. I understand this result, but I still don't understand the previous one.               (* case 5)     s /. (f : Or)[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {Or} *)      **End Edit** I am missing something important about how patterns/rules work. I would like to correct that gap in knowledge. And, secondarily, I'd like to get my function to only accept an appropriate argument and be able to convert the argument into the desired format.


title: solving for one solution to a system of polynomials

text: I'm trying to solve a system of equations:               Solve[ A1 D1 + E1 H1 == 0 && A2 D1 + A1 D2 + E2 H1 + E1 H2 == 0 &&            C1 F1 - E1 G1 == 0 && C2 F2 - E2 G2 == 0 && A1 - B1 + C1 == 0 &&             A2 - B2 + C2 == 0 &&  A3 - B3 + C3 == 0,                  {A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,E1,E2,F1,F2,G1,G2,H1,H2}]       Since we have more variables than equations, we have more than 1 solution satisfying the above equations but I don't want Mathematica to give me all possible solutions -- I would like just only one. **1\. How do I get Mathematica to give me just one possible solution?** One way I thought about doing this is to plug in random numbers such as `A2 = 1/2, B2 = 1, C2 = 1/2`, etc. so that all other variables are determined. But this isn't a very effective strategy in case the numbers I plug in do not satisfy all of the above equations. (One reason why I don't want all possible solutions to a system of equations is because suppose I am working with 30 equations and 80 variables. Then this is crashing Mathematica.)


title: Is Mathematica compatible with primusrun?

text: I use _Mathematica_ 9 on Ubuntu 12.04 LTS x86 (64-bit). My computer has an Nvidia graphics card, for which I installed `primus` and `bumblebee`. If anyone is in a similar situation, I would like to know if they have solutions to the following two related problems:   1. _Mathematica_ does not need OpenGL when it's not rendering any 3D graphics. For this reason I find it convenient to run the program without `optirun mathematica` or `primusrun mathematica` most of the time. However, I noticed that if I do make a `Plot3D` or related command, _Mathematica_ will crash. Is it possible to set the program up in a way so that it doesn't crash, but rather shows an error message, or just doesn't show output, if no 3D rendering is possible?   2. `primusrun` extends `optirun` functionality by saving power when the graphics card is not in use. I suppose that for this reason, if I'm not actively rotating a 3D graphic, it goes blank in a session of `primusrun mathematica` rather than `optirun mathematica`. When using the less efficient `optirun`, all functionality is available and runs as expected. Did anyone figure out a workaround for this? I'm asking on this site rather than AskUbuntu because the solution, if it exists, probably lies in changing _Mathematica_ preferences rather than `primus`'.


title: Stop Mathematica from giving imaginary solutions

text: I have the following equation: $$D=\frac{1}{64} \pi A ^3 B \sin \left(C\right)-\frac{1}{2} \pi A B \sin \left(C\right)$$ which I want to solve for $A$. The equation is cubic in $A$ so this should give me 3 answers and, potentially, imaginary parts to the answers. I know, from the physical meaning of the parameters, that all parameters ($A$,$B$,$C$ and $D$) are positive and real. My question is: how can I use `Solve` on this equation and make sure that there will be no imaginary parts popping up in the solution? I have used the suggestion by Chris and tried:               Solve[d == 1/64 π a^3 b Sin[c] - 1/2 π a b Sin[c], a, Reals]      but I still see that there is a $\imath\sqrt{3}$ term in the answer. Why does this still appear?


title: Why this code is considerably slower in version 9?

text: I have a `Mathematica` code for computing and plotting the density which corresponds to a given potential. The following code was written few years ago using version 5.2 of the `Mathematica`. Recently, I tried this code in the latest version 9 and I observed something very disturbing. Using version 5.2 it needs about 5.5 sec in order to produce the contours. On the other hand, in version 9 I have to wait about a minute (ten times longer than in 5.2!) using of course the same PC. Why this is happening? Do I have to make any modification to make it more compatible with version 9? Here is the code:               Clear["Global`*"];     Off[General::spell];          Vn = -(Mn/Sqrt[r^2 + z^2 + cn^2]);     Vd = -(Md/Sqrt[b^2 + r^2 + (a + Sqrt[h^2 + z^2])^2]);     Vh = v0^2/2*Log[r^2 + β*z^2 + ch^2];     Vt = Vn + Vd + Vh;     Vr = D[Vt, r];     Vrr = D[Vt, {r, 2}];     Vzz = D[Vt, {z, 2}];     ρ = 2.325/(4*π*100)*(Vrr + Vr/r + Vzz);     ρr = ρ /. {z -> 0};          Mn = 400; cn = 0.25;     Md = 5000; b = 6; a = 3; h = 0.2;     v0 = 20; β = 1.3; ch = 8.5;     ρ0 = ρr /. {r -> 8.5};          Print["-----------------"]     Print["ρ0 = ", ρ0]     Print["-----------------"]          S0 = ContourPlot[ρ, {r, -20, 20}, {z, -20, 20}, Contours -> 10,      PlotPoints -> 200, ImageSize -> 550]


title: Confirming the existence of a function related to a matrix

text: Is it possible to get an answer to the following question in _Mathematica_? Let $M$ be a $n$ by $n$ matrix, is there a function $m:\mathbb{N}\times \mathbb{N}\rightarrow \mathbb{Z}$ such that $m_{ij}=m_{ji}$ and $m_{ij}=m_{i+2,j+2}$ for all $i$ and $j$. I am new to _Mathematica_ and interested whether such existential, abstract expressions can be solved in _Mathematica_.


title: Get the last line from each of a large number of files, transform them, and write all results to a single new file

text: I have _several hundreds_ of .csv files that are _not logically named_ (contains numbers, characters, and special characters), all _stored in a directory_. Each file has large but _unequal number of rows and columns_. I do not need any information other than the last line of each file. What would be an efficient way to use _Mathematica_ to get the last line from each file, and summarize them to a new .csv file with the file name as the tag ? @WReach suggested this, but I am not sure how to proceed, especially given the irregular titles.


title: Showing a rectangular plot on an almost-closed sphere

text: I am currently teaching some students about the "point at infinity", and how it allows us to treat circles and lines as "the same", etc. I would like to kind of _show_ this happening with a series of three images:   1. The usual, $x$-$y$ plane plot of some function (say $y=x^3$)   2. That plot, on the surface of an **incomplete** sphere: that is, a sphere with a disk removed (the gluing isn't finished yet).   3. The plot on a complete sphere (bonus points if the ends of the cubic join together!) Now, I have been playing with `Texture` for the last 90min or so, and while I think I can eventually get it to do what I want for step 3., I don't see how to get it to work for step 2. The problem is, when I do an incomplete sphere (I have been using a RegionFunction), the Texture is distorted by this. In fact, the distortion is quite nasty (I am always completely confused by TextureCoordinates). Is there a way to do this in a nice way? I am open to any suggestions! **EDIT** : here is a picture of what I mean by "incomplete sphere": ![enter image description here](http://i.stack.imgur.com/2LD9A.jpg) **2nd EDIT** : here is a picture of what I had in mind (for step 3 anyway): ![enter image description here](http://i.stack.imgur.com/Jr6PU.jpg) Code:               SphericalPlot3D[1, {theta, 0, Pi}, {phi, 0, 2 Pi},  PlotStyle -> Texture[p],              TextureCoordinateFunction -> ({#5, 1 - #4} &), Lighting -> "Neutral",             Mesh -> None, Axes -> False, Boxed -> False]      **3rd EDIT** : Sorry for the confusion, and multiple edits! When I say "that plot" on the surface of a sphere, I mean the graph, the axes, the tick marks, everything.


title: How to Plot Prism in Graphics3D

text: I want to create an image of a rectangular prism, but there is no built-in primitive for it. One method to display a prism is shown in whubers's answer to Mathematica for teaching orthographic projection. What are some alternative ways to display prisms using `Graphics3D`, either with polygons or as wireframe-type models? Assume that the prism cross section is defined by a list of points in the plane.


title: Guides for programming CDFs

text: Are there any tutorials for programming high-quality CDFs, like the interactive calculus textbook presented at wolfram.com? _Mathematica_ 's Help is extremely impressive but it really does not help much when it comes to low-level programming of the nicely typesetted documents. For example, after quite a long time I still sometimes stumble upon the output like > Consider the equation `Cell[BoxData[FormBox[(…), TraditionalForm]]]`. The > right side is… The question might seem unsuitable but I don't think it would be productive to ask questions about the various properties of `Cell`, `TextCell`, `TextData`, etc. instead, because the problem is clearly not that local. Creating practical and good-looking interactive documents involves the use of pretty special techniques, like defining different paragraph styles, setting in- document links, making layout independent of screen resolution and magnification, and so on—maybe even manual kerning presets. Some tasks (like printing inline equations, as in the example above) are so common that there must be a solid number of convenient solutions. I'm still not aware of any tutorial aimed at discussing these particular issues. And I am probably not the only one who is interested.


title: What's the wrong when I use NestWhileList?

text: _**Problem :_**   * A Happy number is a number that if one squares its digits and add them together, and then take the result and square its digits and add them together again and keep doing this process, one comes down to the number 1. Find all the Happy ages, i.e., happy numbers up to 100.* _**This is the problem the book gived,and the solution of author:_** Input:               f[1] = 1;     f[4] = 4;     f[n_] := f[Plus @@ ( IntegerDigits[n]^2)]     Select[Range[100], f[#] == 1 &]      Output:               {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100}      _**But I want to use a different method from the author_** _**My solution:_** Input:               Select[Range[100], NestWhile[Plus @@ (IntegerDigits[#]^2 &), # &, # != 1 &]]      Output: {} _**However,I cannot know where the wrong is?Can Someone help me ?Thanks!_**


title: Plot Ellipse based on EigenSystem

text: Please consider the following :               covMatrice = {{34.925, -10.21}, {-10.21, 22.462}};          COG = Mean@(Nfixations["d"][[1]])[[All, 1]];          fixations = {{19.4688, 17.4281}, {18.0563, 21.7156}, {13.0219, 24.7219},               {22.9594,25.5219}, {28.5406, 24.6719}, {27.0688, 17.1656},               {27.6781,16.325}, {28.9281, 10.7719}, {16.025, 13.6625},               {19.1313, 17.1094}};               With[{           eigVec = Eigenvectors[covMatrice],           eigVal = Eigenvalues[covMatrice]},           Graphics[{                     White, Rectangle @@ frmXY,                      Black, Disk[#, .5] & /@ fixations,                      Red, Line[(# + COG) & /@                                {eigVec[[1]]*eigVal[[1]]/5,                                 {0, 0},                                eigVec[[2]]*eigVal[[2]]/5}]}]]      ![enter image description here](http://i.stack.imgur.com/tvE61.png) How could I draw an ellipse representing on the EigenSystem given that Neither Disk or Circle enable to implement an "orientation" ? A rough example of my desired output as drawn using PPT : ![enter image description here](http://i.stack.imgur.com/r9MUF.png)


title: Compiled function error - nontensor object created

text: I'm trying to optimize code that uses Position MANY times. The following toy code works:               list1 = RandomInteger[{1, 10000}, 500000];     list2 = RandomInteger[{1, 10000}, {3, 500}];          test = ParallelTable[             Flatten[               Map[                 Position[list1, #] &, list2[[i]]               ]              ], {i, 1,  Length[list2]}];      My trouble begins because I have so much data to process. When I use my actual data in the code above, Mathematica takes 34 minutes to complete the computation. This is just too long to be practical, so I began exploring Compile. When I try this:                 test2 =          Compile[{{list1, _Integer, 1}, {list2, _Integer, 2}},            Table[             Flatten[                Map[                   Position[list1, #] &, list2[[i]]                ]             ], {i, 1, Length[list2]}]];             wow = test2[list1, list2]           CompiledFunction::cflist: Nontensor object generated; proceeding with uncompiled evaluation.       You can see that Mathematica complains. My questions are:   1. How can I debug what the problem is in the Compiled statement above? I really don't know how to start figuring out the problem.   2. Is there an obvious alternative to using Position that itself would be faster than Position? I am not new to Mathematica, but I admit to being completely new to compiling code. Any thoughts?


title: Simpler way to repeat an execution with 2D points?

text: q has the coordinates of quadrilateral. I can get the output below with brute- force but I want to find a simpler solution, perhaps something like `f<-q[[1;;2]]`. **Initializations**               f[x_, y_] = {{1, 2}, {3, 4}}.{x, y} + {5, 6};     q = {{1, 1}, {3, 1}, {3, 2}, {1, 2}}      **Want: better way for this, perhaps in some matrix form?**               f[1, 1]     f[3, 1]     f[3, 2]     f[1, 2]


title: What does it mean when a function is defined with two pairs of brackets

text: I have noticed a function defined as such:                f[x_][y_] := expr;      How is the argument y in 2nd pair of brackets being used? What is the difference from defining a function this way:                f[x_, y_] := expr;


title: DynamicModule, SaveDefinitions and global functions

text: * * * ### Unfortunately, I had not checked stackoverflow, because there, the exact same behavior was already reported. Please see the Q&A "SaveDefinitions considered dangerous". * * * Up-front, I'm on Ubuntu 12.04 with _Mathematica_ 9.0.1 and let's start with the questions:   * Should functions which are used in a `Manipulate` be local to this dynamic cell, when I `save them with`SaveDefinitions`?   * Is it OK, that after a kernel-restart `Manipulate` defines global functions? I noticed this behavior a while ago when something did not work as I expected it. Here is a small toy example. First we define a function, which (we assume we don't know this now) is not correct and will be fixed later:               f[x_?NumericQ] := "Wrong Implementation";      Now we make a small dynamic environment where we use this function and we save the definitions used there.               Manipulate[f[x] + x, {x, 0, 1}, SaveDefinitions -> True]      Sliding a bit around gives the correct output: ![Mathematica graphics](http://i.stack.imgur.com/Lg34w.png) Now, we notice our error in `f`, because (let's say) `f` is going to work even when we don't have numeric values. Therefore, we fix the pattern and evaluate               ClearAll[f]     f[x_] := "Correct Implementation!"      this redefinition is instantly shown in the `Manipulate`, which is kind of weird, because we explicitly told _Mathematica_ to save the definition and let me cite the documentation: `SaveDefinition`... > is an option to Manipulate and related functions that specifies whether > **current definitions** relevant for the evaluation of the expression being > manipulated should automatically be saved. ![Mathematica graphics](http://i.stack.imgur.com/NMk91.png) There is even more, because when you now `Quit[]` the kernel and then do nothing else that move the slider, you see that now the first definition is used again and the output changes to `"Wrong Implementation"`. This seems fine, because `Manipulate` finally remembers what is should have saved. However, this is not what broke my neck. What really took time to debug was that the wrong definition of `f` is leaked into the global context:               f[3]          (* "Wrong Implementation" *)      The problem back then, when I had this issue, was that although I evaluated the correct definition,               f[x_] := "Correct Implementation!"      the other one was used, because its pattern was more specific.               f[3]          (* "Wrong Implementation" *)      Any comments?


title: Is it possible to marginalize one or several parameters obtained from fitting procedure?

text: Statistical model analysis package has a few fitting functions. Their arguments are data points, fitting model and parameters in the fit. The result is a set of best values for parameters, which represent the `"BestFit"` to the data. However, one can also specify the `ConfidenceLevel` and obtain `"ConfidenceInterval"` for every parameter, or the total `"ParameterConfidenceRegion"` for all parameters. This region will be an **_n_** -dimensional ellipsoid, for the fit with **_n_** parameters. If you are not interested in one of parameters you could marginalize it, e.g. integrate the likelihood function over all values of that parameter, ending up with **_n-1_** parameters. If you could do this for all but one parameter you would reach to the same `"ConfidenceInterval"` that Mathematica has calculated for that parameter. But if one could do this for only **_p_** parameters, one would end up with **_n-p_** parameters and the `"ParameterConfidenceRegion"` would be **_n-p_** dimensional ellipsoid. Marginalization in terms of `"CovarianceMatrix"` is very simple - remove row and column that correspond to the parameter you want to marginalize. Now I don't know how to get `"ParameterConfidenceRegion"` from this modified `"CovarianceMatrix"` and I don't know if Mathematica has something for parametric marginalization implemented.


title: How to avoid an expensive subset of a Manipulate computation when dependent variables have not changed?

text: I have a `Manipulate` where a portion of the calculation that ends up displayed is dependent on a subset of the `Manipulate` control variables. It would make sense to cache that portion of the computation, only updating it if those controls are altered. Here's an example to illustrate:               ClearAll[preCalculateStuff]     preCalculateStuff = (#1  #2 ) & ;          Manipulate[ DynamicModule[{f},       f = preCalculateStuff[a, b];       Plot[(f t) Sin[  t + r ], {r, 0, 2 Pi}]],      {{a, 0.5}, 0, 1},      {{b, 0.5}, 0, 1},      {{t, 0.5}, 0, 1} ]      My real `preCalculateStuff` builds a big table, each element requiring a 4x4 `Eigensystem` call. I'd like to restrict that calculation to only do it when the control variables it is dependent on change. I've been pointed to `TrackedSymbols :> {var1, var2}` as a mechanism to avoid re-evaluation of the display. However, I still want to re-evaluate the display here (when any variable changes, including any that I would track), so it's not obvious to me how that would be applicable (unless it was to implement a `calculate` button, which wouldn't be terribly elegant).


title: How to control the speed in Manipulation

text: As the title says, I want to control the speed when I use `Manipulate`. I have the following piece of code               Clear["Global`*"];     Manipulate[     V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}];     Vyy = D[V, {y, 2}];     Vzz = D[V, {z, 2}];     ρ = 2.325/(4*π*100)*(Vxx + Vyy + Vzz);     ρxy = ρ /. {z -> 0};     ρxz = ρ /. {y -> 0};     ρyz = ρ /. {x -> 0};          M = 9500; a = 3; h = 0.15; λ = 1.1;          Syz = ContourPlot[ρyz, {y, -30, 30}, {z, -30, 30}, Contours -> 20,      ContourStyle -> Black, PlotPoints -> 50,      RegionFunction -> Function[{y, z}, ρyz < 0],      PerformanceGoal :> "Speed"],     {b, 0, 10, 0.1}]      My problem is that when I evaluate this in order to see what happens when the value of b changes the contours are plotted too fast without any order. Let me be more specific, the slider corresponding to b changes very fast and at any time it shows contours for completely random values of b. What I want, is to start the "animation" and be able to see in smooth and slow motion all the situations from b=0 up up b=10 using step 0.1 Many thanks in advance. **EDIT**               plots = Table[     V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}]; Vyy = D[V, {y, 2}]; Vzz = D[V, {z, 2}];     ρ = (2.325/(4*Pi*100))*(Vxx + Vyy + Vzz);     ρxy = ρ /. {z -> 0};     ρxz = ρ /. {y -> 0};     ρyz = ρ /. {x -> 0};     M = 9500; a = 3; h = 0.15; λ = 1.1;     ContourPlot[ρyz, {y, -50, 50}, {z, -50, 50}, Contours -> 20,      ContourStyle -> Black, PlotPoints -> 50,      RegionFunction -> Function[{y, z}, ρyz < 0],      PerformanceGoal :> "Speed", FrameLabel -> {"y", "z"},      RotateLabel -> False,      FrameStyle ->       Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotLabel -> Row[{"b = ", b}],      LabelStyle ->       Directive[FontSize -> 17, FontFamily -> "Helvetica"],      ImageSize -> 550], {b, 0, 10, 0.1}];


title: Get the correct position of a label on a vertical gauge

text: I am trying to have the value for a vertical slider display next to the indicator arrow for a vertical slider. However, my attempt is slightly wrong; the coordinates are scaled to the entire frame of the vertical slider (and not the coordinates), so at the minimum and maximum values, the location of the label is slightly off. How can I get this to work correctly? When I don't use Scaled, the label goes way off of the vertical slider, but when I do used it, it scales to the wrong values. Code:               Manipulate[      Grid[{        {         Style[" Sample ", 12, Bold, Underlined]},        {VerticalGauge[length, {0, 100},          GaugeFaceStyle -> LightGray,          GaugeLabels -> Placed[Automatic, Scaled[{0, length/100}]]          ]         }        },       Alignment -> Center],      {length, 0, 100}      ]      ![Imgur](http://i.imgur.com/uoYfVhh.gif)


title: RegionPlot is producing odd gaps, even for simple functions. Is there an option to prevent this?

text: When I use `RegionPlot` to plot the region between two functions, I get strange gaps in the resulting figure. Is there a way to prevent this from happening? * * * For example,               RegionPlot[x^2 < y && y < x^4, {x, -3, 3}, {y, 0, 3}]      produces the following strange result: ![enter image description here](http://i.stack.imgur.com/u6MvY.png)


title: Combining Two Plots to Create a Zoomed Callout

text: I want to combine two images to create a zoomed callout, as illustrated below. ![zoom callout](http://i.stack.imgur.com/pIFi6.png) The plot on the right is the zoomed in version of the boxed area on the left. The dotted lines connect the corresponding box corners. I would like to be able to change the location and size of the zoom callout (the right plot) as well as which dotted lines are shown. This is the code I used to make the plots:               bigplot = ContourPlot[x^2 - y^2 == 1/10000, {x, -1, 1}, {y, -1, 1}, ContourStyle -> Directive[Red, Thick], Frame -> None];     xrange = {-1/10, 1/10};     yrange = {-1/10, 1/10};     rect = Graphics[{EdgeForm[Directive[Black, Thick]], Opacity[0], Rectangle[Sequence @@ Transpose[{xrange, yrange}]]}];          combined = Show[bigplot, rect]     zoomedplot = ContourPlot[x^2 - y^2 == 1/10000, {x, xrange[[1]], xrange[[2]]}, {y, yrange[[1]], yrange[[2]]}, ContourStyle -> Directive[Red, Thick], FrameTicks -> None, PlotRangePadding -> None]      I think a solution would use `Inset`. However, I do not understand how the _pos_ argument works.


title: Has Mathematica a function to compute the Smith Normal Form?

text: The Smith normal form is a matrix that can be calculated for any matrix (not necessarily square) with integer entries. See Wikipedia for a more elaborate description. **Has Mathematica a function to compute the Smith Normal Form ?** If not, is there an easy way to compute it in Mathematica?


title: Why are numeric division and subtraction not handled better in Mathematica?

text: There is something that has been troubling me for a while. At least in version 7, the performance of `a / b` and `a - b` is not equivalent to, and significantly inferior to, `Divide[a, b]` and `Subtract[a, b]`, despite the fact that these are treated as equivalent in the documentation. As a terse code fanatic it chafes me to have to write out the longer forms, but that is only the beginning of my concern, because the latter, faster forms are transparently converted into the former, slower forms. Examples from the documentation for `Divide`: > x/y or Divide[x,y] is equivalent to x y^-1. > > Divide[x,y] can be entered in StandardForm and InputForm as x ÷ y, x > `Esc`div`Esc` y or x \\[Divide] y. Proof that these statements are false:               {a, b} = List @@ RandomReal[{-50, 50}, {2, 1*^7}];          Do[a/b, {50}]          // Timing // First     Do[a b^-1, {50}]       // Timing // First     Do[a\[Divide]b, {50}]  // Timing // First     Do[Divide[a, b], {50}] // Timing // First      > >     2.262 >   >     2.231 >   >     2.184 >   >     0.437 >   `Divide[a, b]` is _not_ evaluated in the same manner as the rest. Similarly for subtraction:               Do[a - b, {50}]          // Timing // First     Do[a + (-1 b), {50}]       // Timing // First     Do[Subtract[a, b], {50}] // Timing // First      > >     3.651 >   >     3.65 >   >     1.404 >   Although the examples above use packed arrays (see Why does list assignment with a packed array result in unpacked values? for an explanation of `List @@`) the same performance differential exists with unpacked lists. One can see with `Trace` that the short forms induce additional operations:               a = Range[1, 2];     b = Range[3, 4];          a/b          // Trace     Divide[a, b] // Trace      > >     {{a,{1,2}}, {{b,{3,4}}, 1/{3,4}, {1/3,1/4}}, {1,2} {1/3,1/4}, {1/3,1/4} > {1,2}, 1/3,1/2}} >   >     {{a,{1,2}}, {b,{3,4}}, {1,2}/{3,4}, {1/3,1/2}} >                 a - b          // Trace     Subtract[a, b] // Trace      > >     {{a,{1,2}}, {{b,{3,4}}, -{3,4}, {-3,-4}}, {1,2} + {-3,-4}, {-3,-4} + > {1,2}, {-2,-2}} >   >     {{a,{1,2}}, {b,{3,4}}, {1,2} - {3,4}, {-2,-2}} >   Note the false equivalence in this output; the fast `Divide` and `Subtract` operations are formatted as `{1,2}/{3,4}` and `{1,2} - {3,4}`, yet these slow forms are not part of their evaluation process. More problematic is when this false equivalence changes evaluation. For example, if you try to work symbolically with `Subtract` and `Divide` in an evaluated expression and use the result these faster forms are replaced with the slower ones:               expr = Divide[x, y] + Subtract[x, y];     fn = Function[{x, y}, Evaluate @ expr]     fn // FullForm      > >     Function[{x, y}, x + x/y - y] >   >     Function[List[x,y], Plus[x, Times[x, Power[y,-1]], Times[-1,y]]] >   Note also that `Divide` and `Subtract` are stripped when converting forms in the Front End (menu **Cell** > **Convert To** ) so even without evaluation these operators may be lost. ### Therefore I have these questions:   * Why are these operations universally treated as equivalent when they are clearly not programmatically equivalent?   * Why does _Mathematica_ not include optimization for cases of numeric division and subtraction to eliminate the additional evaluation steps?   * Is there a practical way to add global optimizations to automatically convert these operations to the fast forms before numeric evaluation?   * Failing the above, what is the best way to work symbolically with actual division and subtraction operators for the sake of performance?   * Is internally representing division and subtraction as multiplication and addition really the only mathematically valid design option? Couldn't these instead be first-class operators that are recognized as equivalent to `Times` and `Plus` _for the purpose of pattern matching_ but not _converted into_ `Times` and `Plus` (which introduces additional `Times` and `Power` operations)?


title: Switching off Dynamic updating on a cell by cell basis

text: Is there a simple way to switch off `Dynamic` evaluation for a particular cell? I usually delete the cell if it disturbs other evaluations or affects the performance too dramatically.


title: NSolve missing solutions in Mathematica 10

text: Running Mathematica 8.0.4 and 10.0.0 on a Windows 8.1 machine. Processed the same code with both kernels: `k = .2; NSolve[Rationalize[2 r^2 - .2 r^(k + 2) - 1 == 0], r, Reals]` The version 8 kernel returns two values as expected: `{{r -> 0.742979}, {r -> 100000.}}` The version 10 kernel returns only the first value by default. The second value doesn't appear as a solution until setting `WorkingPrecision` to at least 28. The same behavior occurs for other values of `k`: the version 10 kernel needs massaging to return values the version 8 kernel finds by default. What would cause this?


title: Plotting a Partially Filled Ellipse

text: I would like to plot a partially filled/shaded ellipse. The code below shades the whole ellipse. However, I only want to shade the part of the ellipse to the right of the vertical line where x > cutscore.               Needs["MultivariateStatistics`"]          cutscore = 0.5;      data1 = RandomVariate[MultinormalDistribution[{0, 0}, {{1, 0.6}, {0.6, 1}}], 500];     ellipse1 = EllipsoidQuantile[data1, 0.5];     e1 = Graphics[ellipse1];     line1 = Graphics[{Line[{{cutscore, -1.3}, {0.5, 1.5}}]}];     show1SEL = Show[e1, line1, Axes -> {True, False}, AxesOrigin -> {-2, -2},                 PlotRange -> {{-2, Automatic}, {-2, Automatic}}];     show1SELfilled = show1SEL /. Line[x_] -> {Green, EdgeForm@Thin, FaceForm[Opacity@.2], Polygon[x]}


title: Implicit Interpolating function in Mathematica and its explicit form in small sections

text: I have a set of points $\\{x_i,y_i\\}$ that represents a closed curve. I want to find a function $F(x,y)$ such that $F(x,y) = 0$ gives the needed curve and $F(x,y) \ne 0$ outside the curve. For example, suppose I am given a set of points that forms a circle:               n = 16;     points = Drop[Table[{Cos[2 i Pi], Sin[2 i Pi]}, {i, 0, 1, 1/n}], -1] // N;      I use the `Interpolation[..]` Mathematica function:               args = Join[Table[{points[[i]], 0}, {i, Length[points]}], {{{0, 0}, -1}}];     F = Interpolation[args];      Here I have added a new point $(0,0)$ with value $-1$ in it to my set of points to give "a depth" to $F(x,y)$. First question. Is that solution right? Can I be sure that my $F(x,y) \ne 0$ on non-curve points if I add "an inner" point with non-zero value to my set? What solution is more preferable? Also I have a second (and main) question. Due the peculiarity of my problem I need an explicit expression for my curve in a given section. In other words I want to have an expression for my curve in terms $y = f(x)$ or $x = f(y)$ (does not matter) between near points. I need this $f$ and its derivative $f'$. Thereby $f$ should be an InterpolatingFunction object too (but one- dimensional). Using `Solve` on `F` from previous example does not give a result. How to get $F$ and $f$ (between given near points)? **Update** : In my example $F(x,y) = x^2+y^2-1$ and I can single out two explicit fucntions: $f_1(x) = \sqrt{1-x^2}$ where $x > 0$ and $f_2(x) = -\sqrt{1-x^2}$ where $x \leq 0$. Equations $y=f_1(x), y=f_2(x)$ and equation $F(x,y)=0$ represent the same curve (a circle). This is what I need: implicit function $F(x,y)$ and a set of explicit functions $f_i$. Also I can single out another explicit functions: $f_1(y) = \sqrt{1-y^2}$ where $y \leq x$ and $y \geq -x$; $f_2(x) = \sqrt{1-x^2}$ where $y > x$ and $y \geq -x$; $f_3(y) = -\sqrt{1-y^2}$ where $y > x$ and $ y < -x$; $f_4(x) = -\sqrt{1-x^2}$ where $y \leq x$ and $y < -x$. Together they form a circle. **Update 2** : The given curve is closed and has no self-intersections. Locally $F(x,y)=0$ can be expressed as $y=f(x)$ or $x=f(y)$. This is what I need. I try Solve function but it does not give result for interpolating $F(x,y)$. Instead it gives an error: _"Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system"_


title: Unify the sampling of NIntegrate[ {f, g, h} w ]

text: I'm trying to numerically integrate a function which has a vector-valued slow part and a much faster component which is shared by all the components, i.e. an integral of the form $$ \int_a^b\begin{pmatrix}f(x)\\\ g(x) \\\ h(x)\end{pmatrix}w(x)\,\text dx. $$ Because `NIntegrate` is nicely Listable on its first argument, I can feed it a list-valued argument without a problem. However, it appears to be doing each component as a completely separate integral, which results in a lot of work being re-calculated. For example, the (simplified) example integral               samplePointsList = Reap[         NIntegrate[          {x, x^2, x^3} Cos[10 x + Cos[x]]          , {x, 0, 5}          , EvaluationMonitor :> Sow[x]          ]         ][[2, 1]];      gives the sample point diagram (through `ListPlot[Transpose[{samplePointsList, Range[Length[samplePointsList]]}]]`) ![enter image description here](http://i.stack.imgur.com/FuIiD.png) It is clear that the kernel is doing the initial sampling, and then the further refinements, separately for each component. While the required sample points are not identical, there is a lot of shared work and I feel there is a fair bit of room for optimization there. I am aware that, since the sampling requirements of each component are slightly different, binding them completely will require more evaluations in some components than would be necessary. (For instance, in the example above, the extra detail required by the first component around $2\leq x\leq 3$ would be slowed down slightly if it was required to also calculate the second and third components there, though they do not require it.) However, the components in my case are similar enough that I do not think this would be an issue. Is there a way to force Mathematica into this sort of separation of the integrand and unification of the sampling? If not, is there a way to make it aware of the previously calculated values and sampling points which will speed up the process?


title: Sorting non-numerical lists

text: The `Sort` function will by default sort from lowest to highest.               In[1]:= Sort[{3, 1, 4}]     Out[1]= {1, 3, 4}      However, if the list contains non-numerical values, it will sort it incorrectly               In[2]:= zeroes = {2 Pi - 2 ArcTan[Sqrt[2 + Sqrt[5]]],         2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 Pi + 2 ArcTan[Sqrt[2 + Sqrt[5]]]};          In[3]:= zeroes // N     Out[3]= {4.04615, 2.23704, 8.52022}          In[4]:= Sort[zeroes] // N     Out[4]= {4.04615, 2.23704, 8.52022}      One could use the `Greater` function as a parameter to Sort and then reverse the input               In[5]:= Reverse@Sort[zeroes, Greater] // N     Out[5]= {2.23704, 4.04615, 8.52022}      There is no `Lesser` function in Mathematica, but there must be a better way to do this, without converting the data to floats.


How to map vertex points from the surface of a straight pipe onto 2D plane. The 3D surface points of the straight pipe can be found here: data Working code:               file = "http://pastebin.com/H9y9SqYy";     dat = Import[file, "Table"];     Graphics3D[Point@dat, Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/rP8YS.png) One can imagine as a simple straight cut (anywhere) on the circumference of the pipe. I want to get something like this: ![enter image description here](http://i.stack.imgur.com/VT1gk.png)


title: How would I enable the Evaluate in place item of the Evaluate menu?

text: I would like to be able to suppress multiple outputs when a cell is evaluated. Is there a way to enable the "Evaluate in place" menu item of the Evaluate menu?


title: Copying Greek text from notebooks as unicode

text: > **Possible Duplicate:**   >  How to "Copy as Unicode" from a Notebook? How can I copy Greek text from notebooks as proper Unicode that can be pasted into other applications? If I type some Greek text into a notebook, and then try to paste it elsewhere, it ends up as a set of character names in Mathematica's notation. The screenshot below illustrated the problem. ![Mathematica graphics](http://i.stack.imgur.com/YqVrc.png) It doesn't really matter if the Greek text is typed elsewhere, then pasted into Mathematica, or if it's typed directly into Mathematica: when copying _from_ Mathematica, Greek letters are converted into character names. If you don't have a Greek keyboard layout installed, this can be useful for testing. **Use case:** analysing Greek text and copying results from a notebook.


title: Removing In/Out Labels before printing

text: I know that I can close a notebook and open it again in order to remove the In/Out labels. What I would like to know is if there is another easy way of removing these labels without having to close the notebook. Actually I just want to hide them from my printouts. It seems to me like it should be a printing option, but I can't find it.


title: Scan vs Map vs Apply

text: I cannot understand the difference between `Apply`, `Scan`, and `Map`. I have tried to play with these function by the codes below:               f[x_] := x^2      * * *               Map[f, {{a, b}, c}]      Output:               {{a^2, b^2}, c^2}      * * *                Apply[f, {{a, b}, c}]      Output:               f[{a, b}, c]      * * *               Scan[f, {{a, b}, c}]      There is no output for this one. The function of `Map` is understandable. But I cannot get the purpose of `Apply` and `Scan`. What are the differences between these three function?


title: What is the most efficient way to add zeros to end of a number?

text: Beside `*10^n`, is there a faster way to add thousands of zeros to end of a number? **Updated** Timings:               In[230]:= First[Timing[prime*10^100000000]]          Out[230]= 3.625          In[25]:= First[      Timing[FromDigits[        Join[IntegerDigits[prime], ConstantArray[0, 100000000]]]]]          Out[25]= 7.547      **Updated** According to Mr.Wizard answer:               In[46]:= First[Timing[2213*1*^200000000]]          Out[46]= 0.015 (* The real timing on the clock is 5 seconds *)          In[45]:= First[Timing[2213*10^200000000]]          Out[45]= 5.11          In[3]:= First[Timing[ToExpression["2213*1*^200000000"]]]          Out[3]= 5.078      But the strange thing is that by using special `1*^` notation, the reported timing is almost zero while by clock it takes roughly the same time of `10^n`. Maybe `Timing` function doesn't take Mathematica built-in notations into account.!! **Updated 2** Yet The fastest method to beat native `*^10` adding zero method is by shifting, even though the improvement is very tiny.               In[16]:= First[Timing[1223*10^100000000]]          Out[16]= 2.625          In[17]:= First[Timing[BitShiftLeft[1223*5^100000000, 100000000]]]          Out[17]= 2.547


title: Why function is evaluated backward?

text: I have a simple function: `f[x0_,y0_]:= Module[{x=x0,y=y0},For[i=0,i<2,i++;Print[x],Print[x+y]];]` So when I call it:   `f[2,3]` I get: > 5   >  2   >  5   >  2 Why not: > 2   >  5   >  2   >  5 as expected? Also my indentation of - or + don't seem to format?


title: Converting string representation of boxes into explicit boxes

text: It is very easy and convenient to write textual labels as `Strings` in the WYSIWYG mode. For example, I define a short form describing a linear model: `"2D3O"`, which means "two descriptors of type D and tree descriptors of type O". Everything is good so far. Now I wish to add superscripts and use standard palette to add them. I get ![screenshot](http://i.stack.imgur.com/FoiFh.png) Looks nice. But at some point I have a lot of such labels and wish to apply some formatting to all of them at once. For example, I wish to make all the digits `Bold` and all the letters `Gray`. `FullForm` shows internal structure and I see the string representation of boxes: ![screenshot](http://i.stack.imgur.com/mp7Na.png) This is not a format easy to deal with. The tutorial explains how to convert ordinary boxes to its string representation using `ToString`. But what is the general way to convert string representation of boxes into explicit boxes?