title: How to plot multiple curve in a same plot with Manipulate

text: The manipulate function in _Mathematica_ allows the users to adjust the values of the parameters in a graphical way. How do I plot multiple functions in a same graph and also I can use manipulate at the same time?               Manipulate[      Row[{        Plot[f1(x+n)], {x,           0.0001, 1}, PlotRange -> {-10, 10}],        Plot[f2(x+n)], {x,           0.0001, 1}, PlotRange -> {-10, 10}]}],        {n, 1, 10}]      with give two independent plots with single curve in each. How should I do multiple curve in a **same plot?**


title: Inserting points along a linear interval between adjacent coordinates in an array

text: Say I have a list of coordinates in an array               {{0, 0}, {0, 1}, {1, 1}}      I'd like to create a new array where, between each pair of nearest-neighbor coordinates in the previous array, I place $k$ points equispaced on a linear interval between the points. For example, with $k = 3$ we would generate the array: > >     {{0, 0}, {0, 0.25}, {0, 0.5}, {0, 0.75}, {0, 1}, >        {0.25, 1}, {0.5, 1}, {0.75, 1}, {1, 1}} >   Is there a nice one-liner for doing this?


title: Intersection of Osculating Circle with a Parametric Curve

text: I have the following Parametric plot ![enter image description here](http://i.stack.imgur.com/hKVs2.jpg) Generated from the following:               Manipulate[      ParametricPlot[{(A*Cos[t]^2 + B)*{Cos[t], Sin[t]},         C*{Cos[t] + 1, Sin[t]}}, {t, 0, 2*Pi},        PlotRange -> {{-5, 5}, {-5, 5}}], {A, 1, 10}, {B, 1, 10}, {C, 1,        10}]      I would like to find the exact values of $C$ and $t$ such that the inner circle, with one point fixed to the origin is tangent to the outer curve. This would mean, if I'm not mistaken, for $t\in\left[0,\pi/2\right]$, solving the following system of equations for $t$ and $C$               x1 = (A*Cos[t]^2 + B)*Cos[t]     y1 = (A*Cos[t]^2 + B)*Sin[t]     x2 = C*(Cos[t] + 1)     y2 = C*Sin[t]     x1 == x2     y1 == y2      i.e. find the intersection of the curves, but also they should have the same tangent, so we have:               D[y1,t]/D[x1,t] == D[y2,t]/D[x2,t]      But, for some reason I can't find a solution. What am I doing wrong?


title: Sporadic bug in Mathematica 7.01.0 MatrixPower and/or Eigensystem functions on floating-point symmetric matrices with repeated eigenvalues

text: **Note: From the comments submitted below by other StackExchange users it appears that this apparent bug was fixed sometime after version 7.0.1.** I asked a vague variant of this question a few days ago, but now I will give a concrete example. Floating point matrices with repeated eigenvalues often arise as the solutions to optimization problems. The _Mathematica_ functions `MatrixPower` and `Eigensystem` appear to have sporadic difficulty dealing with such matrices. (It is not clear to me whether this is because of numerical instability when trying to determine whether such matrices have nontrivial Jordan blocks, or if there is some other problem.) I have had to write my own routines for matrix power (and more generally for the functional calculus) to handle such cases, but maybe someone knows a quick fix. In the notebook http://tinyurl.com/lhodpdv I generated the following matrix by random search: (I'm using Mathematica 7.0.1 on 32-bit Windows)                {{0.461964, -0.314388, -0.138647, -2.23115*10^-6},       {-0.314388, 0.510134, -0.128432, -2.06676*10^-6},       {-0.138647, -0.128432, 0.744719, -9.11454*10^-7},      {-2.23115*10^-6, -2.06676*10^-6, -9.11454*10^-7, 0.801359}}      This matrix was defined by taking the average of a matrix and its transpose, so it is exactly self-adjoint. (I searched for it by finding rare matrices for which my usual code for inverting the `Eigensystem` function acting on a Hermitian matrix failed.) The list of eigenvalues               {0.801359, 0.801359, 0.801359, 0.1141}      has three repeated elements. All eigenvalues are positive, so _Mathematica_ should have no trouble computing the unique positive semidefinite square root of this matrix. However, using `MatrixPower[%, 1/2]`, _Mathematica_ reports that the square root is               {0.690223, -0.170008, -0.477225, 0.},     {-0.189862, 0.737704, -0.442063, 0.},     {-0.0837305, -0.0694507, 0.700234, 0.},     {-1.34742*10^-6, -1.11762*10^-6, -3.13724*10^-6, 0.895186}      This matrix **is not even symmetric**. Much worse, _Mathematica_ computes the matrix product               (square root).(square root)       as               {{0.548644, -0.209616, -0.588406, 0.},      {-0.234095, 0.607187, -0.545053, 0.},      {-0.103238, -0.0856309, 0.560987, 0.},      {-1.66133*10^-6, -1.37799*10^-6, -3.86814*10^-6, 0.801359}},      which is nowhere near the original matrix:               {{0.461964, -0.314388, -0.138647, -2.23115*10^-6},      {-0.314388, 0.510134, -0.128432, -2.06676*10^-6},      {-0.138647, -0.128432, 0.744719, -9.11454*10^-7},      {-2.23115*10^-6, -2.06676*10^-6, -9.11454*10^-7, 0.801359}}


title: Optimization for complex inequalities

text: I want to check when the expression $$ \sqrt{\sqrt{\lambda^{2}\left(2E+\lambda^{2}\right)}+E+\lambda^{2}} $$ is real, when it is purely imaginary and when it is complex (with imaginary part not zero). Also I would like to know the sign of the imaginary part in the case it is non-zero. To check the last part, after some steps, I am using `Reduce` for inequalities like $\mathrm{Im}\left(\sqrt{\lambda^{2}\left(2E+\lambda^{2}\right)}\right)>0 $ but this is taking a lot of time on _Mathematica_. Is there a way to get the kind of results that I want more quickly? The variables are real and the code I ran is                 Reduce[ Im[ Sqrt[ e + λ^2  -Sqrt[ λ^2 (2 e + λ^2)]]] > 0, {e, λ}]


title: NIntegrate extremely piecewised functions

text: I often need to integrate extremely piecewised functions, like the following one (not extreme, but gives an idea):               q[time_?NumericQ] :=       Module[{q1 = 0.7, d1 = 600, p1 = 2700, ph1 = 0, q2 = 0.37, d2 = 870.,         p2 = 5000, ph2 = 0},       If[Mod[time, p1] > ph1 && Mod[time, p1] < ph1 + d1, q1, 0] +         If[Mod[time, p2] > ph2 && Mod[time, p2] < ph2 + d2, q2, 0]]      ![enter image description here](http://i.stack.imgur.com/3iWtV.gif) I know that I can list all the mandatory points in the NIntegrate interval `List`. But most of the time I don't know them. Running `NIntegrate`generally returns singularity, accuracy, etc, type of errors.               NIntegrate[q[t], {t, 0, 7*24*3600}]      I can play around with `WorkingPrecision`, `MaximumRecursion`, etc, but it is not that easy to arrive to something that returns no errors, or that runs in a reasonable time. I generally end up running something like:               NIntegrateBis[funct_, list_] :=       Module[{step = 0.1, time = list[[1]], int = 0},        While[time < list[[2]], int = int + funct[time]*step;         time = time + step]; int]          NIntegrateBis[q, {0, 10000}]      Simple and with no messages... but no error control, no variable step, etc (it can even overpass the boundaries, although it is easy to correct that part...) What is the best strategy to integrate my functions? Use `NIntegrate` with a specific set of options (that I don't know of)? Built a personal `NIntegrate`? PS - I'm running optimization simulations with those functions, and so, I need it to run pretty fast.


title: Trigonometry expansion of a product

text: The following command does what I want:               TrigExpand[ Cos[a + b]^2]          (* 1/2 + 1/2 Cos[a]^2 Cos[b]^2 - 1/2 Cos[b]^2 Sin[a]^2 -         2 Cos[a] Cos[b] Sin[a] Sin[b] - 1/2 Cos[a]^2 Sin[b]^2 +         1/2 Sin[a]^2 Sin[b]^2 *)      Unfortunately, it does not apply the distributive property of the product in another case, that is the one I am interested in:               TrigExpand[ Cos[c*(a + b)]^2]          (*  Cos[c*(a + b)]^2  *)      How can I tell _Mathematica_ to do that initial step?


title: Variable scope in nested NMaximize, NMaxValue

text: I'm trying to use NMaxValue inside other statements (FindRoot and NMinimize). Those statements should bind variable names, but I'm getting weird warnings which seem to indicate that the variables aren't bound inside the constraints of the NMaxValue statement? Minimal example:               NMinimize[{NMaxValue[{f[x,y],1<x<y},x],1<y},y]          NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     NMaxValue::bcons: The following constraints are not valid: {1<x,x<y}. Constraints should be equalities, inequalities, or domain specifications involving the variables.     General::stop: "Further output of NMaxValue::bcons will be suppressed during this calculation."      Why are these constraints not valid? y should be in-scope because it's defined by NMinimize, right? Is this a bug?


title: Optimization problem with matrix positivity constraints

text: Is it possible for _Mathematica_ to parametrically find a local minimum of a given function (say of some variable $x$ where $(a,b,c)$ serve as parameters) subject to the constraint that a given symmetric matrix is positive semi- definite? The entries of the matrix are monomials of $(x,a,b,c)$. Namely, the function is: \begin{equation} f(q)=\log\bigg[\frac{(1-q)(1-r^2t^2)(1-x)}{1-q-t^2+qr^2t^2-x+2t\sqrt{qx}-r^2(1-x-t^2+xt^2-xt^4+2t^3\sqrt{qx})}\bigg] \end{equation} (where the logarithm is taken to the base of 2)                      f=Log2[((-1+q)(1-r^2*t^2)(1-x))/(-1+q+t^2-qr^2*t^2+x-2*t*Sqrt[qx]-r^2(-1+t^2+x-t^2*x+t^4*x-2*t^3*Sqrt[q*x]))]      and the matrix is: \begin{equation} S=\left( \begin{array}{cccc} \frac{1}{r^2} & 1 & 1 & t\sqrt{x}\\\ 1 & \frac{1}{t^2} & 1 & \frac{\sqrt{x}}{t}\\\ 1 & 1 & 1 & \sqrt{q} \\\ t\sqrt{x} & \frac{\sqrt{x}}{t} & \sqrt{q} & 1 \end{array} \right). \end{equation}               S={{1/r^2, 1, 1, t Sqrt[x]}, {1, 1/t^2, 1, Sqrt[x]/t},         {1, 1, 1, Sqrt[q]}, {t Sqrt[x], Sqrt[x]/t, Sqrt[q], 1}};      the parameters $(x,r,t)$ are arbitrary value in $(0,1]$, which is also the domain of the variable $q$. Thus I need to find the minimum of $f(q)$ subject to $S\succeq0$ (in the sense of positive semi-definiteness) and $q\geq0$. I have no clue how to do it. I've tried using the `FindMimimum`command but didn't manage to make it work.   If is it indeed possible, it would very much help me to know how to formulate such a command. Thanks!


title: How can we ensure the result of Mathematica is exactly correct?

text: This is an example, I plot a function and find it has a defect when x approximates 400.               Plot[Cos[.3 x] Exp[-0.01 x], {x, 0, 1000}, PlotRange -> All]      ![Mathematica graphics](http://i.stack.imgur.com/d9OvW.png) Another example, we calculate the orbit of planet motion. As we know, the orbit of planet is ellipse when the total energy is negative. However, if we calculate it in a long time, the result will deviate from ellipse markedly - while _Mathematica_ has no any warning or message here! The code and result showed below:               M = 4; a = 700; (*a is the total time of this simulation*)     s =          NDSolve[{x''[t] == -((GM (x[t] + 1))/((x[t] + 1)^2 + y[t]^2)^1.5),                   y''[t] == -((GM y[t])/((x[t] + 1)^2 + y[t]^2)^1.5), y[0] == 2,                   x[0] == .3, x'[0] == .2, y'[0] == -.1}, {x, y}, {t, 0, a},                   MaxSteps -> 10^8];     ParametricPlot[Evaluate[{x[t], y[t]} /. s], {t, 0, a}]      ![enter image description here](http://i.stack.imgur.com/d2uOL.png) What I wonder is how to make sure _Mathematica_ 's result is exactly correct? When we find something special with _Mathematica_ , how can we know it is a new thing, or just a wrong result of _Mathematica_?


title: CPU usage remains at 13% even after I quit the kernel

text: I use _Mathematica_ 10.0.0, and after I run it for a while (a few simple commands for example) the CPU usage (Mathematica.exe) remains at 13% even after the calculations are over. I quit the kernel but the program continues to consume resources until I close the program entirely. Is it a bug? How can I suppress such behavior?


title: Non-convergance of the solution of the 1+1 partial differential equation

text: I am stacked with a partial differential equation as follows: This is the $\LaTeX$ expression for the equation $$ \frac{\partial y}{\partial t}=\frac{\partial^2 y(x,t)}{\partial x^2} -\left(a-\frac{1}{\cosh ^2(x)}\right) y(x,t)-y^3(x,t) $$ The _Mathematica_ code is here. This is the equation with with $a=0.2$ to be specific:               eq = D[y[x, t], t] ==         D[y[x, t], {x, 2}] - 0.2 *y[x, t] + Cosh[x]^-2*y[x, t] - y[x, t]^3;      and here are the boundary and initial conditions:               bc1 = y[-10, t] == 0;     bc2 = y[10, t] == 0;     ic = y[x, 0] == 0.001*(Exp[-x^2] - Exp[-10^2]);      Here I solve and plot it:               s = NDSolve[{eq, bc1, bc2, ic}, y[x, t], {x, -10, 10}, {t, 0, 20},         PrecisionGoal -> 2];          Plot[Evaluate[y[x, t] /. s /. t -> 20], {x, -10, 10},       AxesLabel -> {Style["x", 16, Italic], Style["y(t=20)", 16, Italic]}]      The result looks like this: ![enter image description here](http://i.stack.imgur.com/zFbkM.jpg) and qualitatively it is what I expect. It should be explained here that this equation has a fixed point. Depending upon the parameter $a$ it may be either $y=0$, or a solution like the one shown in the image above. I am only interested in the system behavior in the fixed point. Intermediate steps are of no interest. For this reason I plot the result at $t=20$, expecting that the solution is already close enough to the fixed point. Let us check the conversion of the obtained solution. The simplest way to do that is to look at the evolution of $y(0,t)$. Here it is: ![enter image description here](http://i.stack.imgur.com/DMi1N.jpg) The conclusion is that what we see is, so far, non-converging. I checked up to $t=200$ with the output of the same type showing non-convergence. It seems to be so for any time duration. However, I solved the same equation with Comsol, and there it nicely converges after only a small number of time steps (five or so). For technical reasons I would, nevertheless, prefer it solved with _Mathematica_ , rather than with whatever else. My question: do you see any workaround?


title: How to export data from excel specific cells into mathematica?

text: How to export data from excel specific cells into _Mathematica_? Given that the spreadsheet tab is named XYZ and that I have several cells at various locations in the same column in Excel that I want to export?


title: Just what kind of transformations can TransformedDistribution handle?

text: Why does the following command return an empty plot?               Plot[PDF[TransformedDistribution[(2 Z - 1) X,      {Distributed[X, ExponentialDistribution[1]],      Distributed[Z, BernoulliDistribution[0.5]]}], t], {t, -1, 1}]      Yet `RandomVariate` works just fine:               SmoothHistogram@RandomVariate[TransformedDistribution[(2 Z - 1) Abs[X],      {Distributed[X, ExponentialDistribution[1]],      Distributed[Z, BernoulliDistribution[0.5]]}], 1.*^5]      I merely give a particular example; don't focus unduly on it, I want to generalize.


title: How do I save a variable or function definition to a file?

text: Is it possible to save a function which was created via `Interpolation` of some data in such a way that I can use this function in a new _Mathematica_ session without repeated interpolation of the data? For example, I have some data which I interpolate in the following way:               exampleData={{1,1},{2,3},{3,4},{4,7},{5,5},{6,4},{7,2}};     interPolFunc[x_]:=Interpolation[exampleData,x]      Now one of the following would be nice:   * a way to save the interpolated function so that it can be used the next time when I work with _Mathematica_ (but I do not want to interpolate the data again, so that I can delete them).   * the data and `Interpolation` command are saved in a separated notebook which is executed when I want to use my `interPolFunc` in another notebook. Unfortunately I did not find any solution for that. But I hope that some of you have several suggestions!


title: How to save a list of analytic expressions in a file?

text: I use _Mathematica_ to calculate many analytic expressions, some of them are generated by a loop process, the result can be a vector with a index, e.g., `f[i]`. Now I want to save them in a file, for example _Mathematica_ package file `"result.m"`, and other expression may also want to be added into this file. The file should looks like this:               f[1] = ;     f[2] = ;     ...     f[10] = ;          fsum = ;     gxyz = ;      This should be a simple task, but I can't figure out the solution. Does anyone know how it can be done?


title: Import/Export Cluster Object

text: I want to export and then import back in a cluster object from Agglomerate. After the import, the imported object does not behave as a cluster - for example, ClusterSplit does not recognize it as a cluster object. Is there a data format that can be used, so that after export/import the imported object is a cluster?


title: Save and call matrices with large output in Mathematica

text: If we have the large matrix               A=RandomReal[{-10, 10}, {1000, 1000}];      and I need it for further calculation, how can I save it on hard disk and then call for further calculation? Output is very large and _Mathematica_ can not present it, so I can not copy/paste it? Is it possible to print it and then call from hard disk? Thank you in advance!


title: How to export/import function values

text: I have a function with two variables:               f[x_,y_]:=f[x,y] = ...      I calculated some values (they are fractions like 435345345/3424242424) and would like to store the values from x=1 to x=5000 with y=0 in a file, so that I can use them later again in a function g[x] I exported them:               Export["file.dat", Table[f[x,0],{x,1,5000}]      And then I import them in another file:               data = Import["file.dat", "List"]      Now I can access the fractions in data by using, for example:               ToExpression[data[[7]]]      Which gives me the fraction that was originally stored in f[7,0] So far so good, but I would again like to have the values stored in some function g, with the properties that (in new file) g[x] = f[x,0] (in old file) for x between 1 and 5000 I am not really sure how the notation for that would be :-( Thank you for your help.


title: How to store a SparseArray?

text: How to Export/Write a SparseArray?   How to Import/Read a SparseArray?   Is it always stored as a normal array?   How can it be stored in a dense form?   Is a numerical SparseArray different to   Export/Import from a string one?


title: How can I append Mathematica variables to an output file preserving both names and values?

text: I have a _Mathematica_ program that calculates a series of large vectors that I need to save for future reference (in addition to some scalar values). I want to save all these to a file, tagged by their _Mathematica_ names, as the calculation proceeds. `PutAppend` will not work because only the data values are stored, losing their associated names. `DumpSave` does not seem to append to the file, while it does store the values with their names. My goal is to be able to load back the expressions later for further analysis, with the names I gave them. I'm sure this is simple, but I have no experience with _Mathematica_ I/O and can't find what I need in the help.


title: Exporting large expression

text: I generated a huge mathematical expression (~200k terms, impossible to simplify yet) and want to save it for later analysis. Last time I did `Export` to *.nb file and it froze my whole system so I was forced to kill the kernel and generate it again from scratch. How should I do it correctly and then `Import` it back easily?


title: Transferring a list from one notebook to another

text: I have _Mathematica_ code split into two notebooks. The first part is supposed to run and output a list of numbers into a text file, using `Export`. The second part uses `ReadList` to read numbers from the text file, into a list. I don't like having to convert the list into text and then convert it back to a list. Is there any other way of exporting data which might make it faster for _Mathematica_ to import it again as a list? Edit: Suppose the list output from the second notebook has variables and numbers, is storing the result in a text file still ok? For such a case, here is an example of the output list (the way it looks on the text file):               {1}     {75 + 2*Subscript[x, 10] + Subscript[x, 11]}     {-201 - 4*Subscript[x, 10] - 3*Subscript[x, 11] + Subscript[x, 12]}     {157 + 2*Subscript[x, 10] + 3*Subscript[x, 11] - 3*Subscript[x, 12] + Subscript[x, 13]}     {-Subscript[x, 11] + 3*Subscript[x, 12] - 3*Subscript[x, 13] + 10*Subscript[x, 14]}     {-Subscript[x, 12] + 3*Subscript[x, 13] - 12*Subscript[x, 14]}     {-Subscript[x, 13] + 2*Subscript[x, 14]}      If I need to store expressions, which output format is more apt ?


title: Exporting arrays for storage

text: I have a set of arrays I would like to output to some file `ArrayStorage.txt` s.t. these arrays could be read-in to a separate notebook on a separate kernel. Is there an easy way to export a set of arrays?


title: WaveletScalogram in polar coordinates

text: For given dataset               data = Re[Zeta[1/2 + I Range[0, 100, 0.01]]];      It is nice that Mathematica can plot data in both Cartesian and Polar coordinates.               SetOptions[ListPolarPlot, Joined -> True];     #[data] & /@ {ListLinePlot, ListPolarPlot}      ![enter image description here](http://i.stack.imgur.com/TKZFN.png) WaveletScalogram is an insightful glance in temporal data:               cwd = ContinuousWaveletTransform[data, GaborWavelet[6], {4, 12}, WaveletScale -> 100];     ws = WaveletScalogram[cwd, All, Re, ColorFunction -> "CherryTones"]      ![enter image description here](http://i.stack.imgur.com/M3KD9.png) **Is it possible to somehow visualize it in Polar coordinates?** I would try to extract the data from underlying Graphics, but it is a raster               ws[[1]] // Head     ws[[1, 1]] // Dimensions      > >     Raster >     {48, 5001} >   The only thing that comes to mind is ImageTransformation but I don’t think it is an efficient way (will be hard to scale the axis, etc.). Any advice is appreciated.


title: How can I execute a sequence of statements interactively?

text: I'm fairly new to Mathematica. Suppose I have the following function:               f[x_Integer] := Module[{y, z, r},         y = 5;         z = 10;         r = x + y + z;         r     ];      and I would like to halt the execution after each of the statements `y = 5`, `z = 10` and `r = x + y + z`, and resume only after I press a key. (In other words, I'm looking for something like `Console.ReadLine()` in `C#` or `getline()` in `C++`.) Is there an easy way to do this in Mathematica? Thanks in advance for your help.


title: Cournot Equilibrium

text: I'm trying to determine reaction functions of a Cournot equilibrium for $n$ firms using the same optimal condition, using the fixed point method. This is the method I'm using:               fixedPoint[Gs_, X_, X0_, tol_, nmax_] :=       Module[{G, sol, oldsol, iter, n, i},       (*Vectors Gs and X must have the same length*)       n = Length[X];       G[s_] := Gs /. Table[X[[i]] -> s[[i]], {i, 1, n}];       infNorm[s_] := Max[Abs[s]];       sol = X0;       oldsol = sol + 2*tol;       iter = 0;       While[And[iter <= nmax, infNorm[sol - oldsol] > tol],        oldsol = sol;        sol = G[sol];        iter++];       Print["Performed ", iter, " iterations"];       If[iter >= nmax, Print["WARNING: Maximum number of iterations was reached"]];       sol]      The equilibrium condition is (the derivative of profit with respect to quantity):               (((qt)^(-1/eta)) - (1/eta)*((qt)^(-1/(eta - 1)))*qi )-ai*q1 == 0      Where `eta` and `ai` are parameters, `qt` is the sum of the quantities produced by the $n$ firms, and `qi` is the quantity produced by a single firm. So, my problem is determining the `Gs` argument of my method for $n$ firms. How do I generate $n$ optimal functions, each assuming its corresponding values for `ai` and `qi`?


title: Realtime audio processing using Dynamic

text: Can I make real time audio processing with Mathematica in the same way I can do with images using `Dynamic[CurrentImage[]]`. I know that is possible to use `SystemDialogInput["RecordSound"]` function, but you can't make real time dynamics on it. For example, I would like create one notebook that could make an alert when sound's beyond some level. It's possible?


title: Mathematica plots a discontinuity in piecewise function that does not exist

text: I have the following function defined:               IntImpTri[r1_, r2_, r_] :=        Piecewise[{         {((4/((r2 - r1)^2)) ((r^2 - r1^2)/2 - r1 (r - r1))),           r >= r1 && r < ((r1 + r2)/2)},          {(1/2 - (2/((r2 - r1)^2)) (r^2 - ((r1 + r2)/2)^2) +            (4/((r2 - r1)^2)) r2 (r - ((r1 + r2)/2))),           r >= ((r1 + r2)/2) && r < r2},          {1, r >= r2}}, 0];      I am using _Mathematica 9_ and I do not understand why, when I try to plot this function, which is the integral function of a triangle pulse, the figure shows an interruption in the line. If I try the following command: `Plot[IntImpTri[0, 4, r], {r, -1, 5}]`, I get the following output: ![enter image description here](http://i.stack.imgur.com/mjMV0.jpg) There is a discontinuity around `x=2` but the piecewise covers everything!


title: Why does Plot leave gaps in the graph of a continuous function?

text: I have plotted the overlapping area of the UnitBox and the triangle function as:               Plot[Evaluate[       Integrate[            Piecewise[{{1, -0.5 <= x < 0.5}, {0, Not[-0.5 <= x < 0.5]}}]             Piecewise[{{x + 1 - a, -1 + a <= x <= 0 + a}, {-x + 1 + a, 0 + a <= x <= 1 + a}}],        {x, -Infinity, +Infinity}]],      {a, -2, 2}, PlotRange -> All]      However, the result has gaps as you can see in the plot: ![enter image description here](http://i.stack.imgur.com/t1wCz.jpg) Why is this happening if the function is continuous? Thanks for your time.


title: Inaccuracy of Piecewise function?

text: I have the following issue and can't find a solution so far.               t1 = 60.0*{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,      17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,      33, 34, 35, 36, 37, 38, 39, 40, 41, 42};     T11 = 273.15 + {17.0, 20.5, 22.5, 24.0, 25.5, 27.5, 29.0, 30.5, 32.0,      33.0, 34.5, 36.0, 37.5, 39.0, 40.0, 41.5, 43.0, 44.0, 45.5, 47.0,      48.0, 49.5, 50.5, 52.0, 53.0, 54.0, 55.5, 56.5, 57.5, 58.5, 59.5,      61.0, 62.0, 63.0, 64.5, 65.5, 66.5, 67.5, 68.5, 69.5, 70.5, 71.0,      72};     nlm1 = NonlinearModelFit[Transpose[{t1, T11}],      a*x^2 + b*x + c, {a, b, c}, x, MaxIterations -> 1000];     T1[t_] = Piecewise[{{nlm1[t], t <= Max[t1]}, {nlm1[Max[t1]],       t >= Max[t1]}}];      Then I plot a narrow segment of T1[t]:               Plot[T1[t], {t, 2519.9999, 2520.0001}]      (note that 60*42=2520) and see this: ![plot](http://s2.postimg.org/far2rohax/Shot2.png) This inconsistency leads to more badly inconsistencies in my other calculations. I've tried to set Accuracy and Precision of initial data, those parameters of Piecewise function, WorkingPrecision, but with no result. Does anyone know how to solve this?


title: Enabled option for slider in Manipulate not updating dynamically

text: In a `Manipulate` expression I have a slider control which has the `Enabled` option               Enabled -> Dynamic[bool]      When `bool` changes from `False` to `True`, the content pane in the output cell of the `Manipulate` expression should change from ![enter image description here](http://i.stack.imgur.com/mfTZN.png) to ![enter image description here](http://i.stack.imgur.com/SUj6c.png) and the slider should go from disabled to enabled. The visual change takes place as expected, but the slider stays disabled. Can anyone explain this behavior and suggest a way to fix it? Here is my code:               Manipulate[       Column[{If[bool,           content = {Black, Circle[], Red, Disk[{0., 0.}, r]},           RunScheduledTask[bool = True, {2}]];         Graphics[{content}, ImageSize -> 200],         bool}],       {{r, 0.5}, 0., 1., 0.1, Enabled -> Dynamic[bool],                               Appearance -> "Labeled"},       {content, ControlType -> None},       ControlPlacement -> Bottom,       Initialization :>         (content = {Blue, Disk[]};          bool = False)]      I did test a slider that was not inside a `Manipulate` expression and that had a dynamic `Enabled` option. It worked fine. So why not in `Manipulate`? **Update** I contacted Wolfram Research support and got back a suggestion for a work- around. It wasn't what I was hoping for, but it did lead to me something better than I had before. Only problem remaining is that the _Mathematica_ editor's syntax checker doesn't like what I did. I'm living with that. Here are the details: ![enter image description here](http://i.stack.imgur.com/AjIla.png) The question now boils down to: Can the syntax checker be propitiated? **Another Update** I received another response form WRI tech support. > After talking to our developers, it seems that your original method of using > ControlType -> None should have worked after all. This now looks to be an > issue of bad interaction between RunScheduledTask and DynamicModule. This > issue has been filed into our database so that our development team can fix > it at the earliest.


title: What is the proper way to extract XMLElement values?

text: I have seen and tried many different versions of XML data parsing here on this forum, and even some in the documentation. Is there a tried and true "Best Practice" way to extract all the XMLElement values or is each new file type a hack a thon to extract the correct data and fields? Here's the code I'm using now, but it's not efficient and does not grab all the values needed. Is there a better way?               a=thePartIreallyneeded;     elements = Column@Cases[dat,      XMLElement[tag : _, _, value : _] :> (tag -> value), Infinity];     pairsE = List @@ elements;     gatheredE = GatherBy[pairsE, #[[1]] &];     propertiesE = Part[#, 1, 1] & /@ gatheredE;     targetPositionsE = gatheredE[[a]];      Here is a very small snippet of the section of values I'd like to extract. What I need to get are the Color Names, the Target Id values and the values for each color name. Thank you!               XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Resources"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "ObjectCollection"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",        "Object"}, {"ObjectType" -> "Target", "Name" -> "Target1",        "Id" -> "c1"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "DeviceColorValues"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",            "ColorCMYK"}, {"ColorSpecification" ->             "Unknown"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Cyan"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Magenta"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Yellow"}, {}, {"0"}],            XMLElement[{"http://colorexchangeformat.com/CxF3-core",              "Black"}, {}, {"0"}]}]}]}],      XMLElement[{"http://colorexchangeformat.com/CxF3-core", "Object"}, {"ObjectType" ->   "Target", "Name" -> "Target11", "Id" -> "c11"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "CreationDate"}, {}, {"2013-05-17T11:59:45-06:00"}],       XMLElement[{"http://colorexchangeformat.com/CxF3-core",      "DeviceColorValues"}, {}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",        "ColorCMYK"}, {"ColorSpecification" ->         "Unknown"}, \     {XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Cyan"}, {}, {"11.596052607559"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Magenta"}, {}, {"25.435485248175"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Yellow"}, {}, {"0"}],        XMLElement[{"http://colorexchangeformat.com/CxF3-core",          "Black"}, {}, {"0"}]}]}]}]}]}]


