How can I specify a numerical order for variables?

I need to specify that a variable is less than another, and greater than yet another, in a Mathematica program, because I will later apply a test to them that will determine what functional form to use. I also need `Sign[]` to give the correct answer. I tried using `TagSet` like this:               h /: (h>=d0) = True     h /: (h<=d1) = True      but this does not work with `Sign[h-d0]`, for example, and               h /: Sign[h - d0] = 1;      fails because it says _h_ is too deep. An example of how I will use this:               f[x_] := Exp[ c Sign[h-x] ]      where `x` can take the values `d0` or `d1`. (This will be used to set up boundary relations to solve for a set of coefficients to solve a PDE.) I suppose I could use some `If` statements to set the whole thing up, but thought it would be nicer to have a specification of the properties of `h`. I'm sure this should be easy to do - any help is appreciated.


Draw tangent to point in ListLinePLot

I am using `ListLinePlot` to draw a number of points to a graph:               ListLinePlot[{{5 10^-3, 0}, {4.65 10^-3, 100}, {4.32 10^-3, 200}, {3.74 10^-3, 400},          {3.23 10^-3, 600}, {2.6 10^-3, 900}, {2.09 10^-3, 1200}, {1.68 10^-3, 1500}}]      How can I also draw the tangent to the line in a point?


Nested NIntegrate of vector function

I am performing a nested integration where the upper limit of the inner integral depends on the value of the outer integral, like in the question [Nested NIntegrate]. As in this question my function can not be symbolically integrated. However, my function is a vector (representing a force field in 3D) instead of a scalar. Wolfram Technical Support confirmed that NIntegrate does not support integration of a list of numerical values. Therefore the answer to the Nested NIntegrate question does not directly work. I have considered simply creating three numeric functions that each calculate the force and take a different component of it, then integrating each separately. I could also create three interpolations and integrate them separately, which speeds up the calculation at the expense of accuracy. Is there a better way to do this?


Is it possible to use Composition for polynomial composition?

I want to do this: $P = (x^3+x)$ $Q = (x^2+1)$ $P \circ Q = P \circ (x^2+1) = (x^2+1)^3+(x^2+1) = x^6+3x^4+4x^2+2$ I used `Composition` for testing if that could be done then :               Composition[p, q][x^3 + x, x^2 + 1]      > >     p[ q[ x + x^3, 1 + x^2]] >   I've also tried to use `Expand` on it but It didn't work. The nearest thing I could do was this:               a = x^2 + 1;  Expand[ a^3 + a]      > >     2 + 4 x^2 + 3 x^4 + x^6 >   I was thinking that doing it by hand on longer compositions would be tedious, is there a function or way to do that?


Calculate with units

If I want to calculate with units, for example using Pythagoras theorem, I would do this:               c = Sqrt[(3m)^2 + (5m)^2]      The result will be `5 Sqrt[m^2]`. How can I define that `m = Sqrt[m^2]` and so forth?


ContourPlot - plot contour lines for minimum of list of functions == 2nd minimum of list of functions

I have a list of (ten or so) functions of two variables (x and y, say). I would like to plot the boundaries on the x y plane where two functions have the same value - but only the two functions in the list which have the smallest values at that particular point. Can this be done? (The Physics application - I have a number of states with different energies (the list of functions), and I am trying to plot the different regions where different states are the ground state.) Edit follows, Thanks for your help. I have made some progress with this - functions are parabola. Here is my code so far.               Clear[a, x, y, m, n, p, l]     m[x_, y_] := x^2 + y^2;     n[x_, y_] := x^2 + (2 y + 1)^2;     p[x_, y_] := (x + 1)^2 + y^2;     l = {m[x, y], n[x, y], p[x, y]};     ContourPlot[l[[First[Ordering[l, 2]]]] == l[[Last[Ordering[l, 2]]]], {x,-4,4}, {y,-4,4}, PlotPoints -> 200]     RegionPlot[l[[Last[Ordering[l, 2]]]]-l[[First[Ordering[l, 2]]]]<0.05,{x,-4,4},{y, -4, 4},PlotPoints->200]      The ContourPlot does not work - I get a blank plot - but the RegionPlot does show the regions where the lowest two functions are approximately equal. So is this something to do with the precision at which the calculation is carried out? I did try the solution provided by Verde - thankyou very much for that - but I didn't fully understand it, and had trouble integrating it with the rest of my code. Any further help would be much appreciated! Nick


How to perform a depth-first preorder traversal of an expression?

