on RegionPlot3D and ContourPlot3D

First I have               ContourPlot3D[{       (1 - p1) (1 - p2)^3 == p1 p2^3,        p1 p2^6 (c p1 + (1 - c) p2)^3 ((1 - c) p1 + c p2)^2          == (1 - p1) (1 -p2)^6 (1 - c p1 - (1 - c) p2)^3 (1 - (1 - c) p1 - c p2)^2      }, {p1, 0.2, 0}, {p2, 1, 0.5}, {c, 0, 1},      Lighting -> ({"Directional", White, #} & /@ Tuples[{-1, 1}, 3]),      Mesh -> None,      BoxRatios -> {2, 2, 1},     ContourStyle -> {Yellow, Directive[Red, Opacity[0.5]]},      BaseStyle -> {FontWeight -> "Bold", FontSize -> 20}]      which will show me (please don't mind the labels) ![enter image description here](http://i.stack.imgur.com/AmlnD.png) I want _Mathematica_ to plot the region between the yellow plane and the transparent red plane, so I use `RegionPlot3D` with the same set of equations.               RegionPlot3D[(1 - p1) (1 - p2)^3 > p1 p2^3 &&        p1 p2^6 (c p1 + (1 - c) p2)^3 (c p2 + (1 - c) p1)^2         > (1 - p1) (1 - p2)^6 (1 - (c p1 + (1 - c) p2))^3 (1 - (c p2 + (1 - c) p1))^2,      {p1, 0, 0.2}, {p2, 0.5, 1}, {c, 0, 1},      Mesh -> None, FaceGrids -> All, ViewPoint -> Front,PlotPoints->100]      which will give me the following: ![enter image description here](http://i.stack.imgur.com/Ug62c.png) One will expect `RegionPlot3D` will give a single connected bulk but instead there are several rod-like artifacts. How to get a nice region plot with that set of equations? (Increasing plotpoints to 200 might work, but it takes so long...)


Triangular numbers boolean function

I read the new book by Paul Wellin _Programming in Mathematica_. There is an exercise about triangular numbers. (The `n-`th triangular number is defined as the sum of the integers `1` through `n`.   They are so named because they can be represented visually by arranging rows of dots in a triangular manner. The first ten triangular numbers are: `1, 3, 6, 10, 15, 21, 28, 36, 45`.) In the solution there are given functions which will give the nth triangular number. For instance:               f1[n_] := Total[Range[n]]          f2[n_] := Fold[#1 + #2 &, 0, Range[n]]          f3[n_] := Binomial[n + 1, 2]      Regarding the timings, we have `f3 > f1 > f2` (using the number 50000005000000 from Wellin's book) (in my laptop t3 = 0.01 sec, t1 = 0.18 sec, t3 = 3.8 sec). I was thinking about a boolean function that will return true or false, whether the number is triangular or not. My procedural style approach is:               triangularQ[n_] :=      Module[{y, dy}, For[y = 0; dy = 1, y < n, y += dy++];       If[y == n, Print[True], Print[False]]]      But it does not look so efficient. Are there other approaches that use functional programming? It seems good to compare the various solutions (the number `50000005000000` is from Wellin's book). First the procedural:               In[182]:= triangularQ[50000005000000] // Timing          During evaluation of In[182]:= True          Out[182]= {41.562500, Null}      Aky's               In[185]:= f[x_, n_] := f[x - n, n + 1]; f[0, n_] := True;     f[x_ /; x < 0, n_] := False          In[193]:=     Block[{$IterationLimit = ∞}, f[50000005000000, 1]] // Timing          Out[193]= {114.703125, True}      Eldo's I coud not get true for               MemberQ[ f2 /@ Range@(10^7), 50000005000000]      in reasonable time (less than $2$ minutes). Nasser's               In[226]:= triangularQ[50000005000000] // Timing          During evaluation of In[226]:= True          Out[226]= {41.421875, Null}      So the procedural style is not deficient at all :-)!


Trying to simplify Root expressions from the output of Eigenvalues

I am trying to calculate eigenvalues of a sparse matrix with only two distinct non-zero elements, here Alpha and Beta, which are both negative reals. Mathematica returns some complex expressions with `Root[]` values when using the `Eigenvalues[]` command on the following matrixA: In all cases the matrices are symmetric and real and hence have real eigenvalues.               matrixA={             {α, β, 0, 0, 0, 0, β, 0, 0, β},             {β, α, β, 0, 0, 0, 0, 0, 0, 0},             {0, β, α, β, 0, 0, 0, 0, 0, 0},             {0, 0, β, α, β, 0, 0, 0, 0, 0},             {0, 0, 0, β, α, β, 0, 0, 0, 0},             {0, 0, 0, 0, β, α, β, 0, 0, 0},             {β, 0, 0, 0, 0, β, α, β, 0, 0},             {0, 0, 0, 0, 0, 0, β, α, β, 0},             {0, 0, 0, 0, 0, 0, 0, β, α, β},             {β, 0, 0, 0, 0, 0, 0, 0, β, α}             }      For comparison, with all the other similar matrices I've tried (see below e.g. matrixB) Mathematica will put out simple decimal approximations (using `Eigenvalues[matrixB] // N // Simplify`) Can anyone point out a way to get expressions for the `matrixA` as simple as for `matrixB`? And yes, the desired simple answers for `matrixA` do exist, I can get them with other programs, but I want to use Mathematica! * * * I should add that I already have already used `$Assumptions = α<0 && β <0` at the top of my worksheet.               matrixB={             {α, β, 0, 0, 0, 0, 0, 0, 0, β},             {β, α, β, 0, 0, 0, 0, 0, 0, 0},             {0, β, α, β, 0, 0, 0, β, 0, 0},             {0, 0, β, α, β, 0, 0, 0, 0, 0},             {0, 0, 0, β, α, β, 0, 0, 0, 0},             {0, 0, 0, 0, β, α, β, 0, 0, 0},             {0, 0, 0, 0, 0, β, α, β, 0, 0},             {0, 0, β, 0, 0, 0, β, α, β, 0},             {0, 0, 0, 0, 0, 0, 0, β, α, β},             {β, 0, 0, 0, 0, 0, 0, 0, β, α}             }


How do you use SystemsModelFeedbackConnect?

I'm trying to grasp the new control system functions in Mathematica 8. I'd like to connect a controller model to a model of a plant to simulate the behavior of the system. I define a simple servo model:               servo = StateSpaceModel[{x''[t] == u[t] - x'[t]}, {{x''[t], 0}}, {{u[t], 0}}, x[t], t]      where `x[t]` is the position of the servo and `u[t]` is the input (voltage). and a simple PID controller:               pid = TransferFunctionModel[5 + 0.01*s - 0.00001/s, s]      Now I _assumed_ that I could link the PID controller to the servo model using `SystemsModelFeedbackConnect`:               loop = SystemsModelFeedbackConnect[TransferFunctionModel[servo], pid]      But the system doesn't behave as I would have expected:               input = UnitStep[t - 1] - 0.5 UnitStep[t - 10];     output = OutputResponse[loop, input, t];     Plot[{input, output}, {t, 0, 30}]      ![Plot](http://i.stack.imgur.com/m2OFY.png) There's a lot of overshoot because the PID is not optimized at all, but I would have expected that the P part of the controller would pull the output to the (target) input eventually. But it seems as if the P factor scales the input, rather than the error.


Rearranging a Polynomial

In _Mathematica_ 8.04 on Windows, I want to display a formula in standard textbook format. The formula is the variance of an $N$-security portfolio. For two securities it is: $$w_1^2\sigma_1^2+w_2^2\sigma_2^2+2\sigma_{1,2}w_1 w_2$$ To generate this, I have created the following function:               psd[n_Integer] :=        Sum[Sum[Subscript["w", i] Subscript["w", j] If[i == j, Subsuperscript["σ", i, 2],            Subscript["σ", Min[i, j], Max[i, j]]], {i, 1, n}], {j, 1, n}];      This works, but the terms are out of order as shown in this image of the output of `psd[2]`: ![MMA Output of my psd function](http://i.stack.imgur.com/OXa26.png) I'd like to take the last two terms (with the exponents) and place them in front of the first two. Suppose that I call the output "a", then I can get the parts of a using `Take[a,1]` and `Take[a,-2]`. What I would like to be able to do is to put those two parts back together in reverse order as shown in the original equation. Ideally, I'd be able to specify a sort order, but I can't seem to figure that out. I've tried all of the orders for `MonomialList` with no luck, and when I add the list parts it gets resorted anyway. The order of the terms doesn't matter for calculation, but this is for presentation and I'd like it to look like it does in every textbook. The point is to demonstrate how the formula grows longer as more securities are added to the portfolio. Except for the ordering, it works perfectly in a `Manipulate`. Any ideas?


Make MapIndexed listable

My goal is to apply `MapIndexed` to every element of a nested list without destroying the arithmetic operations within the elements. For example, let's start with this list:               {a, {b, {c^d, {e + f g}}}}      This is what I want achieved using `MapIndexed` and applying a function `h` (this was explicitly typed out, so the bracket placement might be wrong, but you get the idea):               {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}}      * * * **My (failed) attempts** **1)** Of course the `{-1}` levelspec of `MapIndexed` was way too aggressive:               MapIndexed[h, {a, {b, {c^d, {e + f g}}}}, {-1}]      ![Mathematica graphics](http://i.stack.imgur.com/riR3Z.png) **2)** This also did not work:               Function[l, MapIndexed[h, l], Listable]@{a, {b, {c^d, {e + f g}}}}      ![Mathematica graphics](http://i.stack.imgur.com/YzEoi.png) To see why, `MapIndexed` is nested in a `Defer`:               Function[l, Defer@MapIndexed[h, l], Listable]@{a, {b, {c^d, {e + f g}}}}      ![Mathematica graphics](http://i.stack.imgur.com/LdoW2.png) It's clear that `MapIndexed` is threaded over the list first before it evaluated, while what I want is for `MapIndexed` to be applied to the whole list, and only the evaluation thereafter will be listable (I hope the distinction is clear). * * * **My question is** : How can I make my `MapIndexed` listable as seen in the desired output? Solutions without using `MapIndexed` are also appreciated.               {a, {b, {c^d, {e + f g}}}} -> {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}}


How do I generate a 3d histogram of runs

This question is an extension of the question I asked here Histogram of runs. What I would like to do now is generate a Histogram3D that has the run duration on the x axis and the mean level on the y axis. The code given by kguler and VF1 in the previous post generate the duration that I need but I've been having trouble modifying the code to get the mean value along with the run duration. Any help would be greatly appreciated. This is a plot of the input data; ![enter image description here](http://i.stack.imgur.com/UYmPH.png) This is a plot of the 3d histogram using VF1s code; ![enter image description here](http://i.stack.imgur.com/Aux6C.png)


Symbolic scalar-by-matrix derivative

Let's say I want to calculate the following scalar-by-matrix derivative $$\frac{\partial}{\partial A} \text{tr} \left[(\vec X^T A)^T (\vec X^T A)\right],$$ with $\vec X$ and $A$ being a $n \times 1$ and a $n \times m$ matrix, respectively. Is there a way in Mathematica to get the result $$2 \vec X (\vec X^T A)$$ without explicitly defining (for instance)               n=3     m=2     A=Array[a,{n,m}]     X=Array[x,{n,1}]      and calculating               D[Tr[Transpose[Transpose[X].A].Transpose[X].A],{A}]      ? The problem with this approach is that the Mathematica result cannot be easily cast back into an human-readable form like $$2 \vec X (\vec X^T A).$$


Different Vertex Styling in a Graph

We can have this Graph:               v = {1 \[UndirectedEdge] 9, 1 \[UndirectedEdge] 10,      1 \[UndirectedEdge] 8, 10 \[UndirectedEdge] 2,      10 \[UndirectedEdge] 5, 9 \[UndirectedEdge] 3,      9 \[UndirectedEdge] 6, 8 \[UndirectedEdge] 7,      8 \[UndirectedEdge] 4, 7 \[UndirectedEdge] 3,      7 \[UndirectedEdge] 2, 6 \[UndirectedEdge] 2,      6 \[UndirectedEdge] 4, 5 \[UndirectedEdge] 3,      5 \[UndirectedEdge] 4};     g = Graph[v, VertexLabels -> Placed["Name", Center],      VertexStyle -> White, VertexSize -> 0.5]      Which looks like this: ![enter image description here](http://i.stack.imgur.com/lQByL.jpg) How can I add other characteristics inside the vertex labels?Such as other numbers in second line of labels?Or more info such as some codes in third line?


Using ImageTransformation[] with a lookup table

I need to transform images by `ImageTransformation` in a time critical application. Therefore I precalculate a lookup table `lut` of the transformation function for the true pixel range `{{0,width},{0,height}}`. However, when I use               ImageTransformation[img, lut[[#[[1]],#[[2]]]]&, DataRange->Full]      I get the error message > ImageTransformation::imgtrnsfun: The function lu should map a pixel position > of form {x, y} to {x', y'}. >> Is it possible to provide a lookup table to `ImageTransformation`?


Plot a vector valued function of two variables using color density

I have a vector (3D) valued function of two variables. I want to visualize it as a density plot, using R,G,B color values to display the value at the point (x,y). I've come up with a couple of attempts, neither satisfactory. One is to use a Raster, but that doesn't adapt to the function and so needs too many function evaluations. My other solution is to make three contour plots and combine them, but to do that I needed to use Opacity and then the range of colors is muted. Here's an example, with a simple function:               f[x_, y_] := {x, y, x + y}     Table[        DensityPlot[f[x, y][[i]], {x, -1, 1}, {y, -1, 1},                    ColorFunction -> (ReplacePart[RGBColor[0,0,0], i -> #] &)],        {i, 3}]     Show[Table[        DensityPlot[f[x, y][[i]], {x, -1, 1}, {y, -1, 1},              ColorFunction -> ({Opacity[1/3], ReplacePart[RGBColor[0,0,0], i -> #]} &)],        {i, 3}]]      The first table shows three DensityPlots with the RGB components I want, which look like this: ![rgb component images](http://imgur.com/kGOnj5m.png) The Show combines them into one. But what I really want to do is **add** the color values in the three plots, and Show with Opacity averages them, giving a murky image. In this example, I want white in the upper right, black in the lower left.


Why is ParallelMap way slower than Map

I recently tried to use `ParallelMap` instead of `Map` and to my surprise encountered that `ParallelMap` seems to be slower in general than `Map`, which does not make sense to me. Here is a simple test case, that shows the behavior on my system (tested it on Linux 64 Bit QuadCore i7 and on MacOS DualCore Core2Duo, both running Mathematica 9.0.1):               LaunchKernels[];     f[x_] := Sin[x] + Cos[x] + Tan[x];     test = Table[i, {i, 100000}];      Timing results are the following (and they are consistent, additional kernels have been started before):               Map[f[#] &, test]; // AbsoluteTiming      > {0.198230, Null}               ParallelMap[f[#] &, test]; // AbsoluteTiming      > {0.650516, Null} What am I missing here?


Overwrite contents of a cell

I am trying to figure out a way to change the contents of a cell that has previously been evaluated in my notebook. To do this, I'd like to overwrite the cell. I've seen questions like How to pipe a stream to another notebook? and How do I direct output to a specific notebook or cell? and so far they have not helped me accomplish this.               NotebookApply[cell, data]       The above is supposed to write data to the specified cell, but I haven't had any luck with this, I'm most likely incorrectly identifying the cell. The most promising example I've seen so far has been this from the CellObject page:                 Do[CellPrint[        Cell["1", "Output", ShowCellTags -> True,          CellTags -> "overwrite" <> ToString[i]]], {i, 1, 3}];        obj = Cells[CellTags -> "overwrite2"][[1]];       NotebookWrite[obj, Cell["2", "Output"]];      But I don't really understand what it's doing, and I don't understand how to adapt it to suit my needs. If I have thisCell identifying the CellObject I'd like to change...               NotebookWrite[InputNotebook[],       thisCell  = Cell[BoxData[RowBox[{"mysteryVar = 0"}]], "Input"]]      How can I overwrite the contents of this cell? (I'm running ver 9). Thanks!


Plotting points and functions in one graphic

I have this plot:               Plot[{0 x, -x, x, -Sqrt[2 - x^2], Sqrt[2 - x^2]}, {x, -3, 3},       PlotStyle -> {Purple}]      ![enter image description here](http://i.stack.imgur.com/TNLuJ.gif) Now I want to do the following. I want to plot the points: $(-1,0),(1,0),(0,0),(x,0),(1, \pm 1),(1,\pm \frac{1}{\sqrt 3}),(0, \pm \frac{2}{\sqrt 3}),(0, \pm \sqrt 2)$ in this graphic. I'm able to plot points using `Graphics[Point[{x, y}]`but I would like to plot those point in the same graphic. This is probably really easy, but I can't find it in the documentation.


TextRecognize with crosses, circles and spaces results into oddities, why?

I am investigating this answer here about detecting crosses and circles with TextRecognize. I tried to solve this problem here by directly using the builtin command TextRecognize but it does not work as expected: this example should print `xoo x xx x x` in ASCII and not `xoo x 'xx`. Elements are so that empty should return space, x should return `x` or circle should return `o`. ![enter image description here](http://i.stack.imgur.com/O30gf.png) Is TextRecognize bad choice for this task having ASCII gameplay characters such as x, o, # and possibly others? What can explain TextRecognize's malfunctioning? You can see that there is no `'` but it still prints it and it misses some characters.


Is it possible to induce Mathematica to chop off parts of Graphics objects that exist outside of a Frame?

I am running _Mathematica_ 7\. In a `Graphics` environment I am setting `Frame -> True` (and using `FrameLabel -> {"x", "y"}` and `PlotLabel -> "My Title"`, etc) so that I can see length scales in `Graphics` environments. Suppose that I create a `Disk` of radius `0.9`, centered at the origin. I have set `PlotRange -> {{-1, 1}, {-1, 1}}`. The result looks nice: > >     Graphics[{ >       Cyan, Disk[{0, 0}, 0.9] >       }, >      PlotRange -> {{-1, 1}, {-1, 1}}, Frame -> True, >      FrameLabel -> {"x", "y"}, PlotLabel -> "My Disk"] >   > > ![Disk 1](http://i.stack.imgur.com/ikJex.gif) Now, however, suppose that I want to create a `Disk` that is not entirely contained in `Frame`. For example, I might leave `PlotRange -> {{-1, 1}, {-1, 1}}` and increase the `Disk` radius from `0.9` to `1.2`. However, in the resulting image, the `Disk` goes beyond the boundaries of the `Frame`: > >     Graphics[{ >       Cyan, Disk[{0, 0}, 1.2] >       }, >      PlotRange -> {{-1, 1}, {-1, 1}}, Frame -> True, >      FrameLabel -> {"x", "y"}, PlotLabel -> "My Disk"] >   > > ![Disk 2](http://i.stack.imgur.com/tqoyq.gif) Is there any way that I can direct _Mathematica_ to chop off parts of the `Graphics` objects that exist outside of the `Frame`? Thanks for your time.


A Symbol with Subscript and Superscript as an Axis Label

I am trying to have the symbol $\epsilon_{9/2,4}^-$ as the axis label in a graph in Mathematica. First problem is that: when I use Subscript[$\epsilon$,9/2,4], 9/2 changes to $\frac{9}{2}$ (which I don't want, because it doesn't look good). Second problem is that Subscript[$\epsilon$,9/2,4]^- does not work. Can anyone please let me know how to do this? Thanks!


How can I change the Graph required data such as EdgeWeight,VertexWeight,EdgeCapacity,VertexCapacity in the Graph?

I asked this question in different form and because I couldn't receive the proper answer so I have to change my question.I know that was my fault sorry.I need to change the Matrix Data of nodes and edges in the graph. How can I do that on the graph itself by clicking on each node?               Graph[{"Uppsala" -> "Marsta", "Marsta" -> "Uppsala", "UpplandsVasby" -> "Sollentuna", "Sollentuna" -> "UpplandsVasby",        "UpplandsVasby" -> "Marsta", "Marsta" -> "UpplandsVasby",        "Stockholm" -> "Boo", "Boo" -> "Stockholm",        "Stockholm" -> "Lidingo", "Lidingo" -> "Stockholm",        "Stockholm" -> "Sollentuna", "Sollentuna" -> "Stockholm",        "Stockholm" -> "Taby", "Taby" -> "Stockholm"},EdgeWeight -> RandomInteger[{10, 100}, 14]       VertexLabels -> "Name"]


Telling mathematica to output * instead of space for multiplication, so I can copy as plain text

I am trying to get some symbolic expressions in Mathematica which I would like to paste into my C/MATLAB codes. This can be accomplished nicely by selecting the expression and right-clicking to select `Copy as plain-text`. However there is one small issue I have. Consider the simplest possible case for 2 symbols `a` and `b`               In[1]:= c = a*b               Out[1]= a b      How can I tell Mathematica to produce all its output as `a*b` and not `a b` Without this, I have to go through the pain of replacing manually all spaces in my C/MATLAB codes with the `*` espcecially for long expressions.


Is there any way to get Times displayed as $\cdot, *,$ or $\times$ in output form?

In the output of _Mathematica_ , operators $\cdot$ or * or $\times$ are usally displayed as space; e.g., $x * y$ becomes $x \, y$ in output. Is there any option that can be set to make "space" becomes $\cdot$ or * or $\times$ or preferably $*$?


WindowMargins exact CurrentValue

Is there a way to force getting the numerical values of `WindowMargins` instead of `Automatic` for a window? For example let say I want to create a new Notebook that is $62$ pixels below and $62$ pixels to the right of the current `EvalutaionNotebook`. If I run the following it sometimes works and sometimes doesn't depending on the window position on the current screen.               x = CurrentValue[EvaluationNotebook[], "WindowMargins"];     NotebookPut[Notebook[{        Cell["Some text.", "Text"]}],      WindowMargins -> {        {x[[1, 1]] + 62, Automatic},        {Automatic, x[[2, 2]] + 62}        }      ]      For example sometimes the expression throws an error and results in the following because _Mathematica_ is returning a different answer.                {{131, Automatic}, {Automatic, 62 + Automatic}}


Pass unevaluated function with evaluated arguments

I am almost sure that this question has been asked somewhere. I found similar ones, but I cannot find exactly what I need, which might mean that I am on the wrong track. I search a method to pass an unevaluated function with arguments to a second function. I could achieve this with `SetAttribute[,HoldAll]`. However the arguments of the first function should be evaluated when I pass it, which does not seem to be the case with `Hold`. To give an example: I tried things like:               mytest[test_] := Module[{}, Print[test];]     mytest1[test_] := Module[{}, myvar = 2; ReleaseHold[test];]          SetAttributes[mytest1, HoldAll]          myvar = 1     mytest1[mytest[myvar]]      This prints `2`, because that is the value of `myvar` when `ReleaseHold` is called. However I want it to print `1`, the value of `myvar` when I call `mytest1`. In general myvar would be an expression which may contain global variables. I do not insist on using `ReleaseHold`. In fact the solution should be such that `mytest` would be evaluated by `NIntegrate`. In Maple I would achieve this by enclosing the name `mytest` in single quotes when passing it to `mytest1` which would delay evaluation by one step. **Edit** For clarification consider the following example, which is closer to the real case:               parameters = {a -> 1}          mytest[expr_, parameters_] := Module[{},       NIntegrate[expr*a /. parameters, {var, 0, 1}]       ]          mytest1[parameters_] := Module[{},         globpar = 1;         NIntegrate[mytest[globpar*var*var1, parameters], {var1, 0, 1}]       ]          mytest1[parameters]      Mathematica returns the correct result `0.25` for this, but it issues a couple of error messages like `NIntegrate::inumr: "The integrand var\ var1 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}."`. I want to avoid this (not by suppressing the error message!), because I want it to be fast and also the real function `mytest` might have a worse behavior if you insert non-numerical values. Hence I want that NIntegrate in `mytest1` first inserts a numerical value for `var1` and then passes the resulting expression as an argument to `mytest` to integrate it over `var`. I.e. I want that it evaluates the argument of the function first, which can however still contain names after evaluation.


Probability Model

I have the following probability model: $(X_k|\text{ PastHistory}_{k-1}, \theta_0, \theta_1, \theta_2) \sim (\pi\cdot N(\theta_1+\theta_0\cdot X_{k-1},1)+(1-\pi)\cdot N(\theta_2+\theta_0\cdot X_{k-1},1))$ and $X_k=0.5X_{k-1}+\epsilon_k$ with $\epsilon_k \sim N(0,1)$ I've tried something like:               Sample[n_] :=       Module[{lst},       lst = {RandomVariate[NormalDistribution[0, 1/(1 - 0.5^2)]]};       element = 1;       While[element <= n,         AppendTo[lst,            RandomVariate[             TransformedDistribution[              p*X1 + (1 - p) X2, {              X1 \[Distributed]               NormalDistribution[θ1 + θ0*lst[[element]], 1],               X2 \[Distributed]                 NormalDistribution[θ2 + θ0*lst[[element]], 1]           }]]];        element = element + 1;         ];      lst      ];      Is this correct?


How to plot an implicit equation with separate dispersion lines of Lamb waves

I'd like to plot (to try reproduce) dispersion curves of Lamb waves as in http://en.wikipedia.org/wiki/Lamb_waves   But I can't to separate each lines. I was reduce the dispersion equations as X=ωd/Vs, Y=V/Vs, here Vs/Vl=S=0.5;d=0.001;               ContourPlot[Cot[1/2 Sqrt[X^2 (1-1/Y^2)]] Tan[1/2Sqrt[X^2(S^2-1/Y^2)]] ==      ((d^2 (-2 + Y^2))/( 2 Sqrt[X^2 (S^2 - 1/Y^2)] Sqrt[X^2 (1 - 1/Y^2)]))       Thanks for all. Please, help me to separate lines.


Drawing CountryData groups

I'm sure I'm overlooking something obvious, but I can't draw groups of countries. Here are two countries and two country groups:               france = CountryData["France", "Coordinates"] ;     usa = CountryData["United States", "Coordinates"];       eu = CountryData["EU", "Coordinates"];     africa = CountryData["Africa", "Coordinates"];      Swapping the coordinates so that longitude comes before latitude:               franceA = Cases[france , {lat_, long_} :> {long, lat}, Infinity];     usaA = Cases[usa, {lat_, long_} :> {long, lat}, Infinity];     euA = Cases[eu, {lat_, long_} :> {long, lat}, Infinity];     africaA = Cases[africa, {lat_, long_} :> {long, lat}, Infinity];      They should all plot:               Table[Graphics[Line[coords]],       {coords, {franceA, usaA, euA, africaA}}]      but the groups don't: ![error](http://i.stack.imgur.com/jeEeM.png) And I tried this:               Table[      Graphics[       Polygon /@ Map[         GeoGridPosition[GeoPosition[#],             "Mercator"][[1]] &, {coords}, {2}]],       {coords, {france, usa, eu, africa}}]      with a similar problem: ![error 2](http://i.stack.imgur.com/OAfDw.png) I'm thinking that two of the lists are the wrong shape or size, but they look OK:               Dimensions[#] & /@        {france, usa, eu, africa, franceA, usaA, euA, africaA}          {{2}, {1, 4672, 2}, {27}, {58}, {1110, 2}, {4672, 2}, {18404, 2}, {16082, 2}}      I may need some `Flatten`ing magic somewhere...?


KroneckerProduct and Transpose

I need to take the `KroneckerProduct` of the an $n \times n$ identity matrix and a $1 \times n$ row vector (let's call it $T$), both of which are numerical. As in: $S=I \otimes T$ (where $\otimes$ denotes the Kronecker product) More specifically I have:               k = 3;          chebT[0] = 1;      chebT[1] = 2*t - 1;          chebT[n_] := chebT[n] = Expand[2*(2*t - 1)*chebT[n - 1] - chebT[n - 2]];     Tstar = Table[chebT[n], {n, 0, k}]          i = IdentityMatrix[k + 1] // MatrixForm     S = KroneckerProduct[i, Transpose[Tstar]] // MatrixForm      but this gives the message: > Transpose::nmtx: The first two levels of the one-dimensional list {1,-1+2 > t,1-8 t+8 t^2,-1+18 t-48 t^2+32 t^3} cannot be transposed. >> I can use loops to manually calculate the Kronecker product, but I would rather not. What am I doing wrong? Do I need to use `Array` instead of `Table`? Edited to include the whole (and correct) code.


Invert a transcendental function

I have tried `Reduce` and `Solve` in Mathematica, as well as have a long list of tries in Maple, but cannot seem to get anywhere solving the following for `V`:               V^P * (V-1)^Q == c^(P-Q) * X^Q * (V-c^2)^Q,      where `P`,`Q` are positive integers; `V>0`; `U>0` and `X = U^Q * V^P`; `c = Exp[t/2]` where `t` is `i` times a real number. Any suggestions would be great. Btw, I can share a Maple file (http://ubuntuone.com/5WGrFF8PYXR8LSwNB95SRW) where I tried a Fixed-Point/Contraction attempt, a series inverse attempt, and even the Lagrangian Inversion method. For the most part I seem to run out of computing power when I try to get to decent orders of approximation... P.S. I am looking for a symbolic solution, at least to a few orders.


Plot3D constrained to a non-rectangular region

I would like to make a nice 3D graphic of a parabolic bowl, with a cylindrical rim. If I do the following:               Plot3D[x^2 + y^2, {x, -3, 3}, {y, -3, 3}]      I get a paraboloid, but the box is rectangular, so the edges come to points. I want a cylindrical bounding box. The best I've come up with is this:               Plot3D[Piecewise[{{x^2 + y^2, x^2 + y^2 < 1}}], {x, -1, 1}, {y, -1, 1}]      This creates a bowl, but there is also a "floor" to the graphic that I would like to get rid of. I might be able to play games with the coloring, but that seems like a poor hack. Does anyone have any suggestions? More generally, is it possible to create a 3D bounding box of arbitrary shape?


An efficient circular arc primitive for Graphics3D

As many people have noted, the 2D graphics primitive `Circle` doesn't work in a `Graphics3D` environment. Several solutions to this problem have been proposed, both on this site and on StackOverflow. They all have the disadvantage that they result in either rather ugly circles or highly inefficient ones because these circles were generated by a polygon with several hundreds of facets, making interactive graphics incredibly slow. Other alternatives involve the use of `ParametricPlot` which doesn't generate efficient graphics either or yield a primitive that can't be used with `GeometricTransformation`. I would like to have a more elegant solution that creates a smooth circular arc in 3D without requiring zillions of coordinates. The resulting arc should be usable in combination with `Tube` and can be used with `GeometricTransformation`.


How to Make a change of variables

I have the following expresion $$\hat{M}^2=-\left[\frac{1}{\sin\beta}\frac{\partial}{\partial\beta}\sin\beta\frac{\partial}{\partial\beta}+\frac{1}{sin^2\beta}\left(\frac{\partial^2}{\partial\alpha^2}+\frac{\partial^2}{\partial\gamma^2}\right)-2\frac{cot\beta}{sin\beta}\frac{\partial^2}{\partial\alpha\partial\gamma}\right]$$ In my problem i don't want to work with the angle $\beta$, instead i just want to work with the $\cos\beta$ (basically due to the convergence of Legendre functions with respect to spherical armonics), so i'm trying to make a transformation rule for the partial derivative. For instance, $$q=\cos\beta \quad; usin=\sin\beta=\sqrt{1-q^2} \quad and\quad dq=-\sin\beta d\beta$$ My expression for $\hat{M^2}$ is now: $$\hat{M}^2=-\left[\frac{\partial}{\partial q}usin^2\frac{\partial}{\partial q }+ \frac{1}{usin^2}\left(\frac{\partial^2}{\partial\alpha^2}+\frac{\partial^2}{\partial\gamma^2}\right)-2\frac{q}{usin^2}\frac{\partial^2}{\partial\alpha\partial\gamma}\right]$$               Subscript[w, 1] = f[Subscript[r, 1], Subscript[r, 2], α, β, γ, Subscript[Θ, 12]]          M = -(1/Sin[β] D[(Sin[β] D[Subscript[w, 1], β]), β] + 1/Sin[β]^2 (D[Subscript[w, 1],         {α, 2}] + D[Subscript[w, 1], {γ, 2}]) - 2 Cot[β]/Sin[β] D[Subscript[w, 1], α, γ])      I have written a few lines of code, however i don't know how to exactly proceed with the transformation.


Plotting: Is anyone familiar with gradientfieldplot command?

I am trying to plot this graph showing the electric field lines and lines of equipotential based off the electrode configuration(in black) of two parallel lines. This is what I've been using for other electrode configurations:                gradientFieldPlot[(y^2 + (x - 7/2)^2)^(-1/2) - (y^2 + (x + 7/2)^2)^(-1/2), {x, -7, 7},                          {y, -5, 5}, PlotPoints -> 50, ColorFunction -> "BlueGreenYellow",                          Contours -> 15,ContourStyle -> White, Frame -> True,                        FrameLabel -> {"x", "y"}, ClippingStyle -> Automatic, Axes -> True,                        StreamStyle -> Orange]      and am trying to do it in a similar manner, but I do not know how to express the equations for these two finite parallel lines in the `[ ]`. Can any one help? Thanks sooo much!! ![enter image description here](http://i.stack.imgur.com/48vec.jpg)


Keyboard shortcut for moving to last edit location/cell

When you have long notebook with hundreds of cells, you sometimes need to scroll/jump manually to your last edited cell. I dind't find any shortcut for doing that. Any ideas?


Handling "Solve was unable to solve the system with inexact coefficient" errors

> **Possible Duplicate:**   >  How to get rid of warnings when using Solve on an equation with inexact > coefficients? I've been trying to calculate the following in _Mathematica_ :               Solve[205.73/(1 + cet)^5 + 205.73/(1 + cet)^4 + 205.73/(1 + cet)^3 +          205.73/(1 + cet)^2 + 205.73/(1 + cet) == x, cet]      but it keeps returning > "Solve was unable to solve the system with inexact coefficient" How can I calculate the above? I just want to isolate `cet` so I can create an algorithm to solve it.


Look up a non-US stock price

I need to get historical prices of certain non-US stocks (specifically, they are traded at Prague Stock Exchange, Czech Republic) but I am not able to find the proper "name" that Mathematica would accept. For example, is there a way to look up the Mathematica name for a stock if I know the ISIN code or the exchange (but probably not the exchange's Mathematica symbol) where the stock is traded?


Improve speed for calculating a recursive sequence

I want to calculate following recursive sequence: $\alpha_{0}=0,\\\ \cos(\alpha_{i})=\cos(\alpha_{i-1})\cdot\cos(\beta_{i})+\sin(\alpha_{i-1})\cdot\sin(\beta_{i})\cdot\cos(\gamma_{i}).$ In mathematica 8.0.1 I try to do this with:               endRecursion = 20;     beta = Import["beta.txt", "List"];     beta = beta[[1;;endRecursion]];     gamma = RandomReal[{0,2*Pi}, endRecursion];          alpha[0]:= 0;     alpha[i_]:=         ArcCos[Cos[alpha[i-1]]*Cos[beta[[i]]]+         Sin[alpha[i-1]]*Sin[beta[[i]]]*Cos[gamma[[i]]]];          result=Table[alpha[i], {i, 1, endRecursion}];      The values for `beta` are imported because they are generated by another formula which is not important for my question here. Values for `beta` can be found here. The problem is that the calculation of the `result` is very slowly. It takes about 14s for just 20 iterations! And I need about 300 iterations (times ~10000, because I have several lists of beta values). I recognized that the calculation is much faster if I skip the `Cos[alpha[i-1]]` in the first or the `Sin[alpha[i-1]]` in the 2nd summand. Then it takes just ~ 0.01 s for 20 iterations. But unfortunately this falsifies my result. I cannot understand why it is so much faster if there is just one time `alpha[i-1]` on the right side of the equation. Am I doing something wrong? Is there any way to increase the speed of this calculation? I would be glad about any help!


Calculate scalar potential from electric field

Is it possible for Mathematica to solve an equation like $\nabla f(\mathbf{r}) = - \mathbf{E}(\mathbf{r})$ for $f(\mathbf{r})$? I tried `Reduce[Grad[f[x,y,z],{x,y,z}]== -{ex,ey,ez}, f]` but that does not work.


Supported options for compiling LibraryLink code with VC++

I have to generate an interface to Mathematica for a fairly large library. I would like to use LibraryLink, as the generation seems much simpler. The platform is Windows (VS 2012), and I am wondering what the constraints are with regards to compiler options, etc. First and foremost: can I compile in 32 bit mode, or does it have to be 64 bits? (The CygWin toolkit `file` tells me that `MathKernel.exe` is a PE32+ executeable, whatever that is, and that the architecture is x86-64, which is 64 bits.) Would there be any library incompatibilities when compiling with VS2012 (VC11)? And are there any options I must respect?


SetDelayed and avoiding function calls through memoization

I am fairly new to _Mathematica_. I am working my way through a number of books. I have been looking at the use of `SetDelayed` and want to confirm that my understanding is correct. I define a function as follows.               f[x_]:= f[x] = x;      When I evaluate `?f`, I can see a rule for this function. Now each time I evaluate `f`, I see another rule is created for `f`. So by declaring the function as above, I ensure that for any given value of `x` the function will only be evaluated once. Suppose I had declared functions `f` and `g` as follows.               f[x_] := f[x] = Sin[x] + Cos[x];     g[x_] := Sin[x] + Cos[x];      Am I correct in saying that, for any given `x`, `f` will only be evaluated once? That is, for a given value of `x`, `Sin[x]` and `Cos[x]` will only be called once; whereas in the case of `g`, each time `g` is called, _Mathematica_ will evaluate both `Sin[x]` and `Cos[x]`? Will using `Trace` confirm this?


How to improve the performance of solutions to Project Euler (#39)?

This is the problem 39 of Project Euler, which I asked in the chat room two days ago. My original code runs as slowly as snails, and finally I got two answers from JM and Rojo. Unfortunately, both of them are faster than mine but still not enough. Here is the problem: > If p is the perimeter of a right angle triangle with integral length sides, > {a,b,c}, there are exactly three solutions for p = 120. > > {20,48,52}, {24,45,51}, {30,40,50} > > For which value of p <= 1000, is the number of solutions maximised? My terrible answer, runs **more than one minute** :               Last@Sort@ Table[{Select[      IntegerPartitions[i, {3}],      #[[1]] < #[[2]] + #[[3]] && #[[1]]^2 == #[[2]]^2 + #[[3]]^2 &]      // Length, i}, {i, 1, 1000}]      JM's suggestion (not finished):               Count[IntegerPartitions[900, {3}], tri_ /; First[tri] < Total[Rest[tri]]      && Norm[Rest[tri]]^2 == First[tri]^2]//Timing      > `{1.248, 4}` This is from Rojo (not finished):               Transpose[IntegerPartitions[900, {3}]]^2 /. {a_, b_, c_} :>      Length@a - Total@Unitize[a - b - c]//Timing      > `{0.124, 4}` I have noticed that many answers based on other languages ( _e.g._ , C, C++,...) in the forum of Project Euler can cost just **several seconds** , so how fast can MMa get? Since there are so many programming styles here, are there any rules for us to choose different programming styles for different problems? For this question, which style is the best?


How to compare the InputField values in For loop dynamically

I am using a `For` loop for printing five `InputFields`. The loop gets its values from the variable tx. I want to compare the values dynamically with 10 and print the result. But, the comparison is going out of loop, why?               tx = {4, 1, 6, 7, 8};     Reap[For[i = 1, i <= 5, i++,         Sow[ {InputField[tx[[i]]],Dynamic[If[(tx[[i]] < 10), "right", "wrong"]]}]]]


How to see the 'source code' of DockedCells? ALT: How to 'show expression' of DockedCell?

Here is a CDF file with the dockedcells toolbar (at the top). I'm trying to see how he created and positioned the logo, the formatting buttons, table of contents, etc, through a source code of it, but I can't select it like a cell and say 'show expression'. Primary Questions: How to see the 'source code' of DockedCells? Can you do this in a FreeCDF as well as a Notebook? What is the difference between the two formats in regard to seeing source code? Secondary question: How can I see what differs from third party notebooks compared to default mathematica settings? So far I know that Option Inspector and Edit->Preferences and Edit Stylesheet show you most stuff, as well as view expressions in cells, but all of this still didn't show me anything about the dockedcells!


Control Manipulate variables inside Manipulate

I have the data for graph nodes as:               graphComponents = {{"blood", "pressur"}, {"harvard", "oxford"}, {"help",  "lower"},     {"oxford", "benefit"}, {"harvard", "benefit"}, {"lower",  "level"}, {"faceoff", "benefit"}     , {"oxford", "faceoff"}, {"harvard", "faceoff"}, {"over", "benefit"}, {"faceoff", "over"},     {"oxford", "over"}, {"harvard", "over"}, {"benefit", "drug"},      {"oxford",  "drug"}, {"harvard", "drug"}, {"faceoff", "drug"}, {"fast",  "test"},     {"over", "drug"}, {"test", "test2"}};      Then I want to make a `Manipulate` to show the communities of the graph:               Manipulate[       components = graphComponents[[1 ;; L]];       rawGraph = Graph[#[[1]] <-> #[[2]] & /@ graphComponents[[1 ;; L]]];       communities = FindGraphCommunities[rawGraph];       H = HighlightGraph[rawGraph, Subgraph[rawGraph, communities[[i]]]],       {{L, 15, "Number of Tuples: "}, 5, 20, 5},        {{i, 2, "Cluster number: "}, 1, 3, 1},        LocalizeVariables -> False]      The question is as the value of `L` changes the number of communities change as well. So the control list for variable `i` should be updated when `L` changes. How should this be done?


Exporting held expressions through JSON

Trying to round-trip expressions through JSON, I'm getting unexpected errors for held expressions, and would be grateful for advice or clues. Consider, first, something that works well               Export[Environment["USERPROFILE"] <> "\\AppData\\Local\\test.json", {1, 2, 3},"JSON"]      and read it back in               Import[Environment["USERPROFILE"] <> "\\AppData\\Local\\test.json","JSON"]      producing the expected `{1, 2, 3}`. However, when I try a held expression, such as (and now you can see why I might want to do this):               Export[       Environment["USERPROFILE"] <> "\\AppData\\Local\\test.json",       HoldComplete[myList = {1, 2, 3}],       "JSON"]      and we get               Export::badval: The element Data contains invalid values. >>      I haven't been able to find anything useful on this error message. I suspect it's something to do with `HoldComplete` and its friends not being real expressions, but rather some kinds of special syntax in the front end or the kernel, but it's a bit surprising since one of the oft-repeated slogans in Mathematica is _everything is an expression_. Btw, lest we think that the assignment to `myList` is the problem, the following fails with the same message:               Export[       Environment["USERPROFILE"] <> "\\AppData\\Local\\test.json",       HoldComplete[{1, 2, 3}],       "JSON"]


ListPointPlot3D in a Manipulate

I have a program using `Manipulate`. The program given certain values will compute some values. I want these values to appear in a 3D list plot but the problem I am facing is that when the user changes the parameter the previous plot will disappear. How can I keep the previous points plotted even after the user changes the values of x or y with the Manipulators? I want the user to see all the points. Here is an example:               Manipulate[ListPointPlot3D[{{0, 0, 0}, {x + y, x, y/2}}],        {x,  0, 10},        {y, 0, 5}]      I want the plot to show all the points where the user changes x and y not just the latest.


Efficiently Visualising Very Large Data Sets (without running out of memory)

I have put a few really hard problems in combinatorics up against Mathematica 8. I'd have to say that it works really well, _until you want to view the data_. If you look at my question _Advanced Tupling_ there is an elegant solution. One line function. Data of about 12 million sets given the sample data presented. Let's use that question to illustrate. Here are the data:               a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 21, 22, 23, 25, 26, 28};      b = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 30, 31, 33, 37, 41};      c = {6, 10, 13, 14, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 35, 37, 39};       d = {17, 19, 25, 30, 31, 33, 34, 35, 36, 38, 44};      e = {31, 41, 45, 47};      f = {23, 26, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53};       And here is one of the solutions posted in that question:               newTuples[t_, x_] :=        Flatten[ ParallelTable[Append[s, #] & /@ Complement[x, s], {s, t}], 1];       One would however like to verify the results. From everything seen, it looks good. But one wants to see it all. Click 'Show All' output and the program grabs all available memory resources, including consuming all available disk space for page file and still takes literally _days_ to complete. Is there an efficient way to render data? I have had the same problem with graphical plots, it just chokes up after processing. It is as if the entire problem has to be reprocessed for it to render. Surely this cannot be how Mathematica was intended to work. I must be missing something. **What are some memory-efficient ways to visualize a data set as large as the output of the above function?**


Using NSolve in the complex plane

I am trying to find numerical values for $\Im\ e^{\frac{1}{2} +i\ y} = \Im\ \zeta(\frac{1}{2} +i\ y)$ for a given range. I have tried:               NSolve[Im[Exp[0.5 + I x]] == Im[Zeta[0.5 + I x]] && 0 <= x <= 20, x]      I can see that:               Plot[{Im[Exp[0.5 + I x]], Im[Zeta[0.5 + I x]]}, {x, 0, 20}]      gives: ![enter image description here](http://i.stack.imgur.com/5SRSR.gif) ... I am sure it is a problem with my syntax again, but can't seem to fix it :/


Issue with NDSolve

This could be a stupid issue, but I have been checking for ages. I cannot solve this apparently innocuous system of PDEs:               L = 10; \[Xi] = 1; DD = 1; Subscript[\[Phi], 0] = 1;     l = 1; w = 0.13;      v = 0.1; \[Eta] = 0.5; DD = 1; \[Lambda] = 0.1;          \[CapitalOmega] = l \[Pi]/ L ;           Equations                u[\[Alpha]aa_, a_, A_] = -(1/(2 \[Eta] + \[Lambda]^2*(a +A E^(-Subscript[\[Phi],             0] - \[Phi][x] Cos[\[CapitalOmega] x]))*       Sin[2 \[Theta][x] Sin[\[CapitalOmega] x]]^2))*((a +          A E ^(Subscript[\[Phi],            0] + \[Phi][x] Cos[\[CapitalOmega] x])) \[Lambda] w (D[\[Theta][           x] Sin[\[CapitalOmega] x], x])^2 \[CapitalOmega]^2 Sin[        2  \[Theta][x] Sin[\[CapitalOmega] x]] Sin[\[Theta][          x] Sin[\[CapitalOmega] x]]^2 -       2*(a +A E^(-Subscript[\[Phi], 0] - \[Phi][x] Cos[\[CapitalOmega] x]))*       v*(Subscript[\[Phi], 0] + \[Phi][x] Cos[\[CapitalOmega] x])^2 \[Theta][        x]  \[CapitalOmega] Cos[\[CapitalOmega] x]  Sin[\[Theta][          x] Sin[\[CapitalOmega] x]] + (a +A E^(-Subscript[\[Phi],             0] - \[Phi][             x] Cos[\[CapitalOmega] x]))*\[Alpha]aa*(Subscript[\[Phi],          0] + \[Phi][x] Cos[\[CapitalOmega] x])^2*       Sin[2 \[Theta][x] Sin[\[CapitalOmega] x]] +       D[\[Phi][x] Sin[\[CapitalOmega] x],         x] \[CapitalOmega]  Cos[\[Theta][          x] Sin[\[CapitalOmega] x]] (w - \[Lambda] w Cos[           2 \[Theta][x] Sin[\[CapitalOmega] x]]));               eqn1[\[Alpha]aa_, a_, A_] := (-D[\[Theta][x]*Sin[\[CapitalOmega] x], {x, 2}]*(1 -         w Cos[\[Theta][x]*Sin[\[CapitalOmega] x]]^2) (a +         A E^(Subscript[\[Phi], 0] + \[Phi][x] Cos[\[CapitalOmega] x])) +      1/2 (a + A E^(         Subscript[\[Phi],           0] + \[Phi][            x] Cos[\[CapitalOmega] x])) w^2 \[CapitalOmega]^2 (D[\[Theta][          x] Sin[\[CapitalOmega] x], x])^2 Sin[       2 \[Theta][x] Sin[\[CapitalOmega] x]] - (Subscript[\[Phi],         0] + \[Phi][x] Cos[\[CapitalOmega] x]) (a +         A  E^(-Subscript[\[Phi],            0] - \[Phi][x] Cos[\[CapitalOmega] x]))  v   D[\[Theta][         x] Sin[\[CapitalOmega] x],        x] \[CapitalOmega]  Sin[\[Theta][x]*Sin[\[CapitalOmega] x]] -      u[\[Alpha]aa, a,        A] (1 - \[Lambda] Cos[2 \[Theta][x] Sin[\[CapitalOmega] x]]) - (a +         A E^(Subscript[\[Phi],           0] + \[Phi][x] Cos[\[CapitalOmega] x])) w  \[CapitalOmega]  D[\[Phi][         x]  Sin[\[CapitalOmega] x],        x] Cos[\[Theta][x]*Sin[\[CapitalOmega] x]]);               eqn2[\[Alpha]aa_, a_, A_] := -D[(       v (a + A E^(-Subscript[\[Phi],              0] - \[Phi][x] Cos[\[CapitalOmega] x])) (Subscript[\[Phi],           0] + \[Phi][x] Cos[\[CapitalOmega] x])^2 Sin[\[Theta][           x] Sin[\[CapitalOmega] x]] - (DD (1 - \[Xi] Sin[\[Theta][                 x] Sin[\[CapitalOmega] x]]^2) -           w Cos[\[Theta][x] Sin[\[CapitalOmega] x]]^2) (a +           A E^(Subscript[\[Phi],             0] + \[Phi][x] Cos[\[CapitalOmega] x])) \[CapitalOmega] D[\[Phi][           x] Cos[\[CapitalOmega] x], x] + \[Lambda]  u[\[Alpha]aa, a,          A] Sin[\[Theta][x] Sin[\[CapitalOmega] x]] Sin[         2 \[Theta][x] Sin[\[CapitalOmega] x]]), x];           Solving           sol1 = {\[Theta], \[Phi]} /. First[NDSolve[{       eqn1[0.07, 0, 1] == 0,       eqn2[0.07, 1, 0] == 0,        \[Theta][0] == 0,       \[Theta][L] == 0,          \!\(\*SuperscriptBox["\[Phi]",      TagBox[     RowBox[{"(", "1", ")"}],     Derivative],     MultilineFunction->None]\)[0] == 0,          \!\(\*SuperscriptBox["\[Phi]",      TagBox[     RowBox[{"(", "1", ")"}],     Derivative],     MultilineFunction->None]\)[L] == 0}, {\[Theta], \[Phi]}, {x, 0, L}] ];          \[Infinity]::indet: Indeterminate expression 0. ComplexInfinity encountered. >>          \[Infinity]::indet: Indeterminate expression 0. ComplexInfinity encountered. >>          \[Infinity]::indet: Indeterminate expression 0. ComplexInfinity encountered. >>          General::stop: Further output of \[Infinity]::indet will be suppressed during this calculation. >>          NDSolve::ndnum: Encountered non-numerical value for a derivative at x == 0.`. >>          ReplaceAll::reps: {<<1>>==0,<<10>>+(0.1 <<2>> (<<1>>))/(1.+<<21>> <<1>>)==0,\[Theta][0]==0,\[Theta][10]==0,(\[Phi]^\[Prime])[0]==0,(\[Phi]^\[Prime])[10]==0} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>


How to find the nth derivative?

This question is not the same as my last one. How do you find the $n$-th derivative where $n$ is a variable? For example, you can find the nth derivative for a specific $n = 3$               D[Log[1 + x], {x, 3}]      but how do you get _Mathematica_ to show the $n$-th derivative for $n$ as a general variable? For example, from Wolfram Alpha


What is Sub Mathematica?

When looking at the locally available licenses, I see four entries: "Mathematica", "MathKernel", "Sub Mathematica" and "Sub Mathkernel". Now "Mathematica", "MathKernel" and "Sub Mathkernel" are clear, but what are "Sub Mathematica" licenses used for? Are there parallelization constructs for the front end?


Can Mathematica help to rearrange an equation?

I have an equation which I want to rearrange so one variable is on the left side by itself. Normally, I would do this with basic algebra and identities. However, is it possible to use Mathematica to do this for me, automatically?


How to iteratively display the nth derivative?

I am new to Mathematica, but not so new to programming. What I'd like to do in Mathematica (not using an API) is to display on each line, the nth derivative of a function, e.g. for n = 1..10. Is there a way to accomplish this in Mathematica? (without explicitly typing the command for each derivative of course. e.g. does Mathematica have iterative constructs to do this).


Does FindFit support complex numbers or doesn't it?

Inspired by this previous question: Findfit doesn't give the good fit; Changing the starting values will not change the results. Consider the following complex-valued dataset.               f[t_] := b + a/(c + t)     data = Table[f[t] /. {a -> -1 - I, b -> 1 + I, c -> -5 + 2 I}, {t, 1, 10}]        + 0.1 RandomComplex[{-1 - I, 1 + I}, 10];     plot = ListPlot[Through@{Re, Im}@data]      ![enter image description here](http://i.stack.imgur.com/2tFjp.png) Mathematica has no trouble fitting a linear model to it, and successfully finds complex values for the fit parameters.               g[t_] := u + v t;     lfit = FindFit[data, g[t], {u, v}, t]     (* {u -> 1.06445 + 1.59084 I, v -> -0.0604794 - 0.0647658 I} *)     Show[plot, Plot[Evaluate@Through@{Re, Im}@(g[t] /. lfit), {t, 1, 10}]]      ![enter image description here](http://i.stack.imgur.com/LxYNC.png) It likewise has no trouble fitting the original nonlinear model to it if $c$ is held fixed.               fit = FindFit[data, f[t] /. c -> -5 + 2 I, {a, b}, t]     (* {a -> -1.00813 - 0.888072 I, b -> 0.960261 + 1.01034 I} *)     Show[plot, Plot[Evaluate@Through@{Re, Im}@(f[t] /. c -> -5 + 2 I /. fit), {t, 1, 10}]]      ![enter image description here](http://i.stack.imgur.com/C40wR.png) But make $c$ variable and suddenly it can't deal with complex numbers any more.               FindFit[data, f[t], {a, b, c}, t]      > FindFit::nrlnum: The function value {0.318749 -1.36562 I,0.294047 -1.31665 > I,0.306199 -1.5257 I,0.339789 -1.54803 I,<<3>>,0.59458 -1.00036 I,0.343269 > -0.994435 I,0.400584 -0.92625 I} is not a list of real numbers with > dimensions {10} at {a,b,c} = {1.,1.,1.}. What gives?


Lost and found Tooltip in ListPlots

I came upon a strange `Tooltip` behavior in `ListPlot` and `ListLogPlot`. Consider the following code:               data={{{1, 0.755384}, {21, 0.73102}, {41, 0.425711}, {61, 0.344925}, {81,0.298442}, {101, 0.152632}, {121, 0.0959704}, {141, 0.0648073}, {161, 0.04575}, {181, 0.0355283}, {201, 0.0350886}, {221, 0.0697085}, {241, 0.125175}, {261, 0.144639}, {281, 0.0730912}, {301, 0.0833903}}, {{1, 0.244886}, {21, 0.268764}, {41, 0.574521}, {61, 0.655075}, {81, 0.701431}, {101, 0.847269}, {121, 0.903783}, {141, 0.935137}, {161, 0.95431}, {181, 0.964333}, {201, 0.964812}, {221, 0.930292}, {241, 0.874787}, {261, 0.855361}, {281, 0.926909}, {301, 0.916631}}};          ListPlot[      MapIndexed[Tooltip[#1, {"A", "B"}[[First[#2]]]] &, data],       Joined -> True, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/C15Nt.jpg) and               ListLogPlot[      MapIndexed[Tooltip[#1, {"A", "B"}[[First[#2]]]] &, data],       Joined -> True, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/V1pE9.jpg) Surprisingly, the `Tooltip` is lost in the first plot but appears in the `LogListPlot`. Does anybody know why and how to rediscover the `Tooltip` in the `ListPlot`? **EDIT 1:** To elaborate a Little on the weirdness of the Problem. The `Tooltips` work in `ListPlot` for different data sets. For example the following Shows perfect `Tooltip`s:               data2={{{1, 0.999287}, {21, 0.760537}, {41, Missing[]}, {61, Missing[]}, {81, Missing[]}, {101, Missing[]}, {121, Missing[]}, {141, Missing[]}, {161, Missing[]}, {181, Missing[]}, {201, Missing[]}, {221, Missing[]}, {241, Missing[]}, {261, Missing[]}, {281, Missing[]}, {301, Missing[]}}, {{1, 0.000595082}, {21, 0.172139}, {41, 0.32012}, {61,0.229145}, {81, 0.180066}, {101, 0.0638401}, {121, Missing[]}, {141, Missing[]}, {161, Missing[]}, {181, Missing[]}, {201, Missing[]}, {221, Missing[]}, {241, Missing[]}, {261, Missing[]}, {281, 0.0069369}, {301, Missing[]}}, {{1, Missing[]}, {21, Missing[]}, {41, 0.550466}, {61,0.683027}, {81, 0.744493}, {101, 0.863833}, {121, 0.878976}, {141,0.875153}, {161, 0.865458}, {181, 0.858256}, {201, 0.862768}, {221, 0.904684}, {241, 0.949275}, {261, 0.969743}, {281,0.978723}, {301, 0.820449}}, {{1, Missing[]}, {21, Missing[]}, {41, Missing[]}, {61, Missing[]}, {81, Missing[]}, {101, Missing[]}, {121, 0.0768691}, {141, 0.0943452}, {161, 0.111187}, {181, 0.123562}, {201, 0.12506}, {221,0.0852941}, {241, 0.0385046}, {261, 0.0163843}, {281, Missing[]}, {301, Missing[]}}, {{1, Missing[]}, {21, Missing[]}, {41, Missing[]}, {61, Missing[]}, {81, Missing[]}, {101, Missing[]}, {121, Missing[]}, {141, Missing[]}, {161, Missing[]}, {181, Missing[]}, {201, Missing[]}, {221, Missing[]}, {241, Missing[]}, {261, Missing[]}, {281, Missing[]}, {301, Missing[]}}, {{1, Missing[]}, {21, Missing[]}, {41, Missing[]}, {61, Missing[]}, {81,Missing[]}, {101, Missing[]}, {121, Missing[]}, {141, Missing[]}, {161, Missing[]}, {181, Missing[]}, {201, Missing[]}, {221, Missing[]}, {241, Missing[]}, {261, Missing[]}, {281, Missing[]}, {301, 0.128235}}};          ListPlot[      MapIndexed[Tooltip[#1, {"A", "B", "C", "D", "E", "F"}[[First[#2]]]] &, data],       Joined -> True, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/ikJWH.jpg)


Using absolute locator coordinates in Manipulate

In this simplified code below, I'd like to display two plots within `Manipulate`, and use the `Locator` controltype to set the value of `x` relative to its position within the first plot only. With the `Print[x]` command inserted it is obvious that the locator is using the coordinates of the entire graphics plane.               Manipulate[      Print[x];      GraphicsRow[{ListLinePlot[{x, {0, 0}},          PlotRange -> {{0, 2}, {0, 2}}],         ListLinePlot[{x, {2, 2}},          PlotRange -> {{0, 2}, {0, 2}}]}], {{x, {0, 0}, {2, 2}},        ControlType -> Locator}]


How can I simulate a pot lid rotating around an axis that is quickly rotating?

How can I simulate the rotation of a pot lid about an axis that is quickly rotating as in the following image? I'm particular interested in the motion of the red dot. ![rotating pot lid](http://i.stack.imgur.com/9E89Y.gif) Here is my attempt:               φ = π/6; r = 1;     line = Rotate[{Line[          Table[{Cos[θ], Sin[θ], 0}, {θ, 0,             2 π, π/20}]], {Red, Pink, PointSize[Large],           Point[{1, 0, 0}]}}, φ, {0, 1, 0}];     Manipulate[      Graphics3D[{Rotate[         Rotate[line, θ, {0, 0,            1}], θ Cos[φ], {Sin[φ] Cos[θ],           Sin[φ] Sin[θ], Cos[φ]}, {0, 0, 0}], {Line[          Table[{r Cos[φ] Cos[θ1],             r Cos[φ] Sin[θ1], -r Sin[φ]}, {θ1,             0, θ, π/20}]]}, {Blue, PointSize[Large],          Point[{0, 0, 0}]}}, Axes -> True, PlotRange -> 2,        AxesLabel -> {"x", "y", "z"}], {θ, 0, 2 π}]      ![visualization attempt](http://i.stack.imgur.com/4jj1a.jpg)


Can I ask Mathematica to replace the arguments of my functions with a replacement rule?

I have an equation that I evaluate at some point (let's say $x=1$) that have terms of the form               f[1,y] D[g[1,y],{y,2}]      Is there an easy way to replace [1,y] by [x,y] with a simple replacement rule? The thing is that               g[1,y] /. g[1,y] -> g[x,y]      will indeed replace g, but it won't work for any of its derivatives, and there are far too many functions and derivatives for me to make a replacement rule for all of them. Would there be a clever way to do this? So far, my only solution has been copy-pasting my equations in Word and using the text replacement tool in there. It would be neat not having to go outside of Mathematica to do this though.


Am I missing the point of ViewCenter?

Based on this description of 3D graphics and the associated Wolfram Training video, I anticipated that using the mouse to rotate the graphic below would rotate around the point where the three cylinders intersect:               axis = {EdgeForm[], Specularity[White, 10],        FaceForm[Red], Cylinder[{{0, 0, 0}, {0, 0, .5}}, 0.01],        FaceForm[Blue], Cylinder[{{0, 0, 0}, {0, .5, 0}}, 0.01],        FaceForm[Green], Cylinder[{{0, 0, 0}, {.5, 0, 0}}, 0.01]        };     Graphics3D[axis, Boxed -> True, ViewCenter -> {0, 0, 0},       RotationAction -> "Clip", ViewAngle -> 65 Degree]      So far so good. When I make a slight adjustment to the graphic, though, the (for lack of a better term) swivel point has moved to what appears to be {-0.5,-0.5,-0.5}.               Graphics3D[{axis, Opacity[0.5], Sphere[{0, 0, 0}, 0.5]},       ViewCenter -> {0, 0, 0}, RotationAction -> "Clip",       ViewAngle -> 65 Degree]      Can someone enlighten me as to my misinterpretation of `ViewCenter` and how I can get the second object to rotate around {0,0,0} when using the mouse?


Is it possible to export the equations from Mathematica to MATLAB?

Is it possible to export the output expressions from _Mathematica_ computations (e.g., equations) in valid MATLAB syntax?


Export expression to Matlab

> **Possible Duplicate:**   >  Is it possible to export the equations from Mathematica to MATLAB? I like to export a _Mathematica_ expression like....               EQ = -((R2^2 <<7>>)/(-R2^2 RV0 RV1^3 RV2 RV3^3 RV4^3 RV5^3 (<<1>> + <<1>>) \       + R2^2 RV1^3 RV2 RV3^3 RV4^3 RV5^3 (-R2^2 <<7>> -        RV0 (<<1>> + R2^2 <<6>>))))      ... to _Matlab_. I tried to save the variable in a .mat file but get the following error:               Export::type: -(R2^2 <<6>> (-R2^4 RV1^2 RV2^2 RV3^6 RV4^6 RV5^6 ZV1 (R2 RV1 RV3^3       RV4^3RV5^3 ZV2 (-R2 RV3 Power[<<2>>] Power[<<2>>] ZV3 Plus[<<2>>]+R2 RV3       Plus[<<2>>])+R2 RV1 (-RV2 Power[<<2>>] Power[<<2>>] Power[<<2>>] Plus[<<2>>]+R2       Power[<<2>>] Power[<<2>>] Power[<<2>>] Plus[<<2>>]))-R2^2 <<5>> (-R2^2 RV1 RV2 RV3^3       RV4^3 RV5^3 (<<1>>)+R2^2 RV1 <<3>> <<1>> (<<1>>-<<1>>))))/(-R2^2 RV0 RV1^3 RV2 RV3^3       RV4^3 RV5^3 (-R2^4 RV1^2 RV2^2 RV3^6 RV4^6 RV5^6 ZV1 (Times[<<7>>]+Times[<<4>>])+R2^2       RV1^2 RV2 RV3^3 RV4^3 RV5^3 (Times[<<8>>]+Times[<<7>>]))+R2^2 RV1^3 RV2 RV3^3 RV4^3       RV5^3 (-R2^2 RV1^2 RV2 RV3^3 RV4^3 RV5^3 ZV1 (Times[<<8>>]+Times[<<7>>])-RV0       (Times[<<8>>]+Times[<<7>>]))) cannot be exported to the MAT format. >>      The included abbrevations of very long terms are very similar to the expressions you see above. Is there another way to do this?


How can I convert a matrix into matlab form string?

How can I convert a matrix into matlab form?               matrix2Matlab[matrix0_] :=  Module[{matrix = matrix0},   "[" <> StringReplace[    ExportString[matrix, "CSV"], {"\n" -> ";", "," -> " "}] <> "]"]          matrix2Matlab[m = IdentityMatrix[3]]          (*         [1 0 0;0 1 0;0 0 1]     *)      Are there more simpler ways? I use MATLink to deal with the string matrix.


How to use NIntegrate in a purely numerical mode?

I have a function that is defined as the smallest root of a given polynomial. Something like this:               f[param1_,param2_,param3]:= Module[{roots},       roots = getRoots[param1,param2,param3];       Return[Min[roots]];     ]      The function `getRoots`would build a polynomial and use `Solve[]` to solve it. I need to integrate `f`numerically, but I keep getting errors:                NIntegrate::inumr: "The integrand Min[<<1>>] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,300000}}"      Using `Manipulate`, I can calculate values along the integration range, that is, the function indeed has numerical values. I suspect that the symbolic preprocessor tries to analyze the argument of `Min[]`, but it get stuck because the argument is a list of roots of a polynomial. Since the function `f[]`can be evaluated numerically, it should be possible to integrate it in a purely numerical way, without the symbolic analysis. Is there any way, any choice of integration method to do that?


Developing easy code to apply Delta Method to generate prediction bands for custom distributions

I think that this is an interesting issue for all those who when to not only adjust one prediction function, but also to obtain the prediction bands to asses the graphical or tabular error I'm trying to apply step by step the Delta Method to my data, however, as I would like to share with you my advances to get to the final. Summarizing and reviewing the standard method using in commercial software above all, we find: ![Delta Method in confidence and prediction intervals](http://i.stack.imgur.com/tgxx4.jpg) Where the right square root involves the inverse of the Hessian matrix I think, although they call it design matrix. As well as the gradient matrix function. So I share here my code to try to fit a custom non-linear function and assessing its prediction intervals (confidence and prediction, or int Mathematica language, mean and simple prediction intervals). CODE WITH MY EXAMPLE DATA:               (*Example data*)     data = {31, 46, 70, 87, 87, 93, 114, 128, 133, 134, 143, 155, 161,      161, 163, 177, 181, 207, 207, 226, 302, 315, 319, 347, 347, 362,      375, 377, 413, 440, 447, 461, 464, 511, 524, 556, 800, 860, 880,      954, 5200, 12000};          dist = ProbabilityDistribution[{"CDF",      Exp[-a Exp[-x b] - c Exp[-x d]]}, {x, 0, Infinity},      Assumptions -> {{0 < a < 10}, {0 < b < 1}, {0 < c < 10}, {0 < d <      1}}];          res = FindDistributionParameters[data,           dist, {{a, 3.8}, {b, 0.006}, {c, 0.08}, {d, 0.0002}}];                      (* ACOV is:*)     acov[data_, dist_, paramlist_, mleRule_] :=           Block[{len, infmat, cov}, len = Length[data];          infmat = -D[LogLikelihood[dist, data], {paramlist, 2}]/len /.           mleRule;     cov = Inverse[infmat]];          acov[data, dist, {a, b, c, d}, res];                     (* Gradient matrix G', in this case with only one variable x, we obtain a vector with only one element *)     In[1]:= D[Exp[-a Exp[-x b] - c Exp[-x d]], {x}]/. res;                           (* To multiply Transpose-Gradient by acov by Gradient, is not necesary to transpose the first matrix, Mathematica detect the same matrix and does it for us *)          %2.%1.%2                      (*T-student critical value to alpha 0.05 and 42 data*)     Quantile[StudentTDistribution[41], 0.95]      The question/s here are:   1. What snips or lines of code I must to add to complete and apply my code to a numerical example as we can find in here, getting the predicted `y` and the their confidence and prediction intervals? As if you try my code it does't give the table of confidence intervals as does exp["MeanPredictionConfidenceIntervalTable"] in the case of Non-Linear fiiting (that is different of fitting a distribution with the MLE method). That is because I have some doubts and I am not an old user of Mathematica: 1.1.: A little doubt is if finally my ACOV matrix is well assessed with my code. I don't understand why in the post I got the first information about the Hessian and Information matrices they divide the matrix of partial derivates by N (Length[data]). Please, check it. 1.2.: Following the Delta method I have to execute the dot product of the Transpose-Gradient by ACOV by Gradient, that is, %2.%1.%2, so I obtain a simple number. Is this correct?. But I found that if we haven't the same number of columns in the vector that the number of rows in the matrix we obtain other matrix, not a number. If we fill those columns with 0, then we obtain a number, but maybe this isn't the correct way. Please, comment this post if you have any is not clear or edit my code if you know the appropiate code lines. Reference posts:   * A numerical example of a similar way to get confidence interval using also the Delta mathod to calcultes variance: http://www.montana.edu/rotella/502/DeltaExample.pdf   * Standard errors for maximum likelihood estimates in FindDistributionParameters   * How to compute prediction bands for non-linear regression? (Stats.SE)   * Basic question about Fisher Information matrix and relationship to Hessian and standard errors {Stats.SE) I look forward to your help, thank you.


How to efficiently drag points on a curve within a Manipulate

My intention is to demonstrate on any conic various metrics properties on points belonging to the conic and connected by lines.   I want the points to be dynamically moved not the usual way, indirectly with the help of any `Manipulate` controls like `Slider`, but by an artifice, hiding the `Locator` control object and let one feel that by dragging any point on the curve you manipulate directly that point (though of course it is the locator that you manipulate).   Here is my embryonic code so far, just a circle with two points (and I made here the 2 locators visible):               findY[ptX_] := Module[{},     Which[((First[ptX] <= 0 && ptX[[2]] <=  0) || (First[ptX] > 0 &&         ptX[[2]] <=  0) ),                          y /. Solve[x^2 + y^2 == 4, {y}][[1]] /. {x -> First[ptX]},                  ((First[ptX] <= 0 &&         ptX[[2]] >  0) || (First[ptX] > 0 && ptX[[2]] >  0) ) ,                            y /. Solve[x^2 + y^2 == 4, {y}][[2]] /. {x -> First[ptX]}]]          Manipulate[     {{Style[StringForm[      "Locator for the blue point `1` Blue point coords{`2`,`3`}",       Dynamic[ptA], First[ptA], findY[ptA]]]},     {Style[StringForm[      "Locator for the green point `1` Green point coords{`2`,`3`}",       Dynamic[ptB], First[ptB], findY[ptB]]]}},      Row[{LocatorPane[Dynamic[{ptA, ptB}],      ContourPlot[x^2 + y^2 == 4, {x, -3, 3}, {y, -3, 3},       PlotRange -> Automatic, AspectRatio -> 1, Axes -> True,       Frame -> None, ImageSize -> 300,       Epilog -> {{PointSize[Large], Blue,           Point[Dynamic[{First[ptA], findY[ptA]}]]},                          {PointSize[Large], Green,          Point[Dynamic[{First[ptB], findY[ptB]}]]}}],     Appearance -> Style["\[CirclePlus]", 20, Red]]}],      (* Replace with Appearance->None to hide the Locators *)     {{ptA, {-2, 0}},None}, {{ptB, {2, 0}}, None}] (* ptA Blue ptB Green *)           You can see that by clicking on any of the two locators each point will move along the whole circle, even cross each other: if you move your mouse slowly the locator will stay very close to the point but if you do it too quickly the point will move too but the locator may be far off giving an erratic effect to the movement of the point.   And an issue too, having difficulty of retrieving it then with your mouse if the locator is not visible.   My question: On a PC when you want to drag a point which is to be moved along a curve, you start by clicking on the point and then dragging where you want it to be (and not something else). Can the same effect be obtained be obtained with MMA? If internally this means dragging a MMA `Locator` it should be as far as possible transparent. I took pains to check that my question is not a duplicate,sorry if it is. Errare humanum est. * * * In short: How can I constrain a locator to move along a curve, similar to the goal in Constrain movement of a locator inside Manipulate, except that here the curve is defined by an equation instead of parametrically?


Parallel kernel and front end

I have a piece of code which looks like this:               ParallelTable[            Monitor[         Table[         <code here>         ,{i,i1,i2];       ,i];          ]      so basically a `Table` which I parallelize. Each element of this parallelized table being itself a `Table` which I want to monitor. I receive this error message: > FrontEndObject::notavail: A front end is not available; certain operations > require a front end. This error originates from the `Monitor[]`. I suspect that because my first `Table` is parallelized, somehow the dynamic cell into which `Monitor[]` will write to is not connected to any Front End or something... How would I solve this issue?


Need to take infinite sum of residues, is there a way to choose the order of operations for ReleaseHold?

I'm computing an infinite sum of residues. I want to do something like this:               Sum[Sum[(-1)^n (2 \[Pi] I) Residue[(w^(I nu + n/2) ws^(I nu - n/2))/(I nu + n/2)^2, {nu, I n/2 + I m}], {n, 1, \[Infinity]}], {m, 0, \[Infinity]}]      Evaluated like that, this gives zero. However, if I choose a specific value of m, specifically m=0,               Sum[(-1)^n (2 \[Pi] I) Residue[(w^(I nu + n/2) ws^(I nu - n/2))/(I nu + n/2)^2, {nu, I n/2}], {n, 1, \[Infinity]}]      I get a nonzero result. The problem is that for generic m,               Sum[(-1)^n (2 \[Pi] I) Residue[(w^(I nu + n/2) ws^(I nu - n/2))/(I nu + n/2)^2, {nu, I n/2 + I m }], {n, 1, \[Infinity]}]      is zero. It's only nonzero for m=0. I thought that I could make this work by using Hold[], holding evaluation of the residue and releasing it outside the infinite sum. But it appears that applying ReleaseHold[] there doesn't fix the problem, it still evaluates the Residue for the generic case before fitting in the specific ones. Is there a way to make this work, and get the correct answer out of the infinite sum over m? (By the way, I know that in this case, all terms besides m=0 will be zero. I need the infinite sum because the same setup needs to treat cases where some of those terms are nonzero.)


Drawing dessins d'enfants (bipartite graphs subject to certain conditions)

I want to write a function which constructs all possible _dessins d'enfants_ (bipartite graphs fulfilling certain criteria, given below) from a collection of data presented in the following form: $\begin{Bmatrix}r_{0}\left(1\right),r_{0}\left(2\right),\ldots,r_{0}\left(W\right)\\\ r_{1}\left(1\right),r_{1}\left(2\right),\ldots,r_{1}\left(B\right)\\\ r_{\infty}\left(1\right),r_{\infty}\left(2\right),\ldots,r_{\infty}\left(I\right) \end{Bmatrix}$ The graphs produced should be such that:   1. For every $r_{0}\left(i\right)$ there is a white node with $r_{0}\left(i\right)$ edges emanating therefrom; there are $W$ white nodes in total.   2. For every $r_{1}\left(j\right)$ there is a black node with $r_{1}\left(j\right)$ edges emanating therefrom; there are $B$ black nodes in total.   3. White nodes only join black nodes and vice versa (the graph is bipartite).   4. The graph has $I$ faces; the $k$th face is a polygon with $2r_{\infty}\left(k\right)$ sides. (A useful simplification is that in most cases of interest, for all $i$ and $j$, $r_{0}\left(i\right)=3$ and $r_{1}\left(j\right)=2$ - I've been focusing on this specific case in my own attempted solutions). To illustrate, the graphs at the top of page 28 in this article correspond to the data given at the top of page 25 of the same article. Taking the specific example of Ia, we see that:   * The graph has 8 white nodes, all with three connecting edges (criterion (1) above satisfied).   * The graph has 12 black nodes, all with two connecting edges (criterion (2) satisfied).   * The graph is bipartite (criterion (3) satisfied).   * The graph has six faces (one for each of the individual boxes, and one around the outside), each with eight edges (criterion (4) satisfied). I would like to write a Mathematica function which reproduces these graphs, when the corresponding 3-vector of data is input. As a further complication, it is sometimes the case that for one set of data there are multiple _dessins_. For example, consider the following data: $\begin{Bmatrix}3^{8}\\\ 2^{12}\\\ 18,2,1,1,1,1 \end{Bmatrix}$ (The Mathematica input for this would be something like `{{3,3,3,3,3,3,3,3},{2,2,2,2,2,2,2,2,2,2,2,2},{18,2,1,1,1,1}}`.) This has three dessins associated with it, drawn here. (Here, each vertex corresponds to a white node, and the author has omitted all the black nodes - he's presumably only done this for the sake of clarity). (By the way, this example also illustrates something which confused me to start off with - the "polygon" with $18\times2=32$ edges is found by going round the _whole_ of the outside of the graph.) I appreciate that this is not exactly a trivial problem. My approach so far has been to create a graph with $B+W$ vertices and initially no edges, making the first $B$ vertices black and the next $W$ vertices white. Then, connect each of the black vertices to two of the white vertices, such that each white vetex is connected to three black vertices (at least two of which are distinct). Check that the resulting graph is connected. Then use a cycle algorithm (such as the one here) to identify all the cycles of the graph starting at white vertices which do _not_ backtrack, i.e. which do not go from a white vertex to a black vertex and back to a white vertex again, _unless_ the intermediate black vertex is _only_ connected to the initial white vertex. If those cycles have edge numbers given by the $2r_{\infty}\left(k\right)$, then draw the graph and move onto the next permutation of connections between the black vertices and white vertices. Else, just move onto the next permutation of connections between the black vertices and white vertices. I'll post the explicit code for this algorithm ASAP (i.e. after some reworking, which will hopefully get it to do _something_!), but I don't think it's likely to be the most efficient way of going about the problem, and I am sure a more elegant solution is possible.


Speeding up Integrate and the numerical solution

I want to compute the drag of a plate ![enter image description here](http://i.stack.imgur.com/kcEVv.jpg) Below is the code I am using to integrate the function               velcenter = {dotx, doty, 0};                           r = {Cos[θ[t]], Sin[θ[t]], 0};     veltanA = {-Sin[θ[t]], Cos[θ[t]], 0};      velxpoint = Part[Cross[velcenter, r], 3];      dragD = 1/2*ρ*cofD*h*Integrate[(Abs[velxpoint - s*dotθ])*(velcenter +                                             s*dotθ*veltanA), {s, a - l, a}];      The integration is so slow and I want to speed it up. Any suggestions are welcome !


How to define a button inside Manipulate that tells Mathematica to re-evaluate the whole Manipulate code?

I have written a `Manipulate` code carrying out some very complicated tasks. There is no problem for the first run, but if I click the reset button to reset all variables to their initial states (which is also ok) and click the run button a second time, then it is very likely that the Mathematica kernel will crash during the re-run progress, the frequency for such crash happening is about 9 out of 10 times. I have spent almost a month trying to track down the source of this problem, but failed. I also asked the Wolfram support team, they suggested to implement the `Quit` function in the reset button as a workaround, such that the reset button will make the kernel quit, since the first run is always ok. Now the problem is, I cannot directly put `Quit[]` inside the button, for by doing this the kernel loses all definiton about the enclosing `Manipulate`. So I need the reset button doing two tasks:   1. Quit the kernel.   2. Make Mathematica automatically re-run the enclosing `Manipulate` code. I wonder if this is possible?


How to calculate the residue of $1/f(z)$ at a numerical approximation to a root of $f(z)$?

The input               Residue[1/DirichletL[19,10,s],{s,s0}]      gives `0` even when `s0` is a root. For example, from LMFDB, I found `s0 = 0.5 + 1.51608375316006 I` is an approximate root of `DirichletL(19,10,s)`. (In LMFDB this character is actually indexed 18, though.) For the Riemann zeta function, we can get around this by using `ZetaZero[1]` to represent `s0`. What can be done for other $L$-functions?


How to build a funcion that returns a piecewise function

I dont know how to go ahead with this The problem statement is "Make a piecewise linear function maker that accepts lists of points as input and has a piecewise linear function as the output". Lets say for example I have a data sect {1,1,1,0,0,1,1}.


Image basics in mathematica

1) How the pixel values are defined in mathematica or how it is different from matlab? 2) I am wondering how image properties are different in mathematica, and how they are calculated? ComponentMeasurement: properties: such as "Centroid", "IntensityCentroid", "Area". 3) I want to find basic image processing link for mathematica 8 or 9? I felt documentation is not informative enough, any link or help on this topic will be great.


Finding the roots of Hypergeometric1F1[]

I am trying to find the roots, `λ`, for this equation:               Hypergeometric1F1[1/4 (2 -  λ /β), n + 1, β]       for certain `β` and `n`. Here is my _Mathematica_ code.               eq[n_, β_, λ_] = Hypergeometric1F1[1/4 (2 - λ/β), n + 1, β]      Find the root near `λ = β`.               ED[n_, β_] := λ /.        FindRoot[eq[n, β, λ] == 0, {λ, β}]       List all `λ`-values for each value of `n` when `β = 0.00001`               {ED[0, 0.00001], ED[1, 0.00001], ED[2, 0.00001], ED[3, 0.00001], ED[4, 0.00001],      ED[5, 0.00001], ED[6, 0.00001], ED[7, 0.00001], ED[8, 0.00001], ED[9, 0.00001],      ED[10, 0.00001]}      Then, I got `{5.78319, 14.682, 26.3746, 40.7064, 57.5829, 76.9388, 98.7262, 122.907, 149.453, 178.337, 209.54}` However I'm supposed to get `{5.78306, 14.6819, 26.3744, 30.4715, 40.707, 49.2186, 57.5823, 70.8493, 74.8865, 76.9392, 95.2771}` I guess _Mathematica_ gives only one root. How can I also find the 2nd, 3rd, 4th roots, for each value of `n`?


How to understand shared passing of a MTensor in LibraryLink?

According to the documentation, there are four different type of memory managing when passing a MTensor with LibraryLink: Automatic, "Constant", "Manual" and "Shared". The Automatic and "Manual" is easy to understand, since in both of them, the MTensor get copied and passed into the library function. The difference between them is wether the tensor will be automatically clean or not. The "Constant" and "Shared" will pass a reference of the MTensor into the library function, and "Constant" promises the library function to not change the MTensor. I find "Shared" is difficult for me to understand. Does the "Shared" passing means that variable in Mathematica and my library function point to the same data buffer in the memory? And if I change on one side, the changes will be transparent on the other side ? Consider this example from the document:               loadFun =        LibraryFunctionLoad["demo_shared",         "loadArray", {{Real, _, "Shared"}}, Integer];     unloadFun =        LibraryFunctionLoad["demo_shared", "unloadArray", {}, Integer];     getFunVector =        LibraryFunctionLoad["demo_shared", "getElementVector", {Integer},         Real];      If we load the library function with an array               array = Range[1., 20];     loadFun[ array]      and change the array on the Mathematica side               array[[1]] = 2.;     getFunVector[ 1]     (* 1. *)      why the data on the library side not changed? Also, in the documentation, it says after call unload, which disowns the MTensor, array cannot be used anymore,               unloadFun[ ]     (* 0 *)          getFunVector[1]     (* 1. *)          array[[1]]     (* 2. *)      but why I can still use it? What does disown do?


How to print a message dialog window

I'm trying to figure out how to print a message dialog without printing the whole notebook. `FrontEndExecute[FrontEndToken["PrintDialog"]]` displays the print window (just like selecting file -> print but it prints the whole notebook. I have also tried using `FrontEndExecute[FrontEndToken["PrintSelectionDialog"]]` but when the code is run the selected area becomes unselected. I have solved part of the problem with the following               DialogInput[       DialogNotebook[{Column[{Plot[Sin[x], {x, 0, 6 Pi}],            Row[{Button["print",               DialogReturn[               FrontEndExecute[FrontEndToken["PrintDialog"]]]]}]}]}]];      This prints the entire window including the print button as shown.   ![print output](http://i.stack.imgur.com/GXp1E.png)   This is exactly what I am looking for but without the print button.   Any ideas much appreciated,   Christina


NDSolve with Table and Boundary Conditions

I am trying to implement a 1D model of coupled field equations where I split up space into pieces to get a system of coupled ODEs which I call Eeqns and Ieqns. The problem I can't figure out is how to put Dirichlet boundary conditions (NE=0, NI=0 at both edges) into the code. Everything I try results in an error. Below is what I've written (which works) without BCs. Pardon the text conversions problems. I don't know how to fix it. Also, f and g are functions defined in the code.               Eeqns = Table[             {10*D[NE[i][t], t] ==             -NE[i][t]+(1-NE[i][t])*             f[α*10*Sum[dx*g[dx*i-dx*j, bEE, σEE]*NE[j][t], {j, 1, n}]             - α*10*Sum[dx*g[dx*i-dx*j, bIE, σIE]*NI[j][t], {j, 1, n}]             + α*10*(P/2)*(Tanh[10*(i-Elefti)]-Tanh[10*(i-Erighti)])*(1/2)*(Tanh[10*(t-Einputstart)]-Tanh[10*(t-Einputstop)]), aE, θE]}, {i, 1, n}];          Ieqns = Table[             {10*D[NI[i][t], t] ==             -NI[i][t]+(1-NI[i][t])*             f[α*10*Sum[dx*g[dx*i-dx*j, bEI, σEI]*NE[j][t], {j, 1, n}]             - α*10*Sum[dx*g[dx*i-dx*j, bII, σII]*NI[j][t], {j, 1, n}]             + α*10*(Q/2)*(Tanh[10*(i-Ilefti)]-Tanh[10*(i-Irighti)])*(1/2)*(Tanh[10*(t-Iinputstart)]-Tanh[10*(t-Iinputstop)]), aI, θI]}, {i, 1, n}];          Einit = Table[NE[i][0] == 0, {i, 1, n}];     Iinit = Table[NI[i][0] == 0, {i, 1, n}];          u = Table[NE[i], {i, 1, n}];     v = Table[NI[i], {i, 1, n}];          sol = NDSolve[           Join[Eeqns, Ieqns, Einit, Iinit],           Join[u, v],           {t, 0, T},           MaxStepSize -> 0.01][[1]];


Preventing label crowding in PieChart RadialCallout and RadialCenter

Is it possible to avoid this unreadable situation with label crowding when using `PieChart`'s `RadialCallout` and `RadialCenter` methods?               PieChart[tabData109[[All, 2]],       SectorOrigin -> {{Pi/2, "Clockwise"}, 1},       ChartStyle -> tabData109[[All, 1]] /. PACE["TAB_COLOR_RULES"],      LabelingFunction -> (Placed[          Row[{NumberForm[             100 # /Plus @@ tabData109[[All, 2]] // N, {3, 1}], "%"}],           "RadialCenter"] &),      ChartLabels ->        Placed[tabData109[[All, 1]] /. PACE["TAB_DESCRIPTION_RULES"],         "RadialCallout"]]      Gives: ![enter image description here](http://i.stack.imgur.com/i0ey1.jpg)