title: Why does Plot[Hold[x], {x,0,1}] work?

text: It appears that, counter to my expectation, all of these (and probably many others) seem to work fine:               Plot[Hold[x], {x, 0, 10}]          FindRoot[Hold[x^2 == 2], {x, 1}]          NMinimize[Hold[x^2], x]      I would expect `Plot` or `NMinimize` to complain that e.g. `Hold[0]` is not a number. These were mentioned a few times on this site but didn't get any attention: (1) (2). Doing this does appear to solve problems which would normally require `_?NumericQ`. Is this usage of `Hold` supported? Is it _meant_ to work this way, does it work by design, or is it accidental? My guess is that these work accidentally because these functions use `ReleaseHold` internally.


title: How can I plot a loxodrome?

text: Can someone show me how to plot a rhumb line (loxodrome) in _Mathematica_ via the `ParametricPlot` function? Here is what I got so far:               ParametricPlot3D[       {Cos[λ]/Cosh[Cot[π/4]*λ], Sin[λ]/Cosh[Cot[π/4]*λ], Tanh[Cot[π/4]*λ]}, {λ, 0, π}]      I am trying to get this one: ![enter image description here](http://i.stack.imgur.com/AWb0q.gif)


title: Is there a function to generate a minimal clique cover?

text: This is a graph problem known as the "Clique Edge Cover" or "Intersection Number" problem, and the goal is to find, from a given graph like $E=\\{\\{a,b\\},\\{a,c\\},\\{b,c\\},\\{b,d\\},\\{c,d\\}\\}$ and $V=\bigcup E$, a representation $K=\\{\\{a,b,c\\},\\{b,c,d\\}\\}$ of the cliques in the graph that has the smallest $|K|$, where the relation from $K$ to $E$ is that $E=\\{x:|x|=2\wedge\exists y\in K\,x\subseteq y\\}$, i.e. $E$ is the set of all pairs in the elements of $K$, so that the elements of $K$ are interpreted as cliques in the graph. (This is the "clique edge cover" statement of the problem, which is the one I am directly interested in, but it may help to see the "intersection number" version of the problem, described in the links above.) This problem is known NP-hard, but that's never stopped Mathematica in the past, and I am not looking for a super-optimized implementation, just one that works reasonably well on small instances. Is there a Mathematica or Combinatorica function that directly implements a solution to this problem, and barring that, does anyone want to take a crack at implementing an algorithm to do this? This paper is an analysis of the problem that contains a few algorithms and may be helpful to this end. _I've asked this questionbefore at math.SE, in order to find out what the problem was called._


title: Control multiple locators along a plot

text: # Update 1 @ Michael E2, my effort - for what it is worth!:               f[x_] := Im[(-1)^(-1 - x/2) 2^(1 - x) \[Pi]^-x x! Zeta[x]];     f[a_] := -a Zeta[1 - a];     Manipulate[With[{{x0 = Clip[p[[1]], {3, 10}]}, {a0 = Clip[p[[1]], {3, 10}]}},     Plot[{f[x], f[a]}, {x, 3, 10}, ImagePadding -> 20, LabelStyle -> (FontFamily ->      "Ariel"), Epilog -> {PointSize[Large], Red, Tooltip[Point[#], #] &@{x0, f[x0], a0,      f[a0]}}]], {{p, {3, 0}}, Locator, Appearance -> None}, AppearanceElements -> None]      # Original question I would like to control two locators at once (both moving with same x value), outputting 2 sets of coordinates simultaneously. The plot I am working looks like this: ![enter image description here](http://i.stack.imgur.com/O1IaI.gif) generated by the following code:               Plot[{Im[(     N[Zeta[x]] x!)/(\[Pi]^x (2^(x - 1) (-1)^(x/2 + 1)))],      -x Zeta[1 - x]}, {x, 3, 10}, Epilog -> {PointSize[Medium], Red,      Point[{{5, -5 Zeta[1 - 5]},      {5, Im[(N[Zeta[5]] 5!)/(\[Pi]^5 (2^(5 - 1) (-1)^(5/2 + 1)))]}}]}]      Michael E2 and Timothy Wofford provided a code that controls one locator in this post. I would like to achieve the same thing with multiple locators (ideally by moving one locator with cursor & both locators moving with equal x values at the same time - both generating their separate coordinates). If possible also, I would like the manipulate cell to output the value of a function of each point as it moves, along with the sum of both functions. I hope I am making sense here!


title: Why is mathematica giving wrong and incomparable results for the integral?

text: 1) Integration of Gaussian Distribution with $(x,y,z)$ ranging from $-\infty$ to $\infty$ gives 1 as expected using this command in mathematica. (Total Probability = 1) $\sigma = 200000$ and $\mu=1000000$               Integrate[(E^(-(x - 1000000)^2/(2*200000^2))*E^(-(y - 1000000)^2/(2*200000^2))*               E^(-(z -1000000)^2/(2*200000^2))/(200000*Sqrt[2*Pi])^3) , {x, -Infinity, Infinity},                {y, -Infinity,    Infinity}, {z, -Infinity, Infinity}]      2) Now I want to integrate over $(x,y,z)$ such that $$\frac{x}{1+0.1}+\frac{y}{(1+0.1)^2}+\frac{z}{(1+0.1)^3}\geq 2000000 $$ given that $$x,y,z\geq0$$ So I wrote this in mathematica:               Integrate[(E^(-(x - 1000000)^2/(2*200000^2))*E^(-(y - 1000000)^2/(2*200000^2))            *E^(-(z -1000000)^2/(2*200000^2))/(200000*Sqrt[2*Pi])^3) Boole[x/(1 + 0.1) + y/(1 + 0.1)^2              + z/(1+ 0.1)^3 - 2000000 >= 0], {x, 0,   Infinity}, {y, 0, Infinity}, {z, 0, Infinity}]      But the answer I am getting is some very big number ($1.7\times10^{17}$) Can anyone point out the mistake?


