Counting Stochastic Processes and displaying relative value I have two watermarks and multiple stochastic processes given. I want both to display and count the stochastic processes which are below the two watermarks, namely watermark and watermark2: Furthermore I also want do display the relative proportion af all processes below watermark and watermark2 to all processes. In order to count the processes I used first generated a random matrix to get a little bit familiar with the counting fucntion the code is:               dataX = Table[RandomFunction[             GeometricBrownianMotionProcess[0.1, 0.2, 10], {0, 10, 0.1}]["Path"], {3}]      Then:               processesX = Transpose[dataX[[#]]][[2]] & /@ Range@Length[assetsX]      Then I just wanted to count the process values beyond 20 by this code:               Count[Flatten[dataX], _?(# >= 20 &)]      this worked so I tried to apply it for my code, however, I have some problems and I am not sure if I have allpied it properly. I would be greateful for any help. my code:               Manipulate[SeedRandom[seed]; meanvector := Mean[assets];      assets =        Table[RandomFunction[          GeometricBrownianMotionProcess[μ, σ, S0], {0, time,            0.1}]["Path"], {P}];      processes = Transpose[assets[[#]]][[2]] & /@ Range@Length[assets];      processesposition =        Flatten[Position[         Min[processes[[#]]] & /@           Range@Length[assets], _?(# > watermark &)]];      processesposition2 =        Flatten[Position[         Min[processes[[#]]] & /@           Range@Length[assets], _?(# > watermark2 &)]];      watermarkedassets = assets[[#]] & /@ processesposition;      watermarkedassets2 = assets[[#]] & /@ processesposition2;      watermarkedmeanvector = Mean[watermarkedassets];      watermarkedmeanvector2 = Mean[watermarkedassets2];           (*Counting Stochastig processes below watermark and watermark2*)      StoProcbelowwatermark =        Count[Flatten[assets], _?(# >= watermarkedassets &)];      StoProcbelowwatermark2 =        Count[Flatten[assets], _?(# >= watermarkedassets2 &)];      (*Relative proportion of assetes belos watermark and watermark2 to \     all assets*)      RelProportionwatermarktoall = StoProcbelowwatermark/P;      RelProportionwatermark2toall = StoProcbelowwatermark2/P;           (*Functions and Plotting*)      G1 := ListLogPlot[assets,         GridLines -> {{}, {{watermark,             Directive[Green, Thick]}, {watermark2,             Directive[Orange, Thick]}}}, Joined -> True,         AxesLabel -> {"Time", "St"},         PlotLabel ->          Style["Forecasted Stock Price\n (Brownian Motion)", Bold],         PlotRange -> All, PlotStyle -> Directive[{Thin, Lighter@Gray}]];      G2 := ListLogPlot[{meanvector, watermarkedmeanvector,          watermarkedmeanvector2}, Joined -> True,         PlotStyle -> {Directive[{Thick, Darker@Red}],           Directive[{Thick, Darker@Blue}], Directive[{Thick, Black}]}];      Show[G1, G2], {{S0, 100, "Initial Stock Value"}, 1, 500, 0.5,        Appearance -> "Labeled"}, {{μ, 0.08, "Drift μ"}, 0.01, 0.2,        0.01, Appearance -> "Labeled"},           {{σ, 0.2, "Standard Deviation σ"}, 0.01, 1, 0.05,        Appearance -> "Labeled"}, {{P, 6, "Paths"}, 1, 20, 1,        Appearance -> "Labeled"}, {{time, 10, "Time t"}, 1, 20, 1,        Appearance -> "Labeled"}, {{watermark, 75, "Watermark"}, 1, 500,        Appearance -> "Labeled"}, {{watermark2, 70, "Watermark2"}, 1, 500,        Appearance -> "Labeled"}, {{seed, 1, "New Random Case"}, 1, 100, 1},           Button["Set Initial Values", {S0 = 100, μ = 0.08, σ =          0.20, P = 6, time = 10, watermark = 75, watermark2 = 70},        ImageSize -> 150],       Dynamic["Mean watermarked processes = " <>         ToString[watermarkedmeanvector[[-1]][[2]]]],       Dynamic["Mean watermarked2 processes = " <>         ToString[watermarkedmeanvector2[[-1]][[2]]]],      Dynamic["Mean of all processes = " <>         ToString[meanvector[[-1]][[2]]]],      (*Displaying Processes below the two watermakrs*)      Dynamic["Processes below watermark = " <>         ToString[StoProcbelowwatermark[[-1]][[2]]]],      Dynamic["Processes below watermark2 = " <>         ToString[StoProcbelowwatermark2[[-1]][[2]]]],      (*Displaying relative proportions Processes below watermakrs in \     relation to all processes*)      Dynamic["relation processes below watermark and all processes= " <>         ToString[RelProportionwatermarktoall[[-1]][[2]]]],      Dynamic["relation processes below watermark and all processes= " <>         ToString[RelProportionwatermark2toall[[-1]][[2]]]],      ControlPlacement -> Left]


Can I take derivative of a function that represents a piece of music?

Can I take the derivative of a function that represents a piece of music? The music is given in .mp3, .midi or whatever comes in handy.


String replacement question

If you have a string               string="<ALK>ene"      and I have a list `alk={"meth", "eth", "prop", "but", "pent"}`, what function could I use to automatically create a list `{"methene","ethene","propene","butene","pentene"}`, i.e. with `"<ALK>"` replaced by each element of `alk` in turn? I could do something like `alkenenames[ALK_] := StringJoin[ALK, "ene"];Map[alkenenames, alknames];` - but instead of defining functions I would like to be able to define string with pattern replacement rules embedded in them as above. How do I do this in Mathematica? Edit: actually one more question - I noticed that the different proposed solutions below behave differently if the string happens not to contain `"<ALK>"` - in one solution returning an empty list, and in another one returning a list of your original string duplicated n times, where n is the length of the list alk. In actual fact I would like the function to just return the original string if `<ALK>` does not occur in it. Also, I was wondering what would be the most elegant solution to also allow multiple occurences of `<ALK>` in the string, which would then be replaced in a combinatorial fashion. (i.e. replacing the first occurrence of `<ALK>` by each alk element in turn, and then replacing the second occurrence of `<ALK>` by each alk element in turn as well, and so on)


Find positions where two matrices differ

I have two matrices `A` and `B` of identical dimensions. What's the simplest (shortest) way to find the indices of differing elements?


Mma10 mystery: Failure of pure function substitution with Interpretation?

I had code to display with subscripts from Displaying index as subscript on output: e.g. C[i] -> C_i with Notation[...] or Interpretation[..]? which is now breaking an innocuous pure function substitution as in Looking for an elegant way to solve a (system of) ODEs/functional equations with undetermined coefficients The substitution itself has nothing to do with any actual display of subscripts. I am having a little trouble creating a minimal example, but here goes. First, in Mma10 try the pre-side effect code:               ODE = F'[z] == g F[z]     Fguess = {F-> (Exp[a #]&)}     ODE /. Fguess //FullSimplify          => e^(a z)(a - g)== 0, the proper output      Now, add in the following code, stripped down from that previous example. This isn't intended to actually have anything to do with the substitution, but is causing side effects.               NotScriptedVarQ[z_] := ! MemberQ[$scriptedfunctionsvars, z, Infinity];         makeDef[pat_, body_] := (MakeBoxes[a : pat, fmt_] :=          ToBoxes[Interpretation[body, a], fmt] /;           MemberQ[Union[$scriptedconstants, $scriptedfunctions],            Unevaluated@h];       )         makeDef[h_Symbol[argssub__?NotScriptedVarQ], h[argssub]];         $scriptedconstants = {};     $scriptedfunctions = {};         $scriptedfunctionsvars = {};      Now, try the substitution and a few permutations:               (*The ODE and guess are*)     ODE = F'[z] == g F[z]     Fguess = {F -> (Exp[a #] &)}     (*Substituting NOW DOESN'T work*)     ODE /. Fguess // FullSimplify     (*But if the guess is NOT displayed before the substitution(i.e., no ;) WORKS!*)     Fguess = {F -> (Exp[a #] &)};     ODE /. Fguess // FullSimplify     (*And if the guess is substituted directly, IT WORKS!*)     F'[z] == g F[z] /. {F -> (Exp[a #] &)} // FullSimplify      As this used to work fine in Mma9, I imagine this is a bug. If so, any idea of a workaround? One last thing I learned: If you change the definition so that `NotScriptedVarQ[z_] := True`, or change it to always be False, the bug is no longer there!


Is there a better way of creating/assigning variables programmatically than using strings and ToExpression?

For quite a while now I've been wondering how to assign variables programmatically, and I have finally figured out one way of doing this. For example in a game where you have a variable number of players and you want to assign all players a list with specific numbers. You want to create a variable `player1` for the first player, `player2` for the second, and so on. However you don't want to create excess players, nor do you want to create too few, but you want to make sure you only create as many players as are needed. This is what I've done so far:               Do[ToExpression["ClearAll[player" <> ToString[i] <> "]"], {i, 1000}];     players =       Table[numOfPlayers = i;        ToExpression["player" <> ToString[i] <> "=Table[i+j,{j,0,10}]"], {i,         3}]      The `Do` loop clears all `player`s up to 1000. The `Table` then creates as many players as required. My question is, although this method works, it's messy and I would rather not use `ToExpression` if I can avoid it (Wolfram don't like it when `ToExpression` is used in Demonstrations for example). Is there an alternative way of creating and assigning variables programmatically?


Removing empty sets from lists

If I had a list, say,               names= {"Andy", "Bob", "Carly", "Sandy", "Jeff", "Tim", "Tom", "Zach"}      and I decide to pick a characteristic only a certain of them have, and my input would be something that works, (or think of it as something `WordData["....",",,,,"]`, and my output would look like:               {{"Andy", {}, {}, {}, {"Jeff", "Tim"}, {}, {"Zach"}}      I know this type of thing probably isn't possible, but just say if it did, how would I only choose the nonempty set? How would I do this using `Select`? I know I should select from my set of names, but not sure (There's probably a different way, but I wanted to continue to practice this function so I can understand it fully).


Matching Root[...] objects with patterns, unexpected hidden argument

I needed to write patterns that could distinguish between arbitrary-function and polynomial forms of `Root` objects, for example, `Root[{-3 + #1 + #1^E &, 1.2``1}]` and `Root[-3 + #1 + #1^5 &, 1]`.               MatchQ[Root[{-3 + #1 + #1^E &, 1.2``1}], Root[{_, _Real}]]     (* True *)          MatchQ[Root[-3 + #1 + #1^5 &, 1], Root[_, _Integer]]     (* False *)      The last result looks unexpected. An investigation shows that there is a third, invisible and, apparently, undocumented argument `0`:               Root[-3 + #1 + #1^5 &, 1] // InputForm     (* Root[-3 + #1 + #1^5 & , 1, 0] *)      Once we know this, pattern matching is easy to fix, but still there are some questions:   * What's the purpose of this parameter? Is it documented anywhere?   * Why is it invisible in `StandardForm` and `OutputForm`?    * Are there cases when I might need to explicitly provide an argument for it?


Which DirichletCharacter is KroneckerSymbol?

If $d$ is a fundamental discriminant, `KroneckerSymbol[d,n]` is a Dirichlet character modulo $|d|$. _Which one is it?_ If $d>0$ is a prime $\equiv 1\bmod 4$, then it's `DirichletCharacter[d,(d+1)/2,n]`, and similarly if $d<0$, with prime $-d\equiv 3\bmod 4$ it is `DirichletCharacter[-d,(1-d)/2,n]`. In general, there is a function which, on input a fundamental discriminant $d$ outputs $j$ such that `KroneckerSymbol[d,n]` is equal to `DirichletCharacter[Abs[d],j,n]` for all $n$ relatively prime to $|d|$. The ability to compute such $j$ easily would allow one to use the built in `DirichletL` to compute the Dirichlet series attached to the Kronecker symbol. Of course one can build a table of values of `KroneckerSymbol[d,n]` and of all `DirichletCharacter[Abs[d],k,n]` for k=1,2,... `EulerPhi[Abs[d]]`, and then look for a match. I'm looking for something smarter and more efficient than that, for use with large composite d.


How can the lowest non-zero value in a nested list be found and its position in the sublist returned?

In the example code below we have a list of triples that produce one or more sublists with at least one zero value. How can the positions of the lowest non zero value in each sublist be returned where that condition applies, and identify those sublists whose lowest value is zero so that the overall positions of the non-zero values can be obtained, and not lose their positions in the overall list?                In[1]= myList=Partition[RandomSample[Range[0, 8], 9], 3]      Out[1]= {{3, 1, 8}, {5, 0, 2}, {7, 6, 4}}      What I would like to get returned is something like this: {2,z,3} for the above list. Thanks for the help!


Is it possible to use Gaussian cgs units in $Mathematica$ computations?

I was trying to do computations in Gaussian cgs units, and of course I failed due to dimensional issues. For instance, $q_1 q_2/r$ cannot be converted to $\mathrm{erg}$ since Gaussian system uses $4\pi \epsilon_0 = 1$. So, the question is: **Is it possible to use Gaussian cgs unit system in Mathematica computations?** "Using Gaussian cgs unit system" means, for instance, $V_\mathrm{coulomb}=q_1 q_2/r$; no doubt that the units themselves can be called in whatever suitable situation. Personally I think the answer is no, because the only unit systems listed in documentation of `UnitConvert` are `"SIBase"`,`"SI"`,`"Imperial"`, and `"Metric"`. But I am asking to get confirmation, and hopefully we can settle an answer to benefit future Google searches of this topic.


Mathematica Destructuring

### Context I'm writing a function that look something like:               triDiagonalQ[mat_] := MapIndexed[ #1 == 0 || Abs[#2[[1]]-#2[[2]]] <= 1 &, mat, {2}] //          Flatten // And @@ # &      Now, things like `#2[[1]]` and `#2[[2]]` are somewhat hard to read. I'd prefer to do something like:               triDiagonalQ[mat_] := MapIndexed[ #1 == 0 || Abs[i-j] <= 1 &, mat, {2}] //          Flatten // And @@ # & (* with a {i, j} <- #2 somewhere *)      ### Question Is there someway to do something like "destructuring" in _Mathematica_? * * * The following links convey what I mean by "destructuring":   * http://clojure.org/special_forms   * http://java.dzone.com/articles/clojure-destructuring   * http://blog.jayfields.com/2010/07/clojure-destructuring.html (These have nothing to do with _Mathematica_ ; they're posted mainly to demonstrate what is meant by "destructuring")


Server running WolframLightWeightGrid manager loses licensing information

"Once more into the breach..," I have 2 identical Xserves running OS X Server 10.6.8 each with 2 quad core Intel Xenon processors a total of 16 kernels. I have configured both servers identically and use them exclusively as a computing grid for Mathematica. I run the WolframLightWeightGrid manager on the servers and distribute processing jobs to them from a number of different notebooks. An earlier question Wolfram Light Weight Grid and parallel computing from when I setup this environment gives more background. This environment has pretty much run like a charm over the past four months. As a check on what goes on I run the following few lines of code when launching the grid:               Needs["LightweightGridClient`"]     Column[{       ParallelEvaluate[$ProcessID],       ParallelEvaluate[$MachineName],       RemoteServicesAgents[] // ColumnForm}]      This will give me lists of the process IDs and machine names and remote service agents. But today something has gone awry: ![code & output](http://i.stack.imgur.com/xtbJj.png) I should see 8 additional process ID's and 8 additional machine names (specifically "abb-1"). The output correctly identifies the remote service agents, but then it gets strange as it also generates the following error messages: ![messages](http://i.stack.imgur.com/OoTup.png) I've tried calling Wolfram and while I have great respect for the support staff, not all of them have extensive experience with parallel processing and honestly, one can't reasonably expect all of them to have such experience. If I get anything back from them I'll report it here. Until then... The WolframLightWeightGrid manager should launch when the server boots. I have restarted "abb-1" several times, even shutting it down completely and powering it off, but still have the same problem. I have current licenses for all the kernels in question. Since `RemoteServicesAgents[]` identifies the server "abb-1" does this imply that the grid manager has launched? It seems that something has caused to grid manager to lose its licensing infromation.   * What could have gone wrong?   * Where should I look to trouble shoot this? I hope to get this working properly so that I can automate more of my daily processes and calculation. AND I need it to work reliably. Suggestions, solutions, insights, and comments welcome. Thx...


Error in Compiled function at runtime in spatial competition model

I just did a model of spatial competition between two species with different competitive ability & dispersal rates on a lattice with variables nrs of individuals per site. To speed it up I tried to use Compile - but I get an error at runtime. It works OK though if I run it uncompiled. Anybody any ideas what I might be doing wrong? My code is               gridsize = 30;     k = 1000;     zeroMatrix[n_, m_] := Table[0, {n}, {m}];     initSpace[n_, m_, k_] := Block[{s},        s = { zeroMatrix[n, m], zeroMatrix[n, m] };        s[[1, 1, 1]] = k;        s[[2, n, m]] = k;        Return[s];        ];     current = initSpace[gridsize, gridsize, k];      This function does one time step iteration, using synchronous updating:               stepC = Compile[{{current, _Real, 3}, {b, _Real, 1}, {disp, _Real,           1}, {fitness, _Real, 1}},         Block[{tmp, k, k2, n, m, curr = current},         n = Dimensions[curr][[2]];         m = Dimensions[curr][[3]];         Do[          curr[[species]] *= b[[species]];          curr[[species]] +=            Map[Round,             GaussianFilter[curr[[species]], disp[[species]]], {2}];          , {species, 2}];         tmp = (fitness[[1]]*curr[[1]] + fitness[[2]]*curr[[2]]);         k = Max[curr];         Do[          k2 = If[tmp[[i, j]] < k, tmp[[i, j]], k];          tmp[[i, j]] = If[ tmp[[i, j]] == 0, 1, tmp[[i, j]] ];          curr[[1, i, j]] = k2*fitness[[1]]*curr[[1, i, j]] / tmp [[i, j]];          curr[[2, i, j]] = k2*fitness[[2]]*curr[[2, i, j]] / tmp [[i, j]];          , {j, m}, {i, n}];         curr         ],        CompilationTarget -> "C", Parallelization -> True,         RuntimeOptions -> "Speed"];      I then define a function to display the densities of the two species:               getImage[current_] := Module[{img},        img = Map[{#/k, 0, 0} &, current[[1]], {2} ];        img += Map[{0, 0, #/k} &, current[[2]], {2} ];        Return[Graphics[Raster[img]]];        ];      And iterate and display an animation of the dynamics:               b = {2.0, 2.0};     d = {3.0, 1.0};     f = {1.0, 1.3};     current = initSpace[gridsize, gridsize, k];     ngens = 30;     steps = 5;     imgs = Table[0, {ngens}];     Timing[Do[       imgs[[i]] = getImage[current];       Do[current = stepC[current, b, d, f], {steps}];       , {i, ngens}]]     Animate[      imgs[[i]]      , {i, 1, ngens, 1}, AnimationRepetitions -> 1,       AnimationRunning -> False]      During runtime I then get an error "CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation." Any thoughts what's wrong?


NDSolve :: ndode error while solving an coupled ODEs

I have a scenario where in trying to solve for the ground-state of a _Hamiltonian_ , I require to be able to solve some coupled differential equations. Prior to this I have already set k=1 and Δ=5 $$ \text{NDSolve}\left[\left\{\Delta \delta (\phi )-i k e^{-i \phi } \beta (\phi )==-i \alpha '(\phi ),\beta (\phi )-\Delta \gamma (\phi )+i k e^{i \phi } \alpha (\phi )==i \beta '(\phi ),-\Delta \beta (\phi )+i k e^{i \phi } \delta (\phi )==-i \gamma '(\phi ),\Delta \alpha (\phi )+\delta (\phi )-i k e^{-i \phi } \gamma (\phi )==i \delta '(\phi ),\alpha (\pi )==1,\beta (\pi )==-1,\gamma (\pi )==1,\delta (\pi )==-1\right\},\{\alpha ,\beta ,\gamma ,\delta \},\{\phi ,-\pi ,\pi \}\right] $$ Source Code:               NDSolve[{- E^(-I ϕ) β[ϕ] I k + Δ δ[ϕ] == -I α'[ϕ] ,       (E^(I ϕ)) α[ϕ] I k  + β[ϕ] - Δ γ[ϕ] ==  I β'[ϕ],       - Δ β[ϕ] +E^(I ϕ) δ[ϕ] I k == -I γ'[ϕ],       Δ α[ϕ]-E^(-I ϕ) γ[ϕ] I k +δ[ϕ] ==I δ'[ϕ],       α[π]==1, β[π]==-1, γ[π]==1, δ[π]== -1},{α,β,γ,δ},{ϕ,-π,π}]      It gives me an error of > NDSolve::ndode: Input is not an ordinary differential equation. Here's a screen shot of the error on my system: i.stack.imgur.com/14Dwr.png Any idea what i'm doing wrong?


How to solve an equation with two variables in Mathematica

If I solved an example equation like `|x|+|y|=1` numerically, I would to get a 90° rotated rectangle. If I was to plot the equation, it would result in an image like the following: ![example problem](http://i.stack.imgur.com/mVafC.png) As an example, this is the problem I want to solve:               Sin[x] Sin[2y] + Sin[y] Sin[2x] = 0      May I get suggestions on the best method to plot the example problem achieving the same result?


How to insert trigonometric functions into matrices' vector components?

Is it possible to insert a trigonometric function into a matrix which will be able to be used dynamically, as an element of one of the vectors of the matrix? I'm trying to perform an operation like the following:               A1 = {{1,        0,        0},           {Sin[phi], Cos[phi], 0},           {0,        0,        1}};          A2 = {{Sec[phi], -Tan[phi] ,0},           {0,        1,         0},           {0,        0,         1}};      I'd like to be able to multiply those two matrices:               A1.A2 (*For mathematica*)     - or -     A1*A2 (*For humans*)      Figuring this out will hopefully allow me to create a function such that it simplifies the transformation process. This will allow me to write a function like the following:               trans[x_,y_]:= A1.A2.{x,y,1};      Note that **phi represents a random value** which I'd like the matrix to respond to, for example:               x = {2,4};          A = {{Sin[phi], 0},          {0,        1}};          A.x = {Sin[2], 4};


Increasing y-axis on plot as it appears it naturally truncates part of the plot

Changing the x-axis is fine and it will allow me to do so. When I want to change the y-axis (2D vertical), an error occurs. It appears as if the mathematica plot is missing some of the graph data. Is there a way in which I can increase the limits to which the y-axis run? Like you add {x, -Pi, Pi} to determine the interval of the x-axis, I have tried similar with replacing x with y or x with the function definition. Code Example: `Plot[{Sign[x] - f6[x]}, {x, -Pi, Pi}, {y, -0.5, 0.5}]`


nested series expansion

I have to invert the following matrix in which the functions `U[t,x,y,r]` and `K[t,x,y,r]` and all their derivatives are "small";               matr={{(1 - 2*U[t, x, y, r]/c^2 - 2*D[K[t, x, y, r], t]/c), -D[         K[t, x, y, r], x], -D[K[t, x, y, r], y], -D[K[t, x, y, r],          r]}, {-D[K[t, x, y, r], x], -(1 + 2*U[t, x, y, r]/c^2), 0,        0}, {-D[K[t, x, y, r], y], 0, -(1 + U[t, x, y, r]/c^2),        0}, {-D[K[t, x, y, r], r], 0, 0, -(1 + 2*U[t, x, y, r]/c^2)}}      furthermore I need the final expression only up to the order `c^-2`. I am using the code:               Simplify[Series[       Series[Series[         Series[Series[           Series[Inverse[matr], {c, Infinity, 2}], {D[K[t, x, y, r], r],             0, 1}], {D[K[t, x, y, r], y], 0, 1}], {D[K[t, x, y, r], x], 0,           1}], {U[t, x, y, r], 0, 1}], {D[K[t, x, y, r], t], 0, 1}]]      The problem is that inevitably, there are terms of the type:               D[K[t,x,y,r],t]*D[K[t,x,y,r],x]      and so on. Is it possible to tell Math. that those terms are small too, without adding them to the series? Even better: how can I simplify my nested series expansion? **EDIT** To answer @Daniel Lichtblau The "small" terms must be at first order. There are no problem in terms of the type `c.small=TooSmallToKeep`.


How to manipulate plot range with fixed axes

I want to achieve something like this               Manipulate[Plot[Sin[x], {x, 0, r}, PlotRange -> {{0, 10}, {-1, 1}}], {r, 0.1, 10}]      but my function in place of `Sin` is an expensive function, and since what I want is only change of plot range, there is no need to recalculate the values every time. So I try this               p = Plot[Sin[x], {x, 0, 10}];     Manipulate[Show[p, PlotRange -> {{0, r}, {-1, 1}}], {r, 0.1, 10}]      but the plot axes is changing as I change r. So is it possible to manipulate the plot range of a plot with a fixed axes, without reevaluate it every time?


Plotting two surfaces and visualizing their intersection

Trying to plot the following two functions to show points of intersection.               2 x + y - 1 == 0,      x - y + 2 == 0     ContourPlot[{2 x + y - 1 == 0, x - y + 2 == 0}, {x, -5, 5}, {y, -5, 5}]      The above shows the plots, but I find it difficult to see the point of intersection. I suspect that there is a better method than this. Please suggest a good method to plot such equations.


Override Equation structure change in mathematica - CopyToLaTeX

I am writing my thesis, and when I do copy to LaTeX from Mathematica, it changes the equation variables and also it rearranges the structure of the original equation. How can I override that ?? > _New information and further reading > :http://pages.uoregon.edu/noeckel/computernotes/Mathematica/EquationEditing.html_ Its really annoying especially when I have to get the exact same form. EXAMPLE: # 1: Mathematica code:               TeXForm[HoldForm[E^(-I k( (\[Xi]/Subscript[z, 1]+u/Subscript[z, 2]) x+ (\[Eta]/Subscript[z, 1]+v/Subscript[z, 2]) y))]]      # 2: How it looks in Mathematica: ![1](http://i.stack.imgur.com/IZtsJ.png) # 3 Mathematica Output:               \exp \left(-i     k\left(\left(\frac{\xi     }{z_1}+\frac{u}{z_2}\right)     x+\left(\frac{\eta     }{z_1}+\frac{v}{z_2}\right)     y\right)\right)      # 4 Copy paste #3 into LaTeX, the result: ![output on PDF](http://i.stack.imgur.com/1GIiQ.png) Thanks


Adapting NDSolve to circumvent NDSolve::bdord: error for 1-D Euler Equations

I attempted to use `NDSolve` for the 1-D isentropic unsteady flow equations with low subsonic inflow velocity and prescribed inflow total enthalpy; along with a non-reflective subsonic outflow boundary condition (BC) based on the method of characteristics. The latter BC is commonly used in Computational Fluid Dynamics (CFD) and in Computational Aero-Acoustics. `NDSolve` rejects this BC outright in Mathematica 9.0.1. **Code:** Auxiliary Eq's and parameters.               gamma = 1.4;     sigma = 0.25;     uInfty = 0.02;     M$ref = uInfty/Sqrt[gamma - 1];         dhInfty = (-(1/2)) uInfty^2;         h[x_, t_] := 1 + dh[x, t];         c[x_, t_] := ((gamma - 1)*h[x, t])^(1/2);         k = sigma*(1 - M$ref^2);     rule = {      residu -> D[dh[x, t] + (1/2)*u[x, t]^2, x],      residh -> u[x, t]*D[dh[x, t], x] + (gamma - 1)*D[u[x, t], x]};      PDE's for dependent variables `u` and `dh` vs. x and t.               AllEqs = {      ueqn -> D[u[x, t], t] + residu == 0,      dheqn -> D[dh[x, t], t] + residh == 0} /. rule;      BC and IC.               BCICRules = {      bcInFlow -> {(*Inflow Boundary x=0 (subsonic)*)       u[0, t] == uInfty,       dh[0, t] + (1/2)*u[0, t]^2 == 0},      bcOutFlow -> {(*Outflow Boundary x=1 (subsonic, non-reflective)*)       Derivative[0, 1][dh][1, t] - c[1, t]*Derivative[0, 1][u][1, t] +         k*c[1, t]*(dh[1, t] - dhInfty) == 0},      ic -> {(*IC*)        u[x, 0] == (1 - x)*uInfty,        dh[x, 0] == (1 - x)*dhInfty}     };      **Error:** Solve the equations numerically to steady state               NDSolve[Flatten@({ueqn, dheqn, bcInFlow, bcOutFlow, ic} /. AllEqs /. BCICRules),      {dh[x, t], u[x, t]}, {t, 0, 3.}, {x, 0, 1.}]      Following error occurs! > `NDSolve::bdord: Boundary condition 0.157956 (0.0002 +dh[1,t]) > Sqrt[1+dh[1,t]]+(dh^(0,1))[1,t]-0.632456 Sqrt[1+dh[1,t]] (u^(0,1))[1,t] > should have derivatives of order lower than the differential order of the > partial differential equation. >>` **Observation:**   * The reason for failure is `bcOutFlow` specification. Changing it to the following by vanishing the time derivatives results into a solution without any complain. New `bcOutFlow`.               bcOutFlow -> {       Derivative[0, 0][dh][1, t] - c[1, t]*Derivative[0, 0][u][1, t] +        k*c[1, t]*(dh[1, t] - dhInfty) == 0}      Here is the plot.               Plot3D[Evaluate[{#[x, t]} /. soln0], {t, 0, 3}, {x, 0, 1},      Mesh -> None, ColorFunction -> "DarkRainbow",      PlotStyle -> Opacity[.7], PlotPoints -> 40, ImageSize -> 400,      PlotLabel -> #] & /@ {dh, u} // Row      ![enter image description here](http://i.stack.imgur.com/El64a.png)   * Above error states that BC is not allowed to contain time derivatives of the same order as the time derivatives in the PDE's (namely, first-order time derivatives). _THIS CLAIM IS PATENTLY INCORRECT FOR THE COMPRESSIBLE FLOW EQUATIONS_. The non-reflective boundary condition containing time derivatives is widely used, as anyone can verify from the CFD literature of the past two decades.   * I had hoped that, within Mathematica's Method of Lines, the non-reflective outflow boundary condition should just give rise to another ODE in time at the outflow-boundary grid point, x=1. That ODE should be coupled automatically to those at the interior grid points through the stencil of the built-in default spatial differencing scheme.   * The pre-test has caused Mathematica to give the `NDSolve::bdord:` error and reject the problem outright. If the pre-test were bypassed, then there might be hope that `NDSolve` would translate the time-derivative outflow boundary condition into a time-dependent ODE for the dependent variables at the boundary grid point, x=1. It could then go forward with the numerical integration of the ODE system. **Question**   1. Does anyone out there know of a way to circumvent this difficulty with the NDSolve implementation in MA 9.0.1?    2. Specifically, does anyone know if it is possible to bypass NDSolve's pre-test for derivatives in the boundary conditions?   3. Any suggestion how to accommodate reflective BC for a PDE like the above one in Mathematica?


Possible to draw an Item in a Grid with only 3 sides of a Frame?

I'm trying to draw a `Grid` of characters where some of the characters have `Frame` lines on 3 sides. For example:                 +   +     x | x | x       +---+      x   x   x          x   x   x      That's something like a `Grid[item = Table[x,{3},{3}]]`, except with `item[[1,2]] = Item[x,FrameStyle->{{White,Black},{Black,Black}}]`, except that produces a complete box around the `x` for me. When the documentation says: > `FrameStyle->{{left,right},{bottom,top}}` specifies that different sides of > a graphics frame should be drawn with different styles. I fear that the "...of a graphics frame..." part means that this will work for a `Plot`, but not for a `Grid`. Is there a way to style a frame such that I only draw three edges of it? It doesn't have to be pretty--I'm planning on generating the `Grid` from some data that I have lying around.


Coulomb potential as a Fourier transform

It is well known from theory that the Coulomb potential can be obtained as a Fourier transform in the following way: $$ \int \frac{\mathrm{d}^3p}{\left( 2 \pi \right)^3} \frac{e^{\mathrm{i} \mathbf{p} \cdot \mathbf{r}}}{\mathbf{p}^2+m^2} = \frac{e^{-rm}}{4 \pi r} \hspace{20pt} r \equiv \sqrt{x^2+y^2+z^2}$$ (The mass term is here for mathematical convergence reasons, one can set the mass to zero after the transform. The Fourier transform also has a precise physical meaning, but that's out of the scope of this question.) I am trying to reproduce this result with Wolfram Mathematica; skipping some unnecessary constants I use the following code:               FourierTransform[1/(k*k + q*q + r*r + m*m), {k, q, r}, {x, y, z}]      which does not yield the expected result... I'm not an expert of Mathematica, by any means, but I cannot see why it gets this Fourier transform wrong.


Adding rules to permutations

How can I calculate only those permutations of `Range[n]`, that satisfy certain rules? I don't want to filter the result after calculating all the permutations but adding some rules during the calculation of the permutations. I will explain better.               Permutations[Range[4]]={{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}, {1, 3, 4, 2},        {1, 4, 2, 3}, {1, 4, 3, 2}, {2, 1, 3, 4}, {2, 1, 4, 3}, {2, 3, 1, 4}, {2, 3, 4,      1}, {2, 4, 1, 3}, {2, 4, 3, 1}, {3, 1, 2, 4}, {3, 1, 4, 2}, {3,       2, 1, 4}, {3, 2, 4, 1}, {3, 4, 1, 2}, {3, 4, 2, 1}, {4, 1, 2,        3}, {4, 1, 3, 2}, {4, 2, 1, 3}, {4, 2, 3, 1}, {4, 3, 1, 2}, {4, 3,        2, 1}}      I want to wash out permutations where at the second position is 2 for example, but not after the calculation of all the permutations but during. I want all the permutations with some particular rules. I need that because I have to filter permutations with an high rank in principle. The rules I need are of the following kind: "#[[1]] not equal to 4". The code below is very slow for range=10. I need to arrive to range 64.


initialize Manipulate with different selection

Is it possible, and if so, how, to initialize the value of h when the value of g is changed, in the following Manipulate:               Manipulate[      h = t^2;      Grid@{{"t =", t},        {"h =", h}}      , {{t, 2}, {2, 3, 5, 10}}      , Button["give h", {}]      ]      At the moment, when changing the value of t, the value of h is automatically updated. I now wish to initialize the value of h to, let's say, 0, when the value of t is changed. The value of h should be updated when clicked on the `Button`, which is at this moment inactive. What am I missing to accomplish this? Thanks for all help, as always!


Changing ParametricNDSolveValue options for only part of the run

Here is an example of the system that I am running,               eqns = {y'[t] == y[t] (x[t] - 1), x'[t] == x[t] (a - y[t]), x[0] == 1,y[0] == 2.7};     tmax = 100;     pfun = ParametricNDSolveValue[eqns, Integrate[y[t], {t, 0, tmax}] , {t, 0, tmax},{a}];     Plot[pfun[a], {a, 0, 1}, AxesLabel -> {"a", "y"}]      and for a particular range of the parameter, "a", I get numerical giberish as shown here: ![enter image description here](http://i.stack.imgur.com/VWl5v.png) To check what is going on in this region I looked at the timeseries of x and y for different values of "a". If you plot example timeseries for "a" values higher than the numerical noise you get nice oscillating curves ![enter image description here](http://i.stack.imgur.com/HSEWe.png) This was found using this code:               tmax = 100;     amin = 1;     amax = 3;     aint = 1;     eqns1[a_] := {y'[t]==y[t] (x[t] - 1), x'[t]==x[t] (a - y[t]), x[0]==1, y[0]==2.7};     pn1 = ParametricNDSolveValue[eqns1[a], x, {t, 0, tmax}, {a}]     pn2 = ParametricNDSolveValue[eqns1[a], y, {t, 0, tmax}, {a}]          plt1 =Plot[Evaluate[Table[pn1[a][t],{a,amin,amax,aint}]], {t,0,tmax},PlotRange-> All];     plt2 =Plot[Evaluate[Table[pn2[a][t],{a,amin,amax,aint}]], {t,0,tmax},PlotLegends->       Range[amin, amax, aint], PlotRange -> All];     GraphicsRow[{plt1, plt2}]      However, to get the timeseries to plot for the `a` values around the noise, i.e. between 0 and 0.1, I had to add `Workingprecision-> 20` and `Method-> "LSODA"` into `pn1` and `pn2` (into the `ParametricNDSolveValue` options). Which nicely renders the curves ![enter image description here](http://i.stack.imgur.com/YmAcp.png) So the problem is that these options are not necessary for all the "a" values when I plot pfun above. In fact, if I include these options into my real system (which is larger) the whole plot takes exponentially longer to finish. So I would like to turn on these options for only some "a" values and not others, when I make a plot of pfun. Or use another trick you might know. I would greatly appreciate any suggestions on how to do this, or other comments. Thank you.


Solving Det[matrix] == 0 with an 8 x 8 matrix

I want to solve the equation Det[matrix] == 0 which came from the consistency of solutions of a set of 8 equations. This matrix has two constants λ and μ and two variables $P$ and $q$. I want to get the plot of $P$ as a function of $q$, but the result of secular equation is giving a large output, and `NSolve` is not able to give a solution showing the error. > Solve::tdep: The equations appear to involve the variables to be solved for > in an essentially non-algebraic way. I am pasting the input form for the matrix here where I have already put the values for λ and μ. Please tell how to proceed. Ask for any clarifications. Please edit the title if you can make it more clear.                   {1, 1, 0, 0, -1, -1, -1, -1}, {0, 0, 1, 1, -1, 1, 1, -1}, {P, -P, -2, -2,          -Sqrt[1   +  P^2 + Sqrt[1 + 2*P^2]],          Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]], -Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]],          Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]]},          {-2, -2, P, -P, -Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]], -Sqrt[            1 + P^2 + Sqrt[1 + 2*P^2]], Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]], Sqrt[1 + P^2 -Sqrt[1 + 2*P^2]]},         {E^((0.5*I)*P), E^((-0.5*I)*P), 0,          0, -E^(I*(-0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] +           q)), -E^(I*(0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] +           q)), -E^(I*(-0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] +           q)), -E^(I*(0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))},        {0, 0, E^((0.5*I)*P),         E^((-0.5*I)*P), -E^(I*(-0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q)),         E^(I*(0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q)),        E^(I*(-0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] +          q)), -E^(I*(0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))},        {E^((0.5*I)*P)*P, -(P/E^((0.5*I)*P)), -2*E^((0.5*I)*P), -2/       E^((0.5*I)*P), -(E^(I*(-0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q))*       Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]]),       E^(I*(0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q))*      Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]],       -(E^(I*(-0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))*       Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]]),       E^(I*(0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))*      Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]]},       {-2*E^((0.5*I)*P), -2/E^((0.5*I)*P),       E^((0.5*I)*P)*      P, -(P/E^((0.5*I)*          P)), -(E^(I*(-0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q))*       Sqrt[1 + P^2 +          Sqrt[1 +           2*P^2]]), -(E^(I*(0.5*Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]] + q))*      Sqrt[1 + P^2 + Sqrt[1 + 2*P^2]]),       E^(I*(-0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))*       Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]],       E^(I*(0.5*Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]] + q))*      Sqrt[1 + P^2 - Sqrt[1 + 2*P^2]]}}


