title: 3D orbits and inaccuracy over time

text: I wrote a little program to use Newton's Law of Universal Gravitation to animate 3 planets orbiting a central star, but I have run into a problem. Here is the code that I used to create the program (I apologise about the messyness):               orbit1 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 1000, y[0] == 1000, z[0] == 1000,      x'[0] == 0, y'[0] == -100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbit2 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 500, y[0] == -1000, z[0] == -1000,      x'[0] == -110, y'[0] == 100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbit3 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 0, y[0] == 100, z[0] == 500,      x'[0] == 350, y'[0] == -100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbitplotunion =       Animate[Show[{ParametricPlot3D[{{x[t], y[t], z[t]} /.         orbit1, {x[t], y[t], z[t]} /. orbit2, {x[t], y[t], z[t]} /.         orbit3}, {t, 0, a},       PlotRange -> {{-1600, 1600}, {-1600, 1600}, {-1600, 1600}},       AxesLabel -> {x, y, z}],      Graphics3D[{Yellow, Sphere[{0, 0, 0}, 100], Green,        Sphere[{x[t], y[t], z[t]} /. orbit1 /. t -> a, 50], Blue,        Sphere[{x[t], y[t], z[t]} /. orbit2 /. t -> a, 50], Purple,        Sphere[{x[t], y[t], z[t]} /. orbit3 /. t -> a, 50]}]}], {a, 0,      Infinity, 0.1}]      As you can see, there is one orbit calculation for each planet, and these are then animated. Now, my first problem has to do with `NDSolve[]` and its calculation from `t = 0` to `t = 1000`, which means that the animation will break once `t = 1000` is hit. Is there a way to allow the animation to go on indefinitely, instead of having to reset it once `t = 1000` comes along? Secondly, the planets and their trailing lines start out orbiting the star perfectly in the beginning, but over time, the trailing lines of each planet become more and more jagged, until eventually the animation looks horrible. Here is what the orbits look like in the beginning: ![orbits at start](http://i.stack.imgur.com/s81yd.png) And this is what they look like some time later: ![later orbits](http://i.stack.imgur.com/DHagW.png) If anyone knows how to solve the jagged line problem (maybe by editing the amount of trailing line that is allowed, so that it doesn't redraw over itself continually) and knows how to make the animation continue indefinitely, I would love to know. Regards, Alex * * * ## EDIT: After looking at the $n$-body wiki page, I thought I'd give it a go and start out small with a simple Earth-Sun simulation, and if that worked, then move my way up to $3,4,5,\dots$ bodies as well. Unfortunately, as expected, I seem to have run into a problem almost immediately. Here is the code that I am currently using:               G = 6.672*10^-11;     m1 = 5.972*10^24; (* mass of Earth *)     m2 = 1.989*10^30; (* mass of Sun *)          orbitearthsun = NDSolve[{     x1''[t] == -((G (m2) (x1[t] - x2[t]))/Abs[x1[t] - x2[t]]^3),     y1''[t] == -((G (m2) (y1[t] - y2[t]))/Abs[y1[t] - y2[t]]^3),     x2''[t] == -((G (m1) (x2[t] - x1[t]))/Abs[x2[t] - x1[t]]^3),     y2''[t] == -((G (m1) (y2[t] - y1[t]))/Abs[y2[t] - y1[t]]^3),     x1[0] == 1000, x2[0] == 0, x1'[0] == 100, x2'[0] == 0,     y1[0] == 1000, y2[0] == 0, y1'[0] == 100, y2'[0] == 0},     {x1[t], x2[t], y1[t], y2[t]}, {t, 0, 1000}]          NDSolve::ndsz: At t == 3.049010336028579`*^-6, step size is effectively zero;     singularity or stiff system suspected. >>      Does this occur because the denominator of each term becomes zero as they collide?


title: How to open hyperlinks (from web-embedded CDF) in a new tab