title: How to make "molbio-style heat maps" in Mathematica

text: > **Possible Duplicate:**   >  How to combine ArrayPlot's? [NB: This question is specifically addressed to those who have used (or attempted to use) Mathematica to generate "heat maps" (as the term is used in the context of high-throughput biology research).] The short version of this question is: > What functions does Mathematica have to produce "heat maps" like those used > by molecular biologists to visualize high-throughput gene expression data? (For reasons I describe in more detail below, `ArrayPlot` and `MatrixPlot` are _completely inadequate_ for the task.) * * * Long version: In the field of high-throughput molecular biology research, so-called "heat maps" have become a veritable _workhorse format_ for data visualization (even though the data never has anything whatsoever to do with heat). For example, here's a typical one (from the Wikipedia entry on heat maps): ![enter image description here](http://i.stack.imgur.com/uhScL.png) (In the example above, the heat map is decorated with dendrograms along the top and right edges. For the purposes of this question, please ignore these dendrograms. All I'm interested in is the central array of colored rectangles.) Initially "heat maps" were used for visualizing high-throughput gene expression data obtained from microarray-based experiments, but nowadays they are used for visualizing _any type of data_. Given that such "heat maps" are _so ubiquitous_ in mainstream biology research, I had expected that Mathematica would have by now implemented multiple specialized functions and/or packages for producing and manipulating them. After looking very hard for such functions, however, I'm beginning to suspect, in shock, that I may have been completely wrong about this. > _The purpose of this question is to get confirmation that this suspicion is > basically right, or (hopefully) information showing that it is not so._ The closest I have found are the functions `ArrayPlot` and `MatrixPlot`. At first blush these functions seem to fit the bill, until one tries to perform the simplest manipulations with the `Graphics` objects they produce. For example, just to _display side-by-side_ two `ArrayPlot`-generated heat maps of equal heights but unequal widths is a nightmare; e.g.: ![enter image description here](http://i.stack.imgur.com/zD6oA.png) Now, I'm not a Mathematica novice; I've been bashing my skull against it since the early 90's. Still, it took me _about 6 hours_ of mostly failed attempts, and of far more hacking at the internals of these `Graphics` objects than such a trivial task should ever require1. (BTW, the situation with `MatrixPlot` was not any better.) This humbling experience has convinced me that, whatever other utility `ArrayPlot` and `MatrixPlot` may have _they cannot possibly be considered adequate tools for making heat maps._ (I suspect that the reason why `ArrayPlot`\- and `MatrixPlot`-generated `Graphics` are so difficult to work with (as "heat maps" at least) is that they are based on `Raster` objects, but this is just a hunch, since the Mathematica documentation, as usual, remains safely oracular on what may be going on.) So the question at this point is the one at the top of this post. * * * 1I'd love to post the function that I eventually managed to implement to solve the problem, but the post I submitted about this problem was closed by the Gods.


title: $CurrentLink passing down in MathLink SetDelayed functions

text: I would like to utilize the MathLink option of having each `Install` of my package result in a linking object which I can use to control when and how certain elements are used in the underlying `C` code. However, I have difficulties when implementing Mathematica functions on top of the functions which require the `LinkObject`. Of course I need the `SetDelayed` statement due to variable passing etc. Take for instance the `counter.tm` example:               :Evaluate:      BeginPackage[ "counter`"]          :Begin:     :Function:      AddToCounter     :Pattern:       AddToCounter[$CurrentLink, n_Integer]     :Arguments:     {n}     :ArgumentTypes: {Integer}     :ReturnType:    Integer     :End:          :Evaluate:      EndPackage[ ]      This works great until I define additional functions, take for instance this additional function (it _is_ placed within the `BeginPackage/EndPackage`).               :Evaluate:   MyAddToCounter[$CurrentLink,n_Integer] :=                          Return[AddToCounter[$CurrentLink,n+1]]      However, when calling `MyAddToCounter` I only get the function call as a symbol:               In[2]:= MyAddToCounter[link,20]     Out[2]:= AddToCounter[$CurrentLink, 21]      Why is this?   And how can I preserve the separation of each `LinkObject` to the same package?


title: How to partition a list into sublists in a similar way to Histogram

text: I have a list of list as below (I show part of it)               {{1902, 0.4662}, {1903, 0.22443}, {1905, 0.02936}, {1906,        0.02702}, {1908, -0.08354}, {1909, -0.05241}, {1911,        0.02388}, {1912, 0.03738}, {1914, 0.25015}, {1915, 0.2831}, {1917,        0.4415}, {1919, 0.18315}, {1921, 0.2256}, {1923, 0.24132}, {1926,        0.21473}, {1928, 0.29596}, {1930, 0.47693}, {1933, 0.41607}, {1935,        0.22161}, {1937, 0.3322}, {1940, 0.2099}, {1942, 0.23376}, {1944,        0.44114}, {1947, 0.15876}, {1949, 0.43953}, {1951, 0.71407}, {1954,        0.9595}, {1956, 0.59436}, {2000, 0.6832}, {2004, 0.86861}, {2007,        0.48201}, {2011, 0.70796}, {2015, 0.57029}, {2020, 0.61997}, {2026,        0.79266}, {2032, 0.78726}, {2038, 0.83884}}      For example, in {1902,0.4662} "1902" represent time 19:02 and 0.4662 represent the data at time 19:02. **What I want to do is to calculate average of the data in every 5 minutes.** That is from 19:02 to 19:06, from 19:07 to 19:11. **Notice the time step is not evenly distributed.** `Histogram` can naturally count how many of the data are in each interval. I want to partition the list like `Histogram` and then I can calculate average in each interval. And notice that the data may not be in a single day. I can't figure out an elegant way to do this with built-in function. Can somebody help me? Besides I think this is a very simple statistical calculation of data. **I want to know what software could do this easily and directly.** Update: the full data sample is here http://en.textsave.org/VdL with date information


title: Simple blink comparator for two images

text: I tried to build a simple 'blink comparator' - where you can click on an image repeatedly to switch between two similar images. (An old-fashioned notion in the days of powerful image processing software, it's true.) I think the problem with what I've done so far is the behaviour of the symbols inside a `DynamicModule`:               image1 = Thumbnail[ExampleData[{"TestImage", "Mandrill"}], 300];     image2 = Thumbnail[        ColorNegate[ExampleData[{"TestImage", "Mandrill"}]], 300];     DynamicModule[{imageList = {image1, image2}},      EventHandler[       Show[        First[imageList],        Graphics[         {          Text[           Style[            "name of First[imageList]]?",             14, White],           ImageDimensions[First[imageList]]/2]          }         ]],       {"MouseDown" :>          {          RotateLeft[imageList],          Beep[]          }        }]]      ![gratuitous mandrill picture](http://i.stack.imgur.com/75B9K.png) The `Beep` confirms the `EventHandler` action, but the image doesn't change.


title: Appending to sublists using "anchor" values

text: Say I have a set of lists that look like this:               list = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3}},             {{131.048`, 243.364`}, {3, 3}, {56, 56}, {76, 23}}, {{164.911`, 244.039`},               {4, 4}}, {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`}, {6, 6}},              {{184.767`, 234.228`}, {7, 7}}, {{213.044`, 234.24`}, {8, 8}},              {{26.6316`, 221.423`}, {9, 9}}};          appendList = {{{3, 3}, {"Yellow", "Red"}, {"Blue", "Majesty"}},                   {{76, 23}, {"White", "Avalanche"}}}      How can I use the first element in each sublist of `appendList` as an anchor to append the next set of elements in place in `list` generating something like the following?:               finalList = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3},                   {"Yellow","Red"},{"Blue","Majesty"}}, {{131.048`, 243.364`}, {3, 3},                   {56, 56}, {76, 23},{"White","Avalanche"}}, {{164.911`, 244.039`},                    {4, 4}}, {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`},{6,6}},                  {{184.767`, 234.228`}, {7, 7}}, {{213.044`, 234.24`}, {8, 8}},                   {{26.6316`, 221.423`}, {9, 9}}};      After-the-fact question: This is a brief followup which doesn't quite deserve it's own question - how can we only look at the last element in each sublist of `list` to check to see if it matches the "anchor" value at the first position in `appendList`? In other words, where `{{{2, 2}, {"Yellow", "Red"}, {"Blue", "Majesty"}}, {{56, 56}, {"White", "Avalanche"}}}` yields a `finalList = list` since {2,2} and {56,56} are not at the ends of the sublists in `list`?


