title: Interprocedural optimization

text: Lets say I want to build a list of the first 1000000 primes. This is simple enough, I can just do: `AbsoluteTiming[plist = Table[Prime[i], {i, 1000000}];]` and it takes 4.8 seconds. I can also find out of the number of primes less than 15485863 (the million$^{th}$ prime) using : `AbsoluteTiming[PrimePi[15485863]]` which takes negligible time. My impression is that there is no way to get a precise `PrimePi[n]` result without actually finding all the primes less than `n`. This means that to create a list of the first 1000000 primes, it should take negligible time. I believe though that instead of reusing the intermediaries generated from previous `Prime[n]` calls, it instead starts from scratch every time, and this is why it takes so long to run. While I can write my own function to memoize this, I don't see how this could not be built in. Additionally, while in this case I can memoise the process, that is something that I cannot do in general. I assume that in many cases involving table there would be significant savings from saving partial terms from the previous iterations, so I assume that there is a way to do this. Is this a way to enable these optimizations, or is it just wishful thinking? **Update:** Few things: \- Regardless of how `Prime` or `PrimePi` is implemented, taking 4+ seconds to generate the first million primes is rather ridiculous (I have a simple little sieve in C# that can do just over 50 million primes in that time) and I think that it stands to reason that this is because it is doing the same work over and over an over again. Perhaps this is a better example:   `AbsoluteTiming[list1 = Table[Sum[i,i,10000000+q],{q,1,10000}];]`   This took 95 seconds on my computer. That is more than a little excessive. The only possible way that I can think of that it took that long was that for every iteration, it optimized it (hopefully just once, but less hopefully, every time) to $1/2 (1000000 + q) (1000001 + q)$ and then at every time evaluated it. If I instead do `AbsoluteTiming[ list1 = Table[1/2 (1000000 + q) (1000001 + q), {q, 1, 10000}];]` it takes just .06 seconds (much better). Is there a way to get it to always turn the first into the second? Additionally, I would tend to doubt that it realizes that the different in terms forms a linear equation and that it would be easier to do an two additions, than two divisions, three multiplications and a division.


title: Full documentation for AppearanceElements

text: As explained in this solution,               ListAnimate[Table[Plot[Sin[n x], {x, 0, 2}], {n, 3}]]//InputForm      will allow me to view the types of appearance element for the `ListAnimate` controller. But the same method does not work for simple controls or compound `Manipulate`-s, e.g.               Control[{{u, 3, "hello"}, 1, 5, 0.1}] // InputForm     Manipulate[u, {{u, 3, "hello"}, 1, 5, 0.1}] // InputForm      as both are already in `InputForm`. Is there a complete list of `AppearanceElement` types in the documentation (I doubt that) or elsewhere, or a trustworthy way of extracting this information? Added in response to Nasser's solution: it would also be good to allocate exactly which appearance elements are appropriate to each control; looking at `Animator` I've found a couple more which are in the relevant documentation, see below.               appearanceList =        Sort@{"AutorunPlayButton", "BookmarksButton",              "BookmarksPlayButton","ContentResizeArea", "DirectionButton",              "FasterSlowerButtons", "HideControlsButton",              "InteractiveTradingChartMenu",              "InteractiveTradingChartSnapshotButton",              "InteractiveTradingChartResetButton", "InputField",              "InlineInputField", "ManipulatePlayButton", "ManipulateMenu",              "PlayPauseButton", "PlayButton", "PauseButton", "ResetPlayButton",              "ProgressSlider", "ResetButton", "SnapshotButton",              "StepLeftButton", "StepRightButton", "UpdateButton"};     Length@appearanceList     DynamicModule[{sal, dx = 0.5, dy = 0.5, anim1, anim2, loc, swatch},       Column@{         Control[{sal, 1, 10, AppearanceElements -> appearanceList, Appearance -> "Open"}],          Control[{sal, 1, 10, AppearanceElements -> All, Appearance -> "Open"}],         Slider2D[Dynamic@{dx, dy}],(* no appearance elements *)         Animator[Dynamic[anim1], {0, 1, 0.1}, AppearanceElements -> appearanceList,           AnimationRunning -> False],         Animator[Dynamic[anim2], {0, 1, 0.1}, AppearanceElements -> All,            AnimationRunning -> False]        }]      ![image of output of above](http://i.stack.imgur.com/GKDca.jpg) This brings the total to 26, including `All` and `None`. By the way, it is odd that the `ResetPlayButton` looks exactly like the `PlayButton`, as far as I can see.


title: Is there a way to convert an image into a Graph?

text: I'm trying to convert an image with several overlapping dots into a `Graph`. The goal is to be able to derive the Kirchhoff matrix for the randomly created "network of resistors" a.k.a dots with the function `KirchhoffMatrix[]`. Any thoughts or ideas? Here's the image I'm trying to extract the graph from: ![enter image description here](http://i.stack.imgur.com/9HXZ5.png) Haha, sorry I suppose I have been pretty vague with this question. I am currently researching percolation simulations. The dots in the image represent metallic particles. The dots the overlap represent metallic particles connected via a resistor. We randomize the dots on the screen, group the ones that are touching with `MorphologicalComponents[] // Colorize` , and then we Isolate the 'BackBone Cluster' a.k.a the largest component with `DeleteSmallComponents[]`. We check to see if the cluster spans all the way from the top to the bottom and if it does, the sample percolated. We are then trying to find the conductance of the sample from the BackBone cluster. We have been using the Finite Element Method for this, which requires the `KirchhoffMatrix[]`. Your answer, Vitaliy Kaurov, looks like it will very thoroughly answer my question. I'm going to test things before I accept it but thank you for putting so much time into it!!


title: Change of coordinates for an InterpolatingFunction