Items known by CurrentValue

`CurrentValue` can be used to poll the state of numerous system values such as the mouse position. Its help page doesn't list all possible items, though. An item like `"TooltipFontFamily"` isn't listed but it works nevertheless:               In[49]:= CurrentValue["TooltipFontFamily"]         Out[49]= "Segoe UI"      My question is: where can I find a (more) complete list of items that can be used with `CurrentValue`. Or, alternatively, how could I programmatically generate such a list? * * * **EDIT** Based on John Fultz' answer I wrote the following:               Union[      Flatten[       Cases[            Import[#], HoldPattern[CurrentValue[a_]] :> a, Infinity            ] & /@ FileNames[#] & /@        {         FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd",                "StyleSheets", "*.nb"}],             FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd",                "TextResources", "*.nb"}],             FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd",            "SystemResources", "*.nb"}]         },       2       ]      ]      and got this:               (*     ==>      {CommandKey, ControlKey, ControlsFontFamily, ControlsFontSize,       DefaultButtonSize,       DefaultNewGraphics, HyperlinkModifierKey, LicenseValid, MenuFontFamily,       MouseButtonTest, MouseClickCount, MouseOver, NotebookSelected, OptionKey,       PanelBackground, PanelFontFamily, PanelFontSize, ScreenArea, ShiftKey,       ToolbarBackground, TooltipFontFamily, TooltipFontSize, TooltipFrameMargins,       Enabled, Language, {ControlsFontSize, Large}, {ControlsFontSize, Medium},       {ControlsFontSize, Small}, {SystemColor, DialogText},      {SystemColor,DialogTextDisabled}, {SystemColor, MenuText},       {SystemColor, Tooltip}, {SystemColor, TooltipFrame},       {SystemColor, TooltipText}, {TaggingRules, Highlight},       {ScreenRectangle, 1, 2}, {ScreenRectangle, 2, 2}}     *)      in addition to a message complaining about:               Syntax::sntufn: Unknown unicode longname NumberComma.      * * * Other items known by `CurrentValue` (not in the list above) that were used in answers/comments here:   * As per this comment by celtschk:              {"Thickness", "Opacity", "Dashing", "FontFamily", "FontSize", "FontSlant",      "FontWeight", "FontColor", "FontOpacity"}