title: Stochastic Approximation and Simulation using Running Median

text: I have a function $$F(X_{t+1},Y_{t}^{med})= \alpha X_{t+1} + (1-\alpha) Y_{t}^{med},$$ where $$Y_{t}^{med} = Median(Y_1, Y_2,... Y_t).$$ Moreover, $Y_1 = X_1$ and $Y_t = F(X_{t},Y_{t-1}^{med})$ $\forall t>1$. Suppose $X_t \sim X$ is a IID random variable following a Beta distribution, $X \sim Beta(2,1)$. I wish to plot the evolution of $Y_{t}^{med}$ over time. Currently, I have: 1) The function:               f[a_, {x_, y_}] := a x + (1 - a) y      2) Generate data. **Here, I don't know how to generate the running median, that is $Y_{t}^{med}$ in Mathematica.**               sim[length_] :=       Module[{rv = RandomVariate[BetaDistribution[2, 1], length], y, yMed},       y[1] = First@rv;       yMed[t_Integer] := yMed[t] = MovingMedian[rv, t];       y[t_Integer] := y[t] = f[0.5, {rv[[t]], yMed[t - 1]}];       yMed /@ Range[length]]      3) Create the plot/graph for 100 iterations, 5 random walks:               ListPlot[Table[sim[100], {5}], PlotRange -> All, Joined -> True,       Frame -> False, AxesOrigin -> {0, 0}, AxesLabel -> {t, Y},       GridLines -> {{}, {2/3}}, GridLinesStyle -> Directive[Gray, Dashed]]


title: Function that returns the binary string given its index in lexicographic ordering

text: Index the binary strings in lexicographic order, so that the empty string " " corresponds to 0, the string "0" corresponds to 1, the string "1" to 2, and so on. I want a function that, given a natural number $n\geq0$, returns the binary string with lexicographic index $n$.