text: This is a toy example of the question I have but I think it illustrates the point. I have a function `y[x]` which is an interpolating function. Let's define it through:               y=y1 /. NDSolve[{y1''[x]+y1'[x]+y1[x]==0,y1[0]==1,y1'[0]==0},y1, {x, 0, 5}][[1, 1]]      I need to pass this function into another differential equation as the initial condition for the new system (it's time dependent). However, the new differential equation has to be in polar coordinates so I need the above function converted into polar coordinates. Of course I could do this simply by writing:               Interpolation[{Sqrt[y[#]^2 + #^2], ArcTan[y[#]/#]} & /@ Range[0.001, 5, 0.1]]      Which will give me an interpolating function in the right coordinate system. However, with the above, I have had to chose the `x` values that I pass in by hand (ie. `Range[0.001,10,0.1]`). I would like to take as much data from the original `InterpolatingFunction` `y[x]` as I can. The grid within the interpolating function won't be even and there is, as far as I know, gradient data within the function as well. I would like to be able to translate the original `y[x]` `InterpolatingFunction` into a `θ[r]` `InterpolatingFunction` with as much fidelity as I can. I have seen that within `Head[y[x]][[4]]` there is data of the form `{Developer`PackedArrayForm,List_,List_}` but it's not clear what the syntax is. If anybody knows how to pass my `y[x]` into a `θ[r]` as accurately as possible, I would be very grateful. **Edit** Thanks to mmal's comment I see a way forward. In the first link there is an answer to a similar question. If we load:               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]      Then we can define the following function:               Clear[reconstructInterpolatingFunction];     reconstructInterpolatingFunction[intf_InterpolatingFunction] :=      With[{data = intf[[4, 3]],      step = Subtract @@ Reverse[Take[intf[[4, 2]], 2]],      order = Developer`FromPackedArray@InterpolatingFunctionInterpolationOrder[intf],      grid = InterpolatingFunctionGrid[intf]},      Interpolation[MapThread[Prepend, {Partition[data, step], grid}],      InterpolationOrder -> order]];      Inspecting the term `MapThread[Prepend, {Partition[data, step], grid}]` for the `InterpolatingFunction` from `NDSolve` I find that the output is of the form:               {...,{{x},y[x],y'[x],y''[x]},...etc.}      Thus, this is what is needed to be transformed into polar coordinates and turned back into an `InterpolatingFunction`. This is a much simpler task than I originally had so many thanks to mmal. I shan't be able to finish answering this question tonight so if anyone fancies playing with the derivative terms, please do so.


title: Space-efficient null space of sparse array

text: I have a roughly 100,000 × 3,000 matrix (as a `SparseArray`) that I'd like to find the kernel (null space) of. It has about 500,000 nonzero entries, all -1 or 1. When I tried with `NullSpace`, it ate up 8 GB of RAM, complained about insufficient memory and shut down:               No more memory available.     Mathematica kernel has shut down.     Try quitting other applications and then retry.      Is there a better way to do this? Something a bit more efficient with memory (either a different Mathematica technique or a different language altogether)? I don't think there's any structure in the matrix to exploit, beyond what I've mentioned.


title: How to take the derivative w.r.t. an arbitrary function?

text: EDIT: The answer posted by @Jens works for built-in functions only. However I'm starting to wonder if this is related to my Mathematica install somehow. I have version 7. Here is an example in the Mathematica documentation center that implies that if I ask `InverseFunction[]` to find the inverse of a non- built-in pure function, it will be able to. However, as a test I tried to duplicate the result: The documentation center gives `In:= InverseFunction[(a # + b)/(c # + d) &]` `Out:= (-b+d#1)/(a-c#1) &`. Using the exact same input, I get `Out:= InverseFunction[(a # + b)/(c # + d) &]`, which is just the inputted command. :\ The documentation center is talking about version 9. Is there some fundamental difference in how versions 7 and 9 use `InverseFunction`? Is there any workaround? I've also tried to use other definitions other than `InverseFunction[]`, such as `Solve[]`...but in that case `Solve[]` uses inverse functions to find the solution (as evinced by the message I get: `InverseFunction::ifun: Inverse functions are being used. Values may be lost for multivalued inverses. >>` For example, following Jens's answer: `In:=InverseFunction[g][z]` and `In:=q /. Solve[g[q] == z, q][[1]]` both give the same answer, $g^{(-1)}[z]$. If you replace "`g`" with "`Log`" or the head of any other built-in function, they give the same answer; for example, `In:=InverseFunction[Log][z]` and `In:=q /. Solve[Log[q] == z, q][[1]]` give an answer of $e^z$, which is correct. But while the function using `Solve` can deal with non-built-in functions, e.g. `In:=q /. Solve[Log[q] == z, q][[1]]` `Out:=10^z`, which is of course the right answer. The problem is that when trying to implement this as a workaround based on Jens's solution, it hangs up on the same error for some reason, namely that it doesn't know what do to with non- built-in functions. Being relatively inexperienced at programming in Mathematica I'm not sure what other workarounds there may be. It also seems strange that the documentation center's example doesn't work for me, although as I say I think it's probably a version issue. Does anyone have any ideas? _ I want to be able to take the derivative of one function (of a given variable) w.r.t. a different function (of the same variable), i.e. $\frac{df[x]}{dg[x]}$. I know you can use the chain rule to appropriately recast this into the form $\frac{dh[y]}{dy}$, where $h[y]$ is $f[x]$ evaluated at $x=g^{-1}(y)$, with $g^{-1}$ the inverse function of $g$. There are a couple semi-related questions already posted, one of which is here, asking about how to take the derivative of the log of an arbitrary function. I already asked a question about VariationalD (which I initially thought did what I wanted) here. I was referenced to a third question here on the `Dt[]` command, but I can't figure out how to get what I want from there, either. In messing around with `D[]` and `Dt[]`, I have found that, weirdly, `D[]` will actually do this for some special cases. For example, `In:= D[Log[x],Log[x]]` `Out:= 1` and `In:= D[Log[x]^2,Log[x]]` `Out:= 2Log[x]`. However, commands such as `D[Log[x^2],Log[x]]` and `D[x,Log[x]]` return zero. `Dt[]`, meanwhile, heads in the right direction, for example: `In:= Dt[Log[x^2],Log[x]]` `Out:= 2 Dt[x,Log[x]]/x`. This is correct except that I don't know how to make it evaluate, even though I'm sure Mathematica can handle inverting a function to use the chain rule. I don't want to use the logarithm function, it's just an example. I want to be able to take the derivative of a fit (with a complicated functional form) to experimental data w.r.t. different (complicated) functions. So while in principle I could hash out the equivalent derivative w.r.t. $x$, I really don't want to :)


title: $RecursionLimit::reclim: Recursion depth of 256 exceeded. >> error in CDF deployment

text: When I am executing this code in notebook, there is no error but when I am deploying it in CDF, this error is coming. > $RecursionLimit::reclim: Recursion depth of 256 exceeded. >> The code is               With[{y1 = {1, 2, 2, 1, 7}, y2 = {0, 3.27, 4.188, 7.331, 4.694}},       Column[        { Spacer[70],           Text[Style["iPhone and iPad quarterly sales- units, million", Bold, 18]],           Column[            {Spacer[70],              Text[Style["Click on/off:", Bold, 14]],              q1 = True; q2 = True;             Row[               {Labeled[                  Button["     ", q1 = ! q1, Background -> Blue, Appearance->"Frameless"],                  "iPhone", {Right}                ],                 Spacer[19],                 Labeled[                  Button["     ",q2 =!q2,Background -> Orange, Appearance -> "Frameless"],                  "iPad", {Right}                ]               }              ],               Column[                {Dynamic@ BarChart[                            Table[{If[q1, y1[[i]], 0], If[q2, y2[[i]], 0]},{i, 1, 5,  1}],                             BarSpacing -> 0.8, ChartStyle -> {Blue, Orange},                             ImageSize -> {600, 280},                             GridLines -> {None, Automatic}                          ]                }              ]}]}]]      ![Mathematica graphics](http://i.stack.imgur.com/viW3J.png) I have tried using               $RecursionLimit = Infinity        But it has not worked. Please help.


title: Resolving reduced resolution issues in WSMLink

text: I have been attempting to evaluate Wolfram System Modeler (WSM) and it has not been going smoothly. It looks like some of the Modelica Models (combiTable1D for instance) supplied are not complete or not functional in WSM. I am working with Wolfram Support to get some clarification on that, but after days of trying I have been unable to get a simple output=input model working. What I am trying to do as a first step is to just get an audio file into simulation and to port this straight through to an output to verify that it got in with reasonable accuracy. To do this I start with a very simple model:               model AudioProcessing       Modelica.Blocks.Interfaces.RealInput u=5;       Modelica.Blocks.Interfaces.RealOutput y;     equation        connect(u,y)      end AudioProcessing;      Here I have set the input to the constant 5 just to see if I can run the simulations without error and indeed this works fine. In order to bring in the .WAV file I have tried many things, but the best results I get so far is to use `WSMLink` and the `WSMInputFunctions` option of `WSMSimulate` to provide and interpolated version of the .WAV to the simulation. For instance:               Needs["WSMLink`"]     rawAudio = Import["C:\\Users\\vandel\\Desktop\\Mathematica\\Guitar_Sample.wav"]     samplePeriod = N[1/First[rawAudio][[-1]]];     sampleData = First[rawAudio][[1, 1]];     audioTimeSeries = Table[{n*samplePeriod, sampleData[[n + 1]]}, {n, 0, Length[sampleData] - 1}];     audiofunction = Interpolation[audioTimeSeries];     Plot[audiofunction[t], {t, 0, 10}, PlotRange -> All]      This plot looks fine and I can generate reasonable audio using the interpolation function. Now I try to bring that into WSM as follows:               M = WSMSimulate[audioSignal, {0, 10}, WSMInputFunctions -> {"u" -> (audiofunction[#] &)}];      This runs fine but when I plot this as follows:               WSMPlot[M,"y", PlotRange -> All]      The resolution is so reduced that the sound can not be reproduced. The same takes place with the variable `u` and when I use the returned interploation table to build a new signal with higher time resolution such as:               {outputVector} = M[{"u"}];     testPlot = Table[outputVector[t], {t, 0, 10, .00001}];     ListPlot[testPlot, PlotRange -> All]      The plot from this looks just like the earlier plot. I have tried using different solver methods and high numbers of `InterpolationPoints` and `InterpolationOrder` to no avail. Any insight would be appreciated and if there is a better way to get a real world signal sample into the application I'd be happy to look at that as well.


title: Limiting form of a polynomial expression

text: When simplifying an expression by hand, a trick that is often used is to remove terms that are lower powers of the independent variable, for instance, as $x \rightarrow \infty$, $x^2 + x$ becomes simply $x^2$ I am trying to replicate this functionality in Mathematica. Limit seems like an obvious choice, but               Limit[x^2 + x, x -> ∞]      simply returns $∞$ (not terribly helpful). Another option is Series, but it seems that one has to pass the highest power in the expression to get the desired result, with               Normal@Series[x^2 + x, {x, ∞, -2}]      returning the expected $x^2$. However, this does not work in general for more complicated expressions, when the highest power may not be so obvious. Consider the following example: $\frac{x^2+x}{x+1}$ We expect that the limiting form of this expression as $x \rightarrow \infty$ should be $x$ (the top becomes $x^2$, the bottom becomes $x$, and this then simplifies to $x$). However, if you just use the highest power available, Series returns 0 (you have to actually use Normal@Series[x^2 + x, {x, ∞, **-1** }]). My question is, can anyone produce a generalized piece of code that can produce a limiting expression? It would be good if the procedure handled the other extreme as well, when the variable in question approaches 0 (in which case $x^2 + x$ would simplify to $x$). **Edit:** It seems that the main issue for the solutions presented so far is that the form of the expression is not consistent. These operations are relatively easy to perform by hand, but sometimes tedious, which is why it would be nice to have Mathematica do it for me! Here's a pathological example that I can reduce by hand and for which the accepted solution should be able to return the correct result: $\frac{\sqrt{x^3 + x}}{x^5 + x + 1} \frac{x^2}{x^{10} + x} + \frac{x^5 + x}{x}$ (The right answer is $x^4$)


title: Is it possible to `Protect` a dynamic programming process?

text: I wrote a function using dynamic programming to speed up the evaluation. For safety, I also want to protect this function. Take factorial for example:               fac[0] = 1;     fac[n_] := fac[n] = n*fac[n - 1];     Protect@fac;      `fac[3]` will return a `Set::write` error and give the right answer 6. Although `Quiet@fac[3]` or `Off[Set::write]` seems to work, the sacrifice is the speed, which can be verified by`?fac`: > Global`fac > > Attributes[fac]={Protected} > > fac[0]=1 > > fac[n_]:=fac[n]=n fac[n-1] i.e. after the evaluation of `fac[3]`, _Mathematica_ does not store the values: fac[1],fac[2],fac[3].(Of course it doesn't, since the fac is protected.) So what can be done to make `Protect` and dynamic programming process live with each other?


title: Series expansion for $\frac{1}{x+1}$ in terms of $\frac{1}{x-1}$

text: I would like to expand a function as $$\frac{1}{x+1} = \frac{1}{x-1+2} = \frac{1}{x-1} \frac{1}{ 1+\frac{2}{x-1}} = \frac{1}{x-1} \left[ 1- \frac{2}{x-1} + \left(\frac{2}{x-1}\right)^2 + \cdots \right]$$ I tried > Series[1/(x + 1), {x, Infinity + 1, 3}] apprently it does not work. Is there any robust way to realize this kind of expansion? Assume $|x|$ is sufficiently large.


title: How to get the time when a notebook is saved and closed

text: I want to get the time when a notebook is created and the time when the notebook is saved and closed, that is to say, the whole time when a notebook exist. What should I do? Thank you!


title: How to get an equivalent of WeightedData in Mathematica 8?

text: Is there an equivalent command of `WeightedData` (new in version 9) in Mathematica 8 or I have to define it by myself? I haven't found anything in the site or googleing it... If there is not such command do you have some suggestions for defining it?


title: Resonance Curve using NDSolve

text: I am trying to make a resonance curve like this one below, using NDSolve. ![enter image description here](http://i.stack.imgur.com/ely3v.jpg) I tried to use code as below. Basically I try to hold solution for a w (driving frequency value) using NumericQ and then find the max amplitude using FindMaxValue when t is big enough. But my code returns a lot of error code I don't understand. By the way, I am using NDSolve directly, so I can test the accurateness of NDSolve Method.               ClearAll;          f[w_?NumericQ] :=      Block[{sol},        sol = NDSolve[{x''[t] + x'[t] + x[t] == Cos[w*t], x[0] == 0, x'[0] == 0},          x[t], {t, 0, 100}];      (FindMaxValue[x[t], {t, 50}])[[1]]]          ListLinePlot[Table[f[w], {w, 0, 100, 1}], DataRange -> {0, 100}]


title: Express a complex function $f(z)$ as $u(x,y)+iv(x,y)$

text: How can I write a complex function $f(z)$ in the form $u(x,y)+iv(x,y)$ using Mathematica? Re and Im do not work, because they do it for complex numbers, not functions. For example, if I try               Re[2 I (z) + 6 Conjugate[(z)] + Sin[(z)]]      Mathematica returns:               -2 Im[z] + 6 Re[z] + Re[Sin[z]]


title: Calling several compiled functions inside another

text: Below, there is an example how I tried to call the compiled function "position" (which i got from this link position) inside another one.               position = Compile[{{mat, _Integer, 2}, {elm, _Integer, 0}}, Module[{result = Internal`Bag[Most[{0}]], i, j},      Table[If[mat[[i, j]] === elm,        Internal`StuffBag[result, Internal`Bag[{i, j}]]], {i,        Length[mat]}, {j, Length[First[mat]]}];     Table[      Internal`BagPart[pos, {1, 2}], {pos,        Internal`BagPart[result, All]}]], CompilationTarget -> "C", RuntimeOptions -> "Speed"];      Now, I try to call the position function inside another and I do this with the "With"-function.               Ex = With[{pos = position}, Compile[{{G0, _Real, 2}}, Module[{G = G0, P, n, p},      P = {2, 5, 1, 6};      n = Length[G];      p = pos[G, #] & /@ {P[[2]], P[[3]]};      ], CompilationTarget -> "C",      CompilationOptions -> {"InlineCompiledFunctions" -> True}]];      My question is, whether there is another way of calling a compiled function inside another, maybe without defining this variable "pos" at the beginning?


title: Substituting values in 3j symbols

text: I believe these three expressions should give the same answer of `-1/Sqrt[3]`, but the first gives `+1/Sqrt[3]` whereas the second and third give the correct value, using _Mathematica 8_. What am I doing wrong?               ThreeJSymbol[{a, 0}, {b, 0}, {c, 0}] /. {a -> 1, b -> 1, c -> 0}        ThreeJSymbol[{a, 0} /. a -> 1, {b, 0} /. b -> 1, {c, 0} /. c -> 0]       ThreeJSymbol[{1, 0}, {1, 0}, {0, 0}]


title: Real Size Image Printing

text: I am generating a complicated graphics with Mathematica, but with objects of given sizes (e.g. a line of length 1 inch, between two points). I want to make sure that when I export the graphics, e.g. as pdf, and then when I print it, the line length on paper will be one inch, without additional tweaking (assuming no scaling when printing).


title: How do I get a plot with a certain size?

text: I am currently creating a poster for a conference in Scribus. I have a given space on the poster for a plot that I want to create with Mathematica. I don't want to scale in in Scribus, as this would change the font size. Thus, the image should already have the expected size when I export it to PDF. However, the results I put into `ImageSize` don't match the dimensions of the PDF created. Is there a possibility to create a plot that is trimmed to the actual content (plot and labels) without a white border and matches a given size? Here is an example. I have a 100mm x 200mm slot in my poster, and I would like to fill it with the Plot below. AspectRatio etc. should be adjusted to the given dimensions. As I want to preserve my font size, it is not enough to export the correct AspectRatio, but I need the dimensions.               Plot[x^2, {x, 0, 2}, LabelStyle -> {FontFamily -> "Helvetica", 24},       ImageSize -> {2.835 100, 2.835 200}, AspectRatio -> Full,       RotateLabel -> True, Frame -> True,       FrameLabel -> {{"I [a.u.]", ""}, {"position (mm)", ""}}]      I checked with WolframAlpha that 2.835 is the factor pt->mm, as 72 is for pt->inch. However, if I export this plot to PDF, Acrobat tells me the dimensions are 69.8mm x 140.4mm. Additionally, I am dealing with a white border, that I cannot remove with `ImagePadding->0`, as that just leaves the coordinate system without the labels. This is bad because for example, my caption next to the image now starts above the image.


title: Using RSolve correctly

text: I am having problems persuading _Mathematica_ to solve even the simplest recurrence relations. As an example, how would you do the following?               RSolve[{q[i] == 1 + (i - 1)*q[i - 1], q[0] == 0}, q[i], {i}]      ~~**Addendum.** As a further frustration, isn't this exactly equivalent? _Mathematica_ can't solve it it seems. > RSolve[{q[i, k] == 1 + ((i - 1))*q[i - 1, k - 1], q[1, 1] == 1},   >  q[i, k], {i, k}] ~~


title: predator prey model with prey refuge

text: I want to plot the phase diagram of prey predator versus prey refuge to see how the prey refuge influences the population of prey and predator.And this is the system $x'=\alpha x(1-x/k)-\beta\frac{(1-m)xy}{1+a(1-m)x}$ $y'=-\gamma y+c\beta\frac{(1-m)xy}{1+a(1-m)x}$ The prey predator with Holling type II model is incorporating a prey refuge, $mx$ and $k$, $\alpha$, $\gamma$, $c$ and $\beta/\alpha$ are the carrying capacity, growth rate of prey, death rate of predator, conversion factor denoting the number of newly born predators for each captured prey and maximum number of prey that can be eaten by each predator in unit time respectively. I have the numerical value for $a=0.02$, $k=100$, $\alpha=10$, $\beta=0.6$, $\gamma=0.09$, $c=0.02$. Thanks so much!


title: Solve simple differential equation - Error?

text: I get the error "The function Te appears with no arguments." when running this code. I'm not sure why. Is it because of the $Abs[\Gamma]$ ?               C1 = 10^-10;     C2 = 0.1*C1;     R = 50;     Tb = 0.1;     Geb = 5*10^-15;     Z0 = 50;     L[Te_] := 10^-9 + 10^-9*(Te - 0.1);     Zlcr[Te_, w_] := (1/R + 1/(I*L[Te]*w) + I*C1*w)^-1;     Zload[Te_, w_] := -I*w*C2 + Zlcr[Te, w];     \[CapitalGamma][Te_, w_] := (Zload[Te, w] - Z0)/(Zload[Te, w] + Z0);     y[Te_, w_] := (Abs[\[CapitalGamma][Te, w]])^2;     p[Te_, w_] := Abs[\[CapitalGamma][Te, w]]     Co = 10^-28;     Vol = 10^-21;     Cv = Co/Vol;     eqn1[w_, Te_, Pprobe_, t_] :=        Cv*Te'[t] ==   (Cv -   y[Te, w])*5 y[Te, w]* Pprobe     eqn2 = eqn1[3*10^9, Te, 10^-15, t]     sol = DSolve[     {eqn2, Te[0] == 0 }, Te[t], t  ]


title: Combining ArrayPlot and Plot

text: I have two plots.   * plot1 is a colour graph generated using ArrayPlot.    * plot2 is a function plotted using Plot. I want to do two things.   1. Scale the axes of plot1 to be the same as plot2 (instead of just pixel counts).   2. Overlay plot2 onto plot1. As an example, say I have               plot1 = ArrayPlot[RandomReal[{0, 1}, {100, 100}], FrameTicks -> Automatic]      ![](http://i.stack.imgur.com/jyx0B.png)               plot2 = Plot[x^2, {x, 0, Pi}, PlotRange -> {0, 2 Pi}, PlotStyle -> {Thick,Red}]      ![](http://i.stack.imgur.com/JyQAA.png) How do I scale plot1 to read x-values from 0 to $\pi$ and y-values from 0 to $2\pi$ and then overlay plot2 on top of plot1? I'm open to suggestions on using different plotting functions if there's a more logical way of doing this.


title: Why is ListLogPlot skipping entire decades?

text: I'm having an issue with Mathematica wherein, when trying to use ListLogPlot, the scale of the y-axis skips entire decades. Instead of 1, 10, 100, 1000, it goes more like 10^2,10^4,10^6,10^8. I need it to, well, not do this. This is more or less my code, with different numbers introduced (although same order of magnitude)               data1 = {{{1, 1.432*10^8}, {2, 4.2*10^7}, {5., 1.68*10^7}, {7.,         5.21*10^6}, {10., 1.02*10^6}, {12., 5.37*10^5.}, {15., 1.76*10^5.}, {17.,         1.40*10^5.}, {20., 7.87*10^4}}}      Then               ListLogPlot[data1, Joined -> True, PlotMarkers -> {Automatic, Tiny},       PlotStyle -> Red, PlotRange -> {{0, 20}, {1, 1000000000}},       AspectRatio -> 1, Frame -> True]      And, at least for mine, it produces a graph wherein the ticks on the vertical log axis skip decades. There should also be a large white blank space towards the bottom of the graph. This is intentional, as I have several other sets of data I need to include using the Show function, and Show seems to default to the first graph set. So if I can get this graph to work, then it should be pretty easy to graph the others, and use the Show function. Any help is greatly appreciated.


title: How to plot data points in the form X, Y, E(X, Y) where X and Y coordinates are not ordered?

text: I have got a file with field values (RF simulation of a resonator) which consists of 3 columns: `X` and `Y` cartesian coordinates and the field value `E(X, Y)` with 9500 rows. The problem is that my external field simulation software is not able to print the required field on a regular mesh (polar or cartesian map) as shown below: > >       -15.00000      -26.00000   345000.00000 >        15.00000      -26.00000   361000.00000 >        12.20000      -27.40000   490000.00000 >       -12.20000      -27.40000   583000.00000 >        -9.27000      -28.50000  1050000.00000 >         9.27000      -28.50000  1140000.00000 >        16.50000      -28.60000   436000.00000 >       -16.50000      -28.60000   491000.00000 >         6.24000      -29.30000  1520000.00000 >        -6.24000      -29.30000  1730000.00000 >         3.14000      -29.80000  2110000.00000 >   My goal is to create from the data above an interpolated surface from which I could generate a nice field matrix with a certain resolution. My first idea was to use Gnuplot for this job so the scatter plot looks like this: ![enter image description here](http://i.stack.imgur.com/YMCVO.png) ..and then interpolation of the field points on a regular grid like this: ![enter image description here](http://i.stack.imgur.com/EzSmc.png) However, Gnuplot is great but it cannot write this interpolated field back into a file for further post processing. Now I am trying to apply the same procedure in Mathematica (ver 9) For this, I wrote the following simple commands:               stream = OpenRead["~/efields/em.dat"];          data = ReadList[stream, {Number, Number, Number}];          f = Interpolation[data];          ListPointPlot3D[{x, y, f[x, y]},        {x, Min[data[[All, 1]]], Max[data[[All, 1]]]},        {y, Min[data[[All, 2]]], Max[data[[All, 2]]]}]       Unfortunately this did not work and _Mathematica_ returned with 2 error messages: > Interpolation::udeg: Interpolation on unstructured grids is currently only > supported for InterpolationOrder->1 or InterpolationOrder->All. Order will > be reduced to 1. >>   >  ListPointPlot3D::nonopt: "Options expected (instead of {y,-480.,-26.}) > beyond position 1 in * Can anybody provide some support hints on this issue. Lets start with the basic:   1. How to plot the data correctly as scatter plot ?   2. How to create a surface from the randomly distributed field values ?


title: Import audio in uLaw format?

text: How do I import a uLaw-format audio file into _Mathematica_? Here's an example:   * hello-world.ulaw For reference, here's the same file in wav format:   * hello-world.wav As I understand it, the uLaw format contains raw µ-law audio data. In this respect, it should be very similar (or identical) to AU, which _Mathematica_ supports, except there is no header. I have tried:               Import["hello-world.ulaw", "AU"]      but _Mathematica_ returns:               Import::fmterr: Cannot import data as AU/SND format.      From the documentation, it looks like there is probably some combination of parameters and options that will work, but the `Import`/`Export` documentation doesn't go into much detail on how to actually use the various available options. (Or at least, not in a way that makes sense to me!)


title: Lookup in Inverse Symbolic Calculator+ from Mathematica

text: There is a useful feature in _WolframAlpha_ that allows to find a possible closed form for approximate numeric values. It can be used, for example, to guess the value of an integral that _Mathematica_ cannot evaluate symbolically.               Integrate[LogIntegral[x]^3/x^5, {x, 1, ∞}]     (* Integrate[LogIntegral[x]^3/x^5, {x, 1, ∞}] *)          N[%, 20]     (* -2.7107171698324070788 *)          Sign[%] WolframAlpha[ToString[Abs[%]], {{"PossibleClosedForm", 1}, "FormulaData"}] /. Hold[expr_ ≈ _] :> expr     (* -1/4 π^2 Log[3] *)      I noticed that sometimes _Inverse Symbolic Calculator+_ can find a closed form for numbers that cannot be recognized by _WolframAlpha_. Can anybody suggest _Mathematica_ code that queries _Inverse Symbolic Calculator+_ , parses a closed form returned by it and converts it into a _Mathematica_ expression?


title: GraphPlot labels overlapping

text: If I plot the following graph with an `EdgeRenderingFunction`, the position of both the labels are at dead center, and with a large graph I have the labels completely overlapping each other:               GraphPlot[{{1 -> 2, "a"}, {2 -> 1, "b"}},        DirectedEdges -> True, VertexCoordinateRules -> Automatic, VertexLabeling -> True,        EdgeRenderingFunction -> ({Blue, Arrow[#1, 0.1],          If[#3 =!= None, Text[Style[#3, Medium], Mean[#1], Background -> White], {}]} &)]      ![Mathematica graphics](http://i.stack.imgur.com/ueOBx.png) Is there a way to position the labels, say, at 60% down the edge instead of dead center, so that the labels don't have a chance to overlap? I've been toggling with `Mean[#1]` above but can't get this right positioning. Edit: improved formatting


title: Using external variable as a variable inside WhenEvent & NDSolve

text: I'm trying to use the new WhenEvent functionality of NDSolve in Mathematica 9, in order to perform an action when a variable in the system reaches a certain value. I would like this variable to come from an external variable, like so:               var = y; (* this could come from somewhere else *)     list = {};          (* keep track of values of x for which y[x] == 1 *)     NDSolve[{y''[x] == -y[x], y[0] == 1, y'[0] == 0,        WhenEvent[Round[var[x], 0.1] == 1, AppendTo[list, x]]},       y, {x, 0, 10}]      But this produces the errors > NDSolve::nbnum1: The function value Round[y[0.],0.1]==1 is not True or False > when the arguments are {0.,1.,0.,0.,-1.}. >> > > NDSolve::nbnum1: The function value Round[y[0.000143737],0.1]==1 is not True > or False when the arguments are > {0.000143737,1.,-0.000143737,-0.000143737,-1.}. >> > > NDSolve::nbnum1: The function value Round[y[0.000287473],0.1]==1 is not True > or False when the arguments are > {0.000287473,1.,-0.000287473,-0.000287473,-1.}. >> > > General::stop: Further output of NDSolve::nbnum1 will be suppressed during > this calculation. >> How can I use an "external" variable to specify which variable to watch in WhenEvent?


title: Can a function be made to accept a variable amount of inputs?

text: I have a function that takes two inputs and processes them for a single output. What I need is one that can take a varying number of inputs. and process them to a single output. Is this possible in Mathematica?                DatasetAverage[inputData_, inputData2_] := Block[{dataAvg, v, w},        v = Length[inputData];        w = Length[inputData2];        If [v != w,         Print["DatasetAverage: Data sample sizes do not match"]];        dataAvg = Table[Mean[{inputData[[i]], inputData2[[i]]}], {i, 1, Length[inputData2]}]      ]


title: Defining functions with changing number of variables

text: I am working with a bunch of functions of the form               fn[x1_,x2_,x3_,...,xn_] := x1x2+x2x3+...+xnx1      where $n$ changes. Is there a way to create these functions efficiently, without having to explicitly define each? I'm looking for a way of declaring, say, $n=5$ and getting back               f5[x1_,x2_,x3_,x4_,x5_]:=x1x2+x2x3+x3x4+x4x5+x5x1      Perhaps they could be defining iteratively? Since fn and fn-1 only differ by a few monomials. I appreciate any helpo that I can get! Thanks!


title: Function with different set of arguments

text: > **Possible Duplicate:**   >  How to create functions of arbitrary number of variables? i want to use a Function `f[]` with different set of arguments. example: `f[{x,y,z}]` as well as `f[{x1,y1,z1},{x2,y2,z2},...,{xn,yn,zn}]`. How do i write its definition to accept Both type of calls.


title: How write this Function with many arguments?

text: F[x1_,x2_,...,x99_]:=expr How to write this Function in mathematica whithout complete write it?


title: How to define a Mathematica Function with varying number of input and output arguments

text: In Matlab, such issue is handled by               varargout, // a cell structure to store all output arguments     varargin, // a cell structure to store all input arguments     nargout, // number of output arguments     nargin // number of input arguments      Is there any equivalent implementation in Mathematica, and how? A simple working example would be much appreciated!


title: Can I define a function for vectors of arbitrary dimension?

text: Is it possible to do analytic calculations with _Mathematica_? For example, I want to compute: $$\partial \frac{\sum_{j=1}^n G_{j} \prod_{k=1}^{j-1} (1 - G_{k})}{\partial G_l}=-\prod_{k\neq l} (G_k-1)$$ Is it possible to define such analytic functions for an arbitrary parameter $n$? Right now, I do it by hand by defining a function like this               f[a_, b_, c_, d_] = a + b (1 - a) + c (1 - a) (1 - b) + d (1 - a) (1 - b) (1 - c)      but I want to do it generally for an $n$-vector, not a 4-vector


title: Varying number of function arguments

text: I have a function of six arguments:               ffit[q1_, q2_, q3_, q4_, q5_, q6_] :=         (a1*q1^2 + a2*q2^2 + a3*q3^2 + a4*q4^2 + a5*q5^2 + a6*q6^2)      `a1,...,a6` being constants and `q1,...,q6` coordinates. Is there a simple way ho to define the function in a more concise way so that I could easily get also the same function with an arbitrary number of arguments (`ffit[q1_,q2_,q3_]` for instance)?


title: Constructing functions with variable number of output arguments

text: In Mathematica, you can construct a function `f` to have different definitions based on its input arguments. For example, `f[x_] := ...` and `f[x_, y_] := ...`. You can also get more specific and define it for specific heads as `f[x_someHead] := ...` or inputs matching arbitrary patterns as `f[x_?somePatternQ] := ...` (of course, one must be careful to keep the order from specific to general). These definitions are the `DownValues` of the function. Now, I'd like to construct a function that has different definitions based on _the number of output variables/symbols requested_ , but for the same set of inputs. Consider the following dummy example in pseudo Mathematica code               f[mu_, sigma2_] := Switch[OutputArgs[],                                 0, Plot[PDF[NormalDistribution[mu, sigma2], x], ...]                                1, RandomReal[NormalDistribution[mu, sigma2], 1000]                                2, {Mean@#, Variance@#}&@ RandomReal[...]                        ]      Here `OutputArgs[]` is a functionality that I'd like, which when called from inside a function, tells you how many outputs have been _requested_ (loosely reminiscent of `OptionValue` which knows which function it's called from). With this, I can use the function call simply as `f[0,1]` to plot the normal distribution (perhaps inside a `Manipulate` to play with the parameters), then when I'm satisfied, I can use the same function call, but with an output argument as `a = f[0,1]` to get a random sample, and with two outputs to get an empirical estimate of the mean and variance. I realize that this is a bit at odds with the classical notion of a function having a well defined output based on the input, rather than a well defined output based on the number of outputs for a given input. * * * My interest is purely academic and arose from working on porting some MATLAB code to Mathematica. Some might have recognized that right away, and this is a feature that that I _do_ find useful — a sentiment also shared by a few others that I've spoken to here. I wouldn't write code this way and I know that it is also possible to achieve the same by other means such as using flags as `f[0, 1, "Plot"]` or options as `f[0, 1, Options -> "RandomSample"]`, etc. for the above example. However, I'm interested in exploring if there are ways to imitate this behaviour in Mathematica.


title: Show Simplified Directives

text: Is there a way to force Mathematica to convert an already rendered Graphic to the simplified Directive form of that Graphic. **Background:** I am currently editing Graphics using Drawing Tools and then calling `InputForm[gr]`, but this often doesn't work well because the output of `InputForm` are much larger then the original input. For example I am looking for the following code               gr = Graphics[{Red, Circle[]}];     InputForm[gr]      To output the simplest form possible. For example `HoldForm[InputForm[gr]]` could print `Graphics[{Red, Circle[]}]` or `Graphics[{Red, Circle[0,0]}]`. **EDIT:** There are a lot of Graphic directives listed in the docs, so there probably isn't a direct answer, but simply answers that get closer to respecting the original input. The best technique IMO would somehow create a trained function which evolves based on the version of Mathematica that you are currently using. Obviously manual transformation are less then ideal.


title: ListContourPlot interpolation screws up on concave set of data

text: I want to create `ListContourPlot`s for sets of Data (from a physics simulation) given as Triplets {x, y, f(x, y)}. Certain parameter regions in the x-y-plane are excluded by experiments. The list of triplets simply does not contain any Triplets with excluded x-y-parameters. `ListPointPlot3D` shows that this is not the problem. The problem is that `ListContourPlot` (which I prefer to use, since I have to correlate exclusions from different quantities) interpolates values into regions where no data points are given, as soon as the shape of the data- filled region becomes concave. I already tried creating a list that is only defined in the excluded regions and painting it over the original plot, however, my dataset is not entirely concave, so that overpainting will cut off some of the interesting parts of the plot... I figure it has something to do with the "Method" option of `ListContourPlot`, but those things are really badly documented. Here is a list of 140 data triplets that show the problem.               l= {{14., 2.1, 125.433}, {14., 2.1375, 125.957}, {14., 2.175,        126.58}, {14., 2.2125, 127.354}, {14., 2.25, 128.415}, {14.5,        2.1125, 125.698}, {14.5, 2.15, 126.315}, {14.5, 2.1875,        127.087}, {14.5, 2.225, 128.152}, {15., 2.1, 125.593}, {15., 2.1375,        126.238}, {15., 2.175, 127.061}, {15., 2.2125, 128.256}, {15.5,        2.1125, 125.886}, {15.5, 2.15, 126.669}, {15.5, 2.1875,        127.783}, {16., 2.1, 125.73}, {16., 2.1375, 126.534}, {16., 2.175,        127.708}, {16.5, 2.1125, 126.054}, {16.5, 2.15, 127.082}, {17., 2.1,        125.829}, {17., 2.1375, 126.85}, {17.5, 2.1, 125.858}, {17.5,        2.1375, 127.016}, {18., 2.1, 125.868}, {18., 2.1375,        127.185}, {18.5, 2.1125, 126.243}, {18.5, 2.15, 128.277}, {19.,        2.125, 126.76}, {19.5, 2.1125, 126.183}, {20., 2.1, 125.633}, {20.,        2.1375, 127.686}, {20.5, 2.125, 126.573}, {21., 2.1125,        125.763}, {21.5, 2.1, 125.093}, {21.5, 2.1375, 127.062}, {22.,        2.125, 125.806}, {22.5, 2.1125, 124.979}, {22.5, 2.15,        127.707}, {23., 2.125, 125.111}, {23.5, 2.1, 124.03}, {23.5, 2.1375,        125.248}, {24., 2.1, 123.738}, {24., 2.1375, 124.82}, {24.5, 2.1,        123.445}, {24.5, 2.1375, 124.411}, {24.5, 2.175, 126.896}, {25.,        2.125, 123.689}, {25., 2.1625, 124.924}, {25.5, 2.1125,        123.092}, {25.5, 2.15, 123.987}, {25.5, 2.1875, 125.801}, {26.,        2.125, 123.022}, {26., 2.1625, 123.937}, {26., 2.2, 125.892}, {26.5,        2.125, 122.703}, {26.5, 2.1625, 123.512}, {26.5, 2.2,        124.901}, {27., 2.1125, 122.198}, {27., 2.15, 122.848}, {27.,        2.1875, 123.782}, {27., 2.225, 125.874}, {27.5, 2.125,        122.095}, {27.5, 2.1625, 122.745}, {27.5, 2.2, 123.676}, {27.5,        2.2375, 125.734}, {28., 2.125, 121.808}, {28., 2.1625,        122.394}, {28., 2.2, 123.198}, {28., 2.2375, 124.563}, {28.5,        2.1125, 121.39}, {28.5, 2.15, 121.87}, {28.5, 2.1875,        122.506}, {28.5, 2.225, 123.412}, {28.5, 2.2625, 125.253}, {29.,        2.125, 121.29}, {29., 2.1625, 121.747}, {29., 2.2, 122.372}, {29.,        2.2375, 123.256}, {29., 2.275, 124.961}, {29.5, 2.125,        121.036}, {29.5, 2.1625, 121.454}, {29.5, 2.2, 122.006}, {29.5,        2.2375, 122.762}, {29.5, 2.275, 123.966}, {30., 2.1, 120.465}, {30.,        2.1375, 120.896}, {30., 2.175, 121.334}, {30., 2.2125,        121.862}, {30., 2.25, 122.595}, {30., 2.2875, 123.735}, {30.5, 2.1,        120.187}, {30.5, 2.1375, 120.599}, {30.5, 2.175, 121.065}, {30.5,        2.2125, 121.525}, {30.5, 2.25, 122.157}, {30.5, 2.2875,        123.07}, {30.5, 2.325, 124.9}, {31., 2.125, 120.167}, {31., 2.1625,        120.593}, {31., 2.2, 121.078}, {31., 2.2375, 121.561}, {31., 2.275,        122.237}, {31., 2.3125, 123.247}, {31., 2.35, 126.014}, {31.5,        2.125, 119.881}, {31.5, 2.1625, 120.285}, {31.5, 2.2,        120.747}, {31.5, 2.2375, 121.268}, {31.5, 2.275, 121.808}, {31.5,        2.3125, 122.628}, {31.5, 2.35, 124.034}, {32., 2.1125,        119.484}, {32., 2.15, 119.849}, {32., 2.1875, 120.264}, {32., 2.225,        120.742}, {32., 2.2625, 121.268}, {32., 2.3, 121.85}, {32., 2.3375,        122.72}, {32.5, 2.1125, 119.213}, {32.5, 2.15, 119.558}, {32.5,        2.1875, 119.949}, {32.5, 2.225, 120.396}, {32.5, 2.2625,        120.911}, {32.5, 2.3, 121.431}, {33., 2.1, 118.846}, {33., 2.1375,        119.16}, {33., 2.175, 119.512}, {33., 2.2125, 119.91}, {33., 2.25,        120.365}, {33., 2.2875, 120.871}, {33.5, 2.125, 118.783}, {33.5,        2.1625, 119.101}, {33.5, 2.2, 119.458}, {33.5, 2.2375,        119.856}, {34., 2.1, 118.333}, {34., 2.1375, 118.614}, {34., 2.175,        118.923}, {34., 2.2125, 119.261}};          ListPlot@l[[All, 1 ;; 2]]      ![Mathematica graphics](http://i.stack.imgur.com/CkKWd.png)


title: Numerically/Analytically Solving a System of Equations

text: I have $6$ functions $f_i(x,y,z)$, $(i = 1, \ldots, 6)$ in three variables $x,y,z$, and I would like to find a simultaneous instance of these variables, say $(x_0, y_0, z_0)$, such that $f_i(x_0, y_0, z_0) = 0$ for each $i = 1, \ldots, 6$. The functions are pretty well-behaved, with mostly low order polynomial factors and some square roots. I know a solution exists, and with some manual searching I've already narrowed down the area where it must be to a pretty small region. What I would like to do now is (preferably) use an exact solver to find the exact solution, or (alternatively) use a numerical search to further narrow down the region of the optimum. I've tried working with functions like `(N)Solve`, `FindMinimum`, `FindRoot` to do this, but it doesn't seem to work very well. The program just runs forever, with no result. My main question is: **What is the best solution for this problem in Mathematica?** Maybe the problem is just too complicated for Mathematica to solve (even numerically though?!), but if it is not, which routine should I call in this case to have the best chance of getting an answer? (I would also be curious to know in general which of these is suitable for what. Is there any real difference in efficiency between `Solve`, `FindMinimum`, `Minimize`, `FindRoot` etc.? Or do they just end up sharing the same optimized algorithms internally?) Thanks.


title: Nested Nintegrate - two variable limits of integral

text: This is, so to say, the next part of the question: Nested NIntegrate - NIntegrate::inum: - error Now I define three functions:               r[x_] := q[x] /. NDSolve[{q'[t] == 0.0001 + (-1 + I*1 + q[t])*q[t], q[0] == 0}, q,         {t, 0, 50}][[1]]          beta = 1;          fn[k_, t_?NumericQ] := Exp[8*NIntegrate[r[s]*Exp[2*beta*1] + 8*r[s], {s, t, k}]]          f00[x_, t_, p_] :=         p*Exp[-8*NIntegrate[r[s]*Exp[2*beta*1] - 8*r[s], {s, t, x}]] +         8*Exp[-8*NIntegrate[r[s]*Exp[2*beta*1] - 8*r[s], {s, t, x}]]*           NIntegrate[Exp[2*beta*1]*fn[y, t], {y, t, x}]      When I evaluate               f00[20, 2, 0.5]      I obtain the error: > NIntegrate::nlim: s = y is not a valid limit of integration. The difference between the first question is now both limits of the integral in the definition of `fn` are variables, and I have to evaluate the integral               NIntegrate[Exp[2*beta*1]*fn[y, t], {y, t, x}]       What I can do?


title: How to simplify expression and use HoldForm at the same time?

text: Hopefully a simple problem for the experts here. I have a need many times to build a symbolic expression for an equation (say a PDE) to use for plot labels in a low level function inside `Manipulate`, and so I make a function that I call to build the pde in symbolic form, so I can use it for a plot label. I pass the PDE parameters to this function, and the function uses `HoldForm` to build it. But when one of the parameters is 1 (or even zero), and because of `HoldForm`, these remain stuck there and do not simplify away, and I'd like to remove them. Currently I use `If` statement to check for these cases. But I have a feeling there is a better way. Here is the function (example)               f[c_] := Module[{},       HoldForm[c* D["u"["x", "t"], {"x", 2}] == "f"["x", "t"]]        ]      now, when I call it like this               f[1]       it returns ![enter image description here](http://i.stack.imgur.com/Otcoh.png) So now I do               f[c_] := Module[{},       If[c == 1,        HoldForm[ D["u"["x", "t"], {"x", 2}] == "f"["x", "t"] ],        HoldForm[c* D["u"["x", "t"], {"x", 2}] == "f"["x", "t"] ],        ]       ]      and now `f[1]` returns ![enter image description here](http://i.stack.imgur.com/7Qynb.png) I tried many things, (Defer, Simplify, Evaluate, etc...) and nothing works, other than by doing this manual check _before_ using `HoldForm`. And about the use of strings there, I had to do it this way :). Too many problems if I use actual symbols. Long story. May be for another topic I can explain why, but for the above works ok for me now other than those extra checks I have to do manually. question is: is there a trick to do what I am doing about without the If check (I have few parameters to check, and have to do many checks for 1's and 0's as well). Not a big problem for me to do the checks, just wondering if there is a trick I am overlooking. thanks


title: How to set the background of a section to light gray?

text: How to set the background of a section to light gray and leave background of content below and above the section as default?


title: Is it possible to create a compiled function with some symbolic arguments?

text: I am trying to create a compiled function that takes in several arguments. However, some of the arguments contain symbolic entries and thus I get the following error message when executing the cell containing the compiled function: > Compile::cplist: b should be a tensor of type Integer, Real, or Complex; > evaluation will use the uncompiled function. > > Compile::cret: The type of return values in [...] are different. Evaluation > will use the uncompiled function. and this error message when trying to call the function: > CompiledFunction::cfta: "Argument {<<1>>} at position 2 should be a rank 2 > tensor of !(\"machine-size real number\")s. " Here is the compiled function I am trying to create:               calcK=Compile[{{nnpe,_Integer,0},b,{d,_Real,2},j,{t,_Real,0}},         Module[             {i,k,numQuadPts,p,pCoords,w,kSub},             k=Array[0`&,{nnpe*2,nnpe*2}];             numQuadPts=4;             p=1/Sqrt[3];             pCoords={{-p,-p},{p,-p},{p,p},{-p,p}};             w={1,1,1,1};             For[i=1,i<=numQuadPts,i++,                 k+=Transpose[b].d.b*Det[j]*w[[i]]/.{xi->pCoords[[i,1]],eta->pCoords[[i,2]]};             ];         Return[t*k]];     ];      Here is some sample input data (I apologize in advance for the large lists):               nnpe=4;     t=.25;     d={{1.0989*10^9, 3.2967*10^8, 0}, {3.2967*10^8, 1.0989*10^9, 0}, {0, 0,3.84615*10^8}};     b={{((-(1/4) + eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(-(1/4) + xi/4))/(0. - 0.625*eta),         0, ((1/4 - eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(-(1/4) - xi/4))/(0. - 0.625*eta),         0, ((1/4 + eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(1/4 + xi/4))/(0. - 0.625*eta), 0,         ((-(1/4) - eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(1/4 - xi/4))/(0. - 0.625*eta),         0}, {0, ((-(1/4) + eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/          (0. - 0.625*eta) + ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(-(1/4) + xi/4))/          (0. - 0.625*eta), 0, ((1/4 - eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/          (0. - 0.625*eta) + ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(-(1/4) - xi/4))/          (0. - 0.625*eta), 0, ((1/4 + eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/          (0. - 0.625*eta) + ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(1/4 + xi/4))/          (0. - 0.625*eta), 0,         ((-(1/4) - eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/(0. - 0.625*eta) +          ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(1/4 - xi/4))/(0. - 0.625*eta)},        {((-(1/4) + eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/(0. - 0.625*eta) +          ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(-(1/4) + xi/4))/(0. - 0.625*eta),         ((-(1/4) + eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(-(1/4) + xi/4))/(0. - 0.625*eta),         ((1/4 - eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/(0. - 0.625*eta) +          ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(-(1/4) - xi/4))/(0. - 0.625*eta),         ((1/4 - eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(-(1/4) - xi/4))/(0. - 0.625*eta),         ((1/4 + eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/(0. - 0.625*eta) +          ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(1/4 + xi/4))/(0. - 0.625*eta),         ((1/4 + eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(1/4 + xi/4))/(0. - 0.625*eta),         ((-(1/4) - eta/4)*(-10.*(-(1/4) - xi/4) - 10.*(1/4 - xi/4)))/(0. - 0.625*eta) +          ((10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4))*(1/4 - xi/4))/(0. - 0.625*eta),         ((-(1/4) - eta/4)*(0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)))/(0. - 0.625*eta) +          ((-0.25*(-(1/4) - eta/4) - 0.25*(1/4 + eta/4))*(1/4 - xi/4))/(0. - 0.625*eta)}};     j={{10.*(-(1/4) - eta/4) + 10.*(1/4 - eta/4), 0.25*(-(1/4) - eta/4) +         0.25*(1/4 + eta/4)}, {10.*(-(1/4) - xi/4) + 10.*(1/4 - xi/4),       0.25*(1/4 - xi/4) + 0.25*(1/4 + xi/4)}};      And finally, I call the compiled function with:               calcK[nnpe, b, d, j, t]      which produces the aforementioned error message. I'm thinking it has something to do with the fact that the "b" and "j" matrices contain "xi" and "eta". Thus, I cannot define the type in the compiled function definition.


title: Programmatically control notebook resize area

text: How might I programmatically control the notebook resize area? In particular, I want to be able to execute "Restore Down" when the window is maximized.


title: How to convert multidimensional matrix into regular matrix?

text: I have this multidimensional matrix:               {{{{a1, a2}, {a3, a4}}, {{b1, b2}, {b3, b4}}}, {{{c1, c2}, {c3, c4}}, {{d1, d2}, {d3, d4}}}}      I would like to convert it into this regular matrix:               {{a1, a2, b1, b2}, {a3, a4, b3, b4}, {c1, c2, d1, d2}, {c3, c4, d3, d4}}      I have tried to use Flatten and Partition, but then I get this result:               {{a1, a2, a3, a4}, {b1, b2, b3, b4}, {c1, c2, c3, c4}, {d1, d2, d3, d4}}      Thanks in advance :-)


title: Evaluation of OptionValue[]

text: I have a function that takes an `OptionsPattern` and I want to access several options, say `a`, and `b`. This works great:               f1[OptionsPattern[]] := Block[{},        {OptionValue[a],OptionValue[b]}       ];     Options[f1] = {a -> 1, b -> 2};      Calling `f1[]` returns `{1,2}` as expected. The problem is that I don't know in advance which options I'll want to access. So I thought about trying this:               f2[OptionsPattern[]] := Block[{list},        list={a,b};        OptionValue /@ list       ];     Options[f2] = {a -> 1, b -> 2};      `f2` doesn't work, and neither do `f3`:               f3[OptionsPattern[]] := Block[{},        OptionValue /@ {a,b}       ];      They both return `{OptionValue[a], OptionValue[b]}`. However, this **_does_** work:               f4[OptionsPattern[]] := Block[{},        OptionValue[#]& /@ {a,b}       ];      > **Question** : Why on earth do `f2,f3` not work, while `f4` does, and what > is the difference between `f4` and `f3` anyhow? _PS_ These also these don't work:               f5[OptionsPattern[]] := Block[{},       Evaluate[OptionValue /@ {a, b}]       ];          f6[OptionsPattern[]] := Block[{},       OptionValue /@ Evaluate[{a, b}]       ];


title: How to flush machine underflows to zero and prevent conversion to arbitrary precision?

text: I'm working on some pretty intense computation in _Mathematica_ ; when my code started running slowly, I tracked the source of the problem to `Exp[]`. I need to exponentiate every element of a 50x500x500 array; performing the operation on a 500x500 array takes on the order of 3 seconds (according to `AbsoluteTime`), so the entire array should take about 50 times that. Unfortunately, that's calculation needs to happen for every data point. I've read about lots of ways to speed up _Mathematica_ code, but none of those methods seem to apply here. I'm already working in `MachinePrecision`. I have noticed that some of my results are ridiculously small (for example, `4.282835067271648*10^-78127094`), but I'm not sure how to make _Mathematica_ ignore those; they're obviously **much** smaller than `$MachineEpsilon`. Any advice is greatly appreciated! **Update** : Below is a sample of my code and the generated output. To give it some context, `g0`, is a scalar, `σg0` is a length 50 array, and `g` is a 500x500 array.               (* Added after Oleksandr R.'s comment *)     SetSystemOptions["CatchMachineUnderflow" -> False];          n = Length[σg0];     probgs = ConstantArray[N[0], {50, 500, 500}];     For[i = 1, i <= n, i++,       probgs[[i]] =          N[(1/(Sqrt[2 π] σg0[[i]])) Exp[-0.5 ((g - g0)/σg0[[i]])^2]];       ]; // AbsoluteTiming     Precision[probgs]      Output:               {4.816275, Null}     MachinePrecision      Turning off underflow definitely helped; 5 seconds isn't bad at all for what I'm doing.


title: Finite precision - how to get rid of "near zeros"

text: I am performing a finite-precision operation on a matrix `A` which I know precisely; call the result `B`. The operation is taking the square root by `B = MatrixPower[A,1/2]`, but it's not quite relevant. The point is that the form of `A` is such that the output will contain a lot of entries equal to `0`, simply because `A` has a lot of invariant subspaces spanned by the standard base vectors. I would like to see resulting matrix is like: in the first approximation it interests me how many non-zero entries it has and where. The problem is, the entries of `B` which are supposed to be `0` come out as small reals of the type $1.234...\times 10^{-10}$. I've tried applying `N` to `B` with some modest requirement on precision, but this does not seem to help. Ideally, I would like to set all entries of `B` which are approximately `0` to precisely `0`. Any help would be appreciated. P.S. It just occurred to me that I can take a function `f` that maps small numbers to `0`, and is identity otherwise, and apply it to `B` element-wise. But there should be a more elegant solution, it seems to me.


title: How can I replace very small scientific form of numbers in output with 0.0?

text: How cam I get rid of very small scientific form numbers in my output, replacing them with zero? (eg: 2.27682*10^-18 --> 0.0)


title: how to calculate with just double floating point precision

text: I want to calculate with simple double floating point precision.               NestList[#^2 &, 0.5, 50]     =>      {0.5, 0.25, 0.0625, 0.00390625, 0.0000152588, 2.32831*10^-10,       5.42101*10^-20, 2.93874*10^-39, 8.63617*10^-78, 7.45834*10^-155,       5.56268464626800*10^-309, 3.09434604738300*10^-617,       9.57497746095000*10^-1234, 9.1680193377700*10^-2467,       8.4052578577800*10^-4933, 7.0648359655800*10^-9865,       4.9911907221000*10^-19729, 2.4911984824000*10^-39457,       6.206069878700*10^-78914, 3.851530333900*10^-157827,       1.483428591300*10^-315653, 2.20056038500*10^-631306,       4.84246601000*10^-1262612, 2.34494770600*10^-2525223,       5.4987797400*10^-5050446, 3.0236578700*10^-10100891,       9.142506900*10^-20201782, 8.358543200*10^-40403563,       6.986524500*10^-80807125, 4.881152400*10^-161614249,       2.382564900*10^-323228497, 5.67661600*10^-646456994,       3.22239600*10^-1292913987, 1.03838400*10^-2585827973,       1.07824100*10^-5171655946, 1.16260000*10^-10343311892, Underflow[],       Underflow[], Underflow[], Underflow[], Underflow[], Underflow[],       Underflow[], Underflow[], Underflow[], Underflow[], Underflow[],       Underflow[], Underflow[], Underflow[], Underflow[]}      But I would really like to get                {0.5, 0.25, 0.0625, 0.00390625, 0.0000152588, 2.32831*10^-10,       5.42101*10^-20, 2.93874*10^-39, 8.63617*10^-78, 7.45834*10^-155, 0, 0, 0, 0 ...}      And I want                FixedPoint[#^2 &, 0.5]  =>  0.      not                FixedPoint[#^2 &, 0.5]  =>  Underflow[]


title: Replace very small numbers by zero in the output of a list

text: I have a long nested list, but many elements are numbers of order 10^-18 or less, eg               {{0.217548, -0.217548, -0.0373272, -9.83823*10^-18, -8.13807*10^-19}, \     {0.217548, 0.217548, 0.0373272, 7.54332*10^-18, 6.23849*10^-19}, \     {0.183095, 0.0504041, 0.00207916, -0.214279, -0.0218996}, \     {0.985472, -0.193791, -0.461242, 4.17611*10^-20, 1.22184*10^-20}, \     {0.985472, 0.193791, 0.461242, -1.18329*10^-30, -9.86076*10^-31},      {0.60405, 9.7862*10^-23, -9.11593*10^-24, -1.54354*10^-22, -1.91278*10^-23}, \     {0.80994, 0.556147, 0.623645, 0.558531, 0.625958}}      Then, to make the output more readable, I want to print in the output the numbers with absolute value smaller than 10^-18 as zeros. What is the smartest and fastest way to do this? Thanks


title: Does Mathematica 8 work on Windows 8?

text: I just saw that Windows 8 RTM has showed up on Technet, and I've been wondering if I should upgrade my main machine. I've been trying to determine the compatibility of various app with Windows 8 and the one thing I can't seem to find is anybody that has tried Mathematica 8 on Windows 8. Does anybody have any experience with Mathematica 8 on Windows 8?


title: FullSimplify ratio of two gamma functions

text: I have the following input               m = 2;     Gamma[n + m]/Gamma[n + 1];     FullSimplify[%]      It gives me               1+n      For `m=3`, it gives me               (1 + n) (2 + n)      For `m=4`, it gives me               (1 + n) (2 + n) (3 + n)      For `m=5`, it gives me               Gamma[5 + n]/Gamma[1 + n]      I would like to have expression like `(1 + n) (2 + n) (3 + n) (4+n),` how should I do to get it?


title: Building intervals

text: I'm facing the right know the problem of building intervals to an arbitrary number. The special thing is that the first and the last intervals should have fixed length, while the "middle" ones should be of a fixed number. I think an example will make things more clear;-) We take the number 111, the first and the last 3 intervals should have the length 10, in between there should be 5 intervals. The solution would be: {{0,10},{10,20},{20,30},{30,40.2},{40.2,50.4},{50.4,60.6},{60.6,70.8},{70.8,81},{81,91},{91,101},{101,111}} I hope I made the problem understandable. Thank you! rainer


title: How can my Manipulate be aware of a local variable inside a nested Module

text: I have 3 sets of 5 x-y points:               RandomInteger[10, {3, 5, 2}]      ![Mathematica graphics](http://i.stack.imgur.com/m7dna.png) I want to display only one set of points at a time, and use a slider to move on to show the next set. This of course could be simply done with a `Manipulate`:               Manipulate[Module[{l},       l = RandomInteger[10, {3, 5, 2}];       ListPlot[l[[i]], PlotRange -> {{-1, 11}, {-1, 11}}]], {i, 1, 3, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/oezOd.png) However, notice that I have to hard code the Manipulate parameter to have a maximum of 3 (the number of sets there is). To avoid hard-coding, I have to make the `Manipulate` aware of the `Length[l]` i.e. the number of sets there is). I just can't seem to find a way how to do so given that `l` was a variable local to only the `Module`. * * * **My question is** : how can I make my `Manipulate` aware of a local variable in my nested `Module`? * * * **PS** : I could of course nest the `Manipulate` within a `DynamicModule`, but I'm wondering if there's any straightforward way to achieve the same thing with the opposite nesting (`Module` inside `Manipulate`).               DynamicModule[{l},      l = RandomInteger[10, {3, 5}];      Manipulate[ListPlot[l[[i]]], {i, 1, Length[l], 1}]]


title: Correct graphical representation of a discrete function (PMF)

text: I have a list: `{1,2,2,3,3,3,3,4,4,5}`. I want to plot the percentage occurrence of elements in the whole list. So the list plot I want to do is:               list={{1,1/10},{2,2/10},{3,4/10},{4,2/10},{5,1/10}};     ListPlot[list]      What is the name of this kind of plot in _Mathematica_? How should I do it in _Mathematica_ 7?


title: Is my system too complicated for Solve?

text: I am trying to solve a system of three nonlinear equations using _Mathematica_. `Solve` takes forever to run and never solves my system of equations. Is my system too complicated? I have looked through the suggestions on using `Solve` in the _Mathematica_ help, but none of these seem to work. I am wondering if I am going about solving the problem the wrong way. Any help would be greatly appreciated! I have attached my code below. ### Solving the Tensegrity Model Defining reference conditions               l0 = Sqrt[0.375];     s0 = 0.5 ;     k = 1;      Using prestress to define               ξ = 1 - lR/l0;          lR[ξval_] := l0 (1 - ξval);          lRvalues = Table[lR[ξrange], {ξrange, {0.0, 0.1, 0.5, 0.9, 1.0}}];      Defining cable lengths               Clear[sx, sy, sz]     l1[sx_] := 0.5 Sqrt[sx^2 + sy^2 - 2 sy + 2];     l2 := 0.5 Sqrt[sy^2 + sz^2 - 2 sz + 2];     l3[sx_] := 0.5 Sqrt[sz^2 + sx^2 - 2 sx + 2];          F1[lR_] = k (l1[sx] - lR);     F2[lR_] = k (l2 - lR);     F3[lR_] = k (l3[sx] - lR);          F1values = Table[F1[lr], {lr, lRvalues}];     F2values = Table[F2[lr], {lr, lRvalues}];     F3values = Table[F3[lr], {lr, lRvalues}];     F1values[[1]] /. sx -> 0.5     (*-0.612372 + 0.5 Sqrt[2.25 - 2 sy + sy^2]*)          sxval = Range[0.5, 2, 0.5];     For[j = 1, j < Length[sxval] + 1, j++,      For[i = 1, i < Length[F1values] + 1, i++,       Solve[{(F1values[[i]] /. sx -> sxval[[j]]) (1 - sy)/l1[sxval[[j]]] ==           F2values[[i]] sy/l2,          F2values[[i]] (1 - sz)/l2 == (F3values[[i]] /. sx -> sxval[[j]]) sz/           l3[sxval[[j]]],          T == 2 ((F1values[[i]] /. sx -> sxval[[j]]) sxval[[j]]/              l1[sxval[[j]]] + (F3values[[i]] /. sx -> sxval[[j]]) (              sxval[[j]] - 1)/l3[sxval[[j]]])}, {T, sy, sz}]       (*sy1 = NSolve[(F1values[[i]] /. sx -> sxval[[j]]) (1 - sy)/l1[sxval[[j]]] ==       F2values[[i]] sy/l2, sy, Reals] // FullSimplify;*)       (*Print[sy1]*)       ]      ]`


title: Specify a constraint on an interval under FindMinimum

text: I have an interpolated function that looks like this: $\hskip1.2in$![enter image description here](http://i.stack.imgur.com/iRxEx.png) and, based on extreme and critical points, I want to use a polynomial to approximate the function. The points in question are:               pts = {{-0.405234, 1.67277}, {-0.163136, -0.261272}, {0.0847028, -0.183542},         {0.483178, -0.408663}, {0.590177, 1.67277}};      $\hskip1.2in$![enter image description here](http://i.stack.imgur.com/wB56T.png) I know I could use `Fit` to get a polynomial with the desired order, but not every polynomial is acceptable. In order to preserve the qualitative nature of the curve, the polynomial must be _at least_ of order $n=4$, and a requirement is that the polynomial respects the _minima_ of the original curve. Based on that, I did the following: Let $P_4(x) = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + a_4 x^4$. Then I constructed the function (sorry for the lousy programming)               p4[ls_] := Function[x, Module[{a, c4},        a = Flatten@({a0, a1, a2, a3} /.        Solve[Flatten@{(a0 + a1 #1 + a2 #1^2 + a3 #1^3 + a4 #1^4 - #2 == 0) & @@@ #,          (a1 + 2 a2 #1 + 3 a3 #1^2 + 4 a4 #1^3 == 0) & @@@ #} &@ls[[{2, 4}]],          {a0, a1, a2, a3}]);       c4 = a4 /.        (FindMinimum[         Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a4 #1^4 - #2] & @@ ls[[1]] +         Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a4 #1^4 - #2] & @@ ls[[3]] +         Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a4 #1^4 - #2] & @@ ls[[5]],         {a4, 0}])[[2]];       (a[[1]] + a[[2]] x + a[[3]] x^2 + a[[4]] x^3 + a4 x^4) /. {a4 -> c4}       ]];      This function basically finds the coefficients $a_0, ...,a_3$ of the polynomial by imposing it to pass trough the two minima and ensuring that they are indeed minimia (fortunately I didn't had to impose $a_4 > 0$), and determines $a_4$ as the constant that minimizes the function $$|P_4(x_1) - y_1| + |P_4(x_3) - y_3| + |P_4(x_5) - y_5|$$ The result is good but not that good: $\hskip1.2in$![enter image description here](http://i.stack.imgur.com/wwLy7.png) So, I try with $P_6(x) = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + a_4 x^4 + a_5 x^5 + a_6 x^6$ (againg, sorry for the ugly programing):               p6[ls_] := Function[x, Module[{a, c6},        a = Flatten@({a0, a1, a2, a3, a4, a5} /.       Solve[Flatten@{(a0 + a1 #1 + a2 #1^2 + a3 #1^3 + a4 #1^4          + a5 #1^5 + a6 #1^6 - #2 == 0) & @@@ #,         (a1 + 2 a2 #1 + 3 a3 #1^2 + 4 a4 #1^3 + 5 a5 #1^4 + 6 a6 #1^5 == 0) & @@@ #}         &@ ls[[2 ;; 4]], {a0, a1, a2, a3, a4, a5}]);       c6 = a6 /. (Quiet@FindMinimum[          Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a[[5]] #1^4 +           a[[6]] #1^5 + a6 #1^6 - #2] & @@ls[[1]] +           Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a[[5]] #1^4 +           a[[6]] #1^5 + a6 #1^6 - #2] & @@ls[[3]] +           Abs[a[[1]] + a[[2]] #1 + a[[3]] #1^2 + a[[4]] #1^3 + a[[5]] #1^4 +           a[[6]] #1^5 + a6 #1^6 - #2] & @@ls[[5]], {a6, 0}])[[2]];       (a[[1]] + a[[2]] x + a[[3]] x^2 + a[[4]] x^3 + a[[5]] x^4 + a[[6]] x^5 + a6 x^6) /.          {a6 -> c6}     ]];      Again I force the minima, but I add a third condition on the coeficients, that there must be a minima in $x_3$. This works like a charm for `pts`: $\hskip1.2in$![enter image description here](http://i.stack.imgur.com/wWvNW.png) I should be very happy but, if I change the definition for `pts`               pts = {{-0.419826, 1.67277}, {-0.292539, -0.296446}, {0.00452181, -0.162576},        {0.6037, -0.534627}, {0.735329, 1.67277}}      I end up with $\hskip1.2in$![enter image description here](http://i.stack.imgur.com/vuHRr.png) which is terrible (qualitatively speaking that is)! **The solution** is (kinda?) obvious, I need to impose the constraint $$2 a_2 + 6 a_3 x + 12 a_4 x^2 + 20 a_5 x^3 + 30 a_6 x^4 \le 0 \quad x \in (x_2 + \delta_1,x_4 - \delta_2) \tag{C}$$ (where $\delta_{1,2}$ can be fixed to ensure smoothness) but I have been unable to work with the interval. I've tried defining a function by pieces and apply it to $a_6$ in the constraint section of `FindRoot`, use `HeavisidePi`, etc, without success so, **my quiestion is: how to include the constraint (C) in`FindRoot`?** For reference, here is a (coarse) table to generate the original interpolated function for the first and second case:               case1 = {{-0.405234, 1.67277}, {-0.305234, 0.264728}, {-0.205234, -0.2388},        {-0.105234, -0.242507}, {-0.00523355, -0.197663}, {0.0947664, -0.183713},        {0.194766,-0.203222}, {0.294766, -0.252936}, {0.394766, -0.334333},        {0.494766, -0.404536}};          case2 = {{-0.419826, 1.67277}, {-0.319826, -0.275709}, {-0.219826, -0.248922},        {-0.119826, -0.185553}, {-0.0198259, -0.163342}, {0.0801741, -0.169325},        {0.180174, -0.197047}, {0.280174, -0.244685}, {0.380174, -0.313329},        {0.480174, -0.41021}, {0.580174, -0.524263}, {0.680174, -0.190625}};      Thanks for the attention.


title: How to speed up recursive compiled functions?

text: I'm trying to speed up the recursive function that calculates Rotation numbers:               ClearAll[θ]     θ[n_, Ω_, k_] := θ[n, Ω, k] = θ[n - 1, Ω, k] + Ω -         k/(2 π) Sin[2 π θ[n - 1, Ω, k]]     θ[0, Ω_, k_] := 0      Notice that I'm using memoization. Here's the timing of the uncompiled function:               AbsoluteTiming[Table[θ[n, .2, 1]/n, {n, 1, 1000}];]      > >     {0.016223, Null} >   Now I tried compiling the recursive function:               ClearAll[compθ]     compθ =       Compile[{{n, _Integer}, {Ω, _Real}, {k, _Real}},       If[n == 0, 0,        compθ[n - 1, Ω, k] + Ω - k/(2 π)Sin[2 π compθ[n - 1, Ω, k]]],       {{compθ[_, _, _], _Real}},        CompilationOptions -> {"InlineCompiledFunctions" -> True,          "ExpressionOptimization" -> True}, RuntimeOptions -> {"Speed"}]      The timing of the compiled function is worse:               AbsoluteTiming[Table[compθ[n, .2, 1]/n, {n, 1, 1000}];]      > >     {0.342844, Null} >   Of course the timing could be improved if I could somehow use memoization with the compiled function, but I couldn't find any example that shows how to do it. Is it possible? I also noticed with `CompilePrint` that the compiled function calls MainEvaluate, which is probably slowing the computation, but this comment suggests that this may be unavoidable. Is this true?


title: Simplify square roots

text: If I simplify an equation like Sqrt[A^5]+5*Sqrt[A^3]-Sqrt[A] then I get (A^2+5A-1)*Sqrt[A] with no problems. But when I need to simplify Sqrt[(A^5) (1 + a) ] + 5 Sqrt[A^3 (1 + a)] - Sqrt[A (1 + a)] as (A^2+5A-1)Sqrt[A (1 + a)], I get the original one: > >     Sqrt[(A^5) (1 + a) ] + 5 Sqrt[A^3 (1 + a)] - Sqrt[A (1 + a)] >   > > I tried `Simplify`, `FullSimplify`, `Expand`, `Factor`, but they all return > the original equation. What is going on behind the scenes ?


title: Giving a custom style a colored gradient background

text: In _Mathematica_ , customizing Sections, Subsections, Titles and so on, can be done with Format > Style > .... Changing the background color of a style is one of the things you can do. Here is an example where I have colored the background orange: ![enter image description here](http://i.stack.imgur.com/NNIp6.png) But I want to change the background to show a color gradient. I mean, instead of having the same orange in all of the background, there should be a gradient so the orange fades from top to bottom. Gradient styles will be found in Palettes > Color Schemes. But I can't get it to work for changing the color of a cell background.


title: How to change Mathematica cursor globally?

text: I usually use my OS with negative colors (to keep my eyes calm...). I had seen a function called `MouseAppearence` that changes the cursor. I would like configure _Mathematica_ to use another cursors on all notebook area. I need this because when I turn the color to negative the cursor disappears. This would be very useful to me. Someone knows how can I do this?


title: Why does this Quantity calculation lose precision?

text: (Sqrt[#] Sqrt[Quantity[2, "ElectronMass" ("SpeedOfLight")^2] + #] )/(       Quantity[1, "ElectronMass" ("SpeedOfLight")^2] + #) &[      Quantity[50, "Gigaelectronvolts"]]     (* 1.00000 *)     InputForm[%]     (* 0.99999999994777708655477259390422583293`6.882488164549814 *)      The precision is only 6 digits, which is anomalously low. I'm expecting about 0.999999999948, so that `InputForm` magnitude is not just a floating-point error. I'm aware that the physical constants involved, including the ones on which the units depend, are not themselves known to very high precision. But it seems to me that the structure of the expression should allow Mathematica to keep a great deal more precision than it shows me.


title: To solve an equation

text: I am trying to solve the equation:               Solve[Re[Integrate[(2 c - (r^2) Exp[- I 1.4746])^(0.5), {r, 0, 31.7576}]] == 2.1216, c]      I want to integrate an expression in the unknown $c$, in some integration interval, then evaluate the real part, and at last solve the equation, and obtain $c$. I don't know why nothing has been returned.


title: Assuming seems not working and "Solve::svars: Equations may not give solutions for all "solve" variables." issue

text: I am trying to solve these equations                   Assuming[{x1 ∈ Reals && x1 > 0 && x1 < 1},       Solve[{(a3 - r2)^2 + (b3 + r2 - 1)^2 ==          r2^2, (a6 - r2)^2 + (b6 + r2 - 1)^2 == r2^2,         b5 == k1*(a5 - 1) + 1, b3 == k1*(a3 - 1) + 1,         b2 == k1*(a2 - 1) + 1, b6 == k2*(a6 - a1) + b1,         b4 == k2*(a4 - a1) + b1, (a2 - 1/2)^2 + (b2)^2 ==          1/4, (a1 - 1/2)^2 + (b1)^2 == 1/4, (a4 - x1)^2 + (b4 - y1)^2 ==          r1^2, x1 + r1 == 1, (a5 - x1)^2 + (b5 - y1)^2 ==          r1^2, (y1 - b4)*k2 == -(x1 - a4), (b1)*k2 == -(a1 - 1/2), (b2)*          k1 == -(a2 - 1/2), (1 - r2 - b3)*k1 == -(r2 - a3), (1 - r2 - b6)*          k2 == -(r2 - a6), (b5 - y1)*k1 == -(a5 - x1)}, {x1, y1, r1, r2,         k1, k2, a1, a2, a3, a4, a5, a6, b1, b2, b3, b4, b5, b6}]]      And it does output a valid solution > >     x1 -> 5/6, y1 -> 2/3, r1 -> 1/6, r2 -> 1/4, k1 -> 3/4, k2 -> -(4/3), >     a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 7/10, a5 -> 11/15, a6 -> 9/20, >     b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> 17/30, b5 -> 4/5, b6 -> 9/10 >   But it also outputs a bunch of other invalid/undesired "solutions". I was trying to limit the output by using `Assuming`, apparently it does not work though. Also, the console outputs > >     Solve::svars: Equations may not give solutions for all "solve" > variables. >   However, I clearly gave 18 variables with 18 equations. Why so? My mma is 9.0.0.0. on mac.


title: How to represent very long integers with at-most-8-digit(base-10) short integers with * and +

text: I need an algorithm in Mathematica, which can represent any very long integer, prime or not, into the the product operation "*" and sum "+" forms by short integers (not more than 8 decimal digits). Additional rules on the final expression of the very long integer are: (1). the lengths (base-10 decimal digits) of all short prime integers employed should be as close to 6 as possible, the closer the better; if there are _n_ different short integers used, we use the sum of squared differences between their lengths and 6 as the criterion: the smaller the better (first priority); (2). the less "+" operators used the better (second priority); the less "*" the better(the third priority). The final expression of the integer should be usable immediately in C/C++. Example numbers for testing:               29427736469514379027531261659072347     58899562724319710108573382000184640     1732944474195510410991057714955859184      Is there any Mathematica implementation of such algorithm? Thanks!


title: Non-numerical value for a derivative on NDSolve function

text: I am trying to solve the following system of differential equations:               eqn1 = m1 x1''[t] + k1 (x1[t] - x2[t]) + c1 (x1'[t] - x2'[t]) == 0;     eqn2 = m2 x2''[t] + k1 (x2[t] - x1[t]) + c1 (x2'[t] - x1'[t]) + k2 (x2[t]) + c2 (x2'[t])     ==c2*(1.09013 Cos[Pi*13.88*t]) + k2*(0.025 Sin[Pi*13.88*t]);      To solve them I am using the following code for `NDSolve`:               ivals = {x1[0] == 0, x1'[0] == 0, x2[0] == 0, x2'[0] == 0};     soln = NDSolve[{{eqn1, eqn2}, ivals}, {x1[t], x2[t]}, {t, 0, 10}];      When I try to solve this I get the following error message: > NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0 And I don't understand why. I would very much appreciate some help.


title: Memory Leak in Frontend - anyone know a workaround?

text: When using Rasterize on a Graphics expression composed of many differently coloured Graphics objects memory is allocated in the frontend which is then not released or reused when a similar graphic object is created. Rasterize (or its underlying machinery) is used underneath Export when a graphic object is exported using Export, for instance when creating a jpg file. In the example given 4 MB of memory is allocated each cycle but not freed. Eventually the frontend will crash.               Do[Sleep[3]; img = Rasterize[Graphics[Table[       { ColorData["TemperatureMap"][RandomReal[]], Circle[{RandomReal[], RandomReal[]}, 1.0] },        {1000}]]], {1000}];       Does anyone know if this is a known bug and if there are any workarounds pending a fix from Wolfram?


title: How do I draw a DensityPlot in polar coordinates?

text: I am trying to plot $J_m(\chi_{mn} r) \cos(m\phi),$ where $J_m(\chi_{mn}) =0,$ as a `DensityPlot` in polar coordinates (solution to 2D wave equation in polar coordinates). First, some definitions               besselzero = N@Table[BesselJZero[l, n], {l, 0, 25}, {n, 1, 25}];     bzeros[l_, n_] := besselzero[[l + 1, n]];      for speed purposes. For the purposes of this question consider $m=3$ (but there's essentially the same problem for any $m$):               DensityPlot[      Cos[3 ArcTan[y/x] ] BesselJ[3, bzeros[3,1]Sqrt[x^2+y^2]],{x,-1,1},{y,-1,1},      Epilog->{Thick,Circle[]},PlotRange->{-1,1},      RegionFunction->Function[{x,y,z},Norm[{x,y}]<1.]]      ![Mathematica graphics](http://i.stack.imgur.com/SWnqz.png) This is _nearly_ right, except that the sign on the left-hand side ($y<0$) of the plot is wrong (it should not be mirror symmetric around $y=0$, rather continue alternating positive and negative after each $\Delta\phi=\pi/3$). Looking at the `Plot3D` of `ArcTan[y/x]` I realized the cause of the problem was because of how `ArcTan` is defined, so I tried a workaround:               DensityPlot[      Cos[ 3 Piecewise[{{0, x > 0 && y == 0}, {\[Pi]/2,             x == 0 && y > 0}, {(3 \[Pi])/2, x == 0 && y < 0}, {(2 \[Pi])/2,             x < 0 && y == 0}, {ArcTan[y/x],             x > 0 && y > 0}, {ArcTan[y/x] + \[Pi],             x < 0 && y > 0}, {ArcTan[y/x] + \[Pi],             x < 0 && y < 0}, {ArcTan[y/x] + 2 \[Pi],             x > 0 && y < 0}}] ] BesselJ[3,         bzeros[3, 1] Sqrt[x^2 + y^2]], {x, -1, 1}, {y, -1, 1},      Epilog -> {Thick, Circle[]}, PlotRange -> {-1, 1},      RegionFunction -> Function[{x, y, z}, Norm[{x, y}] < 1.]]      ![Mathematica graphics](http://i.stack.imgur.com/LuSwG.png) This is _nearly_ right, except for those white regions. Is there a better way to plot functions of this sort?


title: Padding sub-lists in a list

text: I have a list, say `Alist``               Alist = {{1}, {2}, {1, 3}, {4, 5, 6}, {4}};      and want a list, `Blist` such that               Blist = {{0, 0, 1}, {0, 0, 2}, {0, 1, 3}, {4, 5, 6}, {0, 0, 4}};      What I mean is that, if the set of numbers in Alist has the length smaller than 3, then I want to pad zeros on the left until the whole sub-list has length 3. This should be quite a simple problem, but somehow I could not successfully get a program done (issue with defining conditional variables in the Do and If in each set of loop running). Can someone provide an answer and a short program command for it? The simpler the better.


title: Riffle and Partition

text: At some point I noticed that I was using `Riffle` and `Partition` together a lot. I would do things like               Partition[Riffle[{1,2,3},{4,5,6}],2]      or               Partition[Riffle[{1,2,3}, 6 , {2, -1, 2}], 2]      The question is: are better alternatives, in terms of memory and speed?


title: Facegrids at ticks

text: I want to plot a 3D graphic and I want facegrids at the ticks that I specify. I've tried several solutions but I cannot get this working. The result with the code provided below is that it does its job except in the x-axis where it only draws a facegrid at the middle coordinate (and not in all ticks). Any advice is most welcome. Here is my code:               Plot3D[exp[R, bn, 50], {R, 2, 100}, {bn, 1, 5},            AxesStyle -> Thickness[0.005],            Ticks -> {{2, 10, 20, 30, 50, 100}, {1, 2, 3, 4, 5},                       {0.5, 1.0,1.5, 2.0, 2.5}},             Boxed -> False,            Mesh -> {{0, 2, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100},                      {1,1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}},             PerformanceGoal -> "Quality",            FaceGrids -> All,            AxesLabel -> {"X","Y","Z"}     ]      ![Mathematica graphics](http://i.stack.imgur.com/KKEUo.png)


title: Why Interpolation makes ListPlot3D slow?

text: I'm trying to use `ListPlot3D` to plot some data, and I'm using the `InterpolationOrder` option to make the plot smoother. But the output plot is not very responsive when rotate or edit with the drawing tool. Here is an example:               ls = Table[Sinc[x*y], {x, -10, 10, 0.2}, {y, -10, 10, 0.2}];     ListPlot3D[ls, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/l0mny.jpg) setting `InterpolationOrder->2` gives a smoother plot, ![enter image description here](http://i.stack.imgur.com/eCWs9.jpg) The problem is the second plot response very slowing when rotate with the mouse. So is it possible to produce an interpolated smooth but very responsive plot? Here is what I've tried so far               f = ListInterpolation[ls, {{-10, 10}, {-10, 10}}];     ListPlot3D[Table[f[x, y], {x, -10, 10, 0.1}, {y, -10, 10, 0.1}],       PlotRange -> All];      this gives nicer plot than the first one, but is still seems not as good as the second one. Adding more points seems makes the plot unresponsive.


title: Numerical evaluation of a sum

text: I am trying to compute numerically `NSum[(-1)^n/n^3, {n, 1, Infinity}]`. Of course, using first `Sum` would work here, but often it's not an option (no closed-form). I would like to compute the sum with an arbitrary number of digits. So far, I've found that               NSum[(-1)^n/n^3, {n, 1, Infinity},      WorkingPrecision -> 24,       AccuracyGoal -> 24, PrecisionGoal -> Infinity]      Will give only 16 digits (`-0.9015426773696957`), whatever the value of `WorkingPrecision` and `AccuracyGoal`. However, if I add the option `Method -> "AlternatingSigns"`, I get as many digits as I want, and it's really controled by `WorkingPrecision`. Among the other options, `Method -> "EulerMaclaurin"` gives a wrong answer. Not all digits are correct, and there is an imaginary part: `-0.901542677369695714049804 + 15.503138340149910087738157 I`. And `Method -> "WynnEpsilon"` also fails, giving `-0.9015426773696957140`, even if I ask for more digits. So, is there something I'm doing wrong? Is there a reason it does not work if I don't give a specific method? Is there a more straightforward way to compute a sum (or any numerical result, for that matter)? And, since I'm quite interested by numerical computations with Mathematica and I'm a beginner (with Mathematica, not with numerical analysis :-)), is there a good guide out there ? As an aside, I know Maxima better, and I'm used to the option `fpprec`, that controls "bigfloat" evaluation in every computations. Is there something similar in Mathematica? I think it has a better control of accuracy, so maybe the question does not make sense (maybe there is no "global" setting). * * * To answer rasher's comment, since there is not much space in comments: Actually, if I use larger values of the option `NSumTerms`, I get more and more digits, but they don't agree with what I get with `Method -> "AlternatingSigns"`:               NSum[(-1)^n/n^3, {n, 1, Infinity}, WorkingPrecision -> 50,       AccuracyGoal -> 50, PrecisionGoal -> Infinity, NSumTerms -> 5000]      -0.90154267736969571404980362113358749307373971926               NSum[(-1)^n/n^3, {n, 1, Infinity}, WorkingPrecision -> 50,       AccuracyGoal -> 50, PrecisionGoal -> Infinity,       Method -> "AlternatingSigns"]      -0.90154267736969378050491347983360150530995076960417 After 14 digits, they are different numbers. And here it's possible to check:               Sum[(-1)^n/n^3, {n, 1, Infinity}] // N[#, 50] &      -0.90154267736969571404980362113358749307373971925537 So, the answer with `Method -> "AlternatingSigns"` is also wrong! And it's not better if I combine `Method` and `NSumTerms` options:               NSum[(-1)^n/n^3, {n, 1, Infinity}, WorkingPrecision -> 50,       AccuracyGoal -> 50, PrecisionGoal -> Infinity,       Method -> "AlternatingSigns", NSumTerms -> 5000]      -0.90154267736969571404546474460914681065800480608588 So the results differ after 20 digits. Now I'm even more puzzled :-) I can see that your comment is right, since I get the right answer, but I absolutely don't understand why, and why the other methods fail without notification. Also, it's not a very satisfying approach, since I can't set the number of accurate digits in the output (it depends on `NSumTerms` in a non obvious way).


title: How do I call a 32-bit DLL using .NET/Link and a 64-bit version of Mathematica?

text: The .NET/Link tutorial shows how to call functions defined in DLLs. The example uses the `GetTickCount` Win32 API function               << NetLink`     InstallNET[]     getTickCount = DefineDLLFunction["GetTickCount", "kernel32.dll", "int", {}]          getTickCount[]          (* ==> 91226108 *)      Unfortunately this does not work by default when usign a 64-bit version of Mathematica to call a function defined in a 32-bit DLL. Let's use the 32-bit version of `kernel32.dll` to test:               getTickCount =       DefineDLLFunction["GetTickCount", "c:\\windows\\SysWOW64\\kernel32.dll", "int", {}]          getTickCount[]          NET::netexcptn: A .NET exception occurred: System.BadImageFormatException:         An attempt was made to load a program with an incorrect format.         (Exception from HRESULT: 0x8007000B)        at Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper15.GetTickCount().      How can I call a 32-bit DLL from a 64-bit Mathematica?


title: Why is this infinite series wrongly computed by Mathematica?

text: Could you let me know if _Mathematica_ (newer versions) is able to correctly compute this one?               Sum[(-1)^(n + 1) Cos[3^n x]^3/3^n, {n, 1, Infinity}]


title: How to widen PlotLegends?

text: I have a plot whose legend, when placed at the bottom, is two lines rather than one:               Plot[{x, x^2}, {x, 0, 5}, PlotRange -> {0, 5}, PlotLegends -> Placed[Abs /@ {Subscript[a, 2]/Subscript[a, 1], Subscript[a, 3]/Subscript[a, 1]}, Below]]      If I do the same thing without the absolute value signs, it plots in a row as I'd like:               Plot[{x, x^2}, {x, 0, 5}, PlotRange -> {0, 5}, PlotLegends -> Placed[{Subscript[a, 2]/Subscript[a, 1], Subscript[a, 3]/Subscript[a, 1]}, Below]]      I'm guessing the absolute value signs make this slightly too wide, but putting the two legends side by side would clearly fit into the plot. I've spent a while digging through the documentation and cannot figure out how to do this - help would be appreciated!


title: Listplot imaginary part of complex numbers

text: I have the following list               w={{0.01,99 +0.00001414 I},{0.15,6.6370108 +0.003144129 I},{0.25,3.9515722 +0.00854493297 I},{6,0.10041 +0.28132187 I}}      and I want to `ListPlot` the imaginary part but with the command `Im[w]` I get the list               {{0,0.00001414},{0,0.00314413},{0,0.00854493},{0,0.281322}}      This way I basically lose the x axis values 0.01, 0.15, 0.25 and 6. How can I get in a list the imaginary part and the x axis values? (With `Re[w]` I can get the real part right, the 0.01, 0.15 etc don't change)


title: How to hide Box in Graphics3D?

text: I might be doing something stupid, but I can't see what it is. This simple example shows that I'm trying to hide the Box, but failing. (I tried it just once, in different positions, too.) The code is a little weird, so that might be the problem...               splot1 = SphericalPlot3D[        Cos[\[Theta]], {\[Theta], 0, Pi}, {\[Phi], 0, Pi}, Mesh -> None,         Boxed -> False, PlotPoints -> 80];          aGraphicsComplex = splot1[[1]];          Graphics3D[{Boxed -> False,        Lighting -> {{"Point", RGBColor[1, .9, .9], {2, 2, 4}}},        Boxed -> False,       aGraphicsComplex /. GraphicsComplex[pts_, objs__] :>          GraphicsComplex[          With[{r = 4 Sin[11 (ArcTan[#[[1]], #[[2]]] + #[[3]] )]},             {r, r, 2} #] & /@ pts, objs]}]      ![the box that won't go away](http://i.stack.imgur.com/z1XgV.png)


title: Import invocation fails with Get::noopen : Cannot open JLink error

text: The following function call fails when I invoke it in a fresh _Mathematica_ session:               z1 = Import["Hydrogen Z1.xlsx",         Path -> "F:\\Mathematica Projects\\NIST x-ray attenuation data"][[1]]      The path exists and the Excel file exists in that path, but I get the following errors when I invoke the function:               Get::noopen: Cannot open JLink`. >>     Needs::nocont: Context JLink` was not created when Needs was evaluated. >>     Part::partd: Part specification Null[[1]] is longer than depth of object. >>     Part::partd: Part specification Null[[1]] is longer than depth of object. >>      The result returned is `Null[1]` On the other hand, if I invoke the `Import` function to try to fetch data from a web page using the following command, I get no errors:               Import["http://physics.nist.gov/PhysRefData/XrayMassCoef/ElemTab/z56.html", "Data"]      Unfortunately, there are some problems with the way the data is formatted (which is why I downloaded the data into the Excel files in the first place). Strangely, after using Import to fetch data from the web, the original function call to Import to read the Excel files works just fine without error. This leads me to believe that the failure of the first command occurs because some package is needed but not loaded by default and Import is smart enough to load this package when fetching data from the web but not when attempting to read Excel file data locally. So, presumably a `Needs` statement is needed. What package do I need to load to make this work on the first try (if that is indeed the problem)? Or is the problem something else altogether?


title: How to make AutoAction take effect only one time?

text: **WARNING** : better don't try this when you have any relevant notebooks open, the generated palette will edit your currently selected notebook in ways which are not easily noticed or undone! `AutoAction` will repeatedly take effect when cursor over the button of pallete.               Cell[BoxData[\(\(CreatePalette[\({\(Button[\("Create Inline Cell", \(\(FrontEndExecute[\(FrontEndToken["CreateInlineCell"]\)]\)[\(NotebookRead[\(InputNotebook[]\)]\)]\), \(AutoAction -> True\)\)]\)}\)]\) ;\)], "Input"]      Here is one pallete to create inline cells, I wish it would perform only once when the selected content is the same. How to make `AutoAction` Take effect only for different selected contents Welcome to add an button to revert the value, ie convert new generated inline cell back to the prevous state(maybe plaintext). What is the same content: In one Text Cell, content is `who are you`. when selected content is `who`, just convert `who` into one inline cell, if second time, i select `who are` they are not the same contents.