text: I have a problem with `Hyperlink` (in a web-embedded CDF) opening links in the same browser tab and I couldn't find an option to avoid that. I have the following constraints:   1. CDF is web-embedded (created by me).   2. The hyperlink should open only after mouse clicking, no combinations with keyboard keys are allowed. **Failed attempts:**   * I've tried to click it with `Shift` like it is written in `Help` but it does not work. It doesn't matter because of constraint #2 above. However if it is possible to mimic the `Shift` key being pressed (in some other way than pressing the key) maybe that will help?   * I've tried to replace `Hyperlink` by `Button[ "link", SystemOpen["link"]]` but there is no reaction. I don't think this is important, but this is how I'm testing it:   * I create a CDF file using _Mathematica_   * Export as "web embeddable..."   * I paste script received in the end to a `.txt` file -> save -> switch to `.html` It is quite important for me to find a solution to this, because the CDF resets every time the link opens in the same tab.


title: How can i get the solution of complicated equation?

text: ![enter image description here](http://i.stack.imgur.com/XfRtk.png) This is the equation about zeta. `NSolve[eq]` could not solve this equation. (I think it is too complex to solve by `NSolve`.) I want to know how can I solve this equation, which has such a complicated form. This should be the code for the equation:               eq = (0. - 30.1996 I) ζ^6 +       (0. + 9.81486 I) ζ^5 Sqrt[(0. - 640.701 I) + ζ^2] +       (0. + 20.3847 I) ζ^4 ((0. - 640.701 I) + ζ^2) +       (0. + 20.3847 I) ζ^5 Sqrt[(0. - 1127.53 I) + ζ^2] -       (0. + 20.3847 I) ζ^3 ((0. - 640.701 I) + ζ^2) Sqrt[(0. - 1127.53 I) + ζ^2] +       (0. + 9.81486 I) ζ^4 ((0. - 1127.53 I) + ζ^2) -       (0. + 9.81486 I) ζ^3 Sqrt[(0. - 640.701 I) + ζ^2] ((0. - 1127.53 I) + ζ^2) +       408.549 (         (0. - 0.630868 I) ζ^3 - (0. + 14.0909 I) ζ^2 Sqrt[(0. - 640.701 I) + ζ^2] -         (0. + 1.21667 I) ζ ((0. - 640.701 I) + ζ^2) -         (0. + 6.45738 I) ζ^2 Sqrt[(0. - 1127.53 I) + ζ^2] +         (0. + 14.7217 I) ((0. - 640.701 I) + ζ^2) Sqrt[(0. - 1127.53 I) + ζ^2] +         (0. + 0.585806 I) ζ ((0. - 1127.53 I) + ζ^2) +         (0. + 7.08825 I) Sqrt[(0. - 640.701 I) + ζ^2] ((0. - 1127.53 I) + ζ^2)) == 0;


title: Plotting several functions

text: I'd like to plot a function of one real and one integer variable, but I don't want them all shown in the same 2-D plot - I'd like to see them as separate curves so I can see both 'axes', more like `Plot3D` works. I'm sure Mathematica can do this, but how? Edit: Rephrased, I'd like to `Plot3D` a function of one real and one integer variable. Instead of seeing a surface, I'd like a discrete set of curves in three space.


title: 3D plots with a continuous and discrete input

text: How can I plot a function with one discrete and one continuous input? Plot3D wants everything continuous while ListPlot3D and ListPointPlot3D want everything discrete. I would like be able to say something like               HybridPlot[f[dsc, cnt], {dsc , min, max step}, {cnt, min max}]      or               HybridPlot[f[dsc, cnt], {dsc, someArray}, {cnt, min max}]      I am not seeing a simple way to do this in the docs.


title: Isolating string characters

text: I have the following string:                string=  {{"D(2.00225050736308e-15*A01 - 0.0201549279513608) = \         0.0820842279730734 + 0.08923448712*delay(A35",            " 17) + 0.08669543966*delay(A88",            " 20) + 1.98960079968027e-16*A57 - 0.3146216003*erf(delay(A01",            " 2)) - 0.3157150548*erf(sin(0.00541313376373593*cos(0.\         129564165001876 + 2.22963213427193e-15*A57 - \         gauss(0.00170510841714258 + 1.87338787507e-15*A51)) + delay(A27",            " 24) + gauss(gauss(0.00170510841714258 + 1.87338787507e-15*A51)) - \         2.17740845675611e-15*A81*cos(0.129564165001876 + \         2.22963213427193e-15*A57 - gauss(0.00170510841714258 + \         1.87338787507e-15*A51))))"}}      I want to isolate all characters within the brackets of the **delay** part e.g. delay(A27, 24). In other words I want the characters A24 and 24. My best bet was to go with               StringCases[string,"delay("~~__~~")"]      in order to get all String between the brackets, but this does not work. Still a little bit confused about using string patterns :/.


title: Looking to create a lesson on sensory perception of sound

text: I'm looking to show students a lesson on sensory perception, more specifically on masking. I know a little _Mathematica_ but sound processing has evaded me.   1. I would like to create a white noise and play it, show characteristics etc              noise = RandomReal[1,{5000}];     ListPlay[noise];     Spectrogram[noise];     Histogram[noise];        2. Bandpass the white noise to produce different bandwidth sounds. This didn't work. Bandpassing the noise produces an amplitude constrained sound, but I was looking to constrain the sound to a specific frequency spectrum. How is this possible?   3. Also looking to play two sounds at the same time. `Sound[{sound1,sound2}]` plays sounds in sequence. How can I get them to overlap? The idea would be to show how one sound can mask other sounds.


title: Filtering elements from a list that appear only once

text: I want to be able to select elements from a list that only appear once. I originally had this:               Select[Table[Count[list, i], {i, list}], # == 1]      But the issue is that my list has about 60,000 elements, and it takes way too long. The only way I could think of speeding it up would be to make a function like Count, but that would return after seeing the same element twice, and I have no idea how to do that in Mathematica. Also, I'm not sure if it's important, but the list is actually a list of lines (with a line defined by two 2D points). The goal is to find the edges that are only used by one triangle, hence making them a perimeter edge. Thanks!


title: Can you make the new "Choose color scheme" helper larger?

text: Mathematica 10 has a cool new "color data chooser" feature: ![enter image description here](http://i.stack.imgur.com/OYljG.png) My question is: Can you make that window larger? Right now, I can only see 3-4 color schemes at once, even though all 51 gradients would easily fit on the screen at once, if the windows were a little larger, and showed more than one row, e.g. like this:               Labeled[ColorData[#, "Image"], #] & /@ ColorData["Gradients"] //        Partition[#, 5, 5, {1, 1}, {}] & // Grid      ![enter image description here](http://i.stack.imgur.com/GF6Cx.png)


title: How to unthread?

text: For example               {a + b} == {c + d} // Thread     (*{a + b == c + d}*)      how to get `{a + b} == {c + d}` from `{a + b == c + d}` ? This is my try               Equal @@ List /@ Join @@ {a + b == c + d}      Are there other ways to do this?


title: Read and write files

text: I have a text file, its content is(for example):                388, 399, 100      *Nset, nset=All, internal, generate       1,  48,  1     *Elset, elset=All, internal, generate       1,  35,   1     ** Section:solidplane     *Solid Section, elset=All, material="rigid body"     *End Instance      Now I want use Mathematica read the above content and modify it; for example, (1) I want the number "48 (3rd line)" to change to number"388 (1st line)", (2) I want the word "All (4th line)" to change to word "Whole", How can I realize it? So the output is:                388, 399, 100     *Nset, nset=All, internal, generate       1,  388,   1     *Elset, elset=Whole, internal, generate       1,  35,   1     ** Section:solidplane     *Solid Section, elset=All, material="rigid body"     *End Instance      I have used the function "ReadList" but failed... Hope someone can help me


title: Problem with Poincare section

text: these are equations for some double oscillators: $x'(t)=p, p'(t)=-x-3y, y'(t)=q, q'(t)=-y-3x$ I would like to plot the Poincare section for collection of $(y,q)$ when $x=0$ and $x'(t)>0$ (or for $(x,p)$ when $y=0$ and $y'(t)>0$). I benefited from documentation and nice answer by Mr. belisarius here and I wrote:               abc = {x'[t] == p[t], p'[t] == -x[t] - y[t], y'[t] == q[t], q'[t] == -y[t] - x[t]};     psect[{x0_, p0_, y0_, q0_}] :=     Reap[NDSolve[{abc, x[0] == x0, p[0] == p0, y[0] == y0, q[0] == q0,     WhenEvent[x[t] + 0*y'[t] + 0*p[t] + 0*q[t] == 0,     If[p[t] >= 0, Sow[{y[t], q[t]}]]]}, {x, p, y, q}, {t, 0, 200},     MaxSteps -> \[Infinity], MaxStepSize -> .0005]][[2, 1]];     ps = psect /@ Table[{0.01, 0.005, 0.01, i}, {i, -.01, .01, .00125}];     ListLinePlot[#[[FindCurvePath[#][[2]]]] & /@ ps, Mesh -> All, PlotRange -> All]      But I don't receive anything. I expect to obtain something like this: ![enter image description here](http://i.stack.imgur.com/IbgaN.png) Many thanks for your attention.


title: How to add named characters to Mathematica 10?

text: It appears that native support for the Klingon alphabet has been removed from version 10:               \[KlingonA]      > Syntax::tsntxi: "\"!(\\[ KlingonA])\" is incomplete; more input is > needed.!(\"\")" (Curiously `"Klingon"` remains in the `$CharacterEncodings` list.) As an exercise I wish to restore support of this character set but the underlying character system has been modified; specifically I cannot find the `UnicodeFontMapping.tr` file and I assume it no longer exists. Quoting `TechnicalNotes.nb` found in the `Prerelease` folder: > On all systems, the Mathematica family of fonts (Mathematica*1-7) has been > replaced with a single Mathematica font. > > On Windows, the single Mathematica font is no longer installed under > "c:\windows\fonts". Instead, the user interface loads the font from the > installation directory. > > For prerelease testing, we are interested in learning about any issues > related to this change. `UnicodeCharacters.tr` does remain and the format appears unchanged so I should be able to restore recognition of `\[KlingonA]` etc., but without being able to map these characters to font glyphs that is largely pointless. (Though it would correct unrecognized syntax in legacy code.) ### How can one create named characters and bind them to specifc glyphs in v10?


title: How can I troubleshoot a PDF that fails to import?

text: I'm trying to import a PDF file whose text I'd like to parse, but I'm getting an error with no explanation:               Import["foobar.pdf", {"PDF", "Plaintext"}]     (* $Failed *)      I know the file exists as named, because if it didn't, $Mathematica$ would show a message:               Import["foobaz.pdf", {"PDF", "Plaintext"}]     (* Import::nffil: File not found during Import. *)     (* $Failed *)      Is there any way to get more information than the `$Failed`?


title: Why do Plot and ListPlot use the last PlotStyle when only one thing is plotted?

text: When a list of `PlotStyle`s is given, `ListPlot` behaves as expected when there are multiple things to plot:               ListPlot[{RandomReal[{-1, 1}, 100], 2 RandomReal[{-1, 1}, 100]}, PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/BQwqv.png) When there's only one thing to plot, it chooses the _last_ `PlotStyle` instead of the first one.               ListPlot[RandomReal[{-1, 1}, 100], PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/4uXAE.png) Enclosing the single thing to be plotted in `{}` appears to cause things to behave as expected.               ListPlot[{RandomReal[{-1, 1}, 100]}, PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/fWLQZ.png) `Plot` shows the same behavior. This does not appear to happen with the default `PlotStyle`s, but it does happen if you modify the default styles using this kind of technique. Why is a single plot argument treated as a special case? Can this behavior be changed?


title: Why is my rasterized graphic blank?

text: Consider the following code:               jet[u_?NumericQ] :=        Blend[{{0, RGBColor[0, 0, 9/16]}, {1/9, Blue}, {23/63,            Cyan}, {13/21, Yellow}, {47/63, Orange}, {55/63, Red}, {1,            RGBColor[1/2, 0, 0]}}, u] /; 0 <= u <= 1;     caxis[x_, {min_, max_}] :=        If[x < min, jet[0], If[x > max, jet[1], jet[(x - min)/(max - min)]]];          data1 = Table[        Sinc[x*y] + RandomReal[{0., 0.2}], {x, -2 Pi, 2 Pi, 0.05}, {y, -2 Pi, 2 Pi, 0.05}];     data2 = Table[        Sinc[x*y] + RandomReal[{0., 0.2}], {x, -2 Pi, 2 Pi, 0.02}, {y, -2 Pi, 2 Pi, 0.02}];          Row[{Graphics[Raster[data1, ColorFunction -> (caxis[#, {-0.5, 2}] &)],         ImageSize -> 200],       Graphics[Raster[data2, ColorFunction -> (caxis[#, {-0.5, 2}] &)],         ImageSize -> 200],       Graphics[Raster[data2, ColorFunction -> "BlueGreenYellow"],         ImageSize -> 200]}]      It gives the output: ![enter image description here](http://i.stack.imgur.com/uAShX.png) Why is the second plot blank? If the dynamic updating is turned off, all of the three are blank. ![enter image description here](http://i.stack.imgur.com/qsGi7.png) Why does _Mathematica_ behave like this? I'm using OSX 10.8.4 on a Macbook Air with 1.7 GHz Intel Core i5 and 4GB memory.


title: Computing residues of matrix valued functions symbolically

text: I have a somewhat specific application in mind, but I've run into this kind of problem a few times and never found an elegant solution. Is there an efficient way to get Mathematica to recognize that some variables in a symbolic computation are non-commutative (matrices) while others are commutative (scalars) while still being able to do elementary calculus operations on the commutative variables? Specifically, I have expansions of the form $$ f_j(z) = \frac{\psi_{j,1}}{t \zeta_j(z)} + \frac{ \psi_{j,2} }{t^2 \zeta_j(z)^2} + \frac{ \psi_{j,3} }{t^3 \zeta_j(z)^3} +\dots, \qquad j=1,2,3,\dots \\\ $$ where the $\zeta_j(z)$ are explicit scalar functions with $\zeta_j(0) = 0$ and the $\psi_{j,k}$ are symbolic constant matrices. In the computations I'm doing I need to compute things like $$ G_{j,k}(w) =\operatorname{Res}\limits_{z=0} \frac{f_j(z) f_k(z)}{z-w} . $$ up to some order in $t$ as $t\to \infty$. This is a toy example where the non-commutativity isn't a problem. In the full problem I then need to iterate the computation by computing similar residues on the $G_{j,k}$'s so the commutativity becomes an issue. Is there a way to hand _Mathematica_ the functions $\zeta_j(z)$ and have it compute $G_{j,k}(w)$ and $G_{k,j}(w)$ correctly, _i.e.,_ so that it doesn't think $G_{j,k} - G_{k,j} = 0$? I would like to do this purely symbolically, but as a minimal example one could take $\zeta_1(z) = z$ and $\zeta_2(z) = \sin z$. **My naïve attempt** Here's what I had hoped might work. I included a parameter $t$ in $f$ and an $O(t^{-5})$ term in $G$ to truncate the number of terms in the output.               $Assumptions = {       Table[P[i] \[Element] Matrices[{2, 2}], {i, 1, 4}],      (\[Zeta] | t) \[Element] Complexes     };     \[Zeta][0] = 0;       f = Sum[  \[Psi][j]/(t \[Zeta][w])^j, {j, 1, 4}];       G = Residue[f.f/(w - z), {w, 0}] + O[t, Infinity]^5      This fails though; _Mathematica_ returns only the $O(t^{-5})$ term (the residue is left unevaluated). If I replace the last line with the scalar product               G = Residue[f*f/(w - z), {w, 0}] + O[t, Infinity]^5      then it outputs, but the order of matrix multiplication is lost.


title: How do I randomly select 'k' positions in a list and shuffle their respective elements without effecting the other elements?

text: Imagine I have some list:               listA = {"a","b","c","d","e","f","g","h","i","j"};      I'd like to randomly select `k` positions in the list, for example `k = 3` and we select positions `{1,9,10}`, then randomly shuffle the elements at these positions e.g. giving us ONE of the following five possible outcomes:               listApartialscramble1 = {"a","b","c","d","e","f","g","h","i","j"};     listApartialscramble1 = {"a","b","c","d","e","f","g","h","j","i"};     listApartialscramble2 = {"i","b","c","d","e","f","g","h","j","a"};     listApartialscramble3 = {"i","b","c","d","e","f","g","h","a","j"};     listApartialscramble4 = {"j","b","c","d","e","f","g","h","i","a"};     listApartialscramble5 = {"j","b","c","d","e","f","g","h","a","i"};      Is there a simple way to do this, perhaps with `RandomSample`?


title: RSolve gives a Context::ssle error

text: I want to solve the following recurrence equation               RSolve[{(k + 2) c[k + 2] q^(k + 1) - c[k] == 0}, c[k], k]      During calculation in Mathematica I get this persistent error: Context::ssle: "Symbol, string, or HoldPattern[symbol] expected at position Context[Zeta$^{(1,0)}$]. I tried to solve this equation with Maple and obtained a result $\left\\{ \begin{array}{cc} c (0)\frac{ 2^{-\frac{k}{2}} q^{-\frac{1}{2} k \left(\frac{k}{2}-1\right)} \left(\frac{1}{q}\right)^{k/2}}{\Gamma \left(\frac{k}{2}+1\right)} & k\text{::}\text{even} \\\ c(1)\frac{\sqrt{\pi } 2^{-\frac{k}{2}-\frac{1}{2}} q^{-\left(\frac{k}{2}-\frac{1}{2}\right) \left(\frac{k}{2}-\frac{3}{2}\right)} \left(\frac{1}{q^2}\right)^{\frac{k}{2}-\frac{1}{2}}}{\Gamma \left(\frac{k}{2}+1\right)} & k\text{::}\text{odd} \\\ \end{array} \right.$ So is it just a bug in Mathematica 9 or am I missing something?


title: I want to get a special curve in a picture

text: I have a picture,and I want to get a special curve in this picture ,than draw the line in a new picture.inbut I can't do this . Like this: ![example](http://i.stack.imgur.com/9fza9.jpg) The picture is this ![enter image description here](http://i.stack.imgur.com/coBQa.jpg) Anybody have an idea?


title: Need an efficient method for finding certain matrices

text: I am trying to write a function which produces square matrices with certain characteristics. The function should have two inputs:   1. number of the rows, `n`   2. number of the times each element in the range 1, 2, 3, ..., n should be repeated in the matrix So assuming the function is called `KOCH` then `KOCH[4, {2, 4, 5, 5}]` means the matrix should be 4 x 4 with 1, 2, 3 and 4 repeated respectively for 2, 4, 5, 5 times in the matrix, but each row in the output should be nondecreasing. And finally the function should find all the possible matrices, not only some of them. The code I prepared is as following               Koch[n_, num_] :=        Module[{list},         list = Flatten@Table[Range[n], {i, n}];         list = DeleteDuplicates[Sort /@ Tuples[list, {n}]];         list = DeleteDuplicates[Sort /@ Tuples[list, {n}]];         For[i = 1, i < n + 1, i++,            list = list[[Flatten@Position[Map[Count[#, i, 2] &, list], num[[i]]]]]];         list]      But as you notice what I am doing is to reproduce a large pool of the possible matrices and then filtering them with regards to the constraint on the number of repeatings. So it's inefficient. My function works for up to `n = 4` even though it takes seconds for `n = 4` but for `n = 5` it fails because of memory constraint with shooting this error > General::nomem: The current computation was aborted because there was > insufficientmemory available to complete the computation. I need to compute for up to `n = 15` and, therefore, need a better algorithm to find all the possible matrices given the constraints.


title: Partitioning a list and gathering statistics on the distribution of values across partitions

text: I have a one-dimensional array of 200 elements consisting of the numbers 0, 1, 2. This array needs to be divided into 10 groups (20 items each). Then, for each group, I want to count how many of the elements 0, 1, 2 is in each of them. These findings should be stored in three arrays, n0, n1, n2: n0 containing the statistics for the zeros, n1 the statistics for the ones, n2 the statistics for the threes. For example, one might get `n0 = {3, 4, 3, 6, 8, 12, 1, 9, 15, 16, ...}`, so in the first 20 elements of the original array there were 3 zeros, in the following 20 there were 4 zeros, and so on. I have _Mathematica_ 5.0. Please keep in mind that functions first appearing in later versions are not available to me.


title: How can I make controls have Button-like behaviour?

text: The `Button` control is very easy to understand               Button["Press Me", Print["Pressed"]]      I press the button, I execute the function. No Dynamic tom-foolery (I'll be honest, I struggle with Dynamics when they get above a certain level of complexity). I would like to be able to do the same with other controls. For example.               SetterBar[1, Range[5]]      gives 5 buttons for use in Dynamic settings. I'd like something simpler. I'm thinking of something like               SetterBar[1, Range[5],Foo]      Where `Foo` is a function that gets called when I click on a button on the SetterBar, ideally with an argument corresponding to the button I pressed. So, if I press '5', Foo[5] gets called. Any ideas?


title: on RegionPlot3D and ContourPlot3D

text: 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...)


title: Triangular numbers boolean function

text: 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 :-)!


title: Trying to simplify Root expressions from the output of Eigenvalues

text: 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, β, α}             }


title: How do you use SystemsModelFeedbackConnect?

text: 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.


title: Rearranging a Polynomial

text: 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?


title: Make MapIndexed listable

text: 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}]}}}}


title: How do I generate a 3d histogram of runs

text: 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)


title: Symbolic scalar-by-matrix derivative

text: 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).$$


title: Different Vertex Styling in a Graph

text: 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?


title: Using ImageTransformation[] with a lookup table

text: 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`?


title: Plot a vector valued function of two variables using color density

text: 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.


title: Why is ParallelMap way slower than Map

text: 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?


title: Overwrite contents of a cell

text: 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!


title: Plotting points and functions in one graphic

text: 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.


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

text: 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.


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

text: 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.


title: A Symbol with Subscript and Superscript as an Axis Label

text: 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!


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

text: 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"]


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

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.


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

text: 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 $*$?


title: WindowMargins exact CurrentValue

text: 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}}


title: Pass unevaluated function with evaluated arguments

text: 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.


title: Probability Model

text: 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?


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

text: 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.


title: Drawing CountryData groups

text: 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...?


title: KroneckerProduct and Transpose

text: 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.


title: Invert a transcendental function

text: 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.


title: Plot3D constrained to a non-rectangular region

text: 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?


title: An efficient circular arc primitive for Graphics3D

text: 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`.


title: How to Make a change of variables

text: 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.


title: Plotting: Is anyone familiar with gradientfieldplot command?

text: 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)


title: Keyboard shortcut for moving to last edit location/cell

text: 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?


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

text: > **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.


title: Look up a non-US stock price

text: 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?


title: Improve speed for calculating a recursive sequence

text: 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!


title: Calculate scalar potential from electric field

text: 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.


title: Supported options for compiling LibraryLink code with VC++

text: 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?


title: SetDelayed and avoiding function calls through memoization

text: 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?


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

text: 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?


title: How to compare the InputField values in For loop dynamically

text: 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"]]}]]]


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

text: 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!


title: Control Manipulate variables inside Manipulate

text: 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?


title: Exporting held expressions through JSON

text: 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"]


title: ListPointPlot3D in a Manipulate

text: 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.


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

text: 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?**


title: Using NSolve in the complex plane

text: 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 :/


title: Issue with NDSolve

text: 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. >>


title: How to find the nth derivative?

text: 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


title: What is Sub Mathematica?

text: 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?


title: Can Mathematica help to rearrange an equation?

text: 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?


title: How to iteratively display the nth derivative?

text: 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).


title: Does FindFit support complex numbers or doesn't it?

text: 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?


title: Lost and found Tooltip in ListPlots

text: 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)


title: Using absolute locator coordinates in Manipulate

text: 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}]


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

text: 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)


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

text: 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.


title: Am I missing the point of ViewCenter?

text: 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?


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

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


title: Export expression to Matlab

text: > **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?


title: How can I convert a matrix into matlab form string?

text: 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.


title: How to use NIntegrate in a purely numerical mode?

text: 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?


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

text: 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.


title: How to efficiently drag points on a curve within a Manipulate

text: 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?


title: Parallel kernel and front end

text: 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?


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

text: 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.)