title: What is the most elegant way to display multiple graphs with a common title?

text: I often seek to display two graphs, side by side, with a common label over them. There is no option for adding a label to `GraphicsRow`, which means, I think, that I need to use `Grid` or `GraphicsGrid` and include a row on top that has `SpanFromLeft` set to allow a graphically defined line of text occupy the entire row. It seems like a lot of work to do something simple. Is there a better solution?


title: How to use Optional as an omissible parameter in pattern-match?

text: Below is a function intended to test if an expression is a polynomial in which all the coefficients and exponents are integers:               intPolyQ[Optional[_Integer] +      Plus[Optional[_Integer] x_Symbol^Optional[_Integer] ...], x_] := True;     intPolyQ[___] := False;      It gives unexpected results in some cases. For example,               intPolyQ[#, x] & /@ {x, 2 x, 2 x + 1, 2 x^2 + 3 x, 2 x^2 + 3 x + 1}      gives               {True, True, True, False, True}      which is wrong in the 4th case. Why does this happen? How do I fix it?


title: Exporting as .PDB extension

text: I am working with the 3-D coordinates of proteins. The file format I import and modify coordinates of is in the .PDB format, and the string to import is also in this same format. Currently, when I try to export as in "final.pdb", I get: "Export::type: "String cannot be exported to the !(\"PDB\") format." However, when I export with the extension .txt, and use:               Import["final.txt", "PDB"]      The file imports as the protein structure. My question: Is there a way to export using the .PDB extension. Or even force the export. Having the .pdb extension would be much easier for other programs. If there is a way, please let me know.


title: Differential Equations with Matrices

text: I'm trying to implement the differential equation of a Cellular Neural Network in _Mathematica_ as seen below:               A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};        B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};        u = {{10, 11, 12, 1}, {20, 21, 22, 1}, {66, 77, 88, 1}};     Ioff = 1;          NDSolve[{x'[t] == -x[t] + ListConvolve[A, x[t], 1] + ListConvolve[B, u, 1] + Ioff,     x[0] == u}, x, {t, 0, 2}]      But `NDSolve` returns two errors: > `ListConvolve::kldims:` "The kernel {{1,2,3},{4,5,6},{7,8,9}} and list x[t] > are not both non-empty lists with the same tensor rank." > > `NDSolve::ndfdmc:` Computed derivatives do not have dimensionality > consistent with the initial conditions. I would really appreciate any help since I'm a beginner in _Mathematica_ and I don't know what I'm doing wrong


title: What do the hashtags represent in the result of Solve, and how should I use them?

text: There is a function that I'm trying to get the inverse of. My function is a simple polynomial:               Tn[T_] := 4/9 T^3/Tc^2 + 5/9 T      Now I tried to find `T` as a function of `Tn`, for which I used Solve:               sols=Solve[Tn[x] == a, x, Reals]     {{x -> Root[-9 a Tc^2 + 5 Tc^2 #1 + 4 #1^3 &, 1]}}      Plotting it is no problem, which I did by using this:               Tc = 1;     Plot[Evaluate[x /. sols], {a, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/dPE8s.png) But the problem is that I have no idea what the hashtags in the result of Solve denote, and how I should write the function `T(Tn)`. What do the `#`s mean, and how exactly does `T` depend on `Tn`?


title: How do I work with Root objects?

text: I want to solve the trigonometric equation : $$(3-\cos 4x )\cdot (\sin x - \cos x ) = 2.$$ I tried               Solve[(3 - Cos[4*x])*(Sin[x] - Cos[x]) == 2, x]      It returns the solutions in terms of `Root` objects yielding also this message : > >     Solve::ifun: Inverse functions are being used by Solve, so some > solutions may not be found; >     use Reduce for complete solution information. >> >   How do I tell _Mathematica_ to do that? How can I solve this equation : $\tan(2x)⋅ \tan(7x) = 1$ ?