Memory efficient generation and selection of tuples

The short of this question: I need to find a bunch of n-tuples of {0,1} which do not fail to satisfy a set of (non-linear polynomial) equations, without hogging up all of my memory by trying to generate every possible n-tuple before eliminating the bad ones. This set of 'not bad' n-tuples should be substantially smaller than every possible n-tuple for the problem I am working on. The long of this question: I have a system of non-linear (polynomial) equations I want to solve; indeed, multiple such systems, each one corresponding to a separate case of interest to a larger problem. Simply using Mathematica's built-in `Solve` function isn't very effective, as it quickly consumes memory and then run's at a snail's pace trying to work its way through the problem without consuming extra memory. Thankfully, the systems I'm working with have a couple of nice properties which give a more efficient workaround (indeed, my current method converts what could have taken days with `Solve` into mere minutes). The one of relevance here is that, if I call the variables in the system `d[i]`, then it turns out there are a fair number of equations of the form `d[i]^2==d[i]`, which means all of those variables have to be either 0's or 1's. I am currently using `Tuples` to generate every possible substitution, and then proceeding to eliminate all of those which cannot satisfy the equations. However, this gets extremely memory intensive pretty fast. Even 'small examples' lead to insufficient memory errors at this stage, as they can have up to a few dozen of these squaring relations in each list of equations (and there can be half-dozen or more such lists in a 'small' example). There may be a number of ways to improve the efficiency of my code, as I'm still fairly new to advanced Mathematica programming, but mostly I am looking for ways to keep the memory demands down without drastically inflating computation time. Before getting to this stage, I generate a nested list of equations I'm interested in, denoted `CubeReduced2` (the equations end up being degree 2 multinomials; the reason for the 'cube' is not particularly germane here). The equations are all stored on the final level; the preceding levels effectively serve as markers of which case I'm looking at it, and do not store any other data. I am attempting to solve many possible systems without having to do them individually, especially when I have no advanced knowledge of how many systems there will be. This is the code I am currently using to generate all possible combinations of 0/1 substitutions for these variables               SelfSquares = Flatten[Map[Reap[Do[If[MemberQ[#, d[i]^2 == d[i], Sow[i]],      {i, 1, varnum}]][[2]]&, CubeReduced2, {2}], {{1}, {2}, {3, 4}}];     SquarePossibilities =       ParallelTable[       Tuples[{0, 1}, Length[SelfSquares[[m]][[i]]]], {m, 1,         Length[CubeReduced2]}, {i, 1, Length[CubeReduced2[[m]]]}];     SquareReplaces =       ParallelTable[       Map[Table[          d[SelfSquares[[m]][[i]][[j]]]] -> #[[j]], {j, 1,            Length[SelfSquares[[m]][[i]]]}] &,         SquarePossibilities[[m]][[i]]], {m, 1, Length[SquarePossibilities]}, {i, 1,         Length[SquarePossibilities[[m]]]}];      The `SquarePossibilities` stage is where my system memory quickly vanishes. I `Remove` it after generating SquareReplaces, but when I can't even build the list that doesn't help any. I would then use the following code to eliminate the tuples which definitely won't work:               SquareReplaces2 =        ParallelTable[        Select[SquareReplaces[[m]][[          i]], (And @@             Map[! TrueQ[# == False] &, ((CubeReduced2[[m]][[                 i]]) /. (#))]) &], {m, 1, Length[CubeReduced2]}, {i, 1,          Length[CubeReduced2[[m]]]}];      There may be non-trivial equations left after apply the replacements, which will still need to be solved for. That's why I don't simply look for every equation to evaluate to True, but simply look for those tuples which don't produce a False. Hopefully this explanation is sufficient at this point to describe what I'm trying to accomplish. I'd provide a sample list of equations I have applied this code to (succesfully), but right now my mathematica has the variables as $d_i$, which don't translate very well into an easy copy-paste. I'll try to fix that if a relevant example is desired.


DeleteCases vs. DeleteDuplicates for removing points within a critical Euclidean distance

I'm attempting to remove all points in an array which are within a Euclidean distance "ThresDist" of one-another. Using the command:               DeleteDuplicates[List, EuclideanDistance[#1, #2] <= ThresDist &];      I can remove one point in a pair of points that fall within a distance "ThresDist" of one-another. However:               DeleteCases[List, EuclideanDistance[#1, #2] <= ThresDist  &];      Fails to work similarly. Is there something wrong with my approach? Note : I made a typo earlier in writing DeleteCases, and also used a poor variable name. This was sloppy of me. As for the actual question - how might I best accomplish my goal? I've searched through Mathematica's function directory, and I can't seem to find an appropriate way to prune not just a duplicate point, but all points that fall within a threshold distance of one-another?


How to set the ratio between the vertical and horizontal scales of plots?

The documentation says that when `AspectRatio->Automatic` is specified, Mathematica > determines the ratio of height to width from the actual coordinate values in > the plot. When doing this, Mathematica treats the units in the vertical and horizontal axes as having the same length on the screen. This is reasonable when the units for both axes are the same (e.g., light- years), but not necessarily so when the units for the two axes are incommensurable (e.g. luminosity vs. seconds of arc), or when the extents in the two dimensions are vastly different (which, with `AspectRatio->Automatic`, would correspond to an effective aspect ratio close to 0 or infinity). For such situations I would like a convenient way to set the aspect ratio equal to $r\times A$, where $r$ is a scaling factor of my choosing, and $A$ is the aspect ratio computed per the usual `AspectRatio->Automatic` rules. _**Does Mathematica offer a way to do this?_** * * * In case the description above is not sufficiently clear, here's an example. First I generate some synthetic data.               data = With[{n = 50},       {         {RandomReal[{-35, -30}, n], RandomInteger[{-20100, -20000}, n]}\[Transpose],         {RandomReal[{0, 5}, n], RandomInteger[{0, 80}, n]}\[Transpose]       }     ];      In the horizontal direction, for both datasets the range extends over about 5 units, but in the vertical direction, the ranges extend over ca. 100 and 80 units, respectively. This would correspond to $A = 20$ and $A = 16$, respectively (see above for the definition of $A$). But let's suppose I want $r = 0.25$ (i.e. I want the vertical units to have only one-quarter of the screen length of the horizontal ones). If so, then the desired aspect ratios for the two datasets would be 5 and 4, respectively. In any case, here are the plots that get produced with `AspectRatio->Automatic`, showing the unscaled aspect ratios ($A = 20$ and $A=16$) just mentioned1:               ListPlot[#, AspectRatio -> Automatic, Frame -> True,               FrameTicks -> {None, Automatic}] & /@ data      ![Mathematica graphics](http://i.stack.imgur.com/iNaoM.png) For this example, of course, the calculation of the desired aspect ratio $r A$ was relatively straightforward, since I've concocted datasets having specific values of $A$. In general, however, I don't want to have to figure out $A$ for every plot. * * * BTW, in case anyone wonders, specifying $r$ as `AspectRatio` won't do it:               ListPlot[#, AspectRatio -> 0.25, Frame -> True,              FrameTicks -> {None, Automatic}] & /@ data      ![Mathematica graphics](http://i.stack.imgur.com/OvpzX.png) * * * 1 I show two plots in this example because the main motivation for wanting to control the relative sizes of axis units is to make different plots readily comparable, even when they are not plotted as part of, say, a grid. As it happens, I find the plots shown above unsatisfactory not only because they don't have the desired aspect ratios, but also because their relative sizes are not directly comparable (for this the two plots should have same width, and the one on the right should be 80% as tall as the one on the left). Of course, this second problem is a separate issue altogether, but I mention it here only FWIW, by way of additional background, and to increase the chance that any answer I get for the thread's question is not one that makes solving this second problem unnecessarily difficult.


Series expansion in terms of Hermite polynomials

I am trying to expand a polynomial in terms of orthogonal polynomials (in my case, Hermite). Maple has a nice built-in function for this, `ChangeBasis`. Is there a similar function in _Mathematica_? And if not, where should I look for the algorithm?


Lightweight Grid preferences screen stopped working after v10 install

I am getting the following error when I try to open the Lightweight Grid "Preferences" tab...               JLink`Java::excptn: A Java exception occurred: java.lang.NoClassDefFoundError: Could not initialize class ch.qos.logback.classic.PatternLayout         at com.wolfram.remoteservices.client.impl.LogbackProxy.configureDefaultLogging(LogbackProxy.java:68)         at com.wolfram.remoteservices.client.impl.LogbackProxy.configure(LogbackProxy.java:47)         at com.wolfram.remoteservices.client.impl.RemoteServicesClientImpl.configureLogging(RemoteServicesClientImpl.java:1378)         at com.wolfram.remoteservices.client.impl.RemoteServicesClientImpl.<init>(RemoteServicesClientImpl.java:74)         at com.wolfram.remoteservices.client.impl.RemoteServicesClientImpl.<init>(RemoteServicesClientImpl.java:69)         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)         at java.lang.reflect.Constructor.newInstance(Unknown Source)         at java.lang.Class.newInstance0(Unknown Source)         at java.lang.Class.newInstance(Unknown Source)         at com.wolfram.remoteservices.client.RemoteServicesClientFactory.createClient(RemoteServicesClientFactory.java:73).      Here are some pertinent details:   * I started getting the error after installing version 10   * I get this same error on version 9 too, which used to work fine   * I copied the logback classic jar file on the JLink` default classpath... no effect   * I tried reinstalling Lightweight Grid to no avail... Is anybody having these same problems? Does anybody have an idea what's up?


How can we suppress the asymptotic notation in Series?

`Series` expands a function, and also gives an idea of the asymptotic bounds of the function: Series[$\frac{1-x^3}{1-x}$] returns: $1 + x + x^2 + O(x)^5$ I'd like to eliminate the big-Oh notation, to get, for example: $1 + x + x^2$ How can we eliminate/suppress the asymptotic bounds that `Series` returns?


NMinimize problem again

Following up my previous question which got great replies, I am now trying to do               NMinimize[{1/2 + Sqrt[2] Sqrt[n] - Ceiling[1/2 (-1 + Sqrt[1 + 8 n])],  n > 4}, n]      It gives me the answer `0.328427`.               NMinimize[{1/2 + Sqrt[2] Sqrt[n] - Ceiling[1/2 (-1 + Sqrt[1 + 8 n])],  n > 5}, n]      gives me `-0.0358984` and so it goes on if I change the range or add upper bounds for n as well. Is there any way to get a minimum with any confidence? My guess is that the true minimum for n > 4 is 2*(sqrt(3)-2).


Explore a nested list

This question is similar to Numbering nested list according with Depth (or Level) I have a list like               list = {"A" -> {"a1", "a2"}, "B" -> {"b1"->{"z1","z2"},"b2" -> {"z3","z4"}},"C" -> {"c1" -> {"cc1"-> {"x","y"}, "cc2" -> {"x1", "x2"}},"c2" -> {"xx", "yy"}, "c3" ->{"u","v", "w"}}};      And I would like to build a function that help me navigate it, according to the depth, like in               Navigate[list,1] = {"A","B","C"}     Navigate[list,2] = {"A" -> {"a1", "a2"},  "B" -> {"b1", "b2"}, "C" -> {"c1", "c2", "c3"}}     Navigate[list,3] = {"A" -> {"a1", "a2"},  "B" -> {"b1" -> {"z1","z2"}, "b2" -> {"z3","z4"}}, "C" -> {"c1" -> {"cc1","cc2"}, "c2" ->{"xx", "yy"}, "c3" ->{"u","v", "w"}}}      and so on. By hands I have a solution for small depth, but since the list can be arbitrary nested I think I need a nested approach


Computing the sign of the real part of eigenvalues in a 3D linearized system with 3 parameters

So I have this dynamical system given by: $$ \left\{\begin{aligned} x' &= a(y-\phi(x))\\ y' &= x-y+z\\ z' &= -by \end{aligned}\right. $$ where $\phi(x) = \mu x^3 - \nu x$ and $a,b,\mu,\nu$ are positive real parameters. Obviously, the origin is an equilibrium point. I now want to determine what kind of equilibrium this is, which depends on the signs of the real parts of the eigenvalues of the matrix of the linearized system. The linearized system is given by: $$ X'=AX\\ A=\begin{pmatrix} a\nu & a & 0\\ 1 & -1 & 1\\ 0 & -b & 0 \end{pmatrix} $$ The characteristic polynomial is then given by: $$ p(\lambda)_{a,b,s} = -\lambda^3 + (a\nu-1)\lambda^2 + (a\nu-b+a)\lambda + ab\nu $$ which is pure hell to solve (which may have something to do with the fact that this family of systems is chaotic...). Anyway, I tried throwing this into Mathematica and it just spits out about 4 pages of symbols. Then I tried `Reduce` in order to find out whether these eigenvalues had negative or positive real parts. Sadly, this gives me about 15 pages of symbols, which doesn't really help. Does anybody know a good way to deal with this? # Tl;Dr How can I compute the signs of the real parts of above matrix A, for all possible values of $a,b,\nu>0$? Criteria for them to be positive will also do. # Edit I tried the following input:               A[a_, b_, \[Sigma]_] := {{a*\[Sigma], a, 0}, {1, -1, 1}, {0, -b, 0}}     eig[a_, b_, \[Sigma]_] := Eigensystem[A[a, b, \[Sigma]]]     Table[Reduce[eig[a, b, \[Sigma]][[1]][[i]] > 0, {a, b, \[Sigma]}, Reals], {i, 1, 3}]      The output is displayed by Mathematica as:               A very large output was generated. Here is a sample of it:     {<<1>>, <<1>>, <<1>>}      Basically it is a list with a lot of different cases. This is of course to be expected, but the real problem is that there are tons of `Root`s in it...


Are there advantages to using generalized Part extraction instead of specialized functions like First, Last?

There are many ways to extract different parts of lists in Mathematica. For example, the first part of a list `v` can be accessed either as `v[[1]]` or `First[v]` or `Take[v,1]`. Likewise the last element can be accessed as `v[[-1]]`, `Last[v]` or `Take[v,-1]`. Similarly `v[[2;;]]` is equivalent to `Rest[v]` and to `Drop[v,1]`, and `v[[;;-2]]` is equivalent to `Most[v]` and `Drop[v,-1]`. The more specialized functions `First`, `Last`, `Rest` and `Most` are marginally more efficient. On the other hand, it makes sense to use the more general `Part` (`[[ ]]`) or `Take`/`Drop` if it is part of a calculation that also requires parts to be accessed that do not have a specialist function. Beyond these considerations, are there any reasons to prefer `Part` over `Take`/`Drop` or the more specialized functions, other than personal preferences over coding style?


Strange Error in Bifurcation Diagram:

I am attempting to plot the bifurcation diagram of the _tent map_ $$ f(x):=2\alpha \begin{cases} x, & 0<x<1/2\\ 1-x, &1/2<x<1, \end{cases} $$ i.e., the plot $\alpha$ vs. the limit points of the sequence $x_{n}:=f(x_{n-1})$. I found the following code online to plot the bifurcation diagram of the related logistic map:               ListPlot[ParallelTable[Thread[{r, Nest[r # (1 - #) &,      Range[0, 1, 0.01], 1000]}], {r, 0, 4, 0.01}], PlotStyle -> PointSize[0]]      So naturally, I figured that I could make a simple change to get the bifurcation diagram of the tent map:               ListPlot[ParallelTable[Thread[{r, Nest[2*r*If[0<#<0.5,#, (1 - #)] &,      Range[0, 1, 0.01], 1000]}], {r, 0, 1, 0.01}], PlotStyle -> PointSize[0]]      But it doesn't work! Is there a simple change I can make to get this guy to work?


Plugging values into functions

I am very new to _Mathematica_ , and need to know how to plug values into existing functions. For example, Math World supplies the following code for building a truth table of `n` levels of operator `op`:               TruthTable[op_, n_] :=      Module[{l =       Flatten[Outer[List, Sequence @@ Table[{True, False}, {n}]],        n - 1], a = Array[A, n]},      DisplayForm[     GridBox[Prepend[Append[#, op @@ #] & /@ l, Append[a, op @@ a]],       RowLines -> True, ColumnLines -> True]]]      How do I set the operator and the value of `n`?


What's wrong with my implementation on CountryData

I was wondering, *for which countries is the proportion of _Phone line users to population greater than or equal to that of the United States_?* This is what I inputted below, but the list of countries seem too great.               countries=Last/@Take[Reverse[Sort[{CountryData[#,"PhoneLines"], #} & /@CountryData[]]], All]      Someone suggested I use "Select", but I have difficulties wording it.


Unsaved notebook is crashing: is there any way I can save the state of the MathKernel before I kill it?

So I'm in the middle of generating some plots and all of the sudden the frontend goes dead and I haven't saved my work. I'm using Mathematica 8 in MacOS X. The MathKernel process is still running and I'm hoping to be able to extract the In/Out history from it through Terminal. Is there a way to do this?


Emulating a button push or a mouse click with Mathematica code

I need to perform a long action with a button. I tried setting the `DynamicEvaluationTimeout`, but it seems it doesn't work for me. So I want to try using several buttons to compute pieces of the whole task and here's where my problem starts: How to tell _Mathematica_ that a button should be pressed (or have its action performed) without actually pressing the button by user? Is there a way to emulate such a thing from within the code? I need to use the preemptive link, so `Method -> "Queued"` is not the solution I'm looking for.


Function not recognized by Mathematica?

I'm trying to do triple integration on a bivariate function where one of the upper integration limits is the variable of the outer-most integration. When I execute the following lines, _Mathematica_ takes too long and also returned a not-so-useful answer. This is what I have written so far.                F[θ_, α_, β_] := CopulaDistribution[{"GumbelHougaard", θ},                            {ExponentialDistribution[α],ExponentialDistribution[β]}];      GumExpExp[x_, s_] := PDF[F[θ, α, β], {x, s}] //FullSimplify          M = β Integrate[Exp[(-δ)*(T - s + u)] x GumExpExp[x, u],                     {s, 0, T}, {u, 0, s}, {x, 1, 10}]      And this is what _Mathematica_ returns to me: > >     NIntegrate::slwcon: Numerical integration converging too slowly; suspect > one of the >     following: singularity, value of the integration is 0, highly > oscillatory integrand, >     or WorkingPrecision too small. >> >   $$ \ \beta \int_0^T\int_0^s\int_0^\infty e^{-\delta (T-s+u)}x GumExpExp[x,u]dxduds\ $$ (with $GumExpExp(x,s)$ replaced by the long expression defined in `GumExpExp[x_,s_]`). What is wrong with my function/code? Function `GumExpExp` (pdf of F) does exist. We may assume values of `theta = 1.5`, `alpha = 0.1`, `beta = 10`, and `delta =0.04`. I'd like to obtain a numerical answer to this problem.


Quality control when exporting graphics into JPG

If I export a graphics from Mathematica to JPG format the image quality in JPG is visibly lower than that in Mathematica. Is it possible to control and eventually increase the quality of the exported to JPG graphics? To be precise, I need to make a 3D image out of a list obtained by a simulation using another software, but post-processed in Mathematica. My original list is too large. For this example let us take this:               lst = RandomReal[{-5, 5}, {10000, 3}] /. {x_, y_, z_} -> {x, y,       Exp[-(x^2 + y^2)/3] + 0.0001*z};      I make the graphics and export it into the PDF file using these standard operations:                   pl1 = ListPlot3D[lst, PlotRange -> All,        ColorFunction -> Function[{x, y, z}, Hue[0.9 z + 0.1]]]     Export[NotebookDirectory[] <> "exportTrial.jpg", pl1, "JPG"]      My exported file, though not really bad, looks much poorer than the original image visible in Mathematica. Just to explain the awkwardness of the statement of my question. I know that export into, say, PDF file (and some others) makes a much better quality. However, the image I am making will be submitted as an illustration to an article, and the JPG format is the journal requirement that cannot be circumvented. On the other hand, this journal requires a high quality graphics. My secondary question: is it possible to reproduce the effect of the Glow[] function in the exported JPG file? I tried the graphics in such a form:               pl2 = ListPlot3D[lst, PlotRange -> All,        ColorFunction -> Function[{x, y, z}, Glow[Hue[0.9 z + 0.1]]]]          Export[NotebookDirectory[] <> "exportTrial.jpg", pl2, "JPG"]      but the difference between the images with and without Glow quite visible in Mathematica is not really visible in the resulting JPG files. My ultimate aim related to this latter question is to make the image a bit brighter.


Cannot Plot Output of Solve

I'm trying to plot the output of the following function `t2[x_]` in                   n1[x_] := 4 \[Pi]*x + Sin[2 \[Pi] 0.6 x];              t2[x_] := Solve[4 \[Pi] t + Sin[2 \[Pi] 0.6 t ] - n1[x] == 2 \[Pi] && x < t, t];      Now, if I type in a particular value it gives the expected answer:                   t2[1]      > {{t -> 1.5}} But I can't figure out how to input `x` as a continuous variable, or even a discrete list. I've also tried plotting `Evaluate[t2[x]]` and `Plot[x /. t2, {x, 0, 2}]` in all combinations I can think of but I just can't get it to work. Any help would be greatly appreciated, Rick


Plotting 2D image of functions of several variables

I have a function $f: \mathbb{R}^4 \to \mathbb{R}^2$, and I would like to plot the region $f([0,1]^4)$. Writing $f_1(s,t,u,v)$ and $f_2(s,t,u,v)$ for each coordinate of the output I tried using _Mathematica_ 's parametric plotter:               ParametricPlot[{f1[s,t,u,v], f2[s,t,u,v]} , {s,0,1}, {t,0,1}, {u,0,1}, {v,0,1}]      This failed because _Mathematica_ seems to only support parametric plotting in (at most) two parameters. Does anyone know of a work around? For the sake of having a working example, an abbreviated example of my functions is:               f1[s_,t_,u_,v_]:=(s+1/s)(t+1/t)Cos[\[Pi] u/4]Cos[\[Pi] v/4];     f2[s_,t_,u_,v_]:=(s+1/s)(t-1/t)Cos[\[Pi] u/4]Sin[\[Pi] v/4];


Sum of series with log in each term

I was solving recurrence relation of Introduction to Algorithms by CLRS, 3rd. edition. Problem 4-3 (i)   $$ T(n) = T(n-2) + \frac{1}{lg \; n} $$ I tried few ways, like expending with iteration method. With that i came up with the following equations - For even - $$ T(n) = T(0) + \frac{1}{lg \; n} + \frac{1}{lg \; (n-2)} + \frac{1}{lg \; (n-4)} + ... + \frac{1}{lg \; 6} + \frac{1}{lg \; 4} + \frac{1}{lg \; 2} $$ For odd $$ T(n) = T(1) + \frac{1}{lg \; n} + \frac{1}{lg \; (n-2)} + \frac{1}{lg \; (n-4)} + ... + \frac{1}{lg \; 7} + \frac{1}{lg \; 5} + \frac{1}{lg \; 3} $$ We can assume $T(1)=1$ and $T(0) = 1$. So to solve it I need to be able to sum up $$ \sum ^{n}_{i=2} \frac{1}{lg\;i} $$ Some help will be greatly appreciated. Thanks.


What is the complete sequence of evaluations/transformations from submitting a cell to actual evaluation?

This question is inspired by that one. Reading it, I noticed that while (I think) I know what happens when entering an expression directly to the kernel (i.e. after typing `math` in the terminal), the notebook adds extra complications which I don't fully understand. To start with, I describe what I think happens when interacting directly with the Kernel (so you can correct me if I'm wrong):   * After the expression is input, it first is a string, which is passed to `$PreRead` (if set). That function is expected to return a string, which gets assigned to `InString[$Line]`.   * Then this string is parsed (I guess with `MakeExpression`), and the resulting expression assigned to `In[$Line]`   * Then `$Pre` is applied to this expression, if defined.   * Finally, the expression obtained this way is evaluated (After the expression is evaluated, other things happen to generate the output, but that's outside the scope of this question.) Now, for Notebooks, things are obviously more complicated:   * To start with, as far as I understand, the notebook cells contain boxes, not strings. However I noticed that nevertheless `InString` is set. What is not clear to me is whether this string is part of the processing, or if the boxes-to-string conversion is only done in order to set `InString`.   * Next, there's the `Notation` package, which also is involved in the pre-evaluation process. However being a package, I guess it has to hook into some lower-level interface to do its work.   * There's also the fact that notebooks can define their own private contexts. Those contexts also have to somehow be communicated to the kernel. Since expressions from different notebooks can be sent to the kernel in arbitrary order, those contexts need to be associated with the expression, and setting them must thus be part of expression pre-evaluation.   * There might be other things which I'm not aware of. Therefore my question is: What is the exact sequence of events which happens when submitting a notebook cell, as far as customizable behaviour is concerned?


Scalar product operator of complex vectors

What is the scalar product operator for complex vectors (or matrices) in Mathematica? The usual $Dot[]$ doesn't work. E.g. here is what the Mathematica gives $$\{1,0\}.\{I,0\}=I$$ but the answer should be $-I$, since the scalar product of complex vectors is defined as follows: let $$a,b∈C^n \,\,\, then \,\,(a,b)= ∑_{i=1}^na_i \bar b_i$$ where $\bar b_i$ is the complex conjugate of $b_i$.


Most efficient way to output a cycle starting from an unordered list of graph vertices

I have some graph $G$ and a list of vertices $(v_1, ..., v_N) \in V$. Using graph structures in Mathematica version 9.0, what is the most efficient way to determine whether or not $(v_1, ..., v_N)$ represents a cycle, and then, if so, to output a permutation cycle starting from some desired $v_i$? * * * Let me provide a specific example: Say I have a ring of eight vertices where: $v_1 \to v_2$ $v_2 \to v_3$ $v_3 \to v_4$ $v_4 \to v_5$ $v_5 \to v_6$ $v_6 \to v_7$ $v_7 \to v_8$ $v_8 \to v_1$ And also: $v_2 \to v_4$ $v_4 \to v_6$ $v_6 \to v_8$ $v_8 \to v_2$ Say the above list is scrambled (i.e. we randomly assign the vertex labels). Without scrambling things here, and specifying that I want a permutation to start from $v_2$, how would I output a permutation: $(v_2,v_3,v_4,v_5,v_6,v_7,v_8,v_1)$ Scrambling, we could maybe map the labels: $(v_1, v_2, v_3, v_4, v_5, v_6, v_7, v_8)$ to something like: $(v_{1111111111}, v_{11011}, v_{111110011}, v_{100101}, v_{11}, v_{1010111}, v_{111}, v_{101010101})$ where the labels convey no ordering information.


How do I plot a hemisphere on top of a cone

RegionPlot3D[ Sqrt[x^2 + y^2] <= z && x^2 + y^2 + z^2 <= 2, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, Mesh -> None, AxesLabel -> {x, y, z}, PlotRange -> All, PlotPoints -> 120, PlotStyle -> Directive[Yellow, Specularity[White, 20], Opacity[0.8]]]      It gives me the result (Hemisphere on top on a cone ) I want but because I have never taken high level of math courses I do not have any explanation why I use `Sqrt[x^2 + y^2] <= z` as the equation for the cone. I will appreciate your kindness Thanks


How to remove styling from a formatted object?

I have an object of the form `Style[Grid[...,...],...]` What function do I need to apply to it to get the `Grid[...,...]` part only?


Can I reduce a matrix inequality such as $\mathbf x^\prime\mathbf A\mathbf x > \mathbf x^\prime\mathbf x$?

I'm new to _Mathematica_. When I do linear algebra, I wonder if I can have an inequality such as $\mathbf x^\prime\mathbf A\mathbf x > \mathbf x^\prime\mathbf x$, where $\mathbf x$ is a column vector and $\mathbf A$ is an $n\times n$ matrix, reduced to something like "$\mathbf I-(\mathbf A^\ast+\mathbf A)/2$ is positive definite".


How to unprotect GeneratingFunction

I'm trying to add custom downvalues for `GeneratingFunction`, and to do so I thought I just had to `Unprotect` it. However, that doesn't work:               Unprotect[GeneratingFunction]      > >     {"GeneratingFunction"} >                 GeneratingFunction[2] = 3      > >     During evaluation of In[3]:= Set::write: Tag GeneratingFunction in >     GeneratingFunction[2] is Protected. >> >   >      3 >                 GeneratingFunction[2]      > >     During evaluation of In[4]:= GeneratingFunction::argmu: > GeneratingFunction >     called with 1 argument; 3 or more arguments are expected. >> >   >     GeneratingFunction[2] >   I'm running _Mathematica_ 9 64 bit on Linux. What do I need to do to really remove protection from this symbol?


Attempt to Run["inkskape"] fails

I wrote a little script to convert various graphics files (.ps, .eps, .pdf) to the raster ones (.png). `Export[out, Import[in], ImageSize -> size]` fails for some files without any message at an import step: `Import[in] === $Failed` (well, there’s another issue, something wrong with input files, maybe?). Albeit, Inkscape does the work well via `inkscape $in -w $size -e $out -z`. The problem is: _Mathematica_ ’s `Run` doesn’t like Inkscape.               In[]:= Run["inkscape -z file.ps"]     (*     Emergency save activated!     Emergency save completed. Inkscape will close now.     If you can reproduce this crash, please file a bug at www.inkscape.org     with a detailed description of the steps leading to the crash, so we can fix it.     ** Message: Error: Inkscape encountered an internal error and will close now.     *)     Out[]= 139      I tried in a notebook, in a shell mode, in a _Mathematica_ Script. Other GUI programs `Run` properly. A PHP equivalent I had to write               passthru("inkscape $in -w $size -e $out -z")      works well, as do bare bash. What is this hatred between Inkscape and _Mathematica_? Can you reproduce this behaviour? _Mathematica_ 9 at Scientific Linux is used.


Discard functions with wrong symmetry?

I have functions of `x`, where `x` is the polar angle of spherical coordinates, i.e. `0 < x < Pi`. Some of the functions are of even symmetry about the equator `x = Pi/2` (such as `Sin[x]`), and other functions are of odd symmetry about `x = Pi/2` (such as `Sin[x]Cos[x]` ) (Just `Plot` them to see.) Can one use Mathematica to eliminate odd functions from a sum of even and odd functions? For example, as a test, can one eliminate the odd function from the sum `Sin[x] + Sin[x]Cos[x]`?


How to incorporate functions within Do Loops

I'm attempting to repeatedly perform a simple algorithm with incremental changes of a parameter. I can easily express my changing parameter:               Do[a[n] = (10/180*Pi + n/180*Pi);     Print[a[n]], {n, 0, 70, 1}];      Here is what I wish to do for each iteration:               sol =      NDSolve[{y''[t] == -10 - 0.3*(Sin[a]),      y'[0] == 12*Sin[a], y[0] == 0}, y[t], t];     h[t_]=y[t]/.sol;          FindMaximum[h[t],{t,2}]      I think I need to define sol[n_] and incorporate it into a Table function:               sol[n_]= ??     sol2[n_]=FindMaximum[sol[n],{t,2}]         m = Table[{a[n], sol2[n]}, {n, (Pi*10/180), (Pi*80/     180, Pi/180}];      But this is where I've been stuck for a while. Even a greatly simplified example would be very helpful.


Solving a Partial Differential Equation

I am trying to solve the following PDE:               -D[c2*p[c1, c2, w], c1] +        D[((2*Um/L)*c2 + ((Um/L)^2)*c1)*p[c1, c2, w],         c2] + (1/2)*(\[Sigma]^2)*(Um/(L*Pi))*D[p[c1, c2, w], {c2, 2}] -        D[(c2*(1 - 2*Sqrt[3]) - c1*(Sqrt[3]*Um/L))*p[c1, c2, w],         w] + (3/2)*(\[Sigma]^2)*(L/(Um*Pi))*D[p[c1, c2, w], {w, 2}] == 0      for `p[c1, c2, w]`. I also have the following values for the constants:               Um = 4.315;     \[Sigma] = 1;     L = 50;      However, if I can get the solution of this PDE in terms of `Um,\\[Sigma],L` then I would prefer this. I tried `DSolve` but to no avail. I will solve for the constants using appropriate initial and boundary conditions later. Can someone please help.


Can my permutations function be defined using iteration?

I have two functions, `tuples` and `perm`. They are similar.               tuples[L_, 0] := {{}};     tuples[L_, k_] := Join @@ Table[{x}~Join~y, {x, L}, {y, tuples[L, k - 1]}];          perm[L_, 0] := {{}};     perm[L_, k_] := Join @@ Table[{x}~Join~y, {x, L}, {y, perm[Select[L, # != x &], k - 1]}];          (*tuples[{1, 2, 3}, 2]*)     (*{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}*)     (*perm[{1, 2, 3}, 2]*)     (*{{1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2}}*)      I know `tuples` can be defined using `Nest`, but I don't know whether `perm` can be defined using `Nest` or `Fold`.               tuples2[L_, k_] := Nest[Join @@ Table[x~Join~{y}, {x, #}, {y, L}] &, {{}}, k];


Why Plot3D does not accept Epilog option

I am trying to visualize 3D points with Plot3D using the option Epilog. If you check the options of Plot3D ( `Options[Plot3D]` ), it can be seen that Epilog is one of the options of Plot3D. But when implementing this option not result as expected. for example:                 data = Flatten[       Table[{i, j, i^2 + j^2}, {i, -2, 2, .5}, {j, -2, 2, .5}], 1];         Plot3D[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2},           Epilog -> {PointSize[Large], Point[data]}, PlotRange -> All]      Of course there is another ways (like using `Show`), but the question is why Plot3D does not accept its own option?


Whats the most efficient way to solve an equation numericaly (because it has no analitical solution)

So, I think the problem that Im having is simple but, still, Im not sure on how to do it. I have an equation with no analitical solution: $a_1 \sin \left(2 \theta \right)+a_2 \sin \left(2 \phi\right)+a_3 \cos \left(2 \theta\right)+a_4 \cos \left(2 \phi\right)=a_5$ where $a_i$ are just numbers which are not relevant to the discussion. This equation has numerical solutions, what I need is a list $\{\theta,\phi\}$ that satisfy this equation. What would be the best way to do this? Any help will be greatly appreciated.


Best practice to group and have your favorite custom functions available at startup

The mathematica stackexchange site is a treasure trove of great functions that the user community has shared to make the use of mathematica easier. Many of those functions are very useful for daily use. What do you consider, the best practice to collect these functions, and make them available at the startup of a new document?


How to preserve In/Out tags like what they did in documentation files

Every evaluation generates a pair of In[n]/Out[n] signs tagged before actual input and output. Like the following: ![enter image description here](http://i.stack.imgur.com/T846D.png) If I save the file, close it and re-open it, that In[n]/Out[n] signs will disappear (as expected). Like the following: ![enter image description here](http://i.stack.imgur.com/Lf8hJ.png) However, A code example in documentation file will always have its In[n]/Out[n] signs no matter you have computed that piece of code or not. Like the following: ![enter image description here](http://i.stack.imgur.com/GKirh.png) My question is: How to perserve the In[n]/Out[n] signs generated by computation even if I re-open the same file on a fresh kernel? Like what it looks like for documentation files. Maybe it is necessary to use `DumpSave` like stated in this question? Besides, how to access stylesheet of documentation files? If I can apply that style to my code notes would be great.


Why does Fourier give a shifted frequency?

I have a signal that I want to identify the frequencies in it, I used the Fourier function but I can't get the frequency correctly. Here is a simplified example:               dt = 1/100;     ls = Table[0.1 Cos[30 x] + 2 Sin[x]^2, {x, 0, 200 dt, dt}];     ListPlot[ls, Mesh -> All, MeshStyle -> Red]      ![enter image description here](http://i.stack.imgur.com/prPI7.png) and the Fourier transform               ListPlot[Abs[Fourier[ls]]^2, PlotRange -> {{0, 10}, {0, 1}},       DataRange -> {0, 1/dt},       FrameLabel -> {"Frequency", "Intensity"},       Mesh -> All, MeshStyle -> Red, GridLines -> {{30/(2 π)}, None}]      ![enter image description here](http://i.stack.imgur.com/bjQIX.png) Why do I get the peak not at the original frequency 30/(2Pi), but with a frequency shift? Did I make a terrible mistake? What's the correct way to recover the original frequency using Mathematica's signal processing features? I tried to padding zeros but still have a frequency shift.               ListPlot[Abs[Fourier[PadRight[ls, 2000]]]^2,       PlotRange -> {{0, 10}, {0, .1}}, DataRange -> {0, 1/dt},       FrameLabel -> {"Frequency", "Intensity"},       Mesh -> All, MeshStyle -> Red, GridLines -> {{30/(2 π)}, None}]      ![enter image description here](http://i.stack.imgur.com/MzmWY.png) **Edit** I'm still not convinced that this problem is due to that there are too few periods contains in the signal, nor that number of periods contained in the signal is not an integer. Consider this signal               ls = Table[0.1 Cos[30 x], {x, 0, 200 dt, dt}];      it contains the same number of periods and the number of periods is not an integer, it gives a peak that are not centered,               ListPlot[Abs[Fourier[ls]]^2, PlotRange -> {{0, 10}, {0, 1}},       DataRange -> {0, 1/dt},       FrameLabel -> {"Frequency", "Intensity"},       Mesh -> All, MeshStyle -> Red, GridLines -> {{30/(2 π)}, None}]      ![enter image description here](http://i.stack.imgur.com/6sxcQ.png) but padding zero helps               ListPlot[Abs[Fourier[PadRight[ls, 2000]]]^2,       PlotRange -> {{0, 10}, {0, .1}}, DataRange -> {0, 1/dt},       FrameLabel -> {"Frequency", "Intensity"},       Mesh -> All, MeshStyle -> Red, GridLines -> {{30/(2 π)}, None}]      ![enter image description here](http://i.stack.imgur.com/99Xu2.png)


Change the legend labels' font when PlotLegends is Automatic

I am using the options `PlotTheme -> "Scientific"` and `PlotLegends -> Placed[Automatic, Right]` on a `MatrixPlot` and I would like to change the font size of the legend labels. I would usually do that by specifying               BarLegend[{"LakeColors", {0, 1}}, LabelStyle -> {FontSize -> 20}]      but   * I don't know the color function used by the base theme `"Scientific"` and   * I would like to keep the range of min and max values `{0,1}` as `Automatic` What would be the best way to change the legend font in this case?


Highlight selected curve on the plot

I have several curves on the same parametric 3D plot and I would like to highlight some curves dynamically by choosing them from list.                sol = Solve[ 2 x + 2 x^2 - 3 x^3 + 26 x^4 + 32 x^5 + 21 x^6 - 18 x^7 == r, {x}];      lolAux[r_] = x /. sol;      ParametricPlot3D[         Table[{r, lolAux[r][[i]] // Re, lolAux[r][[i]] // Im}, {i, 1, Length[sol]}],       {r, -5, 5}, BoxRatios -> {1, 1, 1}]      ![enter image description here](http://i.stack.imgur.com/Jdcdn.png) How it is possible?


How to run Mathematica kernel on remote server?

This might be a really stupid question, but I have no idea how to get my copy of Mathematica to run on a remote server in the cloud. I have a Webfaction account and a copy of Mathematica installed on my computer, but I don't know how to actually set up, install and run a Mathematica kernel in the cloud. I understand that beginners' questions are generally not well received on Stack Exchange, so just a pointer to a site or page where I could find instructions would be enough. I've tried finding some myself but have come up completely blank. Thank you


Correct way to integrate a certain function

I want to integrate $$ \int_{0}^{2\pi} dt_1 \frac{a + b*\cos(t_1 - t_2)}{c + d*\cos(t_1 - t_2)} $$ where $a, b, c, d, t_2$ are real numbers and $c + d > 0$ & $0 \leq t_2 \leq 2\pi$.   I used a straightforward command in _Mathematica_ (9.0.1.0),               Integrate[(a + b*Cos[t1 - t2])/(c + d*Cos[t1 - t2]), {t1, 0, 2 π},        Assumptions -> {a ∈ Reals, b ∈ Reals, c >= 0, d <= 0, c + d >= 0, 0 <= t2 <= 2π}]      to get an obviously incorrect answer: $$2\pi \frac{b}{d},$$ because clearly the integral should be $\propto c^{-1}$ for $|c| \gg |d|$. My question is what am I doing wrong here? Is there a general lesson to be learnt here about how _Mathematica_ handles this kind of integrations and the correct way to ask it to perform such integrations?


Testing for OLS Heteroscedasticity White's General Test

I've done my best to search the help and google White's test (http://en.wikipedia.org/wiki/White_test) in Mathematica. Can anyone point me to a function or Mathematica reference for this or do you have to code it up yourself if you want it? Thanks, Peter


Flow/graph-based programming in Mathematica?

Is it possible in Mathematica to write a program inside a graph? For example if you have a bunch of different `If[]` statements that you need to embed within one another, instead of writing them all within one another and getting very confused as to where in the control flow you are up to, is it possible to somehow embed these within a graph, so that you can more clearly keep track of precisely where you are? Thank you


Take both of the diagonals through an element in a matrix

I have a matrix like this:               Reverse@Array[List, {8, 8}] // MatrixForm      ![matrix](http://i.stack.imgur.com/cHW1x.png) I need a function that given an element of this matrix will return all the elements corresponding to the two diagonals that run through it. The first diagonal can be found like this:               Diagonal[matrix, j-i]      where `{i,j}` is the element. How can I get the diagonal that runs orthogonally to this through the same given element `{i,j}`? (It is somewhat related to this question but my problem is more that I can't figure out which diagonal I want once I've reversed the matrix.)


How to export data in scientific form

I am having an issue about how to export data in its scientific form using _Mathematica_. To be concrete, I define a list               alist = {2344. 1111111, 0.0002223344};     ScientificForm[%]     Export["test.dat", %]      but it turns out that doesn't work. Is there any other way to achieve this? Also, what can I do to control the number of digits exported? Any idea?


Change all Options of Plot Dynamically

I am trying to make a series of changes in the appearance of the Plot of some function. I am trying to use Manipulate for my experiments. I tried to change the following code `Manipulate[ Plot[Sin[x], {x, 0, Pi}], {p, HoldForm /@ Options[Plot]}, {q, InputField}]` so that when, for example, p is AxesOrigin ->Automatic and q is changed to {-3,5} then the plot will be updated with Axes Origin at {-3,5}. Similar if p is taken AxesLabeL->None and p is changed to "A label" then the last plot will refreshed showing the label "A label" at the top(without affecting any changes already made in other options like AxesOrigin above).


Apply a function to the current selection in place

Say a have the function `foo`:               foo[x_] := x + 2      Like the `Evalution` `->` `Evaluate in place`, I would like to have a keyboard shortcut that replaces the current selection with the result of applying `foo` to the selection. For example if I have selected `1+3` in a cell with the following contents:               2*1+3-5      By pressing a keyboard combination, I want Mathematica to replace it with the result of `foo[1+3]` (`6`):               2*6-5


Define variable relationships and dynamically update variables

I would like to define a relationship between 3 variables first and then later when I have filled two of the variables with a number, I would like to extract the value of the last value. For example:               a * b == c; (* Somehow define this *)     Attributes[GetValues] = {HoldAll}     GetValues[known_] := With[known, {a, b, c}]          GetValues[{a = 2, b = 3}] (* => {2, 3, 6} *)     GetValues[{a = 2, c = 10}] (* => {2, 5, 10} *)     GetValues[{b = 10, c = 10}] (* => {1, 10, 10} *)      Only two of the variables will be defined at a time and there should always be only one possible value for the last variable, if the other two values are valid. You could possible to this with either `Solve` or `Reduce`, but how?


How to replace characters which have alternate meanings in strings. This code works, but creates errors

**The Problem: I often paste strings into Mathca which have many what I call "extender characters" --which may extend the character set."** We know these have to be dealt with so Mathca can deal with the string without error. **Here is an example of such a string.** The "extender characters" are the \ characters. (Happens to be a directory string pasted from W7.)               myString=     "C:\Users\NEW USER\Documents\Data Files General\Creative Write\Analysis incl Econ Trips etc\Write Econ Soc Chce Fin Trips\Mathca\Learn and How Tos\Projcts Apps Unoptimized\Gradebook12x3x12plus.nb"      **Here is code which converts myString into something more clear to Mathca:**                   FromCharacterCode[            Insert[ToCharacterCode[               myString],92,               Position[ToCharacterCode[myString],92]]]  (* 92 is the ascii code of \ *)      The code works It replaces all "\" by "\\".   But it generates many "Unknown string escape" errors (warning that the \ characters in the string enable the extended character set, etc.) **There needs to be (there must be!) a function** which permits us to optionally suppress the control character potentiality of certain characters. Then I would simply enter:               ConstrainedString[myString,{list of characters to optionally constrain}]      Then I could use               ReplaceAll[myConstrainedString, "\"->"\\"]      I don't want to be blindsided by extender characters not relevant in my code if, in that code, those characters only have the literal meaning. I want a clean way of converting or manipulating strings which have "extender characters", so a longer list of functions will be available.


Interaction between two sliders that update the same variable

I'm basing this on the code found in the _Introduction to Dynamics_. I added one more slider which doesn't use the "round and snap" feature given in the link above:               DynamicModule[{x = 0},      Column@{Slider[         Dynamic[x,           If[Abs[# - Round[#]] < 0.3, x = Round[x], x = #] &], {0, 5}]        , Slider[Dynamic[x], {0, 5}]        , Dynamic[x]        }]      When sliding the second slider, I would have though the first one one stay snapped until `x > 0.3`, but that is not the case: the first slider moves together with the second one. Is the update function **only** evaluating when the first slider is moved?


Substituting Data from File

I have sets of Diff. Eq. that I'd like to solve symbolically, then substitute in numerical values for some of the symbols. I'd like to store the value for each symbol in a file, e.g., an excel spreadsheet, then substitute these values in once I have the required solutions. I'm playing with a toy example: I have a two-column excel file with letters in the first column and numbers in the second. I have an expression that I wanted to substitute into: `f = a + b + c + d`. I import the data, `s = Import["File.xlsx"]`, then try to substitute into my equation using a loop:               For[ i=1, i<=4, i++, f = f/.s[[1,i]][[1]]->s[[1,i]][[2]] ]      This doesn't seem to work. As far as I can tell, it's the difference between the string in the 1st column of s, ith row, e.g., a, and the variable within f that I want to substitute for. What is the correct way to do this?


Palette for pasting matrix templates into a notebook

How I can build a palette of matrices?. So, I would like a palette with a 3x3 square matrix, a square matrix 4x4, 1x3 row matrix, 1x4 matrix row, column matrix 3x1 and 4x1 column matrix.


Manipulating several values from the same interval

Some of my calculations depend on the choice of several values from the interval [-2, 2] (it is more or less interpolation of a fixed function using the points as parameters). I want to create a dynamic control for them. The ideal thing to have would be a Slider with multiple positions to move, or a Locator on a line. As for now, I have tried to implement the second variant:               Manipulate[       points[[All, 2]] = Table[0, {5}];       Plot[points, {x, -2, 2}, PlotRange -> 1/100, AspectRatio -> 0.01],       {{points, ({#, 0} &) /@ RandomReal[{-2, 2}, {5}] }, Locator}]      That works, but with quirks: locator panes still can be lifted visibly higher or lower than the base line. Sure, they fall back immediately due to `points[[All, 2]] = Table[0, {5}]` line, but I hope there is a better solution. Is there?


Creating function with matrix argument

I am completely new to programming, so I apologize in advance for a stupid question. I want to program an algorithm for computing invariant factors of a finitely generated abelian group, so in essence I want to feed the algorithm a matrix of relations and get the reduced form of this matrix. I have compiled a cumbersome code which makes the first step of the procedure, namely it takes a matrix and produces a matrix, in which the upper-left element divides all the elements in first row and in a first columm:               M = {{120, 51, 72, 33}, {30, 15, 18, 9}, {60, 30, 36, 18}};     If[FreeQ[M, 0], ## &[], Print [First[Dimensions[M]]]];     L = SparseArray[M]["NonzeroPositions"];     i = First[First[L]];     j = Part[First[L], 2];     M2 = M;     M2[[{1, i}]] = M2[[{i, 1}]];     M2[[All, {1, j}]] = M2[[All, {j, 1}]];     If[M2[[1, 1]] > 0, ## &[],        M2 = M2*Normal[          SparseArray[{1 -> -1, i_ -> 1}, First[Dimensions[M2]]]]];     A = Table[0, {First[Dimensions[M2]] - 1}];          For[i = 2, i <= First[Dimensions[M2]], i++,        A[[i - 1]] = Boole[Divisible[M2[[i, 1]], M2[[1, 1]]]]];          While[A != Table[1, {First[Dimensions[M2]] - 1}],        For[i = 2, i <= First[Dimensions[M2]], i++,        If[Divisible[M2[[i, 1]], M2[[1, 1]]], ## &[],          M3 = M2*Normal[            SparseArray[{1 -> Quotient[M2[[i, 1]], M2[[1, 1]]]},              First[Dimensions[M2]]]] ; M3[[{1, i}]] = M3[[{i, 1}]];          M2 = M2 - M3; M2[[{1, i}]] = M2[[{i, 1}]]]];        For[i = 2, i <= First[Dimensions[M2]], i++,         A[[i - 1]] = Boole[Divisible[M2[[i, 1]], M2[[1, 1]]]]]];      So on the matrix `M = {{120, 51, 72, 33}, {30, 15, 18, 9}, {60, 30, 36, 18}}` it gives `{{30, 15, 18, 9}, {120, 51, 72, 33}, {60, 30, 36, 18}}`. Now I want to iterate this procedure, so I want to feed an arbitrary matrix into this code as a function. I got stuck on this problem for several hours, so I hope you could help me solve this. Thank you!


How could I define a function as the solution of equations in Mathematica?

I have posed a specific question yesterday but it may be too trivial to answer. I think the question could be asked in a more general way so it is easier to answer. Then I could solve the original problem by myself. Usually, we define a function as               F[x_] := x + 10       where the right-hand side is an expression. Now, I would like define a function where the right-hand side is the solution of a set of equations. Like               optV[V_, r_, λ_, μ_, η_, σ_] :=        V /.          FindRoot[{           A V^θ[r, λ, μ, η, σ] h[V, c, r, λ, μ, η, σ] == V - c,            D[A*V^θ*h[V, c, r, λ, μ, η, σ], V] == 1           },            {A, 0}, {V, 1}];           a[V_, r_, λ_, μ_, η_, σ_] :=        A /.          FindRoot[{           A V^θ[r, λ, μ, η, σ] h[c, r, λ, μ, η, σ] == V - c,            D[A V^θ[r, λ, μ, η, σ]  h[V, c, r, λ, μ, η, σ], V] == 1           },            {A, 0}, {V,1}]      This may not be correct code, but I think you can understand my question from it. `optV` and `a` are both parameters for another final function which would be manipulated. So you could regard `optV` and `a` as intermediate parameters. So the solution of the set of equations, correspondingly `optV` and `a`, varies along with `c`, `r`, `λ`, `μ`, `η`, `σ`, which are parameters input for manipulating plot.


StringReplace except some pattern

StringReplace and search out of one pattern               replace[str_] := StringReplace[ result1 = StringReplace[str, rulesTemp = {"BB"     -> "TwoA", "BBB" -> "ThreeB"}], {"B" -> " OneB ", Sequence @@ Reverse /@ rulesTemp}]      # _case 1_ * * *               replace["BBB afsdfsdfs B sdfjsdfsdf BB sdfsadfasdf B"]      > >     (*BB OneB  afsdfsdfs  OneB  sdfjsdfsdf BB sdfsadfasdf  OneB *) >   The first `"OneB"`in `"BB OneB..."` is not expected. Expect: > >      "BBB  afsdfsdfs  OneB  sdfjsdfsdf BB sdfsadfasdf  OneB" >   # _case2_ * * *               replace["BBBaf\\Left sdfsdfsBsdfjsdf\\Right sdfBBsdfsadfasdfB"]      > >     (*BB OneB af\Left sdfsdfs OneB sdfjsdf\Right sdfBBsdfsadfasdf OneB *) >   The above result is not expected. I'd like only isolated `"B"` (not `"BB"` or `"BBB..."`) to be replaced by `"OneB"`. And in case 2, `"B"` in one StringPattern `\\\Left sdfsdfsBsdfjsdf \\\Right` should be ignored. Expect: > >     "BBB af\\Left sdfsdfsBsdfjsdf\\Right sdfBBsdfsadfasdf OneB " >   # _case3_ ignore one repeated pattern * * *               replace["BBBaf\\Left sdfsdfsBsdfjsdf\\Right sdfBBsd\\Left sdfsdfsBsdfjsdf\\Right fsadfasdfB"]      > >     (*BB OneB af\Left sdfsdfs OneB sdfjsdf\Right sdfBBsd\Left sdfsdfs OneB > sdfjsdf\Right fsadfas >     df OneB *) >   Maybe should use `Except` or other.


Multi-dimensional integral in the complex plane with poles and essential singularity

I've passed the last week searching a way to numerically integrate this multi- dimensional integral in the complex plane **at the poles and avoiding the singularity at z=0:** $$ \oint_{C}\oint_{C\ auound\ the\ poles\ only}\frac{z_{1}z_{2}}{z_{2}^{-1}p+(1-p)z_{1}-1}e^{\frac{1}{z_{1}}+z_{1}+\frac{1}{z_{2}}+z_{2}} \, \mathrm{d}z_{1}\mathrm{d}z_{2} $$ where C is a circle of radius 1 centred at 0 and $p\in]0,1[$ and I used this topic Finding residues of multi- dimensional complex functions to compute this integral.   The fact is that when I give the whole integral to Mathematica, I don't have the contribution of the poles because the contour cannot be deformed due to the singularity. So I'm trying to find a way to exclude the singularity of the contour, maybe with a small contour around z=0 using piecewise or something similar (see the figure here http://img834.imageshack.us/img834/6499/v2uq.png where red=singularity and green=poles) to get only the contribution of the poles.   Thank you for your answers. _Mathematica_ code               NContourIntegrate[f_, par : (z_ -> g_), {t_, a_, b_}] :=        NIntegrate[Evaluate[D[g, t] (f /. par) /. t -> t1], {t1, a, b}]            Clear[Pinfz1];       Pinfz1[p_?NumericQ, z2_?NumericQ] :=        NContourIntegrate[1/(2*I*Pi)^2*z1*z2/(p + (1 - p)*z1*z2-z2)*E^(1/z1 + z1 + 1/z2 + z2),         z1 -> Exp[I t],         {t, 0, 2*Pi}]            Clear[Pinfz];       Pinfz[p_?NumericQ] := NContourIntegrate[Pinfz1[p, z2], z2 -> Exp[I t], {t, 0, 2*Pi }]


Handling Overflow

I have a notebook which takes in a user-defined function and starting value and tracks the orbit of the particle under iteration of the function. The problem occurs when the user enters a starting value with an orbit that goes to infinity.               f[x_]:=x^2;     x=1.1;      I get the error message: > General::ovfl: How can I catch this?