title: How to fix vertical axis scaling across multiple plots?

text: I have a collection of plots, all of which have the same horizontal-axis range, but different vertical-axis ranges. These ranges differ not only in the absolute locations of their maxima (`ymax`) and minima (`ymin`), but also in the differences between these limits (`ymax - ymin`). To make the plots immediately comparable, it is important that they all their vertical axes be _scaled_ equally. By this I mean that the on-screen distance corresponding to a given vertical-axis interval is the same for all the plots. For example, if the vertical ranges for two plots are 80-110 and 150-200, all I require is that the on-screen distance between the vertical coordinates 100 and 90 (for example) in the first plot be the same as the on-screen distance between the vertical coordinates 155 and 145 (for example) in the second plot. Is there a simple way to _fix_ the scaling of the vertical axis? When I have encountered this sort of trouble in the past, I have managed to get around it by using `AspectRatio->Automatic`, but in this case this idea does not work, because the desired transformation is one that should affect only the vertical dimension, while specifying `AspectRatio->Automatic` would normally affect both the height and the width. EDIT (clarifications): First, I apologize for not showing examples. I realize that it is somewhat irritating to read about graphics in the abstract. Unfortunately, the data I'm working with, and even the details of its representation, are proprietary (and not mine!). The fundamental issue here is that there is no "natural origin" for the axes of the plots in question. The basic information being communicated through these plots would be the same if one redefined the origin for either axis (or for both)1. (The plots live in an "affine space", if you like.) More specifically, at the coarsest level, the information conveyed by these plots is mostly entirely visual, and is either in the form of areas (under curves) or in the form of slopes (of piecewise-linear curves). Furthermore, what matters are not the numeric values of these areas and slopes, but rather their comparison across several plots. For such comparison it is therefore essential that the scaling (the "choice of units", as it were) be the same for all the plots being compared. Therefore, the ideal solution to this problem would be a way for me to specify, for each plot, the scaling for the vertical axis, _and let Mathematica calculate everything else_. I can't stress this last point enough: I want to keep to a minimum the number of parameters I need to set in order to achieve consistency of vertical-axis scaling. (That said, if it turns out that the vertical axis scaling can be specified only in conjunction with the specification of the horizontal axis scaling, as long as the two scalings are allowed to be different, then this would be fine too. In fact, this would be the most "correct" solution to the general problem of making multiple comparable plots of data living in the same 2D affine space.) As it happens, for any collection of cases to be compared, the ranges of the horizontal axes always have the same extent2, and this somewhat fortuitous situation tends to keep the scaling of the horizontal axis sufficiently constant for my purposes. Hence, my interest in controlling the scaling of only the vertical axis is the result of this fortuitous situation. Regarding the question of whether the plots will be displayed on a grid, the short, but somewhat inaccurate, answer would be "no". These plots are useful mostly for displaying fairly striking contrasts between various cases. This means that, as long as their scaling is controlled, they can communicate effectively even when they are not displayed side-by-side. (In other words, as long as "long-and-skinny" and "short-and-fat" represent real differences in the data being portrayed, rather than artifacts of scaling, then a comparison between a plot showing a "long-and-skinny" blob with another one two pages earlier showing some "short-and-fat" blob would still easily get the point across.) Assuming the scaling is kept consistent, then the contrasts between the plots are, for the most part, pretty blatant. This means the benefit of a side-by- side display of these plots (e.g. in a grid) is relatively minor. In my original post I mentioned my use of `AspectRatio->Automatic` to deal with analogous problems in the past, and noted this solution is not suitable in this case. Let me be more precise. Using `AspectRatio` to control scaling is reasonable enough when the aspect ratio of the data being presented really does matter (e.g. so that circles don't get displayed as ellipses, etc.), but in the past I've used it, in a pinch, to control scaling even in cases in which the aspect ratio information in the data is not important. A hack, in other words. As it happens, the plots I'm working with is one where the aspect ratio information is not very important3. In fact, the vertical and horizontal axes in these plots are entirely incommensurable. * * * 1This is a slight overstatement. It would be more accurate to say that the information conveyed by the locations of these origins relative to the data being displayed is very secondary, although it is not entirely (ahem) _zero_ , and this is the only reason for not redefining the horizontal-axis origin for all the plots to coincide with, say, the leftmost edge of the `PlotRange`. That said, most of the story we want to tell with these plots would still come across does not depend on the information contained in the axes. 2The relative position of the horizontal-axis origins may differ from one plot to the next, but, as stated earlier, the locations of these origins is not very significant. 3To be more precise all possible aspect ratios within a rather broad range are equally acceptable. Clearly, once aspect ratios become sufficiently extreme, all the information conveyed through slopes and areas gets essentially squashed away.


title: How to add a trusted path in Mathematica for Mac?

text: I would like to add a trusted a path in the global preferences of Mathematica for **Mac**. When I go to `NotebookSecurityOptions`, click the tool button for `TrustedPath`, and click 'Add', a dialog box appears and asks for a path. After reading the official documentation on Notebook Security, I still have no idea how to enter a simple, specific path (eg `~/Desktop`) into that box. I can't find a documentation for the `Filename` function as well, so I'm left with just guesswork. I have tried several guesses in vain.


title: Use different kernels for different Notebooks

text: I know that the command `LaunchKernels[]` starts up four kernels on my machine:               LaunchKernels[]     {KernelObject[1, "local"], KernelObject[2, "local"],       KernelObject[3, "local"], KernelObject[4, "local"]}      I also figured out that the command `SetOptions[EvaluationNotebook[], Evaluator -> "xyz"];` should then set the given Notebook to be evaluated on some kernel "xyz", but I cannot find the right syntax for this "xyz" to refer to for instance `KernelObject[1, "local"]`. What should I write there? **EDIT** This is the relevant command: `FrontEndExecute[FrontEndToken["ModifyEvaluatorNames"]]`. Create a couple Kernel names and evaluate in parallel.


title: Difference of old Graphics`Graphics3D`ListSurfacePlot3D and the current ListSurfacePlot3D

text: Consider the following example data which creates the lines of a cylinder               data=Table[{Cos[phi],Sin[phi],z},{phi,0,2Pi,.1},{z,0,1,.1}];     Graphics3D[{RandomChoice[ColorData[3,"ColorList"]],Line[#]}&/@data]      ![enter image description here](http://i.stack.imgur.com/cbhhV.png) The coloring indicates the structure of `data` which is a _list of lines_ where with lines I mean a list of `{x,y,z}` coordinates. Therefore, `data` is of dimension `{63, 11, 3}`: 63 lines where each line as 11 points. With the legacy package of older _Mathematica_ versions it was now possible to create the surface of the cylinder by               Needs ["Graphics` Graphics3D `"]     ListSurfacePlot3D[data]      If you look on the usage of the built-in `ListSurfacePlot3D` function you see that it can only take a list of 3D points and not such a structured tensor as `data`. When you then try it anyway, you get a surprising result:               ListSurfacePlot3D[data]      ![enter image description here](http://i.stack.imgur.com/I43FH.png) **Question:** is it possible to create the surface of the cylinder like the old version of `ListSurfacePlot3D` did? On this simple examples, a call to               ListSurfacePlot3D[Flatten[data, 1]]      helps. Unfortunately, for my original data here, this doesn't work. You can recreate the error by shearing the cylinder data               data = Table[        {Cos[phi] + 2 z, z, Sin[phi] + z}, {phi, 0, 2 Pi, .1}, {z, -2,          2, .1}];     Graphics3D[{RandomChoice[ColorData[3, "ColorList"]], Line[#]} & /@         data]     ListSurfacePlot3D[Flatten[data, 1]]      and then you get ![enter image description here](http://i.stack.imgur.com/yyCGB.png)


title: AstronomicalData not including units?

text: I like using mathematica to do my physics homework, and `AstronomicalData` is useful for that, but it doesn't seem to work properly with units. [the question is, at what height is the gravitational acceleration 4.9 meters per second square ![enter image description here](http://i.stack.imgur.com/4g68A.png) Is there a way to get AstronomicalData to output with units?


title: wolfram mathematica intersection of two surfaces

text: I use wolfram mathematica. There is a function of two variables which defines the surface z = f(x,y), the second surface is defined as z = const. How to find the line of intersection of these two surfaces and its projection on XY plane?


title: Simplifying If statements

text: How can I get Mathematica to simplify the true and false clauses for If[] statements? For example:               bar[a_] := a     FullSimplify[If[a > b, bar[a], bar[b]]]      > If[a > b, bar[a], bar[b]] I was hoping for at least If[a>b, a, b]. I thought that it might be hesitating to simplify bar[] because of possible side effects in the function, but I noticed this:               FullSimplify[If[a + a + a > b + b + b, a + a + a, b + b + b]]      > If[a > b, a + a + a, b + b + b] Note that the conditional clause was simplified, but nothing else was. But if the form is _slightly_ different, it will simplify:               FullSimplify[If[a > b, a - a + a, b - b + b]]      > {a a > b   >  {b True How can I get simplified expressions within If statements? I feel like I'm missing something very basic.


title: Why does Play fail to produce a widget sometimes?

text: If I define:               aNote[x_] := Sin[440 * 2 * Pi * x];      then this works (i.e. it produces a widget with a Play button, and clicking on this button produces an A note):               Play[aNote[x], {x, 0, 3.5}]      but this doesn't:               env[x_] := HeavisidePi[x - 1] + HeavisidePi[x - 2.5];     Play[env[x] aNote[x], {x, 0, 3.5}]      The latter just produces something like:               Sound[SampledSoundFunction[       Function[{Play`Time24},         Block[{x =            0. + 0.000125 Play`Time24}, ((HeavisidePi[x - 1] +                HeavisidePi[x - 2.5]) aNote[x] + 0.00024672) 1.00025]],        28000, 8000]]      ...but no widget, and no sound. The difference between the two is that in the second one, the sinusoidal sound wave is multiplied by an "envelope" consisting of two rectangular unit bumps of width 1, and centered at 1 and 2.5, respectively.


title: How can I prevent Mathematica from evaluating or "simplifying" an expression?

text: Simple example:               k = 5;     list = {};     For[i = 1, i <= k - 2,      AppendTo[list, 1/(1 + Cos[i Pi/k])];      i = i + 2];     Print[list];          {1/(1+1/4 (1+Sqrt[5])),1/(1+1/4 (1-Sqrt[5]))}      I want the expression to be kept and printed as:               {1/(1 + Cos[Pi/5]), 1/(1 + Cos[3 Pi/5])}      I have tried `Hold` and its several versions, but nothing seems to do the trick.


title: Get both output and return code of external program

text: `Run["program"]` will run an external program and return the return code. `Import["!program", "String"]` will run the program and return the output as a string. How can I get both the output and the return code? I need a cross platform solution. It would be nice (but not strictly necessary) to get stderr too. Do we need J/Link to achieve this?


title: Reversing Autocorrect, aka how to find the word that was supposed to be there

text: When I receive messages from people using their smartphones I usually see typos and, worst, typos corrected by Autocorrect. Now, I receive messages in English, which is not my first language. I can easily understand what unfixed typos are supposed to mean (I just need to take a look at the keyboard), but Autocorrect-ed typos are an entirely different beast. They usually are totally different words, and the context doesn't help very much. Is there a way in Mathematica to provide in input an English dictionary and an Autocorrect-ed word, and get as output all the words that, slightly mispelled, would lead to the Autocorrect-ed word? Addendum: here's the sentence in which I'm 99% sure that "IMAP" is the result of autocorrection. > It is memorial weekend so IMAP working extra long hour


title: Quantities formatting problem

text: So I've developed this simple code               Mes /: MakeBoxes[Mes[mess_, error_, unit_],                       form : (StandardForm | TraditionalForm) : StandardForm                     ] := RowBox[{                        MakeBoxes[NumberForm[Quantity[mess ± error, unit], {20, 2}], form]}]      in order to easily print things like this:               NumberForm[Quantity[1 ± 0.1, "picoFarads"], {20, 2}]      which give a nice output: > >     (1.00 ± 0.10) pF >   but using the `Mes` structure:               Mes[1, 0.1, "picoFarads"]      gives me: > >     Quantity[1.00 ± 0.10,picoFarads] >   On the other hand:               Mes[1, 0.1, "Farads"]      gives: > >     (1.00 ± 0.10) F >   I'm not sure what's going on but it seems to be connected with internet connection needed to interpret the units. How can I make `MakeBoxes` wait for the unit to get interpreted?


title: Specific rearrangement of elements in list

text: I have an $n\times n$ matrix `G` with elements `g[i,j]` that I construct with `Table[g[i, j], {i, 1, n}, {j, 1, n}]` I have tried without success to write a code without loops in Mathematica that rearranges these elements to a vector in a certain way. To illustrate the case $n=4$: $$ G=\begin{pmatrix} g[1,1]&g[1,2]&g[1,3]&g[1,4]\\g[2,1]&g[2,2]&g[2,3]&g[2,4]\\g[3,1]&g[3,2]&g[3,3] &g[3,4]\\g[4,1]&g[4,2]&g[4,3]&g[4,4]\end{pmatrix} \longrightarrow \begin{pmatrix} g[1,1]-g[2,2]\\g[2,2]-g[3,3]\\g[3,3]-g[4,4]\\g[1,2]-g[2,3]\\g[2,3]-g[3,4]\\g[2,1]-g[3,2]\\g[3,2]-g[4,3] \end{pmatrix} = \widetilde{G} $$ I.e, I'm trying to find a way to create a vector where every element is a subtraction between two diagonally consecutive elements in $G$, starting on the central diagonal, working its way to the right and then starting over under the central diagonal working its way to the left. For a fixed $n$ this could easily be done manually, but with my limitations in Mathematica I have not found a way to do this with arbitrary integers.


title: DSolve fails to solve second order PDE

text: I have a very simple example of a second order PDE:               eqn = D[u[x, y], x, y] + u[x, y] == 0;     sol = DSolve[eqn, u, {x, y}]      and _Mathematica_ cannot solve it! What is wrong!?


title: Modify NDSolve`StateData (if possible)

text: I am trying to solve a PDE that needs to be scaled constantly (refer to this). @andre suggests I modify `NDSolve`StateData`. Now, the problem is, I'm not used to the object-oriented side of _Mathematica_ , and I cannot find any useful materials on _Mathematica_ 's "object". For example, to extract the intermediate values I can use `ndssdata@"SolutionVector"["Forward"]`. I don't even know if `ndssdata@"SolutionVector"["Forward"]` is a method or an variable. Assignment like `ndssdata@"SolutionVector"["Forward"]= 2 ndssdata@"SolutionVector"["Forward"]` does not work, i.e. `ndssdata@"SolutionVector"["Forward"]` is not changed after the assignment. Question in short: how to modify the actual data in `NDSolve`StateData`? Optional: Where can I find materials on complex _Mathematica_ objects like `NDSolve`StateData`?


title: Making a list from equations

text: I want to make a list (efficiently) which is the set of lattice solutions of the following equations (depends on $k$): $x_0\geq 0$ and $x_i\in [0,4k]$ for $i=1,\ldots,4$ satisfies $x_0+x_3\leq k+3$, $x_0+x_2+x_3\leq 2k+7$, $x_0+x_1+x_2+x_3\leq 3k+11$, $x_0\leq 15$, $x_1+x_2+x_3+x_4=4k$. How can I do that? EDIT: For example, by doing the following I can make a list of (easy) lattice equations: $x,y\in[1,5]$, $x+y\leq 5$.               Flatten[Table[{i, j}, {i, 1, 5}, {j, 1, 5 - i}], 1]      But I want to make this using if sentence.


title: Plot two functions within manipulate

text: I just want to plot all stochastic processes and their average process. The original code without the average is:               Manipulate[SeedRandom[seed];            test2[μ_, σ_, S_, P_] :=        Table[RandomFunction[          GeometricBrownianMotionProcess[μ, σ, S], {0, 250, 0.05}]["Path"], {P}];           ListLogPlot[test2[μ, σ, S, P], Joined -> True,        AxesLabel -> {"Time", "St"},        PlotLabel -> Style["Forecasted Stock Price\n (Brownian Motion)", Bold],        PlotRange -> {{0, 250}, {0, 3000}}, ImageSize -> 500,        PlotStyle -> Directive[{Thin, Lighter@Gray}]],           {{S, 100, "Initial Stock Value"}, 100, 500, 0.05, Appearance -> "Labeled"},      {{μ, 0.01, "Drift μ"}, 0.01, 1, 0.05, Appearance -> "Labeled"},      {{σ, 0.01, "Standard Deviation σ"}, 0.01, 1, 0.05, Appearance -> "Labeled"},      {{P, 1, "Paths"}, 1, 100, 1, Appearance -> "Labeled"},          {{seed, 77777, "New Random Case"}, 10000, 999999, 1},            Button["Set Initial Values", {S = 100, μ = 0.01, σ = 0.01},      ImageSize -> 150],      ControlPlacement -> Left]      So far I have done the following (changed the original gode a Little bit) but it’s not working properly since I only get the mean of all processes and not both, the processes (in grey colour) and their average process (in red colour).               Manipulate[SeedRandom[seed];            test2[μ_, σ_, S_, P_] :=        Table[RandomFunction[          GeometricBrownianMotionProcess[μ, σ, S], {0, 250, 0.05}]["Path"], {P}];          meanPaths=Mean[test2[μ,σ,S,P][[All]]];           ListLogPlot[{test2[μ, σ, S, P],meanPaths}, Joined -> True,        AxesLabel -> {"Time", "St"},        PlotLabel -> Style["Forecasted Stock Price\n (Brownian Motion)", Bold],        PlotRange -> {{0, 250}, {0, 3000}}, ImageSize -> 500,      PlotStyle -> Directive[{{Thin,Lighter@Gray},{Thickness[Medium],Red}}]],                    {{S, 100, "Initial Stock Value"}, 100, 500, 0.05, Appearance -> "Labeled"},      {{μ, 0.01, "Drift μ"}, 0.01, 1, 0.05, Appearance -> "Labeled"},      {{σ, 0.01, "Standard Deviation σ"}, 0.01, 1, 0.05, Appearance -> "Labeled"},      {{P, 1, "Paths"}, 1, 100, 1, Appearance -> "Labeled"},          {{seed, 77777, "New Random Case"}, 10000, 999999, 1},            Button["Set Initial Values", {S = 100, μ = 0.01, σ = 0.01},      ImageSize -> 150],      ControlPlacement -> Left]      Any ideas what I could be missing? Thank you for your help


title: how to convert string output into executable commands

text: temp = (layer = #;         layerS = ToString[#];         StringForm["Import[\"drainCdg_gdat0``\",\"Table\"]",           layerS]) & /@ {1, 2, 3}      how to get the output of this to actually execute Import command? i.e. go to a directory and import a series of files with indexed filenames ?


title: Placeholders for map inside a map

text: I have a list structured like               list1 = {{"header1","header2","header3"},             {0,1,2}};      and I'm using a custom function to find the number of the column with a specific header name, and then extract the data for this column:               header = "header1"     data = Map[Part[#,All,whatColumn[header]] &,list1];       Now let's say I would like to extract data for both column "header1" and "header2", I would need to Map the above code line on the following list:               list2 = {"header1", "header2"};      but how do I organize my placeholders # ? Something like this doesn't seem to work:               data = Map[Map[Part[#2,All,whatColumn[#1]] &,list1] &, list2];


title: How to insert expression matching the format?

text: I would like programmatically to insert/write an expression at the current insertion point, but matching the current format, such as font size and style, so that it looks like the user typed it. Default use of NotebookWrite[], NotebookApply[] and Paste[] doesn't do this. For instance if you change the colour in a text cell and press the paste button -> it will paste text in black colour, unlike typing that text yourself. How to avoid this? Off course, one could set any specific style when using `Paste[Style[exp, Red]]`, but it is unknown here- it is the style at insertion. And the same for Font.


title: Integrating Mathematica in Blackboard

text: I teach Economics at University. I often use Mathematica to generate interactive diagrams with demand and supply curves. We also use Blackboard (blackboard.com) to manage our subjects, including assessing students through quizzes and numerical questions. I would like to embed Mathematica in Blackboard, for instance using HTML code. I have tried using Mathematica's Computable Document Format (CDF) but I am not sure where to save the CDF, so that Blackboard can use it. Is there anyone who knows how to embed Mathematica in Blackboard (or any similar eLearning platform)? Thanks, Mario


title: How can I control the size of exported image in HTML code under certain magnification value?

text: I've inserted a picture in one cell, however, when I exported the cell as HTML, the size of my image in the html tag was doubled(the image file in HTMLFiles was the same as the original image). I know what makes this happen: The reason is my global magnification value is 2. How can I control my image size? ## magnification=1                     ## magnification=2                     * * * I like magnification=2, how can I control my image size in the cell, and make it the same as the width and height in the `<img>` tag. ![enter image description here](http://i.stack.imgur.com/AUsVi.jpg)


title: InstallR on OS X with external R installation

text: How do I `InstallR` on OS X to use my already installed and configured R? Simply using               InstallR["RHomeLocation" -> "/Library/Frameworks/R.framework/Resources"]      results in               $Failed     InstallR::nopaclet: Could not find RLink runtime installed. Please use RLinkResourcesInstall to install it      How do I connect _Mathematica_ to my installed R? Do I have to install a separate R for _Mathematica_?


title: How do I prevent NIntegrate::inumr errors within other functions?

text: I believe this question is best illustrated with a simple example. If I run               FunctionInterpolation[NIntegrate[a + b, {a, 0, 1}], {b, 0, 1}]      I get errors of the form               NIntegrate::inumr: The integrand a+b has evaluated to non-numerical values for all      sampling points in the region with boundaries {{0,1}}.      So I guess Mathematica is evaluating the expression before plugging in values and trying to interpolate it. Admittedly the code does yield apparently correct results, so I could just turn off the error message and be done with it, but I'd like to address the root cause if possible. Is there some more correct way to do what I'm trying to do that would not spit out an error message in the first place?


title: How to draw rectangle in mathematica with arrow

text: I have a basic question but i cant seem to find an answer for it. How do i draw a rectangle in mathematica with either clockwise or counterclockwise arrow heads. ![enter image description here](http://i.stack.imgur.com/yGSqD.jpg) In this picture i know two points i.e. (xmin,ymin) and (xmax,ymax). I want to stepwise quench my system and show it in this picture and hence many rectangles between min and max. Rectangle command doesnt seem to provide an answer. And i want to do it with very many points, hence couple of answers that are available in forum are not so useful.               (-1+X+1/(1/3+(-3.+3 X)/(3 (1.*10^-18+4.5*10^-12 (2+X)+2.59808*10^-9 Sqrt[4.*10^-12-4 (-1+X)^3+1.*10^-6 (8-(-20+X) X)])^(1/3))+333333. (1.*10^-18+4.5*10^-12 (2+X)+2.59808*10^-9 Sqrt[4.*10^-12-4 (-1+X)^3+1.*10^-6 (8-(-20+X) X)])^(1/3)))/X      This is the plotted function f. Now i want to select two `X` values say `X=1.1` and `X=3` and divide interval into N parts `X = {X1, X2, X3, X4, X5}` and directed rectangle between each of the two consecutive values. Because i cant do it in mathematica i drew it in paint and it looks something like this with clockwise arrows for each rectangle. ![enter image description here](http://i.stack.imgur.com/ZDOzR.jpg) Thanks, Nitin


title: Force function to make assumptions about its input variables in Mathematica

text: I'm trying to force a Mathematica function to make an assumption about its input variables. In my case, I'm trying to define a function to return the pdf of a Gaussian. But let's use a simple toy case:               n[x_]:= x^(1/2);      Thus, n[x] returns               Sqrt[x]      However, n[x^2] returns               Sqrt[x^2]      While this is correct and fine in principle, in my case some of the variables (like variance) will always be positive and will always be real, thus the simplification               n[x^2] = x      is appropriate. I've tried many things like:               n[x_/; x > 0 && Element[x,Reals]]:=x^(1/2);     n[x_]:=Assuming[x > 0 && Element[x,Reals],FullSimplify[x^(1/2)]];      etc. The best I can get it to do is               n[x^2] = Abs[x];       When I want               n[x^2] = x;      Anyone have any advice on how to do this?


title: How to compute the curl of a vector field?

text: Can anyone help me out with this? I am trying to get _Mathematica_ to evaluate curl of a vector field. The vector field is               (y + cos[z]) + (z + cos[x]) + (x + cos[y])      The path from (0,0,0) to (1,1,1) of the arc of the curve that I am trying to graph is `(t, t^2, t^3)`. Now I know there are curl commands in _Mathematica_ , but I am not very familar with them. Can anyone help me set this up so _Mathematica_ will evaluate it?


title: Recursive Integral for Volume of $n$-Ball

text: The volume of an $n$-ball (the $(n+1)$-dimensional analogue of a disk) of radius $r$ can be found by the following integral recurrence: $$V_0(r)=2r$$ $$V_n(r)=\int_{-r}^rV_{n-1}\left(\sqrt{r^2-x^2}\right)\ \mathrm{d}x$$ I would like to use Mathematica to compute a few terms of this recurrence (as an exercise. I am aware that an explicit formula exists). The recursive code I came up with was this:               BallVolume[dimension_, radius_] := If[dimension == 0,       2*radius,       Assuming[radius > 0,        Integrate[         BallVolume[dimension - 1, Sqrt[radius^2 - x^2]],         {x, -radius, radius}        ]       ]      ]      Calling `BallVolume[1, r]` works as expected, giving $\pi r^2$, but Mathematica seems to get stuck when evaluating `BallVolume[2, r]`. This doesn't seem to be a problem with its ability to integrate; if I define explicitly `CircleArea[r_] := Pi*r^2`, then `Integrate[CircleArea[Sqrt[r^2 - x^2]], {x, -r, r}]` correctly gives $4 \pi r^3\over 3$. Why does the above code fail for dimensions $3$ and higher?


title: How to specify the InputField as a String in Manipulate

text: I'm putting together a Demonstration which utilizes a function which operates on a (manipulated) `String`, and I'd like the `InputField` to be of the form `InputField[col,String,FieldSize->3]`. Using the default format gives something like this:               Manipulate[col, {{col, "AB"}}]      ![Mathematica graphics](http://i.stack.imgur.com/0fpbT.png) which requires use of quotation marks. I'm able to hack the function to take expressions and convert them to strings               f[column_String] := column     f[column_] := ToString@HoldForm@column      but then the `InputField` looks strange for `I` or `E`: ![Mathematica graphics](http://i.stack.imgur.com/pMITU.png) I found another possible workaround on MathGroup:               col="AB"     Manipulate[Grid[{{InputField[Dynamic[col], String, FieldSize -> 3], f@col}}]]      ![Mathematica graphics](http://i.stack.imgur.com/Rtkkr.png) However, this requires pre-initializing `col` and messes up multiple `Manipulate` instances. Is there a way to have `Manipulate` assume that what's entered in an `InputField` is a `String`?


title: How to find local minima of a multivariate function with singularity?

text: I am working on a logistic regression problem which requires minimizing a cost function `J[{theta0, theta1, theta2}, X, y]` to find the optimal value for fitting parameter `{theta0, theta1, theta2}`. `X` is a known `M x 3` matrix of real numbers, and `y` an `M`-dimensional vector. `M` is the number of sample data points (approx. 300) in the training data set. The definition for `J` is               J[θ_, X_, y_] := -(1/Length[y]) (y.Log[h[θ, X]] + (1 - y).Log[1 - h[θ, X]])      where               h[θ_, X_] := Sigmoid[X.θ];     Sigmoid[z_] := 1/(1 + Exp[-z]);      When I try to minimize `J` with `NMinimize` and `FindMinimum`, both fail due to singularity:               NMinimize[J[{θ0, θ1, θ2}, X1, y1], {θ0, θ1, θ2}]     (* NMinimize::nnum: The function value Indeterminate is not a number at {θ0, θ1, θ2} = {0.673558,0.659492,0.0861047}. >> *)      and               FindMinimum[J[{θ0, θ1, θ2}, X1, y1], {θ0, 0}, {θ1, 0}, {θ2, 0}]     (* FindMinimum::nrnum: The function value Indeterminate is not a real number at {θ0, θ1, θ2} = {0.00303682,0.364698,0.342032}. >> *)      For comparison, in MATLAB, using `fminunc`, it suffers from `NaN` too               [theta, cost] = fminunc(@(t)(costFunction(t, X, y)), [0;0;0], optimset('MaxIter', 200));     %Warning: Gradient must be provided for trust-region algorithm; using line-search algorithm instead.      % In fminunc at 365      %Error using roots (line 28)     %Input to ROOTS must not contain NaN or Inf.     %<snip>      however, setting the `'GradObj'` option makes it work:               [theta, cost] = fminunc(@(t)(costFunction(t, X, y)), [0;0;0], optimset('GradObj', 'on', 'MaxIter', 400));         %Local minimum possible.     %fminunc stopped because the final change in function value relative to      %its initial value is less than the default value of the function tolerance.         %<stopping criteria details>          theta         %theta =         %  -24.9330     %    0.2044     %    0.1996          cost     % cost = 0.2035      Is there a way to tweak _Mathematica_ to solve this? The notebook showing the details is here. ### Edit (follow-up questions)   1. Is `Indeterminate` always an unachievable $+\infty$?    2. Is there a way to do automatic regularization (i.e. adding a regularization term $\lambda || \vec{\beta} ||^2 $ and optimizing $\lambda$) when fitting parameter vector $\vec{\beta}$ for a binary non-linear logistic regression by using some option/setting with `LogitModelFit`?   3. The best fit found with `NMinimize` is `J_min` as 0.203498 and `{\\[Beta]0 -> -25.1613, \\[Beta]1 -> 0.206232, \\[Beta]2 -> 0.201472}` as compared to `J_min` as 0.203506 and `[-24.932998 0.204408 0.199618]` found with Matlab's `fminunc`. It seems Mathematica wins. Right?   4. Using `LogitModelFit` on the binary nonlinear logistic regression example, it found a decision boundary with a hole. Is there any way to control the complexity/topology of the decision boundary (thinking under-fitting and/or over-fitting)? ### Appendix: complete code The complete code and data is stored in Github. I intend to keep it for as long as Github allows. ### Appendix: example data set (as per comment)               34.62365962451697,78.0246928153624,0     30.28671076822607,43.89499752400101,0     35.84740876993872,72.90219802708364,0     60.18259938620976,86.30855209546826,1     79.0327360507101,75.3443764369103,1     45.08327747668339,56.3163717815305,0     61.10666453684766,96.51142588489624,1     75.02474556738889,46.55401354116538,1     76.09878670226257,87.42056971926803,1     84.43281996120035,43.53339331072109,1     95.86155507093572,38.22527805795094,0     75.01365838958247,30.60326323428011,0     82.30705337399482,76.48196330235604,1     69.36458875970939,97.71869196188608,1     39.53833914367223,76.03681085115882,0     53.9710521485623,89.20735013750205,1     69.07014406283025,52.74046973016765,1     67.94685547711617,46.67857410673128,0     70.66150955499435,92.92713789364831,1     76.97878372747498,47.57596364975532,1     67.37202754570876,42.83843832029179,0     89.67677575072079,65.79936592745237,1     50.534788289883,48.85581152764205,0     34.21206097786789,44.20952859866288,0     77.9240914545704,68.9723599933059,1     62.27101367004632,69.95445795447587,1     80.1901807509566,44.82162893218353,1     93.114388797442,38.80067033713209,0     61.83020602312595,50.25610789244621,0     38.78580379679423,64.99568095539578,0     61.379289447425,72.80788731317097,1     85.40451939411645,57.05198397627122,1     52.10797973193984,63.12762376881715,0     52.04540476831827,69.43286012045222,1     40.23689373545111,71.16774802184875,0     54.63510555424817,52.21388588061123,0     33.91550010906887,98.86943574220611,0     64.17698887494485,80.90806058670817,1     74.78925295941542,41.57341522824434,0     34.1836400264419,75.2377203360134,0     83.90239366249155,56.30804621605327,1     51.54772026906181,46.85629026349976,0     94.44336776917852,65.56892160559052,1     82.36875375713919,40.61825515970618,0     51.04775177128865,45.82270145776001,0     62.22267576120188,52.06099194836679,0     77.19303492601364,70.45820000180959,1     97.77159928000232,86.7278223300282,1     62.07306379667647,96.76882412413983,1     91.56497449807442,88.69629254546599,1     79.94481794066932,74.16311935043758,1     99.2725269292572,60.99903099844988,1     90.54671411399852,43.39060180650027,1     34.52451385320009,60.39634245837173,0     50.2864961189907,49.80453881323059,0     49.58667721632031,59.80895099453265,0     97.64563396007767,68.86157272420604,1     32.57720016809309,95.59854761387875,0     74.24869136721598,69.82457122657193,1     71.79646205863379,78.45356224515052,1     75.3956114656803,85.75993667331619,1     35.28611281526193,47.02051394723416,0     56.25381749711624,39.26147251058019,0     30.05882244669796,49.59297386723685,0     44.66826172480893,66.45008614558913,0     66.56089447242954,41.09209807936973,0     40.45755098375164,97.53518548909936,1     49.07256321908844,51.88321182073966,0     80.27957401466998,92.11606081344084,1     66.74671856944039,60.99139402740988,1     32.72283304060323,43.30717306430063,0     64.0393204150601,78.03168802018232,1     72.34649422579923,96.22759296761404,1     60.45788573918959,73.09499809758037,1     58.84095621726802,75.85844831279042,1     99.82785779692128,72.36925193383885,1     47.26426910848174,88.47586499559782,1     50.45815980285988,75.80985952982456,1     60.45555629271532,42.50840943572217,0     82.22666157785568,42.71987853716458,0     88.9138964166533,69.80378889835472,1     94.83450672430196,45.69430680250754,1     67.31925746917527,66.58935317747915,1     57.23870631569862,59.51428198012956,1     80.36675600171273,90.96014789746954,1     68.46852178591112,85.59430710452014,1     42.0754545384731,78.84478600148043,0     75.47770200533905,90.42453899753964,1     78.63542434898018,96.64742716885644,1     52.34800398794107,60.76950525602592,0     94.09433112516793,77.15910509073893,1     90.44855097096364,87.50879176484702,1     55.48216114069585,35.57070347228866,0     74.49269241843041,84.84513684930135,1     89.84580670720979,45.35828361091658,1     83.48916274498238,48.38028579728175,1     42.2617008099817,87.10385094025457,1     99.31500880510394,68.77540947206617,1     55.34001756003703,64.9319380069486,1     74.77589300092767,89.52981289513276,1


title: Cell output controlled by CellFrameLabel Checkbox?

text: The following generates a `Cell` that returns the state of the checkbox when evaluated:               CellPrint[       ExpressionCell[         {DynamicModule[{val=True}           , Checkbox[               Dynamic[val, (val=#; SetOptions[EvaluationCell[], TaggingRules->{"value"->val}])&]             ]           ]         , Dynamic@CurrentValue[{TaggingRules,"value"}]         }       , TaggingRules->{"value"->True}       , Evaluatable->True       , CellEvaluationFunction->(CurrentValue[{TaggingRules,"value"}]&)]     ]      ![Works](http://i.stack.imgur.com/6HCLE.png) Moving the checkbox into the frame label breaks the functionality. Why?               CellPrint[       ExpressionCell[         Dynamic@CurrentValue[{TaggingRules,"value"}]       , TaggingRules->{"value"->True}       , CellFrameLabels->         {           {ToBoxes[             DynamicModule[{val=True}             , Checkbox[                 Dynamic[val, (val=#; SetOptions[Print[FullForm@EvaluationCell[]];EvaluationCell[], TaggingRules->{"value"->val}])&]               ]             ]           ], None}         , {None,None}         }       , Evaluatable->True       , CellEvaluationFunction:>(Print[FullForm@EvaluationCell[]];CurrentValue[{TaggingRules,"value"}]&)]     ]      ![Fails](http://i.stack.imgur.com/SRmGJ.png) Printing the `EvaluationCell[]` shows that `SetOptions` is setting the `TaggingRules` on the `FrameLabel` cell, not the main cell. **How does one update the tagging rules of the main cell from within a frame?**


title: Using FreeQ with implicit functions

text: In Mathematica 7, I want to determine whether a list of free of numbers greater than 1 or not. It seems like using `FreeQ` would be a concise way to do this:               FreeQ[{2, 1}, # > 1 &] (* The output is: True *)          FreeQ[{1, 1}, # > 1 &] (* The output is: True *)      Why does `FreeQ[{2, 1}, # > 1 &]` give `True`? `{2, 1}` is not free of numbers greater than 1, so I must be using `FreeQ` incorrectly.


title: shortest paths in probabilistically weighted edges?

text: I understand Mathematica can find shortest paths. However, is it also able to find the most probable paths? I mean this is a case where edges are given probabilistic wights (from 0 to 1) and the most probable path from i to j is simply a multiplication (not addition) of weights queuing within the path. * * * I am not currently working on Mathematica. I understood some of its capabilities from the the documentations and tutorial guides. I am enquiring so as to confirm weather Mathematica could serve for my particular need; thence I would pay for a licence and download it. In UCINET, for example, the users have the choice upon the type of weights (e.g cost, probability, etc.) allotted to the edges to compute 'reachability'. Reachability looks for all paths between i and j and computes the product of the path that attains the maximum value. That is: MAX(i * h1 * h2 * h3 * j), where h are the internediate nodes between i and j. However, UCINET only provides the reachability (product of the most probable path) but do not actually tells which path is it.. The answer I am looking for is weather Mathematica could do that or not. Thanks


title: Animating a Voronoi Diagram

text: edit: Excellent answers have been provided and I made an animation which is suitable for my use, however, all the examples rely on bitmap/rasterized data; is there a vector based approach? I would like to animate the formation of a voronoi network from a set of semi- random points.               points = Table[{i, j} + RandomReal[0.4, 2], {i, 10}, {j, 10}];     points = Flatten[points, 1];      The final `VoronoiDiagram` can be easily plotted with `DiagramPlot` in the `ComputationalGeometry` package.               Needs["ComputationalGeometry`"]     voronoi = DiagramPlot[points, TrimPoints -> 50, LabelPoints -> False];      I want to animate a series of circles growing outwards uniformly from each of the points until they intersect to form the voronoi network.               ExpandingCircles[r_, points_] :=       Graphics@{Point /@ points, Circle[#, r] & /@ points}     plots = ExpandingCircles[#, points] & /@ {0.1, 0.2, 0.3, 0.4, 0.5};     GraphicsGrid@Partition[Join[plots, {voronoi}], 3]      ![Mathematica graphics](http://i.stack.imgur.com/LH2fJ.png) Similar to that progression but in mine the circles overlap. I want them to stop growing as they hit the adjacent circle to form the voronoi network but I can't figure out how to do this. Based on @R.M.s pointing out @belisarius answer I've tried this:               GraphicsGrid@      Partition[       ColorNegate@          EdgeDetect@           Dilation[ColorNegate@Binarize@Rasterize@Graphics@Point@points,             DiskMatrix[#]] & /@ Range[1, 24, 3], 4]       ![Mathematica graphics](http://i.stack.imgur.com/Mh7h2.png) However, I can't get them to merge into the voronoi structure. Somewhat like this video (http://www.youtube.com/watch?v=FlkrBSh4514) except all of mine start growing at the same point in time.


title: Selecting terms from a matrix

text: There are similar questions to this on the forum but none fit the purpose here: I would like to extract certain elements of a matrix depending on whether a factor is present or not, and create another matrix of the same size with those elements and zeros everywhere else. For example, given \begin{equation} \left [ \begin{array}{c c} a x & b x^2 \\ c y & d y^2 \end{array} \right ] \end{equation} I would like to create a new matrix with just the elements that have $x^2$ as a member and zeros everywhere else. \begin{equation} \left [ \begin{array}{c c} 0 & b x^2 \\ 0 & 0 \end{array} \right ] \end{equation} I've tried variants of things like this but can't get it to work               SIGMA = {{ a x , b x^2},{c y , d y^2}};          SIGMAx2 = Select[SIGMA , MemberQ[#, x^2] &];


title: Removing reverse versions of lists from a nested list

text: I need to remove the reverse versions of lists from list of lists. I.e.: `{{1,2},{2,2},{2,1},{a,1,2},{2,1,a}}` I need to reduce to `{{1,2},{2,2},{a,1,2}}`. The requirement to remove only the reverse of a given list means that permutations other than the reverse will be conserved, so that               {{1,2,3},{2,1,3},{3,2,1},{1,2,2},{a,1,2},{2,1,a}}      should reduce to               {{1,2,3},{2,1,3},{1,2,2},{a,1,2}}      My try gives correct result but it use nested `For` which is not too nice. Does anyone know of a better way to do it?


title: Make Quantity behave reasonable with Degrees Celsius

text: When using a `Quantity` with the unit of `"DegreesCelsius"` multiplication doesn't work as expected. If you have 10 degrees and multiply it by 2 you get 20 degrees instead of the expected 293,15 degrees. This becomes a real problem if you use the temperature directly in a formula, eg. the ideal gas law. Example code:               t = Quantity[10, "DegreesCelsius"];     T = UnitConvert@t;     UnitConvert[2 * t] // N (* => 293.15 K *)     2 * T // N (* => 566.3 K *)      Is there a way to fix this behaviour to work as I expect it to?


title: Problem regarding 3D plot of a Moebius strip from a set of 2D points

text: First time posting here, although an experienced user of WM. I have a problem regarding graphics which I cannot seem to fix, so I am asking for your help.   1. I start with a set of points $(x,y)$ in the range of $[0,1]\times[0,1]$, so a 2D rectangle. With these points I generate a triangle mesh which I later use with Finite Element Method for solving the eigenmodes of this rectangle OR a coat of cylinder, torus, or moebius, depending on what kind of boundary conditions I use in FEM.   2. If the membrane is a coat of a 3D object, like in this case for a moebius strip, I want to draw the surface of a Moebius strip as a set of points $(x',y',z')$ in 3D. Normally I do this using parametrisation equations. I have found the equations for a moebius strip and they work perfectly. Here are the transformations     * x' = (R+S*Cos[0.5*t])*Cos[t]      * y' = (R+S*Cos[0.5*t])*Sin[t]      * z' = S*Sin[0.5*t] where `t`$\in$ `[0,2Pi] = 2Pi * x` and `S`$\in$`[-0.5,0.5] = y - 0.5`.   3. With these new 3D points I can now do a surface plot in 3D, which shoud look something like this for the case of a cylinder: ![Cylinder](http://i.stack.imgur.com/DcTbu.png) But if I draw these points as a moebius strip, I get weird anomalies. Here are the two cases I tried:     * `ListSurfacePlot3D` -> I get weird anomalies. I tried tweaking `MaxPlotPoints` but it didn't do the trick. ![First case](http://i.stack.imgur.com/XpruE.png)     * `ListPlot3D` -> Works a bit better, but it also fills the hole in between and draws a weird joint. ![Second case](http://i.stack.imgur.com/v5kSQ.png) Here is the data sample of a 2D rectangle: Original Here is the same data sample, but transformed for the case of moebius: Transformed Plot codes for the data               p1=Graphics3D[Point[data3d], Boxed -> False, AspectRatio -> 1,        BoxRatios -> Automatic, SphericalRegion -> True, PlotRange -> All,        ImageSize -> 350]     p2=       ListPlot3D[data3d, Boxed -> False, Axes -> False,        SphericalRegion -> True, AspectRatio -> 1, BoxRatios -> Automatic,        MaxPlotPoints -> 30, PlotRange -> All, ImageSize -> 350,        Mesh -> Automatic, PlotStyle -> Magenta]               Show[{p1, p2}]      Where `ListPlot3D` can also be changed with `ListSurfacePlot3D`. I really appreciate your help.


title: eigenvector bug also for matrix with numeric value

text: I just realize that probably there is a bug also in calculating the eigenvector of a matrix with numeric values (see here for bug in eigenvector calculation with symbolic value). In particular in my case I have a matrix (of large dimensions say N>100) for which the sum of the columns is constant. It can be proved that in this case the unit vector is the right-eigenvector of the matrix corresponding to the eigenvalue with max real part. However if I try to compute the eigenvector with Mathematica it gives me an incorrect output. Example. Import the example matrix m from here. Check the that v1={1,1,1...,1} is an eigenvector of the eigenvalue l1=-0.987:               m.ConstantArray[1.,Length[m]] + (0.987 ConstantArray[1.,Length[m]]) // Chop      Then calculate the corresponding Eigensystem with Mathematica               {v2,l2}=Eigensystem[m,-1]      You can check that although l1=l2, v2 is not the unit vector.


title: NIntegrate is resetting my variables and not giving me a result?

text: I am trying to check if mass conservation holds by integrating the area under a curve but to no avail.               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];      Needs["VectorAnalysis`"]          Clear[Eq0, EvapThickFilm, h, Bo, ϵ, K1, δ, Bi, m, r]     Eq0[h_, {Bo_, ϵ_, K1_, δ_, Bi_, m_, r_}] :=       D[h, t] + Div[(-h^3)*Bo*Grad[h] + h^3*Grad[Laplacian[h]] + ((δ*h^3)/(Bi*h + K1)^3)*Grad[h]       + m*(h/(K1 + Bi*h))^2*Grad[h]] + ϵ/(Bi*h + K1) + r*D[D[h^2/(K1 + Bi*h), x]*h^3, x] == 0;          L = 2*92.389;      TMax = 2491.29*100;      Off[NDSolve::mxsst];      hSol[x_, y_, t_] = h[x, y, t] /.         NDSolve[{EvapThickFilm[0.003, 0, 1, 0, 1, 0.025, 0],            h[0, y, t] == h[L, y, t], h[x, 0, t] == h[x, L, t],            h[x, y, 0] == 1 + (-0.25*Cos[2*Pi*(x/L)] - 0.25*Sin[2*Pi*(x/L)])*              Cos[2*Pi*(y/L)]}, h, {x, 0, L}, {y, 0, L}, {t, 0, TMax},           MaxStepFraction -> 1/60][[1]]      When I use `NIntegrate[...]` to integrate under the area of the curve for a single value of `TMax`, I don't get a single valued number. In fact, my variables are reset! What gives?               NIntegrate[hSol[x, y, 0.1*TMax], {x, 0, L}, {y, 0, L}]      I've tried it with simpler 2D cases instead of 3D and this works fine. FOOTNOTE: Is there some way I could _host_ this code elsewhere? Any websites that support mathematica code format? # EDIT 1: The error that `NIntegrate[..]` gives me is that x = L is not a valid limit of integration. whilst L has actually been defined in the problem previously.


title: Export to file from ParallelDo loop

text: I currently have a Mathematica code similar to:               ParallelDo[      Quiet@Check[        Print[var1, "\t", var2, "\t", integral1[var1,var2], "\t",              integral2[var1, var2]],         err      ],       {var1, 10, 50, 2}, {var2, 10, 100,1}     ]      And, I get the results I want in the GUI. However, I can't seem to figure out the best way to export the data I want, while keeping the `ParallelDo` loop. Ideally I would like a comma separated format, similar to what the above outputs. Any ideas? Many thanks in advance!


title: What does MaxStepFraction do?

text: I find that with `NDSolve[...]` while solving a partial differential equation, changing the `MaxStepFraction` from `1/10` to say `1/60`, improves convergence. Without going into too many details about the PDE itself, is the `MaxStepFraction` the grid sized used? I generally find that when I use a large step fraction of say `1/30` instead of `1/60`, I get an error message that says: > NDSolve::eerr: Warning: Scaled local spatial error estimate of > 1484.278641749214`at t = 240279.84981818125` in the direction of independent > variable x is much greater than prescribed error tolerance. Grid spacing > with 31 points may be too large to achieve the desired accuracy or > precision. A singularity may have formed or you may want to specify a > smaller grid spacing using the MaxStepSize or MinPoints method options. >> Am I to understand that for a large step fraction, my equation either get's stiff (as the step size is large/grid is too coarse)? **EDIT 1:** My 4th order non-linear PDE generally looks like: `h_t + N(h[t,x],h[t,x]^2,h[t,x]^3,h[t,x]^4) = 0` Where `N(...)` is the non-linear portion. **EDIT 2:** I used               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];      and               hGrid = InterpolatingFunctionGrid[hSol];       {nX, nY, nT} =Drop[Dimensions[hGrid], -1]      Where `hSol` is my interpolating function result that `NDSolve` provides, and found that nx,ny and nT are respectively: 41,41,298 when I used `MaxStepFraction->1/40`. So I am guessing, that `MaxStepFraction->` does define the spatial grid. Any thoughts? Comments?


title: Setting the DifferenceOrder Option

text: I've been playing around with `Method` in `NDSolve[...]` and can't quite seem to figure out how to force `NDSolve` to use a certain difference order with a certain method. For instance, I am trying to validate my work against results of solving an ODE with the Backward Euler method which essentially is BDF of order 1. Now, Mathematica does have the BDF method for solving stiff equations but when I set the following: `Method->{"BDF", "DifferenceOrder"->1}` I get the following error: > NDSolve::moptx: Method option DifferenceOrder in > {NDSolve`BDF,{DifferenceOrder->Automatic}} is not one of > {ImplicitSolver,MaxDifferenceOrder,VariableStepCoefficients}. >> > > NDSolve::initf: The initialization of the method NDSolve`BDF failed. >> But when I run `NDSolve` with just `Method->{"BDF"}`, lo and behold, I get my solution. Just to make sure that `BDF` does take `DifferenceOrder` options, I checked with `Options[NDSolve`BDF]` as prompted in a previous question. Is this not how I should set the order for BDF? What am I missing? ### EDIT 1: I realized I should be using the IDA method as that apparently uses the BDF method to solve DAEs. Still trying to figure out how I might go about doing this though. ### EDIT 2: I think I might have figured it out. This is what I changed in `Method` `Method -> {"IDA", "ImplicitSolver" -> "Newton", "MaxDifferenceOrder" -> 5},` From IDA's documentation provided in Advanced Numerical Differential Equation Solving in Mathematica, I think with `IDA` with `Newton` Implicit Solver of Order 5, I am actually using a BDF5 method. ### EDIT 3: Per rcollyer's comment, it should be `"MaxDifferenceOrder"` and NOT `"DifferenceOrder`" in case `BDF` is used as the `Method` Example: `Method->{"BDF", "MaxDifferenceOrder->5"}` executes BDF5. Any thoughts? Comments? Anything else that I might look for, for say other methods such as the `LSODA` etc? ### EDIT 4: As per rcollyer's comment, `BDF` with `"MaxDifferenceOrder"->5`, `NDSolve[..]` changes the order as required UP TO 5 and doesn't just use order 5.


title: I need a technique for determining and drawing a line where the density in a listplot jumps up suddenly

text: Basically I have a two dimensional list plot with a bunch of points between the square of (0,0) and (1,1). The y-values of these points are drawn from a uniform probability distribution between 0 and 1, and the x-values are drawn from a semi-uniform distribution, except it jumps up at x=.5. So in the plot the density of points jumps up at x=0.5. I need a statistical technique that will determine where this jump occurs and will draw a line there, even if we didn't know the jump was at 0.5 or if the initial conditions were changed and it wasn't at 0.5 or even a straight line. ![List Plot](http://i.stack.imgur.com/uAnEk.png)


title: Cubic Splines Functions

text: I have this set of three data points and want the natural cubic spline functions for them:                 dat = {{-.0247500, .5}, {.3349375, -.25}, {1.101000, 0}};      I tried:                 f = SplineFit[dat, Cubic]      Using another approach and code, I get the two cubic functions (I am trying to verify the correctness) as:               -0.481347 + 0.753113 x - 0.0338047 x^2 - 0.455282 x^3          -0.506486 + 0.978281 x - 0.706073 x^2 + 0.213767 x^3      Is there anyway to see these results and the intermediate results to derive the two cubics using Mathematica (I tried looking at documentation and could not make sense of it)?


title: Index-based Array splitting

text: I have an array of arbitrary elements, say strings:               testArray = {"String A", "String B", "String C", "String D", "String E"};      How can I split this into two arrays, one for the element with odd indices in `testArray` and one for elements with even indices in `testArray`:               testArrayOdd = {"String A", "String C", "String E"};     testArrayEven = {"String B", "String D"};      Is there a simple way to do this that generalizes to more complicated partitionings based on, say, the primeness of the index? Clarification!: The strings in the array can be anything "String 1" could be "knejibvei (junk)". We only care about the INDEX of the string in the original array. Sorry about this. For odd / even testing of elements, see here: Separate an array in two arrays, the even and odd terms being separated in these two arrays


title: Deleting Vertices in GridGraph

text: Take a simple `GridGraph`:               g = GridGraph[{3, 3}, VertexLabels -> "Name", ImageSize -> 150, ImagePadding -> 10]      ![g](http://i.stack.imgur.com/ycGpT.png) I am puzzled by the following behavior: Try to delete vertex 2:               h=VertexDelete[g, 2]      ![vd](http://i.stack.imgur.com/POsDU.png) Vertex 2 was deleted, but so were several edges that did not have a node at vertex 2. In addition, Vertex 1 appears to be connected to vertex 3; it wasn't before. Now look at the remaining edges:               EdgeList[h]      > {1 [UndirectedEdge] 4, 3 [UndirectedEdge] 6, 4 [UndirectedEdge] 5, 4 > [UndirectedEdge] 7, 5 [UndirectedEdge] 6, 5 [UndirectedEdge] 8, 6 > [UndirectedEdge] 9, 7 [UndirectedEdge] 8, 8 [UndirectedEdge] 9} According to the edge list, Vertex 1 is not connected to vertex 3 (even though it was draw as connected to 3); but vertex 1 **is** connected to vertex 4 (even though it was not so drawn). * * * Try deleting vertices 1 and 3:               VertexDelete[g, {1, 3}]      ![vd2](http://i.stack.imgur.com/tihaD.png) Either I am misunderstanding something or Mathematica is erring. Can anyone explain which is the case? Thanks.


title: Generated Numbers under a constraint?

text: Let's say I have five four dimensional vectors $p_i^\mu=(p_i^1,p_i^2,p_i^3,p_i^4)$ with $i=1,2,3,4,5$. Now, I want to fill the entries of these vectors ($4\cdot5=20$ in total) with some numbers, but such that the resulting vectors satisfy the following $9$ constraints: $$(p_i^1)^2-(p_i^2)^2-(p_i^3)^2-(p_i^4)^2=0~~~\text{for each }i\in\{1,2,3,4,5\}$$ $$p_1^\mu+p_2^\mu+p_3^\mu+p_4^\mu+p_5^\mu=0~~~\text{for each }\mu\in\{1,2,3,4\}$$ What is a convenient way to create such constrained vectors in _Mathematica_? Maybe there is a built in function that does just that?


title: How can I restrict a notebook to evaluate only if I am user 'root'?

text: I am playing with openCL on Linux with an AMD gpu, and due to a glitch in the driver, I need to be 'root' to get stuff to work. Installation question here.


title: Notation Package Quirk for single Symbols

text: I encounter the following quirk in the Notation package: consider the following ==> and <== declarations               Notation[      ParsedBoxWrapper[RowBox["\[DoubleStruckOne]"]]         \[DoubleLongRightArrow]      ParsedBoxWrapper[RowBox[{"Blade", "[", RowBox[{"{", "}"}], "]"}]]     ]      and               Notation[      ParsedBoxWrapper[RowBox[{"\[DoubleStruckOne]"}]]       \[DoubleLongLeftArrow]      ParsedBoxWrapper[RowBox[{"Blade", "[", RowBox[{"{", "}"}], "]"}]]     ]      the only difference is the Braces in the left hand side `RowBox`. It _only_ works this way. If I use either line with a two-way arrow <==>, it will fail in one direction or the other. Why is that? Do I have to use another Wrapper/Box?


title: Can I get rid of the "learning bar"?

text: I just purchased a home edition of Mathematica 10, and there seems to be a toolbar that I can't get rid of. It is kind of annoying and distracting. I couldn't find the option in the preference panel. Can someone kindly help? ![enter image description here](http://i.stack.imgur.com/IM4z2.png)


title: DateListPlot does not accept PlotRange or GridLine specifications using DateObject

text: This doesn't work...               DateListPlot[{{DateObject[{2014, 1, 1}], 1},      {DateObject[{2014, 1, 2}], 2},      {DateObject[{2014, 1, 3}], 3}},       Joined -> True, GridLines -> {{DateObject[{2014, 1, 2}]}, None}]      Neither does this...               DateListPlot[{{DateObject[{2014,1,1}],1},     {DateObject[{2014,1,2}],2},     {DateObject[{2014,1,3}],3}},      Joined->True, PlotRange->{{DateObject[{2014,1,1}],DateObject[{2014,1,3}]},All}]      Converting the values in GridLines and PlotRange to DateLists works. It seems a bit of an over-sight not to support DateObject here. The question is should this work?


title: How to sort the functions in a Package?

text: Once a Package like `abc`` has been installed, we can use "`?abc`*`" to scan all the functions defined in this Package. Now I write a Package(`abc``). After I have installed it, I use `?abc`*` to scan the functions. But the function list is out-of-order. How can I set the function list to alphabetical order using `?abc`*` ?


title: Converting a string into a nested list of strings

text: The following string can be converted easily into a list with `ToExpression`               string = "{{a},{b,c,d},{e,{f,{g}}}}";     ToExpression@string      However, if the string contains characters that can be misinterpreted as syntax errors, I run in to problems.               string = "{{a},{b,c,d},{e,{[f],{g}}}}"      `ToExpression` throws an error since "[f]" isn't valid Wolfram. (Side note, is that sentence grammatically correct? I would write "...isn't valid Java or C". Is it more appropriate to write "... isn't valid Wolfram Language?") I would like to convert a string into a nested list of strings. For reference (2242) starts with data whose `Head` is `List` and doesn't readily appear to work with nested lists, (43930) is a similar question focusing on `Graph` and looks promising except that the solution uses _levelspec_ in `Cases` which, to my understanding, is not available in `StringCases`.


title: Converting expression into string without evaluating it

text: How can one convert a Mathematica expression into a string without the expression being evaluated first? I tried using `Hold`, but it returns `Hold[expr]`, instead of `expr`. Is there any way to get just the expression? For example, I have a variable `var = 5`, and I need to assign the _name_ of `var` to another variable, so that `var2 = "var"`. How can I do this? My actual use case is this: I am trying to synchronize my mathematica variables with certain fields in an external database. Every time the external database is updated, I call on a function that is supposed to update my corresponding Mathematica variables. It takes in a list of mappings like `{var1 -> "field1", var2 -> "field2"}`, and its role is to access the external database, look up the value in `"field1"`, and assign it to `var1`, then look up the value in `"field2"` and assign it to `var2`. The number of variables in the mapping (and their names) can be arbitrary. The problem is that I need those `var1` and `var2` variables to be passed as variable _names_ , not values, so that I can assign them inside the function. I do the assignment using ` `Do[ i[[1]]->i[[2]]/.remoteData, {i,mappings} ]` ` where `remoteData = {"field1"->"value of field 1", "field2" -> "value of field 2"}`. I need `i[[1]]` to stand for `var1`, not for its value. I tried setting the attribute `SetAttributes[fn,HoldAll]` but that didn't help. The result that I am looking for is `var1 = "value of field 1"`, `var 2 = "value of field 2"`.


title: How can I sequentially apply different graph embeddings?

text: Imagine I have some graph `G`, and I perform a graph embedding using a command like:               G = Graph[GraphEdges, GraphLayout -> {"SpringElectricalEmbedding"}]      I then want to apply a `"GridEmbedding"` to the post-Spring/Electrical embedded graph. How can I do this? Specifically, I have a graph I know to be a rectangular lattice, but the vertices are at random positions initially. Attempting a direct `"GridEmbedding"` yields junk; however the `"SpringElectricalEmbedding"` almost works, but begins to fail around the edges of the graph. Does anyone have advice for dealing with this? Alternatively, can `"GridEmbedding"` be made to respect edge lengths / weights akin to what is possible for `"SpringElectricalEmbedding"`?


title: LogLinearPlot, extact data to a file, part 2

text: My question is based on the discussion that I started: Plot, extract data to a file The method proposed works well for the `Plot` command, but what about `LogLinearPlot`? This was the original motivation when I started the thread. I wanted to extract the data for `LogLinearPlot`, because I wanted a tighter grid for r $\approx$ 0. Otherwise, I could have just used `Table` and wouldn't have started the thread. This doesn't work with `Table`, which produces a uniform grid. Anyways, this is my code:               LogLinearPlot[{f[r]*r, 0}, {r, 0.0001, 1000}, PlotRange -> {-0.5, 0.2}, MaxRecursion -> 15]     data = Cases[%, Line[data_] :> data, -4, 1][[1]];     Export["~/Desktop/1.dat", SetAccuracy[%, 10], Alignment -> Center]      _The catch is that it produces a relative positions of the points on the **r** axis for the 1st column ( **r** coordinates of the points they would have if the **r** -axis wasn't set to be logarithmic on the plot)._ For example,               -9.210340043    -0.044128619     -9.210320733    -0.04412862      ......      whereas I was expecting something like this:                0.000110000    -0.044128619      0.000170000    -0.04412862      ........         The origin of the "fictitious" and real axes coincide. How do I get the actual values of **r**?


title: ListLinePlot filling for accumulated data

text: I have 23 variables (energy production units) which take values for each hour of the day (energy dispatch table). Here is a PasteBin example of data. I am trying to represent the distribution of the total energy production for each hour. So far I have managed a pretty decent plot using :               accunits = Table[Accumulate[Transpose[allunits][[k]]], {k, Range[24]}];     ListLinePlot[Transpose[accunits], PlotRange -> All, AxesOrigin -> {1, 0}, ImageSize -> 500, Filling -> colors, PlotStyle -> Opacity[0]]      I still don't fully understand the proper use of `FillingStyle` with `ColorData`, so I created a list :               colors = Join[      Table[i -> {{i + 1}, Yellow}, {i, 1, 3}],      Table[i -> {{i + 1}, Orange}, {i, 4, 8}],      Table[i -> {{i + 1}, Red}, {i, 9, 15}],      Table[i -> {{i + 1}, Brown}, {i, 16, 20}],      {21 -> {{22}, Blue}},      {22 -> {{23}, Green}}];      Note the two last units are hydro and renewables, so the color scheme is different, while the 21 other units are thermal, so I tried to recreate a simplified `TemperatureMap`. This gives me the following image ![Dispatch](http://i.stack.imgur.com/iq1yk.png) **My question(s) is** :   How can I refine the plot so that the lines between colored regions don't appear so aliased and so that the space between the x-axis and the first unit is also colored? Also, how can I apply a temperature color scheme independent of the number of thermal units (the last two units are always hydro/blue and renewables/green)? EDIT 1 : I found a solution for the coloring of the first unit, by adding a list of zeros as a first "unit" (I had to change the `colors` list to take into account this extra first "unit"):               accunits2 = Table[Accumulate[Transpose[Prepend[allunits2[[i, j]], Table[0, {p, Range[24]}]]][[k]]], {k,Range[24]}]      Cheers, E


title: Finding all/most roots of a discontinuous function more consistently?

text: I have the equation:               f[x_]:=α Tan[α*a] - Sqrt[c - α^2]      and ideally I want to find all of its positive zeros, given a and c, with variable alpha. The problem is that it's a discontinuous graph with large derivatives at the zeros. This is a plot of tan(alpha*a) vs sqrt(c-alpha^2)/alpha, so that the intersection of the two graphs is a zero of the function:               Manipulate[      Plot[{ Tan[α a],         Sqrt[c - α^2]/α}, {α, -0.1, 4}, PlotRange -> {-10, 10}]      , {{a, 1.56}, -5, 5}, {{c, 10}, 0, 10}]      ![graph of b tan\(b*a\) and sqrt\(c-b^2\)](http://i.stack.imgur.com/iPF9J.png) So, for that case there are five positive zeros (ignoring the single one at the end, I don't want to try to find that numerically). To solve for them, I used FindRoot, and based off the properties of the tangent curve, I figure the best place to start would be somewhere well behaved in the tangent function, like when α*a=[Pi]*(n+1/4) for integer n. So to get the roots I call FindRoot whenever this formula for alpha gives a value of Sqrt[c-alpha^2] that is real:               wellroots[a2_, c2_] :=      Table[HoldForm[          FindRoot[           α Tan[α Rationalize[a] ] ==             Sqrt[Rationalize[c] - α^2],           {α, Pi *(n + 1/4)/(a)},           WorkingPrecision -> 30           ]          ] /. {a -> a2, c -> c2, n -> n2},        {n2, 0, Floor[Sqrt[c2] a2/Pi - 1/8]}] // ReleaseHold      (I needed the HoldForm and ReleaseHold commands to make sure FindRoot wasn't evaluated until the function was actually called. I used WorkingPrecision to try to smooth out the problems I was getting, and I used Rationalize so that it turned c into an exact value so I didn't get a "function precision less than working precision" error/warning from FindRoot. The Floor[...] term just puts a bound on n2.) This works decently, and I can plot all approximated roots:               Manipulate[      Show[       Plot[{ Tan[α a],          Sqrt[c - α^2]/α}, {α, -0.1, 4},         PlotRange -> {-1, 10}],       Graphics[Join[{PointSize[0.02]},         (Point[{α, Tan[α a]}]) /. wellroots[a, c]         ]],       Graphics[(Line[{{x, -5}, {x, 5}}])         /. Table[{x -> Pi (n + 1/4)/(a)}, {n, 0,            Floor[Sqrt[c] a/Pi - 1/8]}]        ]       ]      , {{a, 1.56}, -5, 5}, {{c, 10}, 0, 10}]      ![Graph of zeros with starting approximations and calculated roots](http://i.stack.imgur.com/Tsz0o.png) (the black lines are the initial approximations passed in to FindRoot, and the black circles are the approximated solutions.) The problem is that as I drag the manipulate bars for a and c, sometimes the display of roots found flickers, showing that wellroots didn't find all possible roots. (and, the flickering isn't just a graphical thing, when I stop dragging the bar, some roots are still not shown) So, I guess it's a bit much to ask to find all n roots with only n numerical attempts, but, how can I increase reliability so that I can expect to always (or, almost always) find all the roots? And, only the positive roots matter, because the negative roots are just the negatives of all the positives. (this question comes from "A First Course in Computational Physics" by DeVries, section "A little quantum mechanics problem", and is about time independent solutions to the schrodinger equation in a square well with finite side energies, V=c^2*hbar^2/(2m), where c is the value in the equation above. alpha is Sqrt[2 m E/hbar^2], where E is the energy in the schrodinger equation, same units as V. It's not homework/not for a course.)


title: Why does Mathematica struggle with solving this equation?

text: Consider the evaluation of the following expression               In[20]:= Reduce[ 1000 * 1.0609^t == 1500, t]      > >     During evaluation of In[20]:= Reduce::ratnz: Reduce was unable to >     solve the system with inexact coefficients. The answer was obtained by >     solving a corresponding exact system and numericizing the result. >> >                 Out[20]= C[1] ∈ Integers &&        t == -16.9154 (-0.405465 + (0. + 6.28319 I) C[1])      I was expecting just `6.858618708478822` as the solution.


title: Is there a way to use video codecs for avi files in Mathematica?

text: I would like to use _Mathematica_ to create compressed **.avi** video files from image sequences. I read the documentation on **.avi** but couldn't find a solution. In the documentation it says: >   * Internal`$VideoEncodings gives a list of video codecs available on your > computer system. >   * Commonly available codecs include "YUV", "H261", "H263", "JPEG", > "Uncompressed", "Cinepak", and "MotionJPEG". > but none of these video encoding options effectively reduces the file size. When I install the latest version of QuickTime on my computer and use the applicable video encoding options, the exported **.mov** files are encoded. However, I would prefer to have **.avi** files due to compatibility reasons. If I check for available video encodings I get:               Internal`$VideoEncodings      > {"Animation", "BMP", "Cinepak", "Component Video", "DVCPRO - \ PAL", > "DV/DVCPRO - NTSC", "DV - PAL", "Foto - JPEG", "Grafik", \ "H.261", "H.263", > "JPEG 2000", "Keine", "Motion JPEG A", "Motion JPEG \ B", "MPEG-4 Video", > "Planar RGB", "PNG", "Sorenson Video", "TGA", \ "TIFF", "Uncompressed", > "Video"} I also have other ways to create **.avi** files using different software through _Mathematica_ but I would love to have it the pure _Mathematica_ way. I am using version 9.0.1. Are there any good alternatives to create a good quality video? I don't have the impression that the **.mov** files are of good quality... **Edit 24/07/2014**   * QuickTime version 7.7.5 (1680.95.13)    * Mathematica version 9.0.1 Here is an example piece of code that I have created. It gives absolutely the same file size for each **.avi** encoding I use (note that I leave out one of the encoding methods since it conflicts with `FileNameJoin`):               engine = Import["ExampleData/CTengine.tiff"];     outDir = CreateDirectory[        FileNameJoin[{NotebookDirectory[], "AviExport"}]];          Cases[Internal`$VideoEncodings, Except["DV/DVCPRO - NTSC"]]      > {"Animation", "BMP", "Cinepak", "Component Video", "DVCPRO - PAL", \ "DV - > PAL", "Foto - JPEG", "Grafik", "H.261", "H.263", "JPEG 2000", \ "Keine", > "Motion JPEG A", "Motion JPEG B", "MPEG-4 Video", "Planar \ RGB", "PNG", > "Sorenson Video", "TGA", "TIFF", "Uncompressed", "Video"}               ParallelMap[       Export[FileNameJoin[{outDir, "engine" <> # <> ".mov"}], engine,          "VideoEncoding" -> #] &,        Cases[Internal`$VideoEncodings, Except["DV/DVCPRO - NTSC"]]];          ParallelMap[       Export[FileNameJoin[{outDir, "engine" <> # <> ".avi"}], engine,          "VideoEncoding" -> #] &,        Cases[Internal`$VideoEncodings, Except["DV/DVCPRO - NTSC"]]];          Grid[Prepend[{#, N@FileByteCount[#]/1024^2} & /@         FileNames["*mov", {outDir}], {"Filename", "File size [MB]"}],       Alignment -> Left]      > ![mov files](http://i.stack.imgur.com/wuR2E.png)               TableForm[Prepend[{FileBaseName@#, N@FileByteCount[#]/1024^2} & /@         FileNames["*avi", {outDir}], {".avi file", "File size [MB]"}]]      > ![avi files](http://i.stack.imgur.com/M3Zka.png) Thanks for any suggestions!


title: System Dialog Input with Button

text: I am trying to create a button that uses `SystemDialogInput["FileOpen"]` to browse for a file and assigns the file name to a variable. For example:                {Button["Select the file", fname = SystemDialogInput["FileOpen"]], Dynamic[fname]}      This works most of the time; however, when the file that I browse to is several nested folders away from the default directory, it does not update the value of fname. Is there some way around this? Or is there a better function to use? I eventually would like to use this button within `Manipulate`.


title: Evaluating an expression a second time returns wrong result

text: I have the following code:               Sigma = {{1, 1}, {1, 1}};          sol =       Sum[ReplacePart[Apply[KroneckerProduct, Table[id, {i, 1, 2}]], {i -> Sigma}], {i, 1, 1}]          id = IdentityMatrix[2];          sol // Dimensions      > >     {4, 4} >                 sol2 =        Sum[ReplacePart[Apply[KroneckerProduct, Table[id, {i, 1, 2}]], {i -> Sigma}], {i, 1, 1}]          sol2 // Dimensions      > >      {4} >   As you see, when I evaluate the `Sum[...]` expression a second time, the dimension of the result changes and gives the wrong result. The result must be a 4 by 4 matrix. If I had put the `id` before `sol`, then I would have gotten the wrong result on the first evaluation. How can I resolve this problem? * * * I think the problem is with               ReplacePart[Apply[KroneckerProduct, Table[id, {i, 1, 2}]], {i -> Sigma}]      Before assigning `id` the position `i` is clear because we have something like `{id, id}` so `ReplacePart` can change the position `i` which contains `id` with `Sigma`. However, after assigning `id`, the position `i` is not clear anymore. I cannot find a solution to this problem.


title: How to simplify really complicated symbolic expression?

text: I have an expression that contains `Sinh[x]`, `Cosh[x]` and `Sin[g]`, and I want to simplify it into an easier form, based on the physics situation (I am doing some general relativity calculation), I know it should be simplified into a polynomial of `u`, and none of the coefficients of `u` should contain any fractional numbers. What I am doing right now is just using `Simplify` and some really simple patterns as transformation rules. Could someone give me some suggestion on how to simplify it? Or could someone please give me some materials or examples on how to simplify really complicated expressions? Here is my expression that needs to be simplifyed. > ((2 m^2-3 m r+r^2+a^2 u^2+m (2 m-r) Cos[2 g]) Cosh[p4]^2-4 I a m u Cos[g] > Cosh[p4] Sinh[p4]-(r^2+a^2 u^2) Sinh[p4]^2) ((-m r+r^2+a^2 u^2-m r Cos[2 g]) > Cosh[q4]^2+4 m Cosh[q4] (-I a u Cosh[p4] Sin[g]-1/2 r Sin[2 g] Sinh[p4]) > Sinh[q4]+1/2 (-4 m^2+5 m r-2 r^2-2 a^2 u^2-m r Cos[2 g]+m (-4 m+3 r+r Cos[2 > g]) Cosh[2 p4]+4 I a m u Cos[g] Sinh[2 p4]) Sinh[q4]^2) (-(m^2 Cosh[p4] ((4 > m r-3 r^2+3 a^2 u^2+(4 m r-r^2+a^2 u^2) Cos[2 g]) Cosh[p4]-8 I a r u Cos[g] > Sinh[p4]) (2 I a u Cosh[q4] Sin[g] Sinh[p4]-2 I a u Cos[g] Cosh[p4]^2 > Sinh[q4]+(-2 I a u Cos[g] Sinh[p4]^2+m (1+Cos[g]^2) Sinh[2 p4]) > Sinh[q4]-Cosh[p4] ((2 m-r) Cosh[q4] Sin[2 g]+(m+3 r+(-m+r) Cos[2 g]) > Sinh[p4] Sinh[q4])))/((r^2+a^2 u^2) ((-2 m^2+3 m r-r^2-a^2 u^2-m (2 m-r) > Cos[2 g]) Cosh[p4]^2+4 I a m u Cos[g] Cosh[p4] Sinh[p4]+(r^2+a^2 u^2) > Sinh[p4]^2)^2)+(2 m (-2 I a r u Cos[g] Cosh[p4]^2 Sinh[q4]+Cosh[p4] ((-4 m > r+r^2-a^2 u^2) Cos[g] Cosh[q4] Sin[g]+(2 (2 m-r) r Cos[g]^2+(-r^2+a^2 u^2) > Sin[g]^2) Sinh[p4] Sinh[q4])+a u (2 I r Cosh[q4] Sin[g] Sinh[p4]+Cos[g] (-2 > I r Sinh[p4]^2+a u Cos[g] Sinh[2 p4]) Sinh[q4])))/((r^2+a^2 u^2) ((2 m^2-3 m > r+r^2+a^2 u^2+m (2 m-r) Cos[2 g]) Cosh[p4]^2-4 I a m u Cos[g] Cosh[p4] > Sinh[p4]-(r^2+a^2 u^2) Sinh[p4]^2))-(m^2 (2 Cosh[q4] (7 I a m u Cos[g]+I a m > u Cos[g]^3+2 I a u Cos[g] (3 m-4 r+m Cos[2 g]) Cosh[p4]^2-3 I a m u Cos[g] > Sin[g]^2-2 Cosh[p4] (r^2 Cos[g]^2+a^2 u^2 Sin[g]^2) Sinh[p4]+2 I a u Cos[g] > (3 m-4 r+m Cos[2 g]) Sinh[p4]^2+4 m r Sinh[2 p4]-3 r^2 Sinh[2 p4]+3 a^2 u^2 > Sinh[2 p4]+4 m r Cos[g]^2 Sinh[2 p4]+a^2 u^2 Cos[g]^2 Sinh[2 p4]-4 m r > Sin[g]^2 Sinh[2 p4]+r^2 Sin[g]^2 Sinh[2 p4])+(4 (3 m^2-4 m r+r^2-a^2 u^2) > Cosh[p4] Sin[2 g]+4 m^2 Cosh[p4]^3 Sin[2 g]-12 I a m u Cosh[p4]^2 Sin[g]^3 > Sinh[p4]-I Sinh[p4] (a u (m-16 r-m Cos[2 g]) Sin[g]+2 a m u Cosh[2 p4] > Sin[g]^3+6 I m^2 Sin[2 g] Sinh[2 p4])) Sinh[q4]) (8 I a u Cosh[p4] Cosh[2 > q4] Sin[g]+8 r Cos[g] Cosh[q4]^2 Sin[g] Sinh[p4]+(4 m-3 r+7 r Cos[2 g]-r > (3+Cos[2 g]) Cosh[2 p4]) Cosh[q4] Sinh[q4]+8 r Cos[g] Sin[g] Sinh[p4] > Sinh[q4]^2+(4 m-3 r-r Cos[2 g]) Cosh[p4]^2 Sinh[2 q4]+2 m Cosh[2 p4] Sinh[2 > q4]-4 I a u Cos[g] Sinh[2 p4] Sinh[2 q4]))/(16 ((-2 m^2+3 m r-r^2-a^2 u^2-m > (2 m-r) Cos[2 g]) Cosh[p4]^2+4 I a m u Cos[g] Cosh[p4] Sinh[p4]+(r^2+a^2 > u^2) Sinh[p4]^2)^2 ((m r-r^2-a^2 u^2+m r Cos[2 g]) Cosh[q4]^2+4 I a m u > Cosh[p4] Cosh[q4] Sin[g] Sinh[q4]+(4 m^2-4 m r+r^2+a^2 u^2) Cosh[p4]^2 > Sinh[q4]^2-4 I a m u Cos[g] Cosh[p4] Sinh[p4] Sinh[q4]^2-Sinh[p4] ((-m > r+r^2+a^2 u^2+m r Cos[2 g]) Sinh[p4] Sinh[q4]^2-m r Sin[2 g] Sinh[2 q4]))))


title: Methods to speed up numerical NDSolve, NIntegrate,

text: I am not very used to do numerical simulations on Mathematica. Do you have any ideas how to improve i.e. speed up my code?               f4[a_?NumericQ, b_?NumericQ, c_?NumericQ, delta_?NumericQ,      K_?NumericQ, d_?NumericQ] := Module[     {kk1, kk2, out, sigma, beta, rho},     kk1 = NDSolve[{xt'[t] == 10 (yt[t] - xt[t]),       yt'[t] == xt[t] (28 - zt[t]) - yt[t],       zt'[t] == xt[t] yt[t] - 8/3 zt[t],       xt[0] == yt[0] == zt[0] == 1},      {xt, yt, zt}, {t, 15}];     sigma = {13.25, 7, 6.5};     rho = {19, 18, 38};     beta = {3.5, 3.7, 1.7};     kk2 =      NDSolve[Join[       Table[x[i]'[t] ==          sigma[[i]] (y[i][t] - x[i][t]) +           a Sum[x[j][t] - x[i][t], {j, 1, 3}], {i, 1, 3}],       Table[        y[i]'[t] ==          x[i][t] (rho[[i]] - z[i][t]) - y[i][t] +           b Sum[y[j][t] - y[i][t], {j, 1, 3}], {i, 1, 3}],       Table[        z[i]'[t] ==          x[i][t] y[i][t] - beta[[i]] z[i][t] +           c Sum[z[j][t] - z[i][t], {j, 1, 3}], {i, 1, 3}],       Table[x[i][0] == 1, {i, 1, 3}],       Table[y[i][0] == 1, {i, 1, 3}],       Table[z[i][0] == 1, {i, 1, 3}]],       Join[Table[x[i], {i, 1, 3}], Table[y[i], {i, 1, 3}],        Table[z[i], {i, 1, 3}]], {t, 15}];     outt[tt_] := {xt[tt + 5], yt[tt + 5], zt[tt + 5]} /. kk1;     ti = Table[i + 5, {i, 0, (K - 1)*d, d}];     out[tt_] := {1/3 (Sum[x[i][tt + 5], {i, 3}]),        1/3 (Sum[y[i][tt + 5], {i, 3}]),        1/3 (Sum[z[i][tt + 5], {i, 3}])} /. kk2;     dist[tt_] := ((out[tt][[1, 1]] -            outt[tt][[1, 1]])^2 + (out[tt][[1, 2]] -            outt[tt][[1, 2]])^2 + (out[tt][[1, 3]] -            outt[tt][[1, 3]])^2)*0.4^tt;     FC = 1/(K delta ) Sum[       NIntegrate[dist[tt], {tt, ti[[i]], ti[[i]] + delta}], {i, 1, K}];     FC];     f4[1, 1, 1, 1, 10, 0.2] // AbsoluteTiming      Thanks a lot!!


title: How can I scale a plot in my Manipulate?

text: I want use scale in the same way as Mister Trevor Cole in his most excellent demonstration at the Wolfram Demonstrations site: http://demonstrations.wolfram.com/MatchingTemperatureDataToANormalDistribution/ Here is Coles script:               Manipulate[       Show[         histogram,          Plot[scale PDF[NormalDistribution[mean, σ], x], {x, 0, 30},           PlotStyle -> {Thickness[0.01]}],            AxesOrigin -> {0, 0},            PlotRange -> {{0, 30}, {0, 350}},           ImageSize -> {450, 300}],       {{scale, 2400}, 0, 3500, Appearance -> "Labeled"},        {{mean, 17}, 0, 20, Appearance -> "Labeled"},       {{σ, 2.9}, 0.1, 15, Appearance -> "Labeled"},        SynchronousInitialization -> False,        Initialization :> (         data =            Table[             WeatherData["London", "Temperature", {{year, 6, 1}, {year, 9, 30}, "Day"}],              {year, 1976, 2010, 1}];          histogram =            Histogram[Flatten[Table[Part[#, 2] & /@ yearData, {yearData, data}]],             ChartStyle -> "DarkRainbow"];)]      Next, here is my primitive script. Where, pray tell, do I insert references to `scale` to arrive at the same synergy between my data points and my curve of double curvature as Mister Cole?               Manipulate[       Show[         Plot[d[X, n, P], {X, 0.0, 10.0},            Frame -> True,            GridLines -> Automatic,            AxesOrigin -> {0, 0},            PlotRange -> {{0, 10.0}, {0, 1.0}},            ImageSize -> {500, 318.3},            PlotStyle -> {RGBColor[1, 0, 0],            Thickness[0.01]},            AspectRatio -> 2/π,           FrameLabel -> {"DeMoivre"}],          dtplt],          {n, 1.0, 10.0},          {P, 0.001, 10.0}]


title: Getting good-looking matrix form output from a matrix having both scalars and matrices as elements

text: I have a nested matrix `n`:               n = {{a, b}, {c, d}}     a = {{0, t, q, dh}, {0, 1, 0, th}, {1, 1, 0, sh}}     b = {{0, t, q, dh}, {1, 0, 0, th}, {1, 0, 0, sh}}          c = {{0, t, q, dh}, {0, 1, 0, th}, {1, 0, 0, sh}}     d = {{0, t, q, dh}, {0, 0, 0, th}, {0, 1, 0, sh}}      With thanks to Nasser add column and Andy and Mike most efficient for their questions and answers, we can add a vector `m = {rr, kk}` to this nested matrix as a column, for example:               pp = Transpose[Insert[Transpose[n], Flatten@m, 1]]     or     pp=Join[List /@ m, n, 2] // MatrixForm      Finally, after running the above lines we have `pp` as:               {{rr, {{0, t, q, dh}, {0, 1, 0, th}, {1, 1, 0, sh}},                  {{0, t, q, dh}, {1, 0, 0, th}, {1, 0, 0, sh}}},       {kk, {{0, t, q, dh}, {0, 1,0, th}, {1, 0, 0, sh}},            {{0, t, q, dh}, {0, 0, 0, th}, {0, 1, 0,sh}}}}      and `pp/MatrixForm` as: ![enter image description here](http://i.stack.imgur.com/GF7Vt.png) The result is correct but I wanted to obtain an obvious and clarified figure of `pp/MatrixForm` same as : ![enter image description here](http://i.stack.imgur.com/p5ghm.png) Are there any possibility for obtaining the last form instead of the first form for `pp/MatrixForm`.


title: Create a color bar plot legend

text: I have the following list of parametric equations               lst = {10*Cos[u]*Sin[v], 3*Sin[u]*Sin[v], 2*Cos[v]};      I define the following color function               colFun = Function[{u, v}, Hue[Rescale[dam, {0, 1}]]];       whereas               dam = Sqrt[(1296*Cos[u]^4*            Sin[v]^4)/(900*Cos[v]^2 + 36*Cos[u]^2*Sin[v]^2 +              400*Sin[u]^2*Sin[v]^2)^2 + (3600*Cos[u]^2*            Sin[v]^2*(9*Cos[v]^2 + 4*Sin[u]^2*Sin[v]^2))/                (900*Cos[v]^2 +              4*(9*Cos[u]^2 + 100*Sin[u]^2)*Sin[v]^2)^2];       So I get the following parametric plot               g=ParametricPlot3D[lst, {u, 0, 2*Pi}, {v, 0, Pi}, Mesh -> False,       PlotStyle -> Opacity[0.8], ColorFunction -> colFun,       ColorFunctionScaling -> False]      What I want now is to create a color bar which will accompany `g`. This color bar will show the values of               Rescale[dam, {0, 1}]      The coloring of course will be again according to the same defined color function. I am looking for a solution that works with Mathematica 8.


title: NMinimize of a Differential equation

text: f[kpr,tn,tv] is a Block for the Differential equations of a simple control loop with a PID-controller. It calculates the the response x[t] and integrates the t-weighted area under the response. The function f[kpr,tn,tv] works OK. But the Optimization with NMinimize[] gives errors with every Method available.               st = 0; en = 100;     Clear[x, f];     f[kpr_, tn_, tv_] := Block[{tab}, Clear[x]; x = x /. NDSolve[{x'[t]+25(x''[t]+6*x'''[t])==-1.5*kpr(x[t]/tn + x'[t] + tv x''[t]), x''[0]==0.2,x[0]==0,x'[0]==0},{t,st,en}][[1]]; NIntegrate[Abs[x]*t,{t,st,en}]]     f[100,2,0.5]     f[110,2.5,1]     NMinimize[f[kpr,tn,tv],{{kpr,100,110},{tn,2,2.5},{tv,.5,1}},Method->"NelderMead"]


title: Using the OSX Cocoa-APIs from Mathematica via Link-Technology

text: I'd like to access Cocoa-API's (Foundation, AppKit) from _Mathematica_ and have researched the following ways:   1. CocoaLink: A deprecated Package by Rob Schlofield from 2009, which is still available on GitHub but will not compile out of the box due to the introduced changes in the ObjC-Runtime made at that time and around 2010. I got it to work, but not for all Types. I contacted Rob if he will update CocoaLink but he told me that the effort would not justify the usefulness ... unfortunately.   2. MonoObjC: A Mono/.NET package which can be installed and used after Mono has been installed. Mono allows one to use .NETLink and invoke almost all .NET functions of the 4.0 Framework.  I have tried:               Needs["NETLink`"];          monobjc = LoadNETAssembly["Monobjc"];     foundation = LoadNETAssembly["Monobjc.Foundation"];     appkit = LoadNETAssembly["Monobjc.AppKit"];      Then I tried to load and instantiate a NSString but it failed with Messages telling me that the Bridge to ObjC is not available.               nsstring = LoadNETType["Monobjc.Foundation.NSString"];     sstr = NETNew[nsstring]      > NET::netexcptn: A .NET exception occurred: > System.TypeInitializationException: An exception was thrown by the type > initializer for Monobjc.Foundation.NSString ---> > System.TypeInitializationException: An exception was thrown by the type > initializer for Monobjc.ObjectiveCRuntime ---> > System.EntryPointNotFoundException: monobjc_install_bridge ..... I am not sure if there is more to be done to initialize .NETLink when working with other external mono packages.


title: Defining the Moyal Product in Mathematica

text: What would be the best way to define the Moyal Product, $f(x,p)\star g(x,p)$, in Mathematica? $f(x,p)\star g(x,p)$ may be written as $f\star g=\sum\limits_{n=0}^{\infty}\frac{1}{n!}\left(\frac{i\hbar}{2}\right)^n\Pi^n(f,g)$ where $\Pi^n=\sum\limits_{k=0}^n(-1)^k{n\choose k}\frac{\partial^nf}{\partial p^k\partial x^{n-k}}\frac{\partial^ng}{\partial x^k\partial p^{n-k}}$ I'm also wondering how I would then be able to define $f(x,p)\tilde{\star}g(x,p)$ as $f\star(1+\alpha\star_1+\alpha^2\star_2)g$ with $\star_1=cp^3\overleftarrow{\partial_p}\overrightarrow{\partial_p}$, $\star_2=c^2p^6\overleftarrow{\partial^2_p}\overrightarrow{\partial^2_p}$, and c being a constant. Thanks. $\Large{\rm{\bf{Edit}}}$ Here's how I tried to define the Moyal product:               Star[f_, g_] =       Sum[(I*h/2)^n*        Sum[(-1)^k*Binomial[n, k]*D[f[x, p], {p, k}, {x, n - k}]*          D[g[x, p], {x, k}, {p, n - k}], {k, 0, n}], {n, 0, Infinity}]      which output $\sum _{n=0}^{\infty } 2^{-n} (i h)^n \sum _{k=0}^n (-1)^k \binom{n}{k} f^{(n-k,k)}(x,p) g^{(k,n-k)}(x,p)$ I know that $x\star p=xp+\frac{i\hbar}{2}$, so I tried Star[x,p], but got the following output: $\sum _{n=0}^{\infty } 2^{-n} (i h)^n \sum _{k=0}^n (-1)^k \binom{n}{k} p^{(k,n-k)}(x,p) x^{(n-k,k)}(x,p)$ I think my problem is where I used f and g in the function of Star, but I'm not sure how to fix it. Once I figure out how to define $f\star g$ in Mathematica, I think I'll be able to define $f\tilde{\star} g$. $\Large{\rm{\bf{Edit}}}$ I've included the $\frac{1}{n!}$ in the definition of the Moyal Product.


title: Inverse functions - how are they calculated?

text: _Mathematica_ is able to calculate `InverseFunction[LogIntegral]` and `InverseFunction[RiemannR]` (and many other inverse functions). How are these calculated? (I can see how `LogIntegral` and `RiemannR` are calculated if I go to the details section of the docs, but can't find a ref. for inverse functions.) Note: I have tried looking at `Series[LogIntegral[n], {n, 2, 3}]`, and `InverseSeries[Series[LogIntegral[n], {n, 2, 3}]]`, but can't see clearly how this helps.


title: shooting method and stifness problem for NDSolve

text: I'm trying to solve numerically the following differential equation:               1/r[x]^5 + k/Sqrt[1 + r'[x]^2] - (k r[x]r''[x])/(1 + r'[x]^2)^(3/2) == 0      I can set boundary condition in `x=x0` and `x=xF` with `x0` and `xF` being the boundaries of the domain of the `x` variable, i.e., `x=[x0,xF]`. The particular values are not important, I can set what I want as long as `xF>x0>0`. I do not have constraint on the value of the first derivative at the boundaries. This equation has a singulary for `r''[x]` in `x=0`. To avoid this problem, I have to use shooting method with appropriate boundary conditions.               sf = NDSolve[{1/r[x]^5 + k/Sqrt[1 + r'[x]^2] - (k r[x]r''[x])/(1 + r'[x]^2)^(3/2) == 0, r[0] == 1, r[1] == 10}, r, {x, 0.1, 100},        Method -> {"Shooting",          "StartingInitialConditions" -> {r[0] == 1, r'[0] == 0}},        MaxSteps -> 500]      If I do so, I obtain the following errors:               NDSolve::mxst: Maximum number of 200 steps reached at the point x == 0.48535728275604967`. >>     NDSolve::mxst: Maximum number of 200 steps reached at the point x == 0.9112853584099116`. >>     NDSolve::mxst: Maximum number of 200 steps reached at the point x == 0.9766603163139572`. >>     General::stop: Further output of NDSolve::mxst will be suppressed during this calculation. >>     FindRoot::sszero: The step size in the search has become less than the tolerance prescribed by the PrecisionGoal option, but the function value is still greater than the tolerance prescribed by the AccuracyGoal option. >>     NDSolve::berr: There are significant errors {0.0395308,-0.00050132} in the boundary value residuals. Returning the best solution found. >>      But anyway I obtain a solution `sf` in the form of an interpolating function:               {{r -> InterpolatingFunction[{{0.1, 0.920942}},<>]}}      It is this solution reliable? I think that the the differential equation may be affected by stifness issues, so I tried to add as a sub `Mehtod` options to solve stifness mehtod as indicated in the help:               sf = NDSolve[{1/r[x]^5 + k/Sqrt[1 + r'[x]^2] - (k r[x]r''[x])/(1 + r'[x]^2)^(3/2) == 0, r[0] == 1, r[1] == 10}, r, {x, 0.1, 100},        Method -> {"Shooting",          "StartingInitialConditions" -> {r[0] == 1, r'[0] == 0},Method -> {"StiffnessSwitching", "NonstiffTest" -> False}},        MaxSteps -> 500]      The problem is that I obtain several errors, and a discontinuos solution that it's clearly wrong. I will really appreciate any help. Samir


title: Isn't it possible to Pack a SparseArray?

text: I have the following matrix `Va`:               Va = Table[     Which[i == j + 1, 2, True, 0], {l, 1, 2}, {m, 1, 2}, {s, 1,      2}, {q, 1, 2}, {i, 1, 2}, {j, 1,2}];      There is no problem to pack it:               Va = Developer`ToPackedArray[Va];          Print@Developer`PackedArrayQ@Va;          True      But then there is the matrix `Vb`, which is the same as `Va`, but in the `SparseArray` form:               Vb = SparseArray[{l_, m_, s_, q_, i_, j_} :>      Which[i == j + 1, 2, True, 0], {2, 2, 2, 2, 2, 2}];      And this one I can not Pack:               Vb = Developer`ToPackedArray[Vb];          Print@Developer`PackedArrayQ@Vb;          False      Does anybody know the way to pack this `SparseArray` `Vb`?


title: Opposite function to Normal

text: Is there any function opposite to Normal? For example, let as say that I have an SparseMatrix A, then, let as say that for convenience for a certain operation like Packing, I convert it into an Array by doing               A=Normal[A];      and afterwards, I want A to became an SparseArray again. Is there anyway to do this without the need to define the matrix A again? Thanks


title: Obsolete Signal Processing functions

text: I need some tools to detect the fundamental frequency and pitch of a sound. I Googled for "pitch detect" and found some .nb files that do these tasks, but all the files are in _Mathematica_ 3.0 format. I downloaded and installed the Signal Processing package, but this did not help, because these files use some obsolete functions like `DiscreteWindow`, `ContinuousPiecewiseData`, etc. I also tested the Signals and Systems toolbox but for the same reason there was no output in most cases. Are there any newer replacements of these functions or some way to find their definitions in some old packages?


title: Plotting a 3D sphere i.e. how to vizualise the spanned volume $\int_0^{2\pi}\int_0^{\pi} d\theta d\phi$?

text: I am trying to help this guy here to vizualise the integration volume. How can I plot the different integrals ie a ball and the ball adjusted by a trigonometric function? **Integrals needing visual cue: what does their spanned volume look like?** > He was wondering why the first integral is not spherical. I want to provide > some sort of visual cue in this kind of issues. > > $$\int_0^{2\pi}\int_0^{\pi} d\theta d\phi = 2 \pi^2$$ > > $$\int_0^{2\pi}\int_0^{\pi} \sin\theta d\theta d\phi = 4 \pi$$


title: RecurrenceTable with vector

text: Mathematica can do a RecurrenceTable with a vector, here is a simple example:               RecurrenceTable[{x[n + 1] == 2* x[n], x[0] == {1, 2, 3}}, x, {n,  3}]      with output > {{1, 2, 3}, {2, 4, 6}, {4, 8, 12}, {8, 16, 24}} I want to do something similar but instead of multiplying by 2 I want to multiple each element in x[n] by a different number. For example, one would think that this would work:               RecurrenceTable[{x[n + 1] == {1,2,3}* x[n], x[0] == {1, 2, 3}}, x, {n,  3}]      since Times is listable but I get an error > RecurrenceTable::excptn: Value {1,2,3,2,4,6,3,6,9} is a numerical exception. > >> I get the same result using MapThread etc. Thoughts?


title: Map over list of functions

text: I would like to convert a list of $n$ complex equations to a list of $2n$ real ones. At the moment I am doing it like this:               eqs = {a + I b == 0, c + I d == 0}     Flatten[{ComplexExpand[Re[First[#]]] == 0 & /@ eqs,                ComplexExpand[Im[First[#]]] == 0 & /@ eqs}]       I would like to know how I can write this more compactly, since I'm basically using the same command twice, with the only difference being changing the function `Re -> Im`. Perhaps I can use a pure function to map over a list of these 2 functions? Thanks!


title: Different behaviours of Default Argument

text: I don't really understand the behaviour of Default Argument. If I execute this command in Mathematica:               In: {f[a], f[a + b]} /. f[x_ + y_.] -> p[x, y]        > `Out: {p[a, 0], p[b, a]}` Why is the a and b swapped? How can I explain the different behaviour of the above compared with the each of the following:               In: {f[a], f[a + b]} /. f[x_ + y_] -> p[x, y]        > `Out: {f[a], p[a, b]}`               In: {f[a], f[a + b]} /. f[x_. + y_] -> p[x, y]        > `Out: {p[0, a], p[a, b]}`               In: {f[a], f[a + b]} /. f[x_. + y_.] -> p[x, y]        > `Out: {p[a, 0], p[a, b]}` And similarly for:               In: {f[a], f[a b]} /. f[x_ y_.] -> p[x, y]        > `Out: {p[a, 1], p[b, a]}`               In: {f[a], f[a b]} /. f[x_  y_] -> p[x, y]      > `Out: {f[a], p[a, b]}`               In: {f[a], f[a b]} /. f[x_. y_] -> p[x, y]      > `Out: {p[1, a], p[a, b]}`               In: {f[a], f[a b]} /. f[x_. y_.] -> p[x, y]      > `Out: {p[a, 1], p[a, b]}` From Mathematica help, what I understand is that Mathematica will return the default value if the argument of _. is not inputted. But I still cannot make the above statements any sense. Besides the obvious observable output such as reordering, I don't really understand the logic behind _. How does it relate to sum and multiplication? When will _. be useful in other than this situation? Thanks.


title: Check whether a working CCompiler is installed

text: Let me give a bit background: As many of my answers imply, I often use the auto-parallelization (meaning, that _Mathematica_ distributes the calculation automatically over several cores when list-arguments are given) of `Compile` and I often compile to `"C"`. Therefore, in my packages there are things like the following               $adjustGraylevelFunc := ($adjustGraylevelFunc = Compile[{{values, _Real, 1}},       Map[Floor[255.0 * Min[Max[0.0, #], 1.0]^(0.25) + 0.5] &, values, {1}],       RuntimeAttributes -> {Listable}, Parallelization -> True,       RuntimeOptions -> "Speed", CompilationTarget -> "C"     ]);      When the package is loaded, this delayed assignment evaluates instantly, because the function is not compiled until first use. Therefore, the loading of the package is very fast, compared to when all functions in it would be compiled on the `Get` call. Evaluate the next line two times and see the effect               $adjustGraylevelFunc[RandomReal[1, {5, 5, 3}]]      However, I cannot assume that all people have a running C compile installed. Therefore, I would like a _short_ and _simple_ way to test whether I can use C-compiling. Without research, two possibilities come to my mind:   1. Loading the `CCompilerDriver`` package and use `CCompilers` to check. This has two drawbacks. I have to load an additional package which is not really used, except for this one tiny test. More importantly, an installed C-compiler does not indicate whether _Mathematica_ can really create library code with it. I have seen this often (especially on Windows machines) that installed C-compilers could not be used.   2. Compile a small test function which sets a package variable. Such a check could be as simple as              If[Quiet[Check[TrueQ[Compile[{}, 0, CompilationTarget -> "C"][] == 0], False]],       $compileTarget = CompilationTarget -> "C",       $compileTarget = CompilationTarget -> "MVM"     ]      Are there other possibilities? Maybe _Mathematica_ already does this kind of check on startup and the result can be accessed somehow?