title: How can I obtain absolute result for Root[ # ] symbol

text: I'm using mathematica 8.0. When I calculate NDSolve`ImplicitRungeKuttaGaussCoefficients[10, Infinity] function, it gives me some symbolic results. I trided //N and //FuıllSimplify operation as in How do I work with Root objects? topic but it gave me only numerical results or some of absolute results, I didn't get all of my results, but i don't want to this. I want to absolute results for my calculation but I couldn't achieve this.For Example the first element of A matrix is :                (322 - 13 Sqrt[70])/3600      , but second element of A matrix is :                    Root[20242937658868661529 + 13567555581406269206400 #1 +         2767290377721440719680000 #1^2 +         187835459850164351232000000 #1^3 +         1303105350315444928000000000 #1^4 -         113922281443839160320000000000 #1^5 +         1236506465399482368000000000000 #1^6 -         5007540613482086400000000000000 #1^7 +         6998115764183040000000000000000 #1^8 &, 1]


title: What is that Root[...] inside the answer represent?

text: ![enter image description here](http://i.stack.imgur.com/vR9WO.png) So I am encountering this situation, in which mathematica doesn't give me the answer, but in a form of "Root". How do I interpret this ? what is the number after the "&" represent? How should I ask mathematica to evaluate this Root for me? Please don't tell me to use `N[%]`. I have an equation of 4 variables and I don't have numerical value for them. I would like it in symbolic form.


title: Mathematica returns different results when requested by Reduce, Solve

text: When I request with Reduce, Mathematica returns:               In[13]:= N[Reduce[X^3-26X+1 == 0,X, Reals]]                                          Out[13]= X == -5.11814 || X == 0.0384637 || X == 5.07968      However, when I request with Solve, it returns three complex roots               In[15]:= N[Solve[X^3-26X+1 == 0,X]]                                                                                -16     Out[15]= {{X -> 5.07968 + 0. I}, {X -> 0.0384637 + 4.44089 10    I},                                  -16     {X -> -5.11814 - 4.44089 10    I}}      I think the different here is the Reals field. However, I'm confused about the correctness of result. Which one should I follow when I want to solve the equations. Thanks


title: Eigenvalues for large matrices without Root-Solution

text: I read some other questions and tried to implement the given answers but yet, I did not succeed to find proper solutions for my eigenvalues. I hope someone can show me how to do this for this case, and even larger matrices in the same shape:               mat = {{L - 2*s, -w, s, 0, s, 0}, {w, L, 0, 0, 0, 0},             {s, 0, L - 2*s, -w, s, 0}, {0, 0, L, w, 0, 0},     {s, 0, s, 0, L - 2*s, -w}, {0, 0, 0, 0, L, w}};      I used `FullSimplify[Eigenvalues[mat], Assumptions -> {Element[L, Reals], Element[w, Reals], Element[w, Reals]}]` as well as               Sort[Eigenvalues[mat] // Simplify // N]      with the same results that 4 eigenvalues are written as Root.


title: Verify "Type" of solution

text: I've written some _Mathematica_ functions which allow the user to verify if a mathematical function has certain properties. What I'm basically doing is generating "random" functions in respect of certain parameters and then verify if these functions have those properties. So at some point, I solve a system of equations as follows:               sol = Solve[function1 == 0 && function2 == 0, {x, y}, Reals];      Lateron, I use a conditional statement like:               If[Length@sol==1, ...]      In this case, I want to continue if there is exactly 1 solution of the form `{x->value1, y->value2}`. Sometimes, however, the only solution is something like:               {{x -> Root[-8 + 16 #1 + 16 #1^3 + 3 #1^5 &, 1],        y -> -2 - 1/2 Root[-8 + 16 #1 + 16 #1^3 + 3 #1^5 &, 1]^2}}      In this case, my _Mathematica_ function will continue calculating and take minutes for a single function because of the high complexity of the `Solve[...]` return value. Is there a built-in function to determine whether the solution is "explicit", or does someone have a trick for this?


title: Mathematica won't give eigenvectors but Wolfram Alpha will? What am I doing wrong?

text: If I ask Mathematica to find the eigenvectors and eigenvalues of the matrix:               mat := {{a, b, c}, {b, d, e}, {c, e, f}}     Assuming[{a > 0, b > 0, c > 0, d > 0, e > 0, f > 0}, Eigenvalues[mat]]     Assuming[{a > 0, b > 0, c > 0, d > 0, e > 0, f > 0}, Eigenvectors[mat]]      If returns stuff like               {Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 1],      Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 2],      Root[c^2 d - 2 b c e + a e^2 + b^2 f -      a d f + (-b^2 - c^2 + a d - e^2 + a f + d f) #1 + (-a - d -         f) #1^2 + #1^3 &, 3]}      But if I ask Wolfram Alpha: ![enter image description here](http://i.stack.imgur.com/IKI0Q.png) It does it. What am I doing wrong in Mathematica?


title: How do I interpret the Roots syntax when I am finding the eigenvalues of a matrix

text: Here is an example of my problem: ![eigenvalues](http://i.stack.imgur.com/8kayB.png) I am somewhat confused by the syntax of this. I am guessing that the #1 is specifying the start of another root? Why then does one of the roots = u + with nothing after the plus? I think if I better grasped what the #1 stood for I might understand. Also, is there a reason that the Root ends with an &? Thanks!


title: Eigenvalues of a matrix, rhombus/hash sign

text: I wanted calculate the eigenvalues of                A = {{0, 1, 0, 0}, {a, b, c, 0}, {0, 0, 0, 1}, {d, 0, e, f}}      Then assigned the parameters a value               Eigenvalues[A] /. {a -> 3/4 (1 + 4/3 beta^2), b -> -1/2,      c -> 3/4 (1 - 4/3 beta^2), d -> 3/4 (1 - 4/3 beta^2),      e -> 3/4 (1 + 4/3 beta^2), f -> -1/2}      And I get this: > >     {Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 1], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 2], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 3], >     Root[12 beta^2 + (-3 - 4 beta^2) #1 + (-5 - 8 beta^2) #1^2 + >     4 #1^3 + 4 #1^4 &, 4]} >   what does `#1` means and the `&,1`? why it doesnt calculate with beta like in               Eigenvalues[{{a, b}, {-b, 2 a}}]?


title: Solve doesn't return all solutions

text: I got a simple cubic equation as input, but _Mathematica_ does not give all solutions, why is this the case here?               f[α_] := Sqrt[2] α (Δ + 2g^2/Ω(α Conjugate[α]))          Solve[f[α] == 0, α]      > >     {{α -> 0}} >   There should also be the solution where $\alpha \in$ Real, so that $|\alpha|^2 = -\frac{\Delta\Omega}{2g^2}$ under the condition $\Delta\Omega < 0$.


title: What is the difference between Reduce and Solve?

text: `Solve` and `Reduce` both can be used for solving equations. Just by working with them, I know there are some differences between them. but that is about all I know, and I want to know what the differences are. Could someone teach me about this?


title: HarmonicNumber problem

text: I am looking for all the roots of `HarmonicNumber`, in the domain [-30, 1] and [0, 6000] for the real and imaginary parts, respectively, and where the parameter `n` of `HarmonicNumber` is as high as 200. This problem had been asked before in this question. As I increase the size of the domains where I am looking for roots, the following warnings show up: > FindRoot::jsing: "Encountered a singular Jacobian at the point {x,y} = > {56.9935,171.987}. Try perturbing the initial point(s)." > > FindRoot::lstol: The line search decreased the step size to within tolerance > specified by AccuracyGoal and PrecisionGoal but was unable to find a > sufficient decrease in the merit function. You may need more than > MachinePrecision digits of working precision to meet these tolerances " Could you help me fix this? Or suggest another way to solve this equation. I got the same warnings when I tried to apply another technique as described in this answer Here is the code:               Options[FindRoots2D] = {PlotPoints -> Automatic, MaxRecursion -> Automatic};           FindRoots2D[funcs_, {x_, a_, b_}, {y_, c_, d_}, opts___] := Module[     {fZero, seeds, signs, fy},fy = Compile[{x, y}, Evaluate[funcs[[2]]]];      fZero = Cases[Normal[      ContourPlot[         funcs[[1]] == 0,          {x, a-(b-a)/97, b+(b-a)/103}, {y, c-(d-c)/98, d+(d-c)/102},          Evaluate[FilterRules[{opts}, Options[ContourPlot]]]]],       Line[z_] :> z, Infinity];            seeds = Flatten[(      (signs = Sign[Apply[fy, #1, {1}]];        #1[[1 + Flatten[Position[Rest[signs*RotateRight[signs]], -1]]]]) &      ) /@ fZero, 1];      If[seeds == {}, {},       Select[         Union[({x, y} /.            FindRoot[{funcs[[1]], funcs[[2]]}, {x, #1[[1]]}, {y, #1[[2]]},                Evaluate[FilterRules[{opts}, Options[FindRoot]]]] & ) /@ seeds,             SameTest -> (Norm[#1 - #2] < 10^(-6) & )],          a <= #1[[1]] <= b && c <= #1[[2]] <= d & ]]]     n = 20;     zeros = FindRoots2D[{Re[HarmonicNumber[n, x + I y]], Im[HarmonicNumber[n, x + I y]]}, {x, -30, 1}, {y, 0, 6000}]     mediumSeaGreen = RGBColor[0.235298`, 0.702002`, 0.443098`];     violet = RGBColor[0.559999`, 0.370006`, 0.599994`];     orangeRed = RGBColor[1.`, 0.270608`, 0.`];     ContourPlot[{Re[HarmonicNumber[n, x + I y]] == 0, Im[HarmonicNumber[n, x + I y]] == 0},      {x, -30, 1}, {y, 0, 6000},     MaxRecursion -> 3,ContourStyle -> {Directive[Thick, mediumSeaGreen],     Directive[Thick, violet]},      Epilog -> {PointSize[0.02], orangeRed, Point[zeros]}]      The following was my trial of n=20 and range x={-32,1} and y={0,4000}. n = 20; seeds = findSeeds[myHN[n, x + I y], {x, -32, 1}, {y, 0, 4000}, PlotPoints -> 25, MeshFunctions -> {myHNReImCx[n][#1, #2] &, myHNReImCy[n][#1, #2] &}]; // AbsoluteTiming allfoundzeros = Quiet@myFRC[myHN[n, z], {z, -32, 1 + 4000 I}, seeds.{1, I}]; // AbsoluteTiming uniqueszeros = #[[First@Ordering[Abs@myHN[n, #]]]] & /@ findclusters[allfoundzeros, 10.^-6]; // AbsoluteTiming zeros = Pick[uniqueszeros, With[{zz = Developer`ToPackedArray@N@uniqueszeros}, UnitStep[(#1 - (-32)) (1 - #1) (#2) (4000 - #2)] &[Re[zz], Im[zz], 1]], 1]; // AbsoluteTiming Length[zeros] zeroplot = Graphics[{PointSize[0.0035], Red, Point@Transpose@{Re[zeros], Im[zeros]}}, PlotRange -> {{-32, 1}, {0, 4000}}, AspectRatio -> 1, Frame -> True]


title: Is it possible to use WolframAlpha servers to evaluate equations in Mathematica v8.0.4?

text: Is it possible to use WolframAlpha computational power to evaluate equations in Mathematica version 8.0.4? The thing is, it takes ages for my computer to evaluate certain equations. It would be great if I could use WolframAlpha (or something else?) to compute these equations .


title: The algorithm of ListGraphs[n,m]

text: I'm not sure if this is a Mathematica problem, math problem or a CS problem, so if this is off-topic please transfer it. In the package `Combinatorica` there is a function `ListGraphs[n,m]` which returns all nonisomorphic undirected graphs with `n` vertices and `m` edges. What algorithm does it use? All I can think of is to enumerate all graphs with `n` vertices and `m` edges brute-force, and check isomorphism for each graph. But I don't think that's effective. Is there a better algorism for this task? Thanks!


title: Mathematica 9 does not read mathematica 8 ".mx" files

text: Having written a lot of code on M8, I recently switched to M9 and tried to run the code on M9, the code starts by loading an .mx file written by M8, but M9 wouldn't read the .mx file saying that it was written on another machine. This is a major incompatibility issue between M8 and M9. Fortunately, I kept my M8 installation, so for now, M9 is useless to me. Please a solution.


title: ClassifierInformation's "ClassPriors" misreporting?

text: ## To the **TLDR** people It seems to me that when you explicitly set `ClassPriors` when running `Classify`, it creates a `ClassifierFunction` that works fine but reports the `Automatic` class priors instead of those explicitly provided. Is this true, intended, buggy, or am I missing something? ## To the **WHYTPPCWCCAPWWDWFY** people _(What Have You Tried/Please Provide Code We Can Copy And Play With/We Don't Work For You)_ Take a `Classify` documentation example               data = {1 -> True, 2 -> True, 3 -> True, 4 -> True, 5 -> False,        6 -> True};          c = Classify[data];      It automatically chose Naive Bayes. Now we check the class priors               ClassifierInformation[c, "ClassPriors"]          (* <|False -> 0.25, True -> 0.75|> *)      Let's see the probabilites for 5               c[5, "Probabilities"]          (* <|False -> 0.341463, True -> 0.658537|> *)      This doesn't change if one explicitly sets the class priors, and this makes sense to me               c[5, "Probabilities",       ClassPriors -> ClassifierInformation[c, "ClassPriors"]]          (* <|False -> 0.341463, True -> 0.658537|> *)      Now, let's custom set other priors at classification time               priors = <|True -> 0.5, False -> 0.5|>;     c2 = Classify[data, ClassPriors -> priors];      The new probabilies lean more towards `False`, makes sense               c2[5, "Probabilities"]     c[5, "Probabilities", ClassPriors -> priors]          (* <|False -> 0.608696, True -> 0.391304|> *)     (* <|False -> 0.608696, True -> 0.391304|> *)      However, `ClassifierInformation` still returns the old priors               ClassifierInformation[c2, "ClassPriors"]          (* <|False -> 0.25, True -> 0.75|> *)      so these 2 now return different results.               c2[5, "Probabilities"]     c2[5, "Probabilities",       ClassPriors -> ClassifierInformation[c2, "ClassPriors"]]          (* <|False -> 0.608696, True -> 0.391304|> *)     (* <|False -> 0.341463, True -> 0.658537|> *)      Am I missing something when I find this weird/buggy?


title: How to use a scheduled event in a cloud notebook to read data files on a desktop

text: I don't know even how to attempt this, or if it's possible. I would like to be able to examine conditions, data, status of email server on my work desktop from the programming cloud. I recognize that these are three different things (is an application running? does a file xxx.xls have data for something? are processes connected to the desktop running?). One might be do-able and the others not, so to be specific, I would like to be able to check for data, and maybe start applications on my desktop from the cloud. I this even possible?


title: PolynomialReduce inconsistent results

text: I was playing around with gröbner basis and s-polynomials and I fell upon the PolynomialReduce, and I was wondering why it gives different results when I move around the polynomials in its second parameter,               PolynomialReduce[x^2 (x^2 + y) - 1 (x^2 y + 1), {x^2 y + 1, y + x^2, x^4 - 1}, {x, y}]      gives               {{-1, x^2, 0}, 0}      while               PolynomialReduce[ x^2 (x^2 + y) - 1 (x^2 y + 1), {y + x^2, x^2 y + 1, x^4 - 1}, {x, y}]      gives               {{x^2 - y, 0, 0}, -1 + y^2}      which is obviously wrong** as it is very apparent that the coefficients is just x^2 and -1. Can anybody shed some light on this? It's very disturbing and confusing. [edit] **the result might not be wrong, but it does not give the minimal b as per instruced by the documentation http://reference.wolfram.com/language/ref/PolynomialReduce.html


title: How can I export my learned ClassiferFunction[] and PredictorFunction[]s?

text: Mathematica 10 provides beautiful high-level machine learning functionality. Sadly, the learned functions once created are rather opaque objects. I need to use them in other projects, so here is my question: **Can I export the neural networks, random forest decision trees, or any other internals of the learned functions for externally use, e.g. can I export a neural net into a standard FANN File format.** PS. My real hope is to use _Mathematica_ **V10** to generate machine-vision convolutional neural networks and then embed them within my clojure, pythons and iOS projects.


title: What is the most efficient way to add rows and columns to a matrix?

text: Say I have a matrix m and a vector v.               v = {a[1], a[2], a[3], a[4]};          m={{a[1,1],a[1,2],a[1,3],a[1,4]},        {a[2,1],a[2,2],a[2,3],a[2,4]},        {a[3,1],a[3,2],a[3,3],a[3,4]},        {a[4,1],a[4,2],a[4,3],a[4,4]}};      What is the most efficient way to add v to the rows of m to create...               mrow={{a[1],a[2],a[3],a[4]},           {a[1,1],a[1,2],a[1,3],a[1,4]},           {a[2,1],a[2,2],a[2,3],a[2,4]},           {a[3,1],a[3,2],a[3,3],a[3,4]},           {a[4,1],a[4,2],a[4,3],a[4,4]}}      Likewise, what is the most efficient way to add v to the columns of m to create...               mcol={{a[1],a[1,1],a[1,2],a[1,3],a[1,4]},           {a[2],a[2,1],a[2,2],a[2,3],a[2,4]},           {a[3],a[3,1],a[3,2],a[3,3],a[3,4]},           {a[4],a[4,1],a[4,2],a[4,3],a[4,4]}};      **EDIT** : I've tested some of the suggestions for adding a column with a large matrix and was somewhat surprised by the results.               m = RandomVariate[NormalDistribution[], {1000, 1000}];          v = RandomVariate[NormalDistribution[], 1000];          In[37]:= AbsoluteTiming[Do[MapThread[Prepend, {m, v}], {100}];]          Out[37]= {1.809623, Null}          In[38]:= AbsoluteTiming[Do[Transpose[Prepend[Transpose[m], v]], {100}];]          Out[38]= {2.449231, Null}          In[39]:= AbsoluteTiming[Do[Transpose[Join[Transpose[m], {v}]], {100}];]          Out[39]= {2.271853, Null}


title: Merge two lists for List3DPlot

text: I have a two lists: `list1 = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}, {x5, y5}}` and `list2 = {z1, z2, z3, z4, z5}` and I want to make a third one like this `output = {{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4,z4}, {x5, y5, z5}}` What nice command can do the trick? It is to do a `ListPlot3D` with two lists with more than 10000 entries. I tried with `Map` and pure function but it is giving me troubles. Thank you


title: A Faster way to combine two Lists of different structures into one of a different structure

text: I have the following two lists (each containing over 500,000 elements). Here is a sample:               lis1 = { {1.86582, 1.70162, 1.25256}, {1.82707, 1.29901, 1.10659},        {1.76547, 1.21544, 1.09433}, {1.18306, 1.28322, 1.75524},        {1.12555, 1.98011, 1.53359}, {1.10584, 1.12299, 1.88411},        {1.83799, 1.5275, 1.76179}, {1.42352, 1.45163, 1.45318},        {1.63669, 1.78145, 1.60307}, {1.61749, 1.44287, 1.57405}      };      and               lis2 = {0.826095, 0.73286, 0.918137, 0.937434, 0.506525,              0.562795, 0.664915, 0.789321, 0.6559, 0.398447}      They both have equal `Length`s. I want to combine both Lists to obtain a new list that looks like this               { {1.86582, 1.70162, 1.25256, 0.826095},      {1.82707, 1.29901, 1.10659, 0.73286},      {1.76547, 1.21544, 1.09433, 0.918137},      {1.18306, 1.28322, 1.75524, 0.937434},      {1.12555, 1.98011, 1.53359, 0.506525},      {1.10584,1.12299, 1.88411, 0.562795},      {1.83799, 1.5275, 1.76179, 0.664915},      {1.42352, 1.45163, 1.45318, 0.789321},      {1.63669, 1.78145,1.60307, 0.6559},      {1.61749, 1.44287, 1.57405, 0.398447} }      That is, each element of the combined list contains the corresponding elements of `lis1` and `lis2`, with the first three elements being from `lis1` and the fourth element from `lis2`. Here is what I did to combine them in this fashion:               Transpose[{lis1, lis2}] //. {{a_, b_, c_}, d_} :> {a, b, c, d}      Is there a faster way to achieve this as my lists are huge ?


title: Adding columns of data to a matrix

text: I create a matrix of values using `Table`. Here's my code:               Matrice = Table[N[Spectral[i,j]], {i, 1, 50}, {k, {0.1, 0.2, 0.5, 0.8}}]      so I have a matrix `50x4` where `Spectral` is a function previously defined. I would like to have the `i`s on my first column, thus having a `50x5` matrix. How could I do that?


title: Nested List Product

text: I want to apply `Times` on the elements of a list such that:               {2,3,5,7,11,13,17,19} =>      {{2,3,5,7,11,13,17,19},{6,35,143,323},{210,46189},{9699690}}      I wrote this function :               listProduct[list_] :=       Apply[Times, Partition[list, Ceiling[Length[list]/2]]]          Nest[listProduct, {2, 3, 5, 7, 11, 13, 17, 19}, 1]      Using `Nest` at each level generate the desired element but I am having difficulties with combining the results. Also, I want to be able to use each element once computed.


title: How can I make DensityHistogram obey the lower bound in PlotRange in version 10?

text: In version 9, `DensityHistogram` worked with `PlotRange` as expected:               SeedRandom[0]     DensityHistogram[      Transpose[{RandomReal[NormalDistribution[], 1000],         RandomReal[NormalDistribution[], 1000]}],      PlotRange -> {{0, 3}, {0, 3}}     ]      ![enter image description here](http://i.stack.imgur.com/nQ1QZ.png) In version 10, the upper bound (3) is obeyed (with some new padding) but the lower bound (0) is ignored: ![enter image description here](http://i.stack.imgur.com/uVaJU.png) How can I make DensityHistogram obey the lower bound in PlotRange?


title: How do I expand a sum?

text: I have a problem with _Mathematica_ 's symbolic manipulations. As an example, consider the following expression: $$\sum _{i=1}^n -2 x_i \left(-a x_i-b+y_i\right)=0$$ How do I get _Mathematica_ to expand it into this form: $$-\sum _{i=1}^n x_i y_i +a \sum _{i=1}^n x_i^2+b \sum _{i=1}^n x_i=0$$ What I mean is: what functions do I apply to get the product to expand and the summation operator to distribute?


title: Efficient code for the Ten True Sentences puzzle

text: I am trying to solve Ten True Sentences Puzzle. > Take a look at the following sentences: > >   * The number of times the digit 0 appears in this puzzle is **_**. >   * The number of times the digit 1 appears in this puzzle is **_**. >   * The number of times the digit 2 appears in this puzzle is **_**. >   * The number of times the digit 3 appears in this puzzle is **_**. >   * The number of times the digit 4 appears in this puzzle is **_**. >   * The number of times the digit 5 appears in this puzzle is **_**. >   * The number of times the digit 6 appears in this puzzle is **_**. >   * The number of times the digit 7 appears in this puzzle is **_**. >   * The number of times the digit 8 appears in this puzzle is **_**. >   * The number of times the digit 9 appears in this puzzle is **_**. > > > Fill these sentences with digits such that all the sentences holds true. I wrote the following code, but it didn't work.               Do[       If[Tally[Range[0, 9] ~Join~ x][[All, 2]] == x, Print@x],       {x, Tuples[Range[0, 9], 10]}] // AbsoluteTiming      How can I imporve my code? **Updated**               Compile[{},        NestWhile[Join[{1, 7, 3, 2}, RandomInteger[10, 6]] &, Range[0,9],            Tally[Range[0, 9] ~Join~ #][[All, 2]] != # &],         CompilationTarget -> "C", RuntimeOptions -> "Speed"        ][] // AbsoluteTiming


title: Why is Mathematica treating my text as input?

text: I have typed in some text input by using Alt-7 to convert everything into text, but why is text still evaluated? Or is there better way to make comments other than (* text here *), because in my text there are numbers and it is also evaluating them too?


title: FindRoot options

text: I found an example of `FindRoot` usage that I couldn't find documented. It looks like:               FindRoot[f[x] == 0.4, {x, 0, 1, 0, 1}]      The documentation shows this case `FindRoot[lhs==rhs, {x, xstart, xmin, xmax}]` searches for a solution, stopping the search if x ever gets outside the range. But the example I found has an extra argument. What does it mean? Thanks.


title: Coloring a set of polygons, each polygon to have a specific color

text: In addition to my previus post, regarding plotting the surface of a Möbius strip, I now realised, that some of the eigenmodes for a Möbius strip are either oscillations of a scalar field OR a vector field, meaning that not all eigenmodes of this object can be shown in 3D as wobbles in the direction normal to the surface, because the Möbius strip is not orientable, like a cylinder is. Now that I have learned this fact, I have to do the following:   1. Represent all **transversal** oscillations as wobbles in the direction normal to the surface. This means that these are oscillations of a vector field with only one component. This has been succesfully done with the help in my previous question. Here is the solution for the case of a cylinder.   2. I need to represent all the **longitudinal** oscillations as oscillations of a scalar field, which is usually done by showing changes of color on an object, like shown in this example for a cylinder: ![enter image description here](http://i.stack.imgur.com/egcXZ.png) **Problem** I would like to plot 4D data $(x,y,z,F)$ as a set of polygons that have been made using `DelaunayTriangulation[]` of a 2D mesh in 3D using `Graphics3D`for the case of a Möbius strip, where $(x,y,z)$ are the data points and $F$ is the color. In my previous question I noted that `ListSurfacePlot3D` and `ListPlot3D` are not working properly for the case of the Möbius strip. The solution was to plot the strip as a set of polygons, generated by the mesh. A uniformly colored polygon surface looks like this: ![enter image description here](http://i.stack.imgur.com/cc4b3.png) **What I want** I would like to color these polygons with the color equal to the average value of $F$ for the surrounding 3 points. **Here is the provided data and code** Original 2D data of a rectangular $[0,1]\times[0,1]$ membrane:               data2D = Import["http://pastebin.com/raw.php?i=0Liw8F1r", "NB"];      Transformed 4D data parametrised as a Möbius strip with color data as the 4th column:               data4D = Import["http://pastebin.com/raw.php?i=zgrCRiQh", "NB"];      The code to draw the strip without the color data $F$:               tri = First@        Cases[ListDensityPlot[Join[#, {0}] & /@ data2D],          Polygon[idx_] :> idx, Infinity];              Graphics3D[          GraphicsComplex[           data4D[[;; , 1 ;; 3]], {Yellow, EdgeForm[], Polygon /@ tri}],           Boxed -> False, AspectRatio -> 1, BoxRatios -> Automatic,           SphericalRegion -> True,           PlotRange -> 0.9 {{-1, 1}, {-1, 1}, {-0.5, 0.5}}, ImageSize -> Large]      I tried to find some answers before posting the question, but all solutions had either discrete points or smooth plots in 3D, andI need to color the specific polygons. Thank you all for your help, I hope that the problem is clearly stated.


title: Can this function be numerically integrated

text: I need to integrate the function, $f(a,b)=-g(a,b) _ln(g(a,b)) = -1/ Pi_ (( (E^(-((a^2 - E^(-t [Gamma]) [Alpha]^2)/( 1 + 2 [Sigma]^2)))) [Pi] ([Sigma]^2) )/((1 + 2 [Sigma]^2) (E^(2 [Alpha]^2) + Cos[[Phi]])) (Exp[ I*(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)] + Exp[-I*(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)]) + (( E^(-((b^2 + (a + Sqrt[E^(-t [Gamma])] [Alpha])^2 - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/( 1 + 2 [Sigma]^2)))) [Pi] )/((2 + 1/[Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]])*E^(t [Gamma])) + (( E^(-((b^2 + (a - Sqrt[E^(-t [Gamma])] [Alpha])^2 - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/( 1 + 2 [Sigma]^2)))) [Pi] )/((2 + 1/[Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]]) _E^(t [Gamma])))/ Normalization_ (Log[( [Pi] ([Sigma]^2) )/((1 + 2 [Sigma]^2) (E^( 2 [Alpha]^2) + Cos[[Phi]]))] - ( a^2 - E^(-t [Gamma]) [Alpha]^2)/(1 + 2 [Sigma]^2) + Log[(2* Cos[(4 b E^(-((t [Gamma])/2)) [Alpha] + [Phi] + 2 [Sigma]^2 [Phi])/(1 + 2 [Sigma]^2)]) + E^(-((b^2 + 2*a*Sqrt[ E^(-t [Gamma])] [Alpha] - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/(1 + 2 [Sigma]^2)))* E^(-t [Gamma]) + E^(-((b^2 - 2*a*Sqrt[ E^(-t [Gamma])] [Alpha] - (2 [Alpha]^2 + t [Gamma]) (1 + 2 [Sigma]^2))/(1 + 2 [Sigma]^2)))* E^(-t [Gamma])] - Log[Normalization]) where $g(a,b)=$![enter image description here](http://i.stack.imgur.com/m1fEs.png) `a,b` are variables, `I` is a imaginary unit and others are constants having the following values. Normalization= 0.00585175 [Alpha] = 0.8 [Gamma] = 0.005*0.08 [Phi] = 0 [Sigma] = 0.02 t = 0 $f(a,b)$ cannot be analytically integrated, and so I'd like to numerically integrate it. As you can see in $g(a,b)$, $f(a,b)$ is a highly oscillatory function. So I'm using option `"LevinRule"`.               NIntegrate[f, {a, -Infinity, Infinity}, {b, -Infinity, Infinity},       Exclusions -> g == 0, Method -> "LevinRule",       MaxRecursion -> 100], WorkingPrecision -> 60]      The problem is _Mathematica_ says that > >     Numerical integration with "LevinRule" failed. The integration continues >     with Method ->"MultiDimensionalRule" >   The result of the numerical integration with `"MultiDimensionalRule"` is not accurate enough. Anyone knows how I can numerically integrate $f(a,b)$?


title: Is there a guideline about when to end expressions with semicolons?

text: Whether for nested `If`s or within scoping constructs like `Module` and `Block`, I never know whether to end the final expression with a semicolon. I know the semicolon suppresses output, but, for example, in a series of nested `If`s, one needs only to semicolon the outermost `If` to suppress output. So, is it better practice to semicolon _everything_ unless output is needed? Or is it better to semicolon _nothing_ until the last point where output is unwanted?


title: Find all the integer numbers $a$, $b$, $c$, $d$, $e$, $f$, $k$ to this equation have three integer different solutions?

text: How to find all integer numbers $a$, $b$, $c$, $d$, $e$, $f$, $k$ that belong to interval $[-10,10]$, so that the equation $$\sqrt[3]{a x + b} +\sqrt[3]{c x + d} + \sqrt[3]{e x + f} =k$$ has three different integer solutions? I tried               Reduce[{Root[#^3 - (a x + b) &, 1] + Root[#^3 - (c x + d) &, 1] +          Root[#^3 - (e x + f) &, 1] == k, -10 <= a <= 10, -10 <= b <=         10, -10 <= c <= 10, -10 <= d <= 10, -10 <= e <= 10, -10 <= f <=         10, -10 <= k <= 10}, {a, b, c, d, e, f, k, x}, Integers]      **Update** With $k=0$, we can transform the given equation of the form $$(a+c+e)x + b + d + f = 3\sqrt[3]{(ax + b)(cx+d)(ex+f)}$$ Cubing both sides of the equation:               ClearAll;     f[x_] := (a + c + e) x + b + d + f;     g[x_] := 3 ((a x + b) (c x + d) (e x + f))^(1/3);     Collect[f[x]^3 - g[x]^3, x];     Discriminant[%, x]      Next, we solve for `Discriminant > 0` But I can not get the answer. This is some equations   * $\sqrt[3]{-2 x + 8}+ \sqrt[3]{x + 2} + \sqrt[3]{x - 10}=0$.   * $\sqrt[3]{-2 x + 4}+ \sqrt[3]{x + 6} + \sqrt[3]{x - 10}=0$.   * $\sqrt[3]{-3 x + 9}+ \sqrt[3]{x + 1} + \sqrt[3]{2x - 10}=0$.   * $\sqrt[3]{-6 x + 6}+ \sqrt[3]{4 x + 4} + \sqrt[3]{2x - 10}=0$.


title: How safe are ReadProtected and Locked symbols?

text: > **Possible Duplicate:**   >  How to distribute proprietary Mathematica code I suspect that there is a way to expose the down values of such symbols with an attack along these lines:               Unprotect[SetAttributes, Set, Attributes]     SetAttributes[sym_, att_Symbol] /; MemberQ[{Locked, ReadProtected}, att] := Null     SetAttributes[sym_, atts_List] /;  MemberQ[atts, (Locked | ReadProtected)] :=       SetAttributes[sym, DeleteCases[atts, (Locked | ReadProtected)]]     Attributes /: Set[Attributes[sym_], att_Symbol] /;        MemberQ[{Locked, ReadProtected}, att] := Null     Attributes /: Set[Attributes[sym_], atts_List] /;        MemberQ[atts, (Locked | ReadProtected)] :=       SetAttributes[sym, DeleteCases[atts, (Locked | ReadProtected)]]     Protect[SetAttributes, Set, Attributes];      Can anyone recover the down values of this MrE[] function if you load "FindMeEncoded.m" into a fresh kernel?               MrE[x_] := With[{y = "you found me!!!!"}, ToString[x] ~~ ": you can't find me"]     SetAttributes[MrE, ReadProtected]     SetAttributes[MrE, Locked]     Save["FindMe.m", MrE]     Encode["FindMe.m", "FindMeEncoded.m"]


title: Read/Write protection of script

text: I have a script file (.m), which I need to distribute for execution. How can I read/write protect it? thanks


title: Solving an ODE in power series

text: How do I find a series solution to an ODE? I do not mean taking the Taylor series of an exact solution; I want to solve nasty nonlinear differential equations locally via plug and chug. Surely, that is a built-in option in _Mathematica_.


title: How to configure two Mathematica in different places with different settings

text: For some reasons, I should use two language versions _Mathematica_. The most reason is I want to see the comparison of Help page(English version and Chinese version) to improve my English, both are useful.   * [update]However, When I just concentrate on the language of Help page, that problem is nothing, just put english help page in the english version, and chinese help page in the chinese version, open Mathematica by two shortcut, it's OK now, ignore the language of the UI(both Chinese). ## question 1: How to make `FrontEnd` do not show this popup dialogue? ![enter image description here](http://i.stack.imgur.com/kmgok.png) ## question2: I've installed two _Mathematica_ 9 with different language versions. One in Disk D `English` Version One in Disk E `ChineseSimplified` Version How to configure two different settings? # _(Hard point:)_ Because they share the configures, some configure files are stored here in my computer.               "E:\\Users\\Quaternions\\AppData\\Roaming\\Mathematica"     "E:\\Users\\Quaternions\\AppData\\Roaming\\Mathematica\\FrontEnd\\init.m"      How to make the different configures, such as `Language`, `Background` and others. For background color, the value of `Background` is easy to setting. As I've tried, one can add               SetOptions[FrontEndSession,Background->LightBlue]      in some init.m here               "D:\\Program Files\\Wolfram\\Research\\Mathematica\\9.0\\SystemFiles\\Autoload\\PacletManager\\Kernel\\init.m"      or here               "D:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\AddOns\\AutoLoad\\English\\init.m"      And then when open _Mathematica_ in Disk D, the background is LightBlue. When open _Mathematica_ in Disk E, the background will be White ($FrontEnd background value). What's the tough thing? The value of `$Language` So the keypoint of the problem is： How to open _Mathematica_ in Disk D whose `$Language` is English [Help page language is English, and also UI is English], and Open _Mathematica_ in Disk E whose `$Language` is ChineseSimplifed [Help page language is ChineseSimplified and also UI is ChineseSimplified]


title: Drawing a complete graph of an ego network

text: I have an ego network (a network of a person (ego) and his friends). It is drawn with the ego at the center surrounded by the friends. It might be possible that all the friends are connected to each other, in which case one can have a complete graph. Mathematica however draws a complete graph with no focal node. How can I make Mathematica draw a complete graph with a center node in it? How can I remove some connections so that it would still be an ego network but not a complete graph? Thanks.


title: Fast calculation of commute distances on large graphs (i.e. fast computation of the pseudo-inverse of a large Laplacian / Kirchhoff matrix)

text: I have a large, locally connected and undirected graph $G$ with $\approx 10^4$ vertices and $\approx 10^5$ to $\approx 10^6$ edges. Moreover I can bound the maximum vertex degree as $Q_{max}$. I would like to obtain all pairwise commute times between vertices in two sets $(v_{(a,1)}, ..., v_{(a,M)}) \in V_a$ and $(v_{(b,1)}, ..., v_{(b,N)}) \in V_b$ where $N >> M$, and do this without simulation of the underlying Markov process. To do this I need to compute the Laplacian matrix of $G$ (which is apparently computed using KirchhoffMatrix[G] in Mathematica, and takes about $\approx 50$ milliseconds on an X5690 3.47 GHz Intel Xeon processor), and then to compute its pseudoinverse, which I believe is an $O(n^3)$ operation. My question is - does Mathematica have a nice way of computing the pseudoinverse for a large Laplacian matrix, allowing me to efficiently extract commute times between pairs of vertices? How large can $G$ be? * * * Update - Following from Szabolcs comments, can anyone confirm that the time complexity of PseudoInverse[] is $O(n^3)$?


title: Is there a keyboard shortcut for Centered Math Cell?

text: I've been typesetting in mathematica and would like to know if it is possible to use a keyboard shortcut to place a centered math cell or equation symbol aligned math cell in my document without having to use the writing assistant.


title: Unexpected result from Map

text: I'm using _Mathematica 8.0_. Is the following output a bug or do I miss something?               f[a_] = 2 a;     Map[f,1+x]      gives $2+2x$ as expected, but               Map[f,x]      results in the output $x$


title: Determining the RGB values of the default plot color

text: In Mathematica 7, the default plot color is a purple-like color (although I think it is _not_ `Purple`). Is it possible to use Mathematica to determine the RGB color values of the default plot color? Thanks for your time.


title: Maximum tuple value

text: Is there a simple way to make a maximum tuple value (similar to python)? For example, in python               max([ (1,2), (1,3), (3,1), (4,0) ])      returns `(4,0)`, using lexicographic order. If I have a tensor in Mathematica, is there a way to take the max without flattening it? i.e. a way to call               Max[ { {1,2}, {1,3}, {3,1}, {4,0} } ]      so that it returns `{4,0}` instead of `4`?


title: Determine Functions Given Data Points

text: Is it possible for Mathematica to solve for f(x,y) = 0 such that {x,y} contains `{{0,0.5}, {1,0.5}, {0.6,0.8}, {0.4,0.2}}` ? Do we need to specify f(x,y) first ? Thank you


title: Plotting a network or a graph with given coordinates for vertices

text: I'm new to _Mathematica_ yet have coded a lot in MATLAB. Currently I'm working on a network simulation. My model is implemented in MATLAB, but I need to port it to _Mathematica_. **Here is my question** : Given a graph `g` and coordinates `x` and `y` for each node. I want to plot the network with nodes at the corresponding coordinates. How can this be done? In case you are also used to MATLAB, there is the function `gplot`, which does the job. Is there a similar plotting function in _Mathematica_?


title: Can you label an array by variables or strings instead of integers?

text: Is there a way to label an array by a variable instead of an integer? For example calling the array `I[i,j]` with `{i,j} = {x,y,z}` instead of `{i,j} = {1,2,3}`? For example, I might want to label the components of the Inertia tensor by `I[x,x]`, `I[x,y]`.. instead of `I[1,1]`, `I[1,2]`..


title: BoxWhiskerChart without whiskers

text: I would like a chart showing the median, 1/4, 3/4 quartiles, without the whiskers or fences. how can I achieve this? I cannot figure out how to turn off both the whiskers and the fences in the result of:               BoxWhiskerChart[RandomVariate[NormalDistribution[0, 1], 100]]      but doing so would do the trick.


title: Want more vibrant colors in plots

text: Is it possible to create plots that have vibrant colors like those I create in Python? For instance, take this thread function returning 0 where I used rainbow and here is the temperature gradient: ![enter image description here](http://i.stack.imgur.com/VmXIe.png) Now here is a heat map I created in Python for comparison. ![enter image description here](http://i.stack.imgur.com/uAyax.png)


title: How to create moving graphics that maintain shape

text: In the output code for the following graphic:               a = .5;     b = .4;     Subscript[θ, 1] = π/4;     Subscript[θ, 2] = π/4;     Q = 5;     p = 1;     {Slider[Dynamic[Subscript[θ, 2]], {0, 2 π}],       Dynamic[Subscript[θ, 2]],       Dynamic[ListPlot[        Flatten[{Table[{a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {a, -.5, .5, .1}],           Table[{a + p, -b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {a, -.5, .5, .1}],           Table[{a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {b, -.25, .25, .05}],           Table[{-a + p,               b}.{{Cos[Subscript[θ, 2]],                Sin[Subscript[θ, 2]]}, {-Sin[Subscript[θ, 2]],                Cos[Subscript[θ, 2]]}}.{{Cos[Subscript[θ,                 1]], Sin[Subscript[θ,                 1]]}, {-Sin[Subscript[θ, 1]],                Cos[Subscript[θ, 1]]}} + {Q*              Cos[Subscript[θ, 1]],              Q*Sin[Subscript[θ, 1]]}, {b, -.25, .25, .05}]}, 1]        , PlotRange -> {{-5, 5}, {-6, 6}}]]}      The shape moves as I move the dynamic slider. However, the shape is distorted. I would like to figure out how to maintain the original shape of the rectangle as I move the plots of points around in the circle. How do I do this?


title: Displaying a locator that moves smoothly and updates some dynamic variables

text: I want to select a point on a graph and display a function of the coordinates value. Asking here a related question I learned to use Setting. Consider the example, where I display the coordinate `x` and its double `2*x`:               Manipulate[      xp = Dynamic[First[pt]];      z = Setting[2*xp];      Column[{        Style[StringForm["x=`1`, z=`2`", xp, z], Blue, 16],        LocatorPane[Dynamic[pt],         ListPlot[{{0, 0}},          Epilog -> {Red, PointSize[Large], Point[Dynamic[pt]]}          ]]}, Center],      {{pt, {0, 0}}, None}      ]      By clicking on the graph, the value of `x` and `z = 2*x` is correctly displayed above the graph. However, one cannot move the `Locator` smoothly, each point must be clicked! The problem is caused by `Setting`. By removing it, the point can be moved around smoothly, `x` is displayed dynamically but then the `z` is not calculated but displayed as `2 x`. Is it possible to display the value of `z` without loosing the fluency in the point selection? Is there a different way to get the value of `z` without using `Setting`?


title: Using Wolfram Language without Raspberry Pi

text: What are the different ways I can start using Wolfram Language even though I dont want to use Raspberry Pi? Are there any convenient ways? I actually have a raspberry pi but I am trying to find alternative workarounds as well.


title: How is Wolfram Language different than regular Mathematica?

text: From all I can see there seems to be no difference between "Wolfram Language" and regular Mathematica. Is Wolfram just a marketing rebranding of Mathematica or is there a new capability I am missing?