Due to confusion of terminology on my part I asked the wrong question before.   Since it has already received other answers I shall not edit it, but instead ask the question I meant to in the first place. _Mathematica_ provides functions that perform a depth-first postorder traversal, or which use such a traversal, including: `Scan`, `Count`, `Cases`, `Replace`, and `Position`. It is also the standard evaluation order therefore functions Mapped (`Map`, `MapAll`) will evaluate in a depth-first-postorder. It is quite direct to do this:               expr = {{1, {2, 3}}, {4, 5}};          Scan[Print, expr, {0, -1}]      > 1 > > 2 > > 3 > > {2,3} > > {1,{2,3}} > > 4 > > 5 > > {4,5} > > {{1,{2,3}},{4,5}} It is not as obvious how to do a depth-first **preorder** scan. (Simply storing then reordering the output is not adequate as it doesn't change the order in which expressions are visited.) `Scan` has the property that it does not build an output expression the way that e.g. `Map` does, and conserves memory. How can one do a `Scan`-type operation in depth-first **preorder**?


Jumps in NDSolve results

I need to compute using `NDSolve` routine, some function $F(x)$, having two possible values $F_1(x)$ and $F_2(x)$ depending on whether the argument exceeds some critical value $x>x_c$. The problem is that `NDSolve` routine return "jumping results" for the region $x>x_c$. As an example of a problem assume following system (some simple forced pendulum with nonlinear frequncy shift, so-called "fold over" effect):                w00 = 7000;         G0 = 50;         Q = 14000;         hU = 0.6*G0;         w0=w00-x              e1:=D[A[t], t] + G0*A[t] + I*(w0+Q*Abs[A[t]]^2 )*A[t] ==I*hU;              NDSolve[{e1, A[0] ==10^-6, {A[t]}, {t, 0, tmax},         MaxSteps -> Infinity, AccuracyGoal -> 50, MaxStepSize -> 0.01];      I am interested in $|A(t)|^2$ dynamics depending on the parameter `x`. Here $G0,Q,hU$ are some constants Exact solution:                   p4 = ContourPlot[{A == (hU^2/((G0)^2 + (w0 - x + Q*A)^2))}, {x, 6000,          9000}, {A, 0, 0.2}, PlotPoints -> 40, ContourStyle -> {Dashed, Thick}];            Show[p4,PlotRange -> All]          Numeric solution using module:              Calc[x_] := Module[{q = x},       w0 = 7000;       G0 = 50;       Q = 14000;       hU = 0.6*G0;            w00 = w0 - q + Q*Abs[A0[t]]^2;       At = 10^-6;       G1 = 1.0 G0;       tmax = 4;       e1 := D[A0[t], t] + G0*A0[t] + I*w00*A0[t]== I*hU;            s2 = NDSolve[{e1,           A0[0] == (0.7 + 0.5 I)  + 0*10^-6}, {A0[t]}, {t, 0, tmax},          MaxSteps -> Infinity, AccuracyGoal -> 50, MaxStepSize -> 0.01];            {Evaluate[Abs[A0[t] /. s2 /. t -> tmax]][[1]]        }            ]      h1 = {};         Dynamic[z]     For[z = 9000, z > 6000, z = z - 50,      temp = Calc[z];      h1 = Append[h1, {z, temp[[1]]^2}];      ]     num = ListPlot[{h1}, PlotRange -> All, Joined -> True,        PlotStyle -> Thick]     Show[num]      Comparing both:               Show[p4,num]      ![Comparing NDSolve and exact solutions](http://i.stack.imgur.com/zj57L.png) Solid line – `NDSolve` solution, dashed line - exact solution The result and number of jumps greatly depends on initial conditions.               A[0]=0.7+0.5*I      ![enter image description here](http://i.stack.imgur.com/WRv8j.png)               A[0]=10^-6      ![enter image description here](http://i.stack.imgur.com/NuJPl.png) The problem is I want to divide the two "branches" of the function $F_1$ and $F_2$ and plot them independently. How can I do this using `NDSolve` and force it to go along the chosen branch and not "jump?"?


Is there a command returning information about a particular object?

Suppose I have a variable `var1`, a function `MyFunction`, and a graphic `SomePlot`. I remember seeing a feature, which returned information about a particular object (either it was in Mathematica or in Python, but I don't recall the exact form or place in which I read about it). Suppose it was in a form `objects_name?`, for example:               var1?      would return: `a variable, var1 = 4` etc.               MyFunction?      would return: `a function, MyFunction[#1,#2,...] = ...` etc.               SomePlot?      would return: `2d plot...` etc. Is there something like that in Mathematica? I suppose there is, but I wasn't able to skillfully enter a proper search query in the Documentation nor in Mathematica.SE...


NDSolve error when solving pde

I am trying to calculate speed of viscous fluid in a rotating hollow sphere. The sphere is rotating round z axis. The fluid is incompressible. I used Navier-Stockes equations. The only boundry condition I have, is rotational speed of sphere. My code:               v = {vr[r, ϑ, ϕ], vt[r, ϑ, ϕ], vf[r, ϑ, ϕ]}          eq =  Curl[Cross[v, Curl[v, {r, ϑ, ϕ}, "Spherical"]], {r, ϑ, ϕ}, "Spherical"] +            Curl[Laplacian[v, {r, ϑ, ϕ}, "Spherical"], {r, ϑ, ϕ}, "Spherical"]          NDSolve[{eq[[1]] == 0, eq[[2]] == 0, eq[[3]] == 0, vf[1, ϑ, ϕ] == Sin[ϑ],      vr[1, ϑ, ϕ] == 0, vt[1, ϑ, ϕ] == 0}, {vr, vt, vf}, {r, 0, 1}, {ϑ, 0, Pi}, {ϕ, 0, 2*Pi}]      Mathematica displays an error: > NDSolve::ivone: Boundary values may only be specified for one independent > variable. Initial values may only be specified at one value of the other > independent variable. >> I have no idea what is wrong, so if anyone can help me, I'll be very happy. Thanks.


Mixing Text and Formulas

I'm trying to do some typesetting in which I mix text with formulas. The _Mathematica_ documentation has a section titled `"Mixing Text and Formulas"` which pretty much describes what it is that I'd like to do. However I can't seem to work out how they do it. The tutorial says to use `Ctrl`+`(` to start entering a formula within text or vice versa, however I don't seem to get the result I am after. This is what their example looks like: ![enter image description here](http://i.stack.imgur.com/rMCup.png) Notice that they have been able to mix text with a formula that is in `TraditionalForm`, this is what I would like to be able to do. If I enter: `"Hello World = " x^2` but `Ctrl`+`(` before I enter the `x^2`.... > >     Hello World = x^2 >   * * * ## Further Clarification Some further clarification (I would have preferred to enter this clarification after all of your helpful hints below but the guidelines recommend against answering your own question or adding further clarification in that way): In my text box I'd like to use a prior defined equation rather than having to re-enter and format it in the text box. Hopefully this next image will clarify: ![enter image description here](http://i.stack.imgur.com/tqF0p.png)


Dispatch not behaving like a normal expression in Mathematica 10

In Mathematica 9, I used to be able to do               rules = Dispatch[{'a' -> 1, 'b' -> 2}]     rules[[1]]      to extract the rules from `Dispatch`wrapped list of rules. In Mathematica 10 the following error is raised:               Part::partd: Part specification Dispatch[...][[1]] is longer than depth of object. >>      Is this a bug? I am using only the trial version currently. I got aware of it because it breaks the AutomaticUnits package.


Nest Replace Function with different rules

I have a table of data that I want to filter. Any value of zero in the table means that value was not calculated, so it should get populated with the tag "NC". Next the table is filtered for all those values that line within 0.25 of -1.51. Finally the table is cleaned up and "1.51 + NC" gets removed. The series of replacements works just fine, but it is extremely messy and unclear. Can any one propose a more readable/easier to understand version? In the real version test is a 27 X 27 table.               test = {{0, -1, -1.5, -1.45}}      targets = {ORR -> -1.51, CORedCO -> -1.2, ORedCO -> -1.25, HER -> -0.24}          Replace[Replace[       Replace[test , a_ /; a == 0 -> "NC", {2}] - ORR /.         targets, a_ /; Abs[a] >= 0.25 -> 0, {2}],       a_ /; a == (-ORR /. targets) + "NC" -> "NC", {2}]      the correct output is:               {"NC", 0, 0.01, 0.06}}


Optimizing a functional using variational calculus

Here I am, trying to get the trajectory $(x(t),y(t))$ that will minimize the following Lagrangian (i.e. the integrand of the functional) between $(-1,-1)$ and $(-1,y_{eff})$ where $x_{eff}$ is defined as the point where $V(x_{eff},-1)=V(-1,-1)$. So here's the integrand of the functional: $L=\frac{1}{2}((\partial_tx)^2+(\partial_ty)^2)-V(x(t),y(t))$ with $V(x(t),y(t))$ defined as follows: $(x(t)^2-1)^2(x(t)^2-\delta_1)+\frac{(y(t)^2-1)^2-\frac{\delta_2}{4}(y(t)-2)(y(t)+1)^2}{x(t)^2+\gamma}$ and $x(-1)=-1=y(-1)$ $x(0)=x_{eff},y(0)=-1$ $x'(0)=y'(0)=0$ Yet I get the following error code:               NDSolve::dvnoarg: The function x appears with no arguments.       For the record, here's the code (for $\delta_1=\delta_2=\gamma=0.1$):               Needs["VariationalMethods`"]     gamma = 0.1;     delta1 = 0.1;     delta2 = 0.1;     V[x[t_], y[t_]] := (x[t]^2 - 1)^2 (x[t]^2 - delta1) + ((y[t]^2 - 1)^2 -        delta2 (y[t] - 2) (y[t] + 1)^2/4)/(x[t]^2 + gamma);     U[x_, y_] := (x^2 - 1)^2 (x^2 - delta1) + ((y^2 - 1)^2 -        delta2 (y - 2) (y + 1)^2/4)/(x^2 + gamma);     ftn = 1/2 (D[x[t], t]^2 + D[y[t], t]^2) - V[x[t], y[t]];     Veff[x_] := U[x, -1];     x0 = FindRoot[Veff[x] == U[-1, -1], {x, -0.2}]     sln = EulerEquations[ftn, {x[t], y[t]}, t]     solution = NDSolve[{sln, x[-1] == -1, y[-1] == -1, x[0] == x0, y[0] == -1, x'[-1] == 0, y'[-1] == 0}, {x[t], y[t]}, {t, -1, 0}]      It would be well-appreciated if I could have a plot as well.


How does Mma compute Confidence Intervals?

I am trying to understand how Mma computes the Confidence Intervals after a `NonlinearModelFit`. Consider the following example:               data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}, {6, 4}, {7, 5}};     nlm = NonlinearModelFit[data, Log[a + b x^2], {a, b}, x];     Show[ListPlot[data, Joined -> False], Plot[Normal@nlm, {x, 0, 8}],ImageSize -> 200]     (*out*)      ![Fitting results](http://i.stack.imgur.com/gBu0w.png) Which comes with the following R squared and confidence intervals:               nlm["RSquared"]     nlm["ParameterConfidenceIntervalTable"]          (*Out*)0.957573     (*Out*)      ![enter image description here](http://i.stack.imgur.com/63avR.png) The table above assumes the default 95% Confidence Interval and, I am assuming, normal distribution around `a=1.50632` and `b=1.42633`. Questions:   1. How does Mma estimate the Standard Error of `a` and `b`?   2. The mean used to estimate such confidence intervals is the sample mean, i.e. ~2.6667? I could not find in the documentation how this was done from a fitting. Thank you in advance.


ReplaceAll a list of rules to an equation

Given the following equation and rule, how would I `Solve` the equation for `tr`, `k` and `c`?               eq = T == tr - E^(-k * t)*c;     rule = {t -> {0, 5, 10}, T -> {2000, 1300, 1100}};      `eq /. rule` results in this, which is almost what I want:               {2000, 1300, 1100} == {tr - c, tr - c/E^(5k), tr - c/E^(10k)}      I would like to get a list of equations instead like so:               {2000 == tr - c, 1300 == tr - c/E^(5k), 1100 == tr - c/E^(10k)}      which could then be used to solve the equations (using `And` on the list).


Time derivative of unit vector in spherical coordinates

Is it possible to take a time derivative of a vector given in some curvelinear coordinate system (i.e. spherical)? Mathematica would need to take into account the time dependence of the basis vectors. $$ \frac{d}{dt}\vec{r}=\dot{r}\hat{r}+r\dot{\theta}\hat{\theta}+r\sin[\theta]\dot{\phi}\hat{\phi} $$ I bet that there is something built into mathematica already to get the above result, but I can't figure it out. Edit: Thanks for your answers, they already helped me a lot. In the end I was hoping for a quick way to get: $$ \frac{d}{dt}\left( \begin{array}{c} f(r,\theta,\phi) \\\ 0 \\\ 0 \end{array} \right)=\left(\frac{d}{dt}f(r,\theta,\phi)\right) \left( \begin{array}{c} \dot{r} \\\ r\dot{\theta} \\\ r\sin[\theta]\dot{\phi} \end{array} \right) $$ just by typing $$ Dt[\\{f(r,\theta,\phi),0,0\\},t] $$ in Mathematica. I could get this behavior by multiplying the time derivative of $f$ with the result from TransformedField, but this could quickly become tedious with higher time derivatives and more vector components. Is there a more direct way to do it? Thanks a lot


Excluding region with `RegionDifference`

I can't make `RegionDifference` work for two `Rectangle`:               Ω =       RegionDifference[Rectangle[{0, 0}, {10, 10}],        Rectangle[{4, 4}, {8, 8}]];     RegionPlot[Ω]      ![enter image description here](http://i.stack.imgur.com/gDaOP.png) What's wrong? It only worked for me if I specify the second `Rectangle` to touch the edges. Windows 8.1, Wolfram Mathematica 10.


Possible JLink memory leak (during) object creation

Using MMA 9.0.1 on win7-64. When creating a large number of java objects I noticed memory being consumed in huge quantities (several Gb). This memory is returned/deallocated after my call completes but is non-linear in the problem size so large problems are unmanageable. I have reduced the problem to this example (Requires JLink/InstallJava[])...               mem = Reap[     JavaBlock[       Do[Sow[MemoryInUse[]];         JavaNew["java.util.Date", 0], {1000}]];][[2, 1]];          ListPlot[Rest[Differences[mem]],         Frame -> True,  FrameLabel -> {"# Objects Created", "Extra Memory Allocated / object"}]      ![enter image description here](http://i.stack.imgur.com/KEyr8.png)               ListPlot[mem, Frame -> True,       FrameLabel -> {"# Objects Created", "Total Memory Allocated"},       Epilog -> Text["Not linear!", Scaled[{.3, .35}]]]      ![enter image description here](http://i.stack.imgur.com/0CJ9Q.png) You can see, I hope, that the _increments_ in `MemoryInUse[]` are each time an object is created are not constant (as I would expect) but increase. The first time a date object is created costs about 6kb (which seems a lot in any case), the 1,000 date object costs 14kb. Why isn't the memory load a constant per object? A workaround is to wrap each JavaObject creation in JavaBlock but forcing its retention...               mem = Reap[JavaBlock[Do[(Sow[MemoryInUse[]];JavaBlock[KeepJavaObject[JavaNew["java.lang.Long",0]]]),{1000}]];][[2,1]];      This appears to force Mathematica to tidy up its memory management there and then but probably costs a bit of performance.


Integrating a function forcing parameters to be real and positive

I'd like to integrate the function $f(x)=x^{a-1}e^{-b x}$ over the interval $[0,\infty)$.               f[x_] := x^(a - 1)*Exp[-b*x]      Then:               Integrate[f[x], {x, 0, \[Infinity]}]      But I get:               ConditionalExpression[b^-a Gamma[a], Re[b] > 0 && Re[a] > 0]      How can I force both a and b to be real, positive parameters, then try the integration again?


Higher order periodic interpolation (curve fitting)

I have a list of points in 3D, and I want to get a smooth interpolation or curve fit (it is more for illustration) of these points such that the first and second derivatives at the start and end points agree. With               ListInterpolation[pts1, {0, 1}, InterpolationOrder -> 4, PeriodicInterpolation -> True]      even the first derivatives do not agree.


Ideas for NDSolve?

I'm currently trying to find a numerical solution to a differential equation of the form:               D[W[X], {X, 4}] ==(-(1/(delta + G - (G X)/L)^2) + 1/(delta + (G X)/L)^2)      Subject to the boundary conditions:               W[0] == 0, W[L] == 0, W'[0] == 0, W'[L] == 0      NDSolve appears to be choking on a singularity or a stiffness constraint. Any ideas on how I might go about dealing with this? Thanks in advance!


Memory handling by ConstantArray

I noticed the following issue when using `ConstantArray`:               a = ConstantArray[0., {10000, 100}];     ByteCount[a]     (* 8000152 *)      Then I set:               a[[1,1]] = 1;     ByteCount[a]     (* 25040080 *)      So to be sure my array will not expand in memory without reason I must multiply each element I want to change by 1.0 Is there another way (more efficient) to ensure I won't change the type of data by accident? `Real` to `Integer` shouldn't be a problem...


FindRoot Domain restriction

I am solving a system of four non-linear equations in four variables using FindRoot. I have some sense of the relationship between the variables so I don't want Mathematica to do its computations in certain funky regions of the domain. For example, I want to solve: $\begin{align} g_1(w,x,y,z) &=0\\\ g_2(w,x,y,z) &=0\\\ g_3(w,x,y,z) &=0\\\ g_4(w,x,y,z) &=0\\\ \end{align}$ such that $\begin{align} x &\in& \\{25,75\\} \\\ y &\in& \\{0,80-f_1(x)\\} \\\ z &\in& \\{x+f_2(x),800\\} \\\ w &\in& \\{y,z\\} \end{align}$ and I would like my FindRoot to operate only in the above domain. How can I get it to do that? Simply writing this doesn't seem to work:               FindRoot[{g1==0,..,..},{x,50,25,75},{y,a,0,80-f1(x)},{z,b,x+f2(x),800},{w,c,y,z}]


What is the default file path used by the Put function and how do I pre-evaluate an expression to use in Put?

I have a problem of trying to store some output in an external file. In one note book I define a function `f[x_]:=AdvancedCalculation`, where this function generates a relatively large output and is dependent on a significant number of definitions. In another notebook, I would like to have the expression `terms=f[x]`, but I do not want to actually calculate `f[x]` more than once because it would take too long. Currently I have stored the output of `f[x]` in a file called `Terms.m` that has a single line of code.               terms=OutputFromOtherNotebook      I then load this file in my second notebook using the command `<<Terms.m`. My current solution is to copy and paste `OutputFromOtherNotebook` directly from the first notebook into the file `Terms.m`. I would like to automate this process because larger outputs have become too cumbersome. I am trying to use `Put` to write the output using the following line of code.               terms=Evaluate[f[x]]>>Terms.m      However, I cannot find the resulting file. Where does the function `Put` create the file? As a side issue, how can I ensure that `f[x]` is evaluated before being written to the external file?


Reproducing Image Patterns with Mathematica

Surfing on the net I stared at this pattern. It´s a bamboo steam, and it´s awesome. I'm new to Mathematica so I'm a little lost, I'd like to try to reproduce this pattern, of course in a very simplified manner. Does anyone have any tips on how I could start it. Thanks.. ![bambusa_steam](http://www.quorumtech.com/media/image_gallery/cache/Bamboo_stem.jpg)


fragment loss with ContourPlot3D

I expect to have a chimney-look plot out of the function `z = 1/(x^2 + y^2)`, but what I got is a broken one. Is there a way to get an intact plot from `ContourPlot3D` without any fragment loss?               ContourPlot3D[      1/(x^2 + y^2) - z == 0, {x, -1, 1}, {y, -1, 1}, {z, -150, 150}]      ![enter image description here](http://i.stack.imgur.com/XMys7.gif)


Detecting and counting signals in list data: checking pulse rate

Hope this isn't too much of a basic question: I'm looking for some Mathematica functions, but I don't know which ones. _Background_ I recently read about a simple technique for reading your body's pulse rate using the camera built into the computer (eg an iSight camera at the top of an iMac). The idea is that you put your finger over the camera in a reasonably well-lit room, record a movie (about 15 - 20 seconds), then analyze the frames for varying light intensities, which somehow indicate your pulse. So far the technique seems to be promising. The code is:               getDataFromList[frames_] :=        Module[{},        Mean[Flatten[ImageData[#]]] & /@              (ColorSeparate[#][[1]]  (* red channel is best? *)         & /@ frames)];          AbsoluteTiming[           testFrames = CurrentImage[200];           testData = getDataFromList[testFrames]]          ListLinePlot[testData]      The `testData` starts off like this:               {0.193808, 0.196383, 0.197617, 0.198657, 0.200555, 0.201459,        0.201391, 0.1975, 0.197983, 0.198238, 0.200564, 0.201397, 0.202331,        0.20271, 0.199668, 0.196999, 0.197857, 0.19826, 0.199329, 0.200624,        0.201472, 0.202583, 0.199393, 0.198472, 0.199569, 0.200466, 0.201441,        0.203286, etc.       When plotted, the data for me and my left forefinger looks like it might be working (or could at least be a vaguely human pulse): ![my pulse](http://i.stack.imgur.com/jXSBY.png) The data is probably too large to include here - but some of you might have cameras and fingers too, and could generate something similar? In this plot there looks to be about 24 pulses, and the time from `AbsoluteTiming` was 16.965258, so my pulse rate was about 84. (So holding my finger up to the screen was hard work, obviously...) _Question_ Which Mathematica functions can I use to extract the actual pulse rate from this and similar sets of data?


Detecting change of a variable (detect mouse clicks)

I want to do something when the mouse is clicked. But it shouldn't matter where the mouse is clicked, so I can't use `EventHandler`. Instead, I'm trying to do it like this:               DynamicModule[{i = 0},      WhenEvent[ControllerState["Button 1"], i = i + 1]       i]      `WhenEvent` is not the right function. What I want is a function that will do something when `ControllerState["Button 1"]` switches from `false` to `true`.


Fastest way to do vector / matrix multiplication with constant matrix

Suppose we have a fixed n x n matrix, call it $B$. What is fastest way to evaluate $v^t B\;v$ over many different vectors $v$? Since $B$ is a constant matrix, does this allow the number of operations needed to evaluate $v^t B\;v$ for an arbitrary $v$ to be reduced?


Dynamically show usage

As the title states I would like to dynamically show `::usage` on several functions. Let's consider two functions here:               funlist={Plot,Plot3D};      Thus I do:               Input[       Panel[        PopupMenu[Dynamic@whichfun, funlist], "usage should be here"],        Dynamic@whichfun]      Instead of `"usage should be here"` I obviously tried `(Dynamic@whichfun)::usage` but it's complaining that the `Head` is not a `Symbol`, so I tried to convert it to a `Symbol` but it still fails. Thus the question is: How can I convert `Dynamic@whichfun` in order to be able to have its `usage`?


Trig angles simplifying in worksheet

I would like to generate a table of trig questions such as:               Table[RandomChoice[{Sin, Cos, Tan}][     RandomInteger[{-180, 450}] \[Degree]] //     TraditionalForm, {3}, {4}] // TableForm       does. MMA however evaluates this to acute angles. What syntax can be used to keep the evaluation as sin(200˚) say? Thanks in advance.


Formatting numbers for sending to the WolframAlpha[] function

I have a function that gives me a number of meters; how do I attach "meters" to it and send it to WolframAlpha? The function generating the result isn't a unit-aware calculation or anything:               distance := someFunction[AstronomicalData["Mercury", "Radius"]]      The result is about 6.07x10^15 Now I want to ask WolframAlpha[] to give me context for that number of meters. (Show me the number converted it to various units, show me comparisons, etc; all the stuff W|A is great for.) I figured I'd say something like               WolframAlpha[ToString[distance]<>"meters"]      But no way that I format that number into a string gives me a result that WolframAlpha[] understands, and I can't find anything in the manual explaining a better way to format it. I've tried the `Quantity[]` function, and all kinds of variations on               x := NumberForm[N[distance], 10]     WolframAlpha[ToString[x] <> "meters"]      But it just interprets it as "15x6.068x10 meters" I've tried Googling every variation on "format a number to send to the wolframalpha function" and found nothing. Is there an easy way to do this that I'm missing?


How do I stop my joystick from rotating a 3D graphic?

I am trying to use _Mathematica_ to illustrate mixed strategies in Game Theory. I want my students to be able to use common joysticks as controllers. What I find, however, is that in addition to doing what I want, moving one of the controls on my gamepad rotates the 3D graphics in such a way as to ruin the presentation. Basically, all I want the controls to do is change the strategy each player uses. The Graphics3D object should not rotate. Here's a very simplified of the code that illustrates the undesired behavior.               Manipulate[     Column[{x, y,      Show[Graphics3D[{Line[{{x, y, 0}, {x + 1, y + 1, 1}}]},       Axes -> True, ImageSize -> 400],           Graphics3D[{Tube[{{x, y, 0}, {x - 1, x - y, 1}}]}]]}],      "X1" -> {{x, 0.71}, 0, 1}, "Z1" -> {{y, 0.5}, 0, 1},      ControllerPath -> "Joystick"]      ![Mathematica graphics](http://i.stack.imgur.com/5oETP.png) I also thought it might be useful to show you the following, which is the results from               ControllerState["PLAYSTATION(R)3 Controller", "Mapping"]          (* {"X2" -> "Z Axis", "Y2" -> -"Z Rotation", "JB" -> "Button 11",       "JB1" -> "Button 11", "JB2" -> "Button 12", "JB3" -> None,       "TLB" -> "Button 5", "TRB" -> "Button 6", "BLB" -> "Button 7",       "BRB" -> "Button 8", "X" -> "X Axis", "Y" -> -"Y Axis",       "Z" -> "Z Axis", "X1" -> "X Axis", "Y1" -> -"Y Axis",       "Z1" -> "Z Axis", "X2" -> "Z Rotation", "Y2" -> -"Slider",       "Z2" -> None, "X3" -> "Hatswitch X Axis",       "Y3" -> -"Hatswitch Y Axis", "Z3" -> None,       "X4" -> Switch[{"Button 1", "Button 3"},        {False, False}, 0,        {True, False}, -1,        {False, True}, 1,        {True, True}, 0.00001], "Y4" -> Switch[{"Button 2", "Button 4"},        {False, False}, 0,        {True, False}, -1,        {False, True}, 1,        {True, True}, 0.00001], "X5" -> Switch[{"Button 7", "Button 5"},        {False, False}, 0,        {True, False}, -1,        {False, True}, 1,        {True, True}, 0.00001], "Y5" -> Switch[{"Button 8", "Button 6"},        {False, False}, 0,        {True, False}, -1,        {False, True}, 1,        {True, True}, 0.00001], "X6" -> Switch[{"Button 9", "Button 10"},        {False, False}, 0,        {True, False}, -1,        {False, True}, 1,        {True, True}, 0.00001], "B1" -> "Button 1", "B2" -> "Button 2",       "B3" -> "Button 3", "B4" -> "Button 4", "B5" -> "Button 5",       "B6" -> "Button 6", "B7" -> "Button 7", "B8" -> "Button 8",       "B9" -> "Button 9", "B10" -> "Button 10", "B11" -> "Button 11",       "B12" -> "Button 12", "DefaultAbsolute" -> False} *)      Also, for what it's worth, the Sony Playstation gamepad I am using has two main analog controls that appear to move in at least a left right and up down configuration. Moving the left control left and right appears to correspond to "X1" and moving the right control left and right appears to correspond to "Z1". I'm hoping my problem is not Sony PS3 controller specific but is due to some lack of understanding on my part about how to map the physical controls to _Mathematica_ behavior.


How to determine all cases consistent with constraints

Suppose that $(i, j), (k, l)$ and $(m, n)$ are pairs of non-negative integers, satisfying the following constraints: $$i < j,\;\; k < l, \;\; m < n$$ and $$ (i, j) < (k, l) < (m, n)$$ ...where the ordering of the pairs implied by the last set of inequalities is the lexicographic one (e.g. $(i, j) < (k, l)$ iff either (1) $i < k$, or else (2) $i = k$ and $j < l$). For each possible cardinality of the set $\\{i,j,k,l,m,n\\}$, I would like to find, subject to the constraints above, all the possible configurations of equality and inequality relationships among elements of the set that would yield such a cardinality. For example, cardinality 3, one such configuration would be $$i = k, j = m, l = n$$ The brute-force solution to this problem would be to generate all possible configurations of equality/inequality relationships among the six variables, weed out the ones that are inconsistent (either internally or relative to the constraints), and finally classify the remaining configurations according to the cardinality they imply. I think I can write the _Mathematica_ code to generate all the possible configurations, but I'm not sure how to weed out the ones that are inconsistent, or incompatible with the constraints. To give an example of what I mean by "configuration", consider the simpler problem where we have only three variables $i, j, k$, and only one constraint, $i < j$. The following are three possible configurations: $$i < j,\;\; j < k, \;\; i < k$$ $$i < j,\;\; j = k, \;\; k = i$$ $$i > j,\;\; j > k, \;\; i > k$$ The first one is OK, the second one is internally inconsistent, and the third one is incompatible with the constraint. When I enter the above expressions in _Mathematica_ , it just returns them verbatim:               In[1]:= i < j && j < k && i < k     Out[1]= i < j && j < k && i < k     In[2]:= i < j && j == k && i == k     Out[2]= i < j && j == k && i == k      (I had hoped that the first expression would have evaluated to `True` and the second one to `False`.) Does _Mathematica_ provide a convenient way to weed out the invalid configurations?


Does Mathematica support collaborative filtering and recommendation systems?

Does _Mathematica_ support collaborative filtering and recommendation systems such as can be found in Apache Mahout? I could not find any resources about advanced data mining techniques, beyond clustering and NN algorithms. Does anyone know any _Mathematica_ libraries that support advanced data mining? The problem: I'm building a specific type of a recommendation engine. Data:   * each product can belong to many categories   * categories form a forest   * products are organized in a graph to show the relationship that consuming an entry level product X will make the more advanced product Y more suitable for the consumer   * for each consumer we have a timeseries of choosen products and the objective and subjective satisfaction levels Desired outputs:   1. ranked list of products per category that would maximize the objective satisfaction level while still in a threshold of the subjective satisfaction   2. Rank products according to subjective satisfaction but occuring in preferable circumstances (if you've found the right patterns of when to introduce a product use product rating when introduced in a similar pattern)


Finding Limits in several variables

Is there a way to find a limit of a multivariable function, like $$\lim_{(x,y)\to (0,0)} f(x,y)$$ with _Mathematica_? When $f$ is continuous, we can use $$\lim_{(x,y)\to (0,0)} f(x,y)=\lim_{(x,0)\to (0,0)} f(x,0)$$ or something similar, which could be implemented with code like               Limit[Limit[f[x,y],y->0],x->0]      When $f$ is not continuous, like for example $$f(x,y)=\begin{cases} \frac{xy}{x^2+y^2} & (x,y)\neq (0,0)\\\ 0 & \text{else} \end{cases}$$ we could make at least a small control with something like               Table[Limit[f[x,y] /. y -> k * x, x -> 0], {k, 0, 5}]      which gives us a list of the limits $$\lim_{x\to 0} f(x,k\cdot x)$$ Taking $f$ to be $$ f(x,y)=\begin{cases} 1 & \exists \alpha \in \mathbb{Q} \text{ such that } x=\alpha \cdot y\\\ 0 & \text{else}\\\ \end{cases}$$ gives us a function where this won't work. So, is there a way to compute those limits (or getting the result that the limits don't exist) in _Mathematica_?


Drawing minor gridlines

What's the best (most elegant, shortest, easiest to read) way to add minor grid lines to a plot? Here is an example:               data = Table[{x, Log@x}, {x, 100}];     ListPlot[data, Frame -> True, GridLines -> Automatic]      ![what I get](http://i.stack.imgur.com/HrgZs.png) But this gives gridlines only at the position of the major frameticks. I'm looking for an easy way to automatically generate minor grid lines at the positions of minor frameticks (in a style different from the major gridlines). Here is an example (yes, made in excel) ![What I would like to get](http://i.stack.imgur.com/JEKOg.png) I guess I could write half a page of code to generate both the frame ticks and the gridlines, but it seems like an overkill. I realize this is very similar to this question, but if I have to enter the ranges manually for each plot then I might as well draw my plots in excel.


Precise cropping with ImageCrop

The built-in `ImageCrop` function "effectively removes borders from _image_ whose pixel value distribution is **almost uniform** " (emphasis mine). I need an efficient cropping function which removes borders whose pixel values are **identical**. What is the best way to do this in _Mathematica_? I don't need support for 3D images, but images with an alpha channel should be supported. Here is an example of inconsistent behavior of `ImageCrop` (v. 9.0.1):               img = Rasterize[        Graphics[{Circle[{0, 0}, 1],           Text[Style[l, FontFamily -> "Times"], {1.2, 0}]}, Frame -> False,          PlotRange -> {{.9, 1.3}, All}], "Image", Background -> None];     Show[#, Frame -> True, FrameTicks -> False,         PlotRangePadding -> None] & /@ {img, ImageCrop[img],        ImagePad[img, -BorderDimensions[img, 0]]}      ![screenshot](http://i.stack.imgur.com/r83pg.png)


Looking for better way of plotting families of functions

I'm trying to plot this:               i = 0.01;          ListLinePlot[Table[Cos[x]^p, {x, 0, π/2, i}, {p, 0, 1, i}],                   ImageSize -> 400, PlotRange -> {{0, 100}, {0, 1}}]               ListLinePlot[Table[Cos[p x], {x, 0, π/2, i}, {p, 0, 1, i}],                   ImageSize -> 400,   PlotRange -> {{0, 100}, {0, 1}}]      When `i = 0.001`, it takes a lot of time to render and my computer become unusable. Is there something I can do for rendering it faster or at least making the process slower so I can use my computer normally? I have a Nvidia GTX460 video board and I know about the CUDA link, but if it's not asking too much, I'd like to get advice from someone who has more experience than me at such matters.


How can I change the color of the bar in a ProgressIndicator?

I want to change the color of the progress bar in a `ProgressIndicator`. I want the progress bar to be red instead of green. For this purpose I wrote the following code, but still it doesn't work.               Style[ProgressIndicator[90, {0, 100}], Red]      ![Mathematica graphics](http://i.stack.imgur.com/jd8Af.png) How can I do change the color?


Using NestWhileList to determine smallest prime value in series

I have a function recursively defined as follows: $a_{n+1}-1=(a_n-1)\times lpf(a_n)$, whe $lpf(x)$ is the least prime factor of $x$. Now, given an initial value of $a_0$, I would like to find the smallest value of $a_n$ such that $a_n$ is prime. Here is my attempt at a code, with $a_0=6$. `NestWhileList[((#1 - 1)*FactorInteger[#1][[1, 1]] + 1) &, 6, ! PrimeQ]` However, my code always simply returns the initial value of $a_0$. What am I doing wrong here?


Parallel evaluation and memory use

I have never used Mathematica's parallel evaluation before and have some trouble getting it to work properly. For the record, I am running Mathematica 9 on Linux with an Intel Core i7 processor (4 physical cores). I have a function `Foo` that performs randomised numerical calculations with some matrices and returns a small list. I am interested in running it multiple times and collecting the results, so if I use `Table` on one kernel, everything works fine and I experience no issues. I then attempt to parralelise it with something like:               LaunchKernels[2];     DistributeDefinitions[Foo];          ParallelTable[Foo[bar], {10000}];      Two kernels work fine as well, but in that case Mathematica starts to use up to 10GB of RAM. Running four kernels, however, causes a lot more problems. Mathematica quickly uses up all of my 16GB of RAM leaving the computer literally unusable, complains about running out of memory all the time and keeps shutting down kernels. Even if I get my results, I am often unable to use them because any operation on the returned list causes the shutdown of the main kernel and the loss of all data. `MaxMemoryUsed[]` gives `37 686 808`. I have tried alternative approaches with `ParallelDo` and some stranger constructs (motived by wanting to be able to stop the calculations and retain all the results obtained so far) such as               a = {};     Do[      AppendTo[a, ParallelTable[Foo[bar], {100}]],     {100}]      but these cause an even faster kernel failure due to the lack of memory. I should also mention that after I stop using 4 kernels and go back to 1-kernel calculations, I frequently run into some random "`No more memory available. Mathematica kernel has shut down. Try quitting other applications and then retry.`" even though Mathematica is not even using much of my system memory at this point. This does not happen prior to attempting 4-kernel evaluation in the same session. Am I approaching this problem incorrectly? Resources on the internet about Mathematica's parallel evaluation are sparse, so I was unable to find much information. One thread here on StackExchange mentioned that calling `ClearSystemCache[]` in the function can free up some memory used by Mathematica in parallel computations, but it seems to have no effect at all. I would appreciate any information and help. Thank you.


How do I remove Wolfram Branding in a CDF?

I have a _Mathematica_ Enterprise License, which lets me export Pro-feature CDFs. One of the benefits is supposed to be removal of branding and full customization of UI. Does anyone know how to get that done? Because in Player and in Plugin, I'm still getting the Wolfram Bar and all the usual stuff.


How to migrate or export projects with Workbench

Imagine the following scenario: user A is developing a project with documentation in workbench. She wants to give her (unfinished) work to user B , so that user B can continue work on the project and eventually deploy it on her PC. The 2 users might have different operating systems. What is the best way to accomplish this? WRI does something similar when it offers sample projects online. We "import" the project into our WB. So in the above scenario, user B has to "import" the project, in order to make it work in her WB. What is not too clear to me is what is that user A has to do. One would think that user A has to "export" the project, but there are many different (and unclear to me) options available for exporting a project. So, even assuming that "export" is the right thing to do, what precisely is the correct procedure? I performed a couple of experiments and it seems to me that the end result of some of these "export" options, generate folders or archives which have a different file structure than the original project folder has. Hence my question.


ContourPlot - plot only one connected component

How do I plot only one component in ContourPlot when specifying a height. For example,               ContourPlot[       Sin[Sqrt[x^2 + y^2]] Exp[-x^2 - y^2] == 0,       {x, -10, 10}, {y, -10, 10}     ]      produces concentric circles. How do I plot only the innermost one? That is the component going through (Pi,0).


Reduce on equations involving integrals

Here's part of problem from a college physics text: > A time-dependent force **F** = (8.00 **i** \- 4.00 _t_ **j** ) N (where _t_ > is in seconds) is applied to a 2.00-kg object initially at rest. (a) At what > time will the object be moving with a speed of 15.0 m/s? Here's one way to solve the problem using Reduce:               {       vx == Integrate[Fx/m, {t, 0, t}],       vy == Integrate[c*t/m, {t, 0, t}],       speed^2 == vx^2 + vy^2,       c != 0, speed != 0, Fx != 0       };     Reduce[%, {t, vx, vy}];     % /. {speed -> 15, Fx -> 8, c -> -4, m -> 2}      The output is:               (t == -5 I || t == 5 I || t == -3 || t == 3) && vx == 4 t &&       vy == -((t vx)/4)      The answer given in the book is t = 3. In the set of equations passed to `Reduce`, the `Fx/m` comes from `Fx = m * ax` and `c*t/m` comes from `c*t = m * ay`. Instead of doing that manual substitution, I'd like to pass those equations to `Reduce` and have it do the right thing. I.e. something like:               {       Fx == m * ax,       c*t == m * ay,       vx == Integrate[ax, {t, 0, t}],       vy == Integrate[ay, {t, 0, t}],       speed^2 == vx^2 + vy^2,       c != 0, speed != 0, Fx != 0       };     Reduce[%, {t, vx, vy}];     % /. {speed -> 15, Fx -> 8, c -> -4, m -> 2}      Of course, that doesn't work because `Integrate` doesn't know that `ax` and `ay` are in terms of `t`. Any suggestions on how to make something like this work?


Efficiently filling area with disks located at certain points

Starting from a set of points, I want to fill an area using disks. Each disk's center should be one of the points and the disks should not overlap. I've managed to write a function that, given a list of points, finds the respective radii of the disks:               findRadii[pts_] := Module[{        vars = Unique /@ (("x" <> ToString@#) & /@ Range@Length@pts),        norms = Norm[Subtract[##]] & @@@ Subsets[pts, {2}],        dists, constraints},       dists = Plus @@@ Subsets[vars, {2}];       constraints = Thread[dists <= norms]~Join~Thread[vars > 0];       NArgMax[{Total@vars^2, constraints}, vars]       ]      The function just maximises the square of the sum of radii with the constraint that each radius should be positive and the sum of two radii should be smaller than the dsitance between the respective points (I know that this in fact does not maximize the filled area, which maximizing `Total[vars^2]` would, but I've found the result to look nicer). Testing the function (and timing it) yields the following:               SeedRandom@1; foo = RandomReal[{0, 10}, {20, 2}];            Timing[radii = findRadii[foo];]     (* {13.931, Null} *)          Graphics[{MapThread[Circle[#1, #2] &, {foo, radii}], Red, Point[foo]}]      ![enter image description here](http://i.stack.imgur.com/Jcp9p.jpg) Am I missing a simpler way to calculate the distances? How can the function's performance be increased? Ultimately, I would like to use it with >100 points in reasonable time. Note that I don't need a strict maximum of the covered area, but rather a visually appealing result.


Efficient by-element updates to SparseArrays

I have a very large `SparseArray` called `A`. What is the most efficient way to update say element `{i,j}` with value `x` to the value `f[x]` ? I worry about **memory usage and code speed** if I need to make a very large number of updates. I've seen Leonid's comment here about a similar problem. But there is a lot of info scattered over old SO site and I am looking for function and a syntax something like `f[A_, {i_,j_}, f_]` that will do the job. I think it is a very essential question for recursive by-element updates to `SparseArrays' and would love to see a complete solution here.


How to add equations' left and right sides together?

If we have two equations E1 and E2, and instead of using `Solve` to solve it, we simply need to manually add them up which would allow some simplification that could lead to better visibility of its structure, I found that               E1 + E2      would always fail. Instead, I need to extract left and right sides of an equation explicity using               E1[[1]] + E2[[1]] == E1[[2]] + E2[[2]]      ![enter image description here](http://i.stack.imgur.com/GFbkk.jpg) Is there any built-in function to do this?


How to switch between a binary number as String and a as a list of digits?

I was trying with String Functions and I viewing any posts and have no results I want to know 1.- From               cromo33 = Table[RandomInteger[], {i, 1, 33}]     cromo33      that gives {1,0,1,1,1,0,1,......,1,0,0} , alist of 33 elements How can you obtain "1011101.....100" ? 2.- From               IntegerString[RandomInteger[8], 2] // InputForm      that gives 101 (a little add-on... ¿how can I force this to obtain 4 digits in any random number?) How can you obtain a list {1,0,1} ?


Generating an Airy disk on a plane

I wish to generate a surface intensity plot of an Airy disk (or perhaps a two- dimensional Gaussian approximation to an Airy disk) on an (x, y)-plane at a specified coordinate. The hope is to have something like this: http://en.wikipedia.org/wiki/File:Airy-3d.svg with solid surface coloration. I am OK with a decent mesh approximation of a representative curve. Is there a built in method of generating these sorts of intensity plots and treating them like Graphics3D objects that can be translated and placed as desired?


How to determine cluster membership using FindClusters?

I have a 1000 by 3 data matrix in which for each person we have 3 scores. I want to cluster those persons into 8 cluster using Agglomerative method. I did the clusetring by:                class=FindClusters[data, 8, DistanceFunction -> ManhattanDistance,       Method -> {"Agglomerate", "Linkage" -> "Complete"}]      I want to find out how and which persons are classified into those 8 clusters.In other words, I want to have a vector of class membership for each person (similar to what we can get using `ClusteringComponents[data,8,1]`). As an example, suppose we have this data set:               data={{3, 2, 4}, {1, 1, 0}, {5, 2, 4}, {2, 3, 2}, {4, 4, 4}, {3, 2, 4}, {3,        2, 3}, {2, 1, 3}}      result of `FindClusters` is:               class = FindClusters[data, 3, DistanceFunction -> ManhattanDistance,        Method -> {"Agglomerate", "Linkage" -> "Complete"}]          {{{3, 2, 4}, {2, 3, 2}, {3, 2, 4}, {3, 2, 3}, {2, 1, 3}}, {{1, 1,         0}}, {{5, 2, 4}, {4, 4, 4}}}      through the output it can be seen that persons number 1,4,6,7&8 are classified in first cluster; person number 2 in second cluster and persons number 3&5 are in third cluster. I want to have a vector like:               {1,2,3,1,3,1,1,1}      then I can determine which person is located in which cluster and how many persons are in each cluster. I decided to use `FindClusters` because I didn't get reasonable results from `Agglomerate` function for hierarchical clustering. My main aim is doing hierarchical clustering with different linkage functions. Any help and additional ideas are appreciated. Amin.


Series expansion of a complex function

How do I expand a function $f(z)$ in a particular region? For example, how would I expand $f(z)=(z^2-3z+2)^{-1}$ in the region $0<|z-1|<1.$? I believe this can be done by the binomial theorem. But how to arrange things to make the binomial expansion valid? Please give me an idea for doing this.


Assigning several values inside DynamicModule

I have coded a model that contains several parameters. The parameters can be changed interactively by the user using an interface contained in a DynamicModule[]. There are several "basic states" of the model, i.e. several sets of parameters that can be chosen as default. The user can pick the defaults by pressing appropriate buttons in the interface. For example:               DynamicModule[{a,b,defaultParameters,userParam},       defaultParameters = {Hold[a=1;b=1;],                            Hold[a=2;b=2,]}            Button["Default 1",ReleaseHold[defaultParameters[[1]]]]       Button["Default 2",ReleaseHold[defaultParameters[[2]]]]     ]      At several places in the code, I take advantage of the set of parameters being "saved" in the variable `defaultParameters`, as it is quite convenient to set all parameters in a single statement: `ReleaseHold[defaultParameters[[n]]]`. In reality, there are many more parameters than just `a` and `b`. Now to my question: When the user is changing the model interactively, I want him to able to save the current state of the model as another default set. However, I do not know the correct combination of `Hold`, `Evaluate`, etc to make it work. I want something like               Button["save parameters",userParam = Hold[a=Evaluate[a];b=Evaluate[b];]]      but this doesn't do the trick. In the end, I wish to be able to call the parameters with `ReleaseHold[userParam]`.


What are the exact guidelines for what is allowed in a CDF?

I have read the guidelines published by Wolfram (these are restricted: non- numeric input fields, dialog windows, and data import and export) but I have a CDF that seems simple enough and seems to satisfy these constraints but does not work in the browser (gray box is all that displays). This CDF can be found here.


Create filling between two trig functions

Working with trig functions, period, amplitude, etc. I found a worksheet at a calculus website, with some nice questions related to interpreting trig functions, at least, they provide some "fun" context. It has to do with a couple, different phases in their relationship, etc. See http://math.arizona.edu/~calc/m124/Denise&Chad.pdf Anyway, my Mathematica question, is related to filling between two curves. In the worksheet, consider that "happy" means positive. A couple is “happy” when they both like each other. A couple is unhappy when they both dislike each other. Here are the two curves as given in the worksheet.               Plot[{Sin[9 \[Pi] t/10], 2 Sin[7 \[Pi] t/10]}, {t, 0, 20},       AspectRatio -> 0.2, AxesLabel -> {"weeks", "affection"}]      ![enter image description here](http://i.stack.imgur.com/XpLb0.png) Is there a clever Mathematica way to fill in just those portions of the curve where the couple are happy, I.E. both are positive? Is there a nice way to visualize this?


Making a list of terms ordered by product order

I have some expressions `f,g,h` that are elements of a symmetric tensor algebra. The expressions are generated by a basis `{e1,e2,e3,...en}` and so takes the form of a polynomial of the basis elements with coefficients that are linear polynomials made from `{c1,c2,c3,...cm}` and parameter `k`. I know that there is a unique assignment of the `c`'s such that `f=g=h=0`. I initially used `SolveAlways` and gave the basis as the second argument. However `SolveAlways` became very slow for larger `f,g,h` as it continued attempt to solve for `k` even though it was not possible to determine a specific value. I varied the attempt by using `Solve[!Eliminate[!{f==0,g==0,h==0},basis],constantslist]` which did speed up the process significantly likely because mathematica correctly identifies k as a parameter. Now however as the size of the basis I'm dealing with grows it seems `Eliminate` is slowing down the process. For a an example to for a basis of dimension 25 and `f= (c1-1)e1+c2 e2...+c25 e25` it takes 10 seconds and nearly 1.3 GBs of memory to to tell me that all but one coefficient must be 0. I do have a way around this when I know that `f` only has linear terms of the basis. This involves a brute force method of solving the zeroes of the coefficients one by one then replacing the rules back into f. This comes out as                Module[{tempvalue = e1-c1 e1+c2 e2...+ c25 e25,temprules = {},tempcoef},     For[i = 1, i <= GeneratorSize, i++,       tempvalue = tempvalue /. temprules;      tempcoef = Coefficient[tempvalue, GeneratorBasis[[i]]];     temprules = Join[temprules, Solve[tempcoef == 0][[1]]]];     temprules]      However, I would believe that this method would be impracticable when f has non-linear terms of the basis. As asking for e1's coefficient in `c1 e1 e2 +c2 e1` would lead to `c1 e2 +c2` and unless I again use `SovleAlways` I won't find a solution which keeps the `Eliminate` problem. To fix this I would need to generate a list that goes from the highest order terms to the lowest. This may be possible but I am unsure how to go about it. As an example of what would be needed to solve the problem. Suppose `f=(c1-c2+1)e1 e2 + (c1-1/3)e1^2 + c3 e1`, what is needed is to some how extract the 3 equations that are needed to solve for `{c1,c2,c3}` here they are:                c1-c2+1=0      c1-1/2=0      c3=0      A method that could be possible would be to generate a list of terms generated by the basis elements `{e1,e2}` ordered from most highest order product to least. Here that list would be `{e1 e2, e1^2,e1}` which would then be used with `Coefficient` to extract the equations above. The reason the set must be ordered in this way is that after the equation is extracted its solution is put back into `f` and so would eliminate that term being picked up by lower ordered terms. This means that when `Coefficient[f/.rules,e1]` is called one would get `c3` rather then `c3+(c1-c2+1)e2`. This leads to the question at hand. Either, is there a way to generate a list of the terms of a polynomial made from the basis ordered so that the high order products are first, or is there a better way to approach the problem as a whole?


Clearing a specific definition

Consider the case where a symbol has multiple definitions attached to it,               a /: Subscript[a,2] := 1     a[b_] := 2     a[b_, c_] := 3      How does one clear (/unset/remove) only one of those definitions while leaving the others intact?


Overlaying a Plot within a Manipulate Control Panel

Is there a way to overlay a plot into a blank area of a Manipulate control panel, that will still update according to the controls in the Manipulate function? This is an image of what I have: ![Imgur](http://i.imgur.com/NlHRqoi.jpg) You can see on the bottom left that I have a semi-function plot there. I am using the function Overlay[] to do this, but I'm not sure if its the best way. What you see is two nested Manipulates, one with the control panel on the left, and the 2nd with the control panel on the bottom. Unfortunately, the extra plot doesn't update with any of the sliders. I guess something with Dynamic[] could work, but I don't know how to combine that with Manipulate! Thanks!


How can I compare a dynamic variable with a literal in Mathematica?

I'm doing a Mathematica Notebook and I want to make an alarm clock. Something like this:               SetAttributes[Horas, HoldRest]           (* Get System Hour *)     Hours = Dynamic[Refresh[DateList[][[4]], UpdateInterval -> 1]];            SetAttributes[Mins, HoldRest]           (* Get System Mins *)     Mins = Dynamic[Refresh[DateList[][[5]], UpdateInterval -> 1]];           If[       SameQ[ToString[Hours], ToString[alarmh]]          && SameQ[ToString[Mins],ToString[alarmm]],          Quiet@EmitSound[Sound[SoundNote["D", 1,"Tinklebell"]]]     ];      `alarmm` and `alarmh` are variables that the user select from a listbox When the variables from the listbox are the same with the system hour I want to sound a bell. The problem is that if I make Dynamic variable I can't compare them, but if I do this:               Refresh[DateList[][[5]], UpdateInterval -> 1];      I can compare between them, but the time doesn't update... How can I make it update?


Write C/C++ programs calling Mathematica functions

I need to write a C/C++ program and call some functions in _Mathematica_ especially those like `Solve` or `NDSolve`. The problem is that in the _Mathematica_ documentation it seems to me there is no mention about this. There are plenty of details regarding how to create a C function and then call it from within _Mathematica_ , but in my case I need the opposite. Maybe I did not read well, but can you explain me how to do this?


Prevent text from wrapping in a notebook

By default in the Notebook interface the text wraps. Is it possible to prevent this wrapping?


Finding a fit to a multi-dimensioned function

I have a model function $f:\mathbb{R}^2\rightarrow\mathbb{R}^2$, and a bunch of data points for which I'd like Mathematica to fit for me. Unfortunately `FindFit` seems to only deal with functions $\mathbb{R}^n\rightarrow\mathbb{R}$. I guess I could make my own square difference from the data to the model and use `NMinimize` on that, but I wondering if there was an easier way? ### Edit - toy example with answers $g\left(x,y\right)=\left<abx+(2c+d)y,(2a+b)x+cdy\right>$               g[{x_, y_}, {a_, b_, c_, d_}] := {a b x + (2 c + d) y, (2 a + b) x + c d y};     points = Flatten[Table[{{x, y}, g[{x, y}, {1, 2, 3, 4}]},       {x, -1, 1, 0.5}, {y, -1, 1, 0.5}], 1];      Finding a fit for each component separately doesn't work:               data1 = points /. {{x_, y_}, {u_, v_}} -> {x, y, u};     data2 = points /. {{x_, y_}, {u_, v_}} -> {x, y, v};     FindFit[data1, g[{x, y}, {a, b, c, d}][[1]], {a, b, c, d}, {x, y}]     FindFit[data2, g[{x, y}, {a, b, c, d}][[2]], {a, b, c, d}, {x, y}]      > `{a -> 0.729723, b -> 2.74077, c -> 3.35659, d -> 3.28681}` > > `{a -> 1.48555, b -> 1.02891, c -> 2.81936, d -> 4.25629}` Jens suggestion works well:               data3 = points /. {{x_, y_}, {u_, v_}} -> Sequence[{x, y, 0, u}, {x, y, 1, v}];     FindFit[data3, g[{x, y}, {a, b, c, d}].{1 - s, s}, {a, b, c, d}, {x, y, s}]      > `{a -> 1., b -> 2., c -> 3., d -> 4.}` My original suggestion (which is similar to user840's links)               error = Plus @@ (points /.         {{x_, y_}, {u_, v_}} -> Norm[g[{x, y}, {a, b, c, d}] - {u, v}]^2);     NMinimize[error, {a, b, c, d}]      Gives a different, but still correct, solution (or at least a close approximation thereof) > `{1.41754*10^-13, {a -> 1.00004, b -> 1.99993, c -> 2., d -> 6.}}`


Minimise a function taking a vector as an input directly

f1[x_] := x*2 // Abs;     f2[x_] := (x // Transpose).x;     Minimize[f1[x], {x}] (* fine, returns 0 *)     Minimize[f2[x], {x}] (* not fine, returns "Minimize[Transpose[x].x, x]" *)      A workaround for this would be to do:               Minimize[f2[{{a}, {b}}], {a, b}]     {0, {a -> 0, b -> 0}}      However, that isn't very nice when X is a long vector. Is there a way to minimise a function taking a vector directly without resorting to workarounds? If I have to use a workaround, is there a way to automate what I did in that example maybe using "macros"?


How do I direct output to a specific notebook or cell?

> **Possible Duplicate:**   >  How to pipe a stream to another notebook? Is there any way to create a stream so that all output to the stream (from `Write` or something similar) goes to a specific notebook, or to a specific cell? I think `CellPrint` almost does what I want, but I would need to manipulate the selection in order to have the newly generated cell end up where I want it, and more annoyingly, I can no longer make use of the functionality by using a stream as an argument. **EDIT** to add: As an example of what I'm trying to do, say I have a function like this:               foo[] := Print["I am Spartacus!"];      What I want is some function, `whatever`, which will allow me to do this:               Block[{$Output = whatever[]},      foo[]];      and have "I am Spartacus!" appear in another notebook, instead of in a cell underneath the cell I just evaluated. I don't want to have to change the definition of `foo`, because it's really a long function with a lot of `Print` statements used for logging purposes.


When importing GIF animation, how to find the correct list of "DisplayDurations"?

When importing GIF animations with variable frame durations, the settings for "DisplayDurations" are not recovered correctly. As an example, I'm using the movie from this earlier question: ![slowDown](http://i.stack.imgur.com/UEQpN.gif) Here I'm repeating the code to generate it, putting the gradually increasing frame durations in a variable `durations`:               frames =        Table[Graphics[         Text[Style["Slow Down", FontFamily -> "Futura", FontColor -> Blue,            FontSize -> 48], {0, y}], Background -> Cyan,          PlotRange -> {{-1, 1}, {.1, 1.5}}], {y, 1.2, .2, -.1}];     durations = Append[Range[Length[frames] - 1]/20, 2];     Export["slowDownMovie.gif", frames, "DisplayDurations" -> durations,        "AnimationRepetitions" -> Infinity];          durations//N      > `{0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 2.}` Now compare to the durations that we get when re-importing the same animated GIF:               newDurations = Import["slowDownMovie.gif", "DisplayDurations"]      > `{20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20.}`               newDurations == durations      > `False` As expected from this negative result, `ListAnimate` also plays the animation at an incorrect, constant frame delay. It seems clear that this is a bug. Before I start looking for a platform-specific hack to fix this: **is there any way to get the correct display durations from a GIF with the`Import` function?** I looked into the `"Frames"` element of the GIF import, but that also seems to have the wrong display duration in it. I haven't looked at the raw data, but if one has to do that it may be better to find a non-Mathematica hack instead. **Edit** Wolfram support has confirmed it's a bug [TS 19773].


Producing cleaner Mathematica output

I asked this in chat and it turns out it would make for a good question make a posting for. I am writing up a handout type notebook and I'd like to have some clean output for presentation's sake. Say I have multiple functions I wish to evaluate in one cell. How can I force the output to a more condensed space/format such as one line? **What Is Happening** Input:               a = 1 + 1     b = 1 + 2      Output:               2          3      **What I Have Been Doing** I have been using the `List[]` command.               List[a = 1 + 1,          b = 1 + 2]      But this gives me some 'extraneous' curly braces.               {2, 3}      **What I Want** Output:               2, 3      **Other** The fix should keep the formatting of output functions (should not reduce functions to one-line input style syntax).


How to export transparent raster plots?

Is there an easy way to get transparent plots that work with `Save Graphic As` using a compatible file format such as GIF or PNG? I tried `Background->Opacity[0,White]` and `Background->None`, yet the exported PNGs appear to still have a white background.


How to Write into multiple files?

Note: this is fixed in version 9. * * * I want to put expressions into multiple files simultaneously, with the following code:               tex1 = OpenWrite["test1.txt"];     tex2 = OpenWrite["test2.txt"];          Write[{tex1, tex2}, "anything"]          Close[tex1];     Close[tex2];      Why is `test2.txt` empty? Why does it work correctly with `WriteString` instead of `Write`? Now of course I can always `Map` the `Write` statements over streams, or just go with `WriteString`, but since it would be convenient to use a list as `Write`'s first argument I did post this issue. Is it a bug?


Is there a way to solve the linear equation, Ax=b, in which A is a "non-constant" sparse matrix that depends on x?

I want to solve the Linear Equation, $Ax=b$ in Mathematica using Kylov subspace solver method preferably BICGSTAB(http://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method). Suppose $A^{BE}_{\Delta,\Omega}$ is the following Laplacian+ Angular Momentum operator.![enter image description here](http://i.stack.imgur.com/RMoW8.png) Instead of using the finite difference matrices for evaluating $A^{BE}_{\Delta,\Omega}$, I am using the derivatives in Fourier space for higher accuracy. ![Derivatives](http://i.stack.imgur.com/wG316.png) where ![Description of operators](http://i.stack.imgur.com/cPwC3.png) How can one solve this Linear equation $A^{BE}_{\Delta,\Omega}\psi=\phi$ equation where $A=A^{BE}_{\Delta,\Omega}$, $x=\psi$, and $b=\phi$ in $Ax=b$? How can one extract $A^{BE}_{\Delta,\Omega}$ to plug it in `LinearSolve[A,b]`when it clearly depends upon $\psi$? I have used: `LinearSolve[A,b]` but as A ($A^{BE}_{\Delta,\Omega}$) depends on x ($\psi$), I do not get the correct result. One can solve this in MATLAB using the following function: `x = bicgstab(A,b)` Here it attempts to solve the system of linear equations A*x=b for x. A can be a function handle, afun, such that afun(x) returns A*x. Is there an analog of this function handle operation in Mathematica, in `LinearSolve`, where it can deal with the matrix A that depends on its x, in Ax=b? Any help is appreciated.


Finding the roots of a function with a parameter

I am using a differential equation method for finding the roots of a function. My function is much more complicated but I can illustrate my problem with a trivial example. The problem occurs when roots coincide and change direction. I use a differential equation method. The example equation is               eq = s^2 + 2 a s + 1;      where _a_ is a parameter (0 < _a_ ) and I wish to find the roots as the parameter is varied. To form the differential equation I take two derivatives and put them together as follows               deq = {D[eq, s], D[eq, a]} /. s -> s[a];     de = deq[[1]] s'[a] + deq[[2]] == 0     (* 2 s[a]+(2 a+2 s[a]) (s^\[Prime])[a]\[Equal]0 *)      I set up the differential equation so that I can solve with different initial conditions and over different ranges of the parameter _a_               ClearAll[sol];     sol[ic_, ae_] := s /. First[NDSolve[{de, s[0] == ic}, s, {a, 0, ae}]]      I have initial conditions from               ic = s /. Solve[eq == 0 /. a -> 0]     (* {-\[ImaginaryI],\[ImaginaryI]} *)      First case is fine               a1 = 0.999;     rts = sol[#, a1] & /@ ic;     ParametricPlot[Evaluate[{Re[#[a]], Im[#[a]]} & /@ rts], {a, 0, 0.999}]      ![Mathematica graphics](http://i.stack.imgur.com/wjOBS.png) Second case attempts to go further               a1 = 2;     rts = sol[#, a1] & /@ ic;      NDSolve gets stuck as it attempts to go "round the corner" at -1. Is there a way to get NDSolve to go round the corner? Can I get both solutions going round the corner and choosing opposite directions? (One solution should go towards the origin the other towards infinity.) Thanks for help and suggestions.


How to find the smallest root

I have a continuous, differentiable, monotonic, bounded function called `F[t]`. If `t -> Infinity` then `F[t] -> c`. I know `c`, and I want to find the smallest `t` value called `t*`, that suffices `F[t]=c` (I am sure there is one). Could somebody give me some hints about which functions to use for this task? Since I am afraid that `FindRoot` does not work in this case, because even if I know that there is a given `T` that `T` is smaller than `t*`, starting `FindRoot` from `T` as center won't give me the nearest solution, only a solution somewhere near `T` (Or am I wrong?). And neither does Solve work, because `F[t]` is not injective.


make mathematica recognize CCompiler and compile CUDA code on remote Windows machine

I have set up a _Mathematica_ remote kernel on a Windows 7 64 bit machine, which has Microsoft Visual Studio 2010 installed. When I start _Mathematica_ on the windows machine _Mathematica_ recognizes the C-Compiler without any problems and I can compile code using `Compile` as expected. But when I connect to the same machine via remote kernel, _Mathematica_ does not find any C-Compiler, i.e.               Needs["CCompilerDriver`"]; CCompilers[]      yields only an empty list `{}`. When using _Mathematica_ on the same machine locally the MS C-Compiler is listed when using `CCompilers[]`. How can I make _Mathematica_ recognize my local C-Compilers when connecting via remote kernel connection? Furthermore how can I compile CUDA-Code via the remote kernel connection, see below for the errors I get, when the MS C-Compiler is working? _Additional Information:_ I do connect to the windows machine from a Mac using Wolfram-SSH. I am running Cygwin OpenSSH on the remote windows machine. The setup seems to work fine otherwise. I tested remote connections to computers running Mac OS and Ubuntu Linux and I did not have any trouble with C-Compilers there. **Update (CCompiler working, still no luck with compiling CUDA code):** I have been able to get the MS C-Compiler working by explicitly setting               $CCompiler = {"Name" -> "Visual Studio",        "Compiler" ->         CCompilerDriver`VisualStudioCompiler`VisualStudioCompiler,        "CompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "CompilerName" -> Automatic}      But my next step is to get the NVCC compiler to work in order to be able to compile CUDA code using `CUDAFuncitonLoad`. Unfortunately my intended target `Windows-x86-64`, which corresponds to my `$SystemID` is not recognized as a valid target option any more (it is though when running any nvcc compilation locally on the remote machine). This can be seen by executing the following example code:               cudaString = "__global__ void addTwo(mint * A, mint length) {         int index = threadIdx.x + blockIdx.x*blockDim.x;         if (index < length)             A[index] += 2;     }"          res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"}]     (*CreateExecutable::target: Target system specification "TargetSystemID" -> Windows-x86-64 is not available for NVIDIA CUDA Compiler installation "C:\Users\Wizard\AppData\ Roaming\Mathematica\Paclets\Repository\CUDAResources-Win64-9.0.2.0\CUDAToolkit\bin\*)      Manually adjusting the compiler paths does not help in this case, the following command gives me the same error as mentioned above:               res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"},        "CompilerInstallation" ->         "C:\\Users\\Wizard\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-9.0.2.0\\CUDAToolkit\\bin\\",        "XCompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "TargetSystemID" -> $SystemID]      **Update 2 (Changing`"TargetSystemID"`):** As you can see in the code snippet above `"ShellCommandFunction" -> Print` has been set, but I did not get any output except the error I mentioned above, i.e. > CreateExecutable::target: Target system specification "TargetSystemID" -> > Windows-x86-64 is not available for NVIDIA CUDA Compiler installation > "C:\Users\Wizard\AppData\ > Roaming\Mathematica\Paclets\Repository\CUDAResources- > Win64-9.0.2.0\CUDAToolkit\bin\ When setting the `"TargetSystemID"->"Windows"` (which is the wrong target) in the `CreateExecutable`-call above, mathematica asks for a correct `"XCompilerInstallation"`-path, which is a good sign. When I manually supply the path (as you can see in the call to `CreateExecutable` below) I get more information from the `"ShellCommandFunction"`, which I currently cannot make sense of (except that nvcc seems to be called in the right way):               cudaString = "__global__ void addTwo(mint * A, mint length) {             int index = threadIdx.x + blockIdx.x*blockDim.x;             if (index < length)                 A[index] += 2;         }";          res = CreateExecutable[cudaString, "addTwo", "Compiler" -> NVCCCompiler,        "CreatePTX" -> True, "CompileOptions" -> "-v",        "ShellCommandFunction" -> Print, "TargetDirectory" -> "C:\\temp",        "WorkingDirectory" -> "C:\\temp\\Working",        "Defines" -> {"mint" -> "int"},        "CompilerInstallation" ->         "C:\\Users\\Wizard\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-9.0.2.0\\CUDAToolkit\\bin\\",        "XCompilerInstallation" ->         "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0",        "TargetSystemID" -> "Windows"]      Which gives me the output from the `"ShellCommandFunction"`: > call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" > x86 > > > "C:\Users\Wizard\AppData\Roaming\Mathematica\Paclets\Repository\CUDAResources- > Win64-9.0.2.0\CUDAToolkit\bin\nvcc.exe" -ptx -m32 --compiler-bindir > "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" -arch=sm_10 -O3 > -v -Dmint=int -o "C:\temp\Working\addTwo.ptx" "C:\temp\Working\addTwo.cu" But also the following error messages (which I find confusing, because the path mathematica complains it cannot open is never created): > OpenWrite::noopen: "Cannot open > !(\"C:\\\Windows\\\m-1937a361-0128-49fa-8ead-8640028d2166\")." > General::stream: $Failed is not a string, InputStream[ ], or OutputStream[ > ]. ... and more errors that follow from the initial one


Setting individual CellContext for each notebook loses autocomplete suggestions

I'm running _Mathematica_ 9.0.1 under OS X. In order to have separate contexts for each of my notebooks, I used the instructions in the last part of the accepted answer from the following link: Is there a way to separate variables between multiple notebooks? To quote the relevant part of the answer: > "To set this automatically for all new notebooks, open the Options Inspector > (Ctrl/Command+Shift+O), and change the scope to "Global Preferences." Then, > the option CellContext is found under Cell Options -> Evaluation Options. > Change it to "Notebook." However I've found that after I do this, I lose auto-completion suggestions for symbols that I define in my notebook(s). Is there any way to fix this?


Solving functional equations in Mathematica

I am trying to solve functional equations in _Mathematica_ , but got nowhere. Just a simple example: $$f(x+y)^2=f(x)^2+f(y)^2$$ for all $x,y \in R$, assuming f is a real-valued function. How should I approach this problem in _Mathematica_ ?


Strange NSum behavior

If I do:                NSum[(i + 1)/(i + 2) LegendreP[i, 0] LegendreP[i, 0], {i, 0, Infinity}]      I get:               1.25216      If I do:               Sum[(i + 1)/(i + 2) LegendreP[i, 0] LegendreP[i, 0], {i, 0, 1000}] // N      The result is:               2.40862      This last result is larger than the infinity sum, but the sum terms are all nonnegative. That is not possible. Am I wrong or is Mathematica?


Incorrect information displayed when slider is moved (intermittent)

All, the following code graphs 10 different solutions for a first order ODE and allows the user to modify certain equation parameters to see how the graph is affected:               Manipulate[     (*Find 10 different solutions for the ODE*)     eqn = {a y''[t] == b y[t] + d, y'[0] == c};     sol = DSolve[eqn, {y[t]}, {t}];     func[t_] = y[t] /. sol[[1]];     t[x_] = Table[func[t] /. C[1] -> j, {j, 1, 10}];          (*Display graph*)     Plot[Evaluate[t[x]], {t, -tmax, tmax}],           (*Variables to parameterize*)     {a, 1, 5, 1}, {b, -1, 1, 1}, {c, -10, 10, 1},      {d, 0, 100, 10}, {tmax, 1, 10, 1},          (*Aesthetic labeling stuff*)     Delimiter,     Dynamic[Style[Row[{"Input: ", a , " y''(t) = ",      b, " y(t) + ", d, ", y'(0) = ", c}], 12]],     Delimiter,     Dynamic[Style[Row[{"Output: ", func[t]}], 12]],          (*Misc. Manipulate stuff*)     ContinuousAction -> True, SaveDefinitions -> True,      TrackedSymbols :> {a, b, c, tmax, d}]      The problem that arises is the equation that is displayed after the "Output:" label. If you are patient enough, and move around the sliders (I have been varying parameter d), you will occasionally see the equation display as something like: ![enter image description here](http://i.stack.imgur.com/2S0nx.png) When it should be: ![enter image description here](http://i.stack.imgur.com/CiBs6.png) There are also some funky little things I have noticed like the slider "dragger" in picture 1 is still highlighted even after I release it. Are there any glaring things that I am doing incorrectly that could be causing these symptoms? Is there anyone else that can reproduce the problem? One other thing - I cannot make this problem happen if I use the stepper controls instead of using my mouse to change the value of the slider.


Expectation problem using empirical distribution

I am having trouble with this Mathematica command:                Probability[ x + y + z > 14, {x, y, z} \[Distributed]       ProductDistribution[{DiscreteUniformDistribution[{1, 6}], 3}]]`      outputs 5 / 54. What I would like to do is use the EmpiricalDistribution sort of like this:                Probability[x + y + z > 14, {x, y, z} \[Distributed]      ProductDistribution[{EmpiricalDistribution[{1, 2, 3, 4, 5, 6}], 3}]]      of course, that does not work and just spits out the command. How can I get the Empirical Distribution to work like that?


Numerical sum does not give consistent results

Consider the function               λ[n_] = Sqrt[2 n];     ϕ[n_, x_] = 1/Sqrt[2^n n! Sqrt[π]] HermiteH[n, x];     f[x_] = Sum[2 Re[(-1)^(n + m) (1/(λ[m] + λ[n + 1]) + 1/(λ[n] + λ[m + 1]))                 If[n != m, 1, 1/2]] ϕ[n, x] ϕ[m, x] E^-x^2, {n, 0, 100}, {m, n, 100}];      Why is               f[-4.0] == 4.9697      while               f[-4] // N == 1.07681      ? The second result is correct as you can check by using `SetDelayed` in the definition of `f`. This discrepancy has to do with approximations. It would be good to fix it, since computations are faster if the function is defined with `Set`. I would also appreciate suggestions to evaluate this sum more efficiently. Thank you!


Is it possible to verify the accuracy of a file downloaded using URLFetch

**Objective:** I am trying to save a HTML file using the **URLFetch** function (native to Mathematica 9 onward). Sometimes the file is huge. **Question:** Is there a way to check/verify (using the headers or other parameters native to URLFetch) that the **COMPLETE PAGE HAS BEEN DOWNLOADED** , i.e. the page was not partially downloaded? Is there a protocol say like MD5 for file downloads, which allows one to confirm that the HTML file's contents were completely downloaded? (or can I be _assured_ that URLFetch returns/transfers control **ONLY** after the COMPLETE page has been fetched?) **Related questions** :   * IF the download was partial (not complete), will the "STATUS" (from the URLFetch) still be 200 ?   * Can this be solved using **Import** function


How to increase the number of minor ticks in a plot?

I want to increase the number of minor ticks in a plot, but I don't want to label them. I searched through this site and also _Mathematica_ documentation, but I didn't find any solution yet. Could anyone please tell me how to do this. For an example:               Plot[2*Sin[x], {x, 0, 10}, Frame -> True,       FrameTicks -> {True, True, False, False}, Axes -> True,       AxesOrigin -> {0, 0}]      I want to get 10 minor tick marks in between 0 and 1 and so on (in between major tick marks on both axis). ![Here is the output plot](http://i.stack.imgur.com/C4jSZ.png)


Conditional break point in Wolfram Workbench?

Is it possible to set up a conditional break point in Wolfram Workbench? For example I want the code to stop if an index `i` is equal to a given value.


Solving an ODE with parameters and conditions

I am trying to use Mathematica to solve a relatively simple ODE involving parameter(s). I would like to use a set of conditions to solve for the particular solution of the ODE. I understand how to make Mathematica find values for the constants that arise during the process of solving the ODE, but what about solving for constants/coefficients already present in the original ODE? Here is a simple example involving Newton's Law of Cooling... ![enter image description here](http://i.stack.imgur.com/rivKO.jpg) Here is the code I tried:                  DSolve[          {           T'[t] == -k*(T[t] - Ta),           T[0] == 70,           T[1/2] == 110,           T[1] == 145           },          {T[t], t, k},          {t}          ]      I feel like I need a two step process... first solve the ODE with the parameters, and then solve for the parameters afterwards. I'm just not sure where to start. Thank you in advance!


Making data persistent, as in xmgrace

I've been using xmgrace for quite a long time as my favorite solution for scientific data manipulation and plotting. These data often come from home- made fortran programs, in the form of, e.g., a formatted file with `x y z f` columns. I discovered that Mathematica (v9 here) is quite remarkable for this purpose. In xmgrace, the data you are plotting is stored (made persistent) in the xmgrace file itself (file.agr), which is very convenient because sharing the xmgrace file both shares the plot and the data being plotted. Is it possible to make the data stored inside the Mathematica (.nb) file? Note: the answer should be compatible with any quantity of data. For illustration purpose, my xmgrace file can exceed 500 MB.


Label area on plot

I created the following plot using _Mathematica_ : ![Mathematica plot](http://i.stack.imgur.com/JzMQy.png)               (* defining functions *)     msp[h_, a_, b_, c_] :=         Piecewise[{{c + b*(1.5*h/a - 0.5*(h/a)^3), h <= a}, {0, h == 0}}, b + c];     mex[h_, a_, b_, c_] := Piecewise[{{c + b*(1 - Exp[(-3*h)/a]), h != 0}}, 0];     mga[h_, a_, b_, c_] := Piecewise[{{c + b*(1 - Exp[(-(3*h)^2)/a^2]), 0 < h}}, 0];          (* plot *)     Show[Plot[{msp[x, 2, 3, 1], mex[x, 2, 3, 1], mga[x, 2, 3, 1]}, {x, 0, 2.5},        PlotRange -> {{0, 2.5}, {0, 5}}], ImageSize -> {500, 400}]      I would like to mark the y axis from 0 to 1 and the x axis from 0 to 2 using curly braces like it is done here (E(x)): ![Example](http://i.stack.imgur.com/O5Nq2.png) Is it possible to do this with _Mathematica_?


How to substitute the Skip function in special cases?

filedata={"    1       2578Hot Pink            47:21:17  9512971  ",               "    2        294Pale Green          24:57:18  4437289  ",               "    3       2497Light Yellow        39:40:57  4987642  ",               "    4       2010Turquoise           16:04:17  3290855  "}      There is an external file.   You open a Stream.   You Skip to a far postion.   It takes a long time for a large file.   How can one conceive a more direct method for a special   straightforward highly regular file structure like this?   We got an index and know the file size anyway.   A low level file function approach? * * * ## **Update** Records in file: 100.000.000   Set StreamPosition to: 60.000.000   Time needed: 40 seconds That is: Skip and SetStreamPosition takes the same chunk of time.


Value of $BaseDirectory within Ant script?

I'm using an ant script to install my application from the Workbench (as suggested in this answer). In past I've used two ways of specifying the destination for the build:   1. Hard-coded directory, like `/Users/me/Library/Mathematica/Applications`. This would be fine for a single computer, but I store the code in a versioning system, and access it from computers having different filesystems (e.g., MacOSX laptop, linux desktop). It is inconvenient to change the ant build file for each build.   2. Setting an environment variable on each computer (`$MMA_APP_DIR`, say) and using `<property environment="env"/>` within ant to get that variable using `${env.MMA_APP_DIR}`. Much better than option #1, since I don't have to change the code itself, but still an inconvenience. _Mathematica_ 's, `$BaseDirectory` and `$UserBaseDirectory` are the destinations I'm after. **How can I access the values of these variables from the ant script?** They are built into the Workbench framework, showing up as destination folders when using the Application View to export to an archive or to a folder. I've yet to discover how to access them.


Accessing data on local machine from remote kernel

I have a remote kernel on a server that I would like to use to process some data. The connection works, i.e, I'm able to use the local front end and the remote kernel. However, I cannot figure out how should I access from the remote kernel the data that are on my local machine. I thought I could simply use `Import` with the path to my computer and to the file that I want to import, but I didn't succeed. Something like:               Import["computerName@ip_address:/Users/myUserName/Desktop/data.txt","Table"]      > Import::nffil: File not found during Import. >>


Overlay : zoom, graphic tools, get coordinates save as etc

I used Jens' legendmaker to `Overlay` graphics to get a nice legend on my `ListPlot`. My question is if is there any way to make the output from `Overlay` behave like output from `ListPlot` in terms of the ability to zoom in to investigate, get co-ordinates, drawing tools, ability to right click on the graphic itself and save high resolution graphic as a host of things etc? I was able to right click the cell and save selection as a very low resolution jpeg. Thanks, **EDIT:**               boundaryplot = ListPlot[{H0SPlot, H0DPlot},PlotRange -> Full]     opts = Sequence[Background -> LightOrange, RoundingRadius -> 10];     labels = {"H0S", "H0D"}     Overlay[{boundaryplot, legendMaker[labels, opts]}, All, 1,Alignment -> {0.5, 0.5}]      While the `Overlay` options enable me to zoom in etc, when I right click on the image to `save graphic as` , I tried jpeg and pdf, it only saves the `ListPlot` and not the `Legend`. When I right click on the cell itself and use `save selection as` then I am able to save as jpeg something lower-res that also includes the legend.


Using Physical Constants in V9

How is one supposed to work with physical constants in _Mathematica_ V9? When I first open _Mathematica_ , physical constants such as `SpeedOfLight` are not recognized. If I load the PhysicalConstants package using:               << PhysicalConstants`      I get the following error message: > General::obspkg: "!(\"PhysicalConstants`\") is now obsolete. The legacy > version being loaded may conflict with current Mathematica functionality. " However, at this point `SpeedOfLight` is properly defined!


Computing the equivalence classes of the symmetric transitive closure of a relation

I have a list of pairs, for example:               pairs={{13, 10}, {12, 14}, {10, 36}, {35, 11}, {3, 5}, {1, 6},     {20, 24}, {21, 22}, {33, 7}, {31, 8}, {31, 27}, {32, 25},      {21, 35}, {34, 19}, {18, 15}, {14, 16}, {9, 5}, {4, 7},      {1, 13}, {15, 2}, {6, 36}, {4, 34}, {8, 2}, {9, 3}, {25, 20},     {19, 26}, {22, 11}, {23, 12}, {32, 28}, {30, 33}, {23, 16},     {24, 17}, {29, 27}, {26, 30}, {17, 28}, {18, 29}};      `pairs` can be seen as the definition of a relation $R$. $x$ and $y$ satisfy the relation if and only if `{x,y}` $\in$ `pairs`. I need to compute the equivalence classes of the symmetric transitive closure of $R$. In other words, I need to compute a list `eqvclss`. The elements of `eqvclss` are lists themselves. For example, 13, 10, 36, 6, 1, ... should all be in the same list in `eqvclss`. (If you understand that, then I explained the question properly; if you don't, say so in the comments so I can try to improve).


Assuming monotonicity and concavity

I have an expression that I would like to evaluate:               2 phi''[1 + a (-1 + u[10])] phi'[q]^3 > phi''[q] phi'[q] phi'[1 + a (-1 + u[10])]^2      Is there any way of telling Mathematica that the function `phi` is strictly increasing and convex?


Predictive code completion and custom functions in contexts

Suppose I work for organisation PQR, and have been developing a suite of packages, `PQRUtilities`, `PQRVisualization` etc, all of which are neatly arranged in a context `PQR`. They can all then be loaded with a single package call `Get["PQR`"]`. The only content of the PQR package is               BeginPackage["PQR`" ,{"PQR`PQRVisualization`","PQR`PQRUtilities`"}]     (* Exported symbols added here with SymbolName::usage - but nothing here *)         Begin["`Private`"]     (* Implementation of the package - nothing here either*)       End[]         EndPackage[]      I have noticed that if I call the subsidiary packages directly with `Get["PQR`PQRVisualization``"]` or the `Needs` equivalent, I get predictive code completion pop-ups including my custom functions. However, if I just call `Get["PQR`"]`, my functions are loaded but I do not get the nice predictive code completion. Ultimately all these packages will be put in the `Autoload` part of the path, so maybe this doesn't matter. I would like to be able to provide the simpler way to load all the custom packages I've developed, and still enjoy the benefits of the code-completion suggestions. Some of my function names are quite long, e.g. `PQRScatterGraph`. Is there a way I can get functions from packages loaded in this way to be visible to the code completion functionality?


why set values in this way doesn't work?

question is as follows define a list               ttt={1,2};      and if I set values in this way               {ttt[[1]],ttt[[2]]}={3,4}      then the value of list ttt now becomes {3,4} Now I try this               f:={ttt[[1]],ttt[[2]]}      then `?f` will show that `f:={tmp[[1]],tmp[[2]]}` then if I just write               f={3,4}      this will not affect the values of list ttt . **the question is that I want the values of list ttt changes as well when I set values to f. How to do this?** * * * **More Question!!** why the following code didn't change the value of ttt??               Table[With[{i = i}, Defer@ttt[[i]]], {i, 1, 2}] = {111, 222}      while               Table[With[{i = i}, Defer@ttt[[i]]], {i, 1, 2}]      really gives               {ttt[[1]],ttt[[2]]}


how do I can create a list of the first interval such as [-10+Sin [k], 10+Sin [K]]

A (k) =the closed interval [-10+Sin [k], 10+Sin [k]] How do I can create a list of the first 20 of such interval The find the intersection of the first 14 of them


How to set the working precision globally? $MinPrecision does not work

I want to increase the precision globally to `50` at least, but `$MinPrecision` does not work.               $MinPrecision = 50;     x = Sin[2.]     (* -> 0.909297 *)          Precision[x]     (* -> MachinePrecision *)      How to set the working precision globally, i.e., make all the calculations in the notebook use the new precision?


Constrain plot points to below a certain line

I have a set of curves that take on large values when approaching 1. I'm trying to create a straight line with certain slope and then truncate the plot for any curve that goes above that line for any value of x. This is my current code:               lm := Sqrt[M^2 - 1]     C1 := 2/lm     C2 := ((1.4 + 1)*M^4 - 4 M^2 + 4)/(2*lm^4)                pr1[o_, M_] := (C1*(o*Pi/180) + C2*(o*Pi/180)^2)*1.4*M^2/2 + 1;          Plot[Table[pr1[o, M], {o, {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}}] // Release, {M, 1, 3},         AxesOrigin -> {1, 0}]      ![enter image description here](http://i.stack.imgur.com/OmLbV.png)


Reduce can't reduce an equation without appropriate assumptions

When there are three unknowns (`x`, `y`, `z`), _Mathematica_ can solve it:               Reduce[ Abs[x] + Abs[y] + Abs[z] == 1 && z != 0, {x, y, z},              Reals, Backsubstitution -> True]      for four variables (`x`, `y`, `z`, `t`), _Mathematica_ can't return a result in reasonable time:               Reduce[ Abs[x] + Abs[y] + Abs[z] + Abs[t] == 1 && t != 0, {x, y, z, t},              Reals, Backsubstitution -> True]      _Maple_ can solve this quickly: ![enter image description here](http://i.stack.imgur.com/GCcZk.png) Is it possible to solve this with _Mathematica_?


Plotting Fresnel function

I am trying to plot the partial sums and the cesaro means of the function $\sqrt{|x|}$ and for $a_{n}$, I obtained the following code which contains FresnelS.               (-((Sqrt[2] FresnelS[Sqrt[2] Sqrt[n]])/n^(3/2)) - (Sqrt[2] FresnelS[Sqrt[2] Sqrt[Abs[n]]])/Abs[n]^(3/2) + (2 Sin[n \[Pi]])/n + (2 Sin[\[Pi] Abs[n]])/Abs[n])/(2 Sqrt[\[Pi]])      Now my question is is it possible to graph such function using Mathematica? I have tried many examples using trial and error and some of the my examples also contain BesselJ which can't be graph. Hence I would like to know if it is true that if there is BesselJ and FresnelS in the code, then the graph cannot be drawn using Mathematica. Please correct me if I am wrong. I am graphing out its graph using this code:               f[x_] := Sqrt[Abs[Mod[x, 2 Pi, -Pi]]];     s[k_, x_] := ???     partialsums[x_] = Table[s[n, x], {n, {4}}];      c[n_, x_] := (1/n) Sum[s[m, x], {m, 0, n - 1}]     Plot[Evaluate[{f[x], partialsums[x], c[{4}, x]}], {x, -Pi, Pi},     PlotLegends -> {"f(x)=x", "Fourier, 4 terms", "Cesaro, 4 terms"},      PlotStyle -> {{Blue}, {Dashed, Thickness[0.006]}, {Red,Thickness[0.006]}}]


Operate on several lists to create one list

How do you put corresponding values from different lists together according to some operation? E.g. I have three lists giving the velocity in the x, y and z direction respectively. I'd like create one list giving the 2-norm, $\sqrt{x^2+y^2+z^2}$. I would be able to do it procedurally by using for example MapIndexed on one of the lists toghether with Part, I suppose. But I'd like to know if there is a more elegant solution.


ReadList problem related to Record type

A simple file reading issue is baffling me here. I am reading a around **200 MB** textual file in `.dat` format. Now the file contains **many lines** but to phrase my problem I am taking here first two lines from the example file.               str = "Tue 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0.\nTue 2 Jan 2013 2 : 20 : 01; 47; {3,4}; 3.5; 110.";      Now I want to use `;` and newline `\n` as my `RecordSeparators` and it works as expected.               ReadList[StringToStream[str],{Record, Record, Record, Record, Record},     RecordSeparators -> {"\n", ";"}]      > {{Tue 1 Jan 2013 23 : 00 : 01, 17, {}, 32.5, 0.},{Tue 2 Jan 2013 2 : 20 : > 01, 47, {3,4}, 3.5, 110.}} But if I want to specify the `Type` of each separate `Record` using for example `{String, Number, Expression, Number, number}` above code fails to work. The error is the following. > Read::readn: Invalid real number found when reading from StringToStream[Tue > 1 Jan 2013 23 : 00 : 01; 17; {}; 32.5; 0. Tue 2 Jan 2013 2 : 20 : 01; 47; > {3,4}; 3.5; 110.]. >> Is this problem solvable or I need to change the formatting of my input .dat file in a way so that it works with `ReadList`? PS: If I need to change the file format what will be best separator to use in this context?