title: Colouring of multiple data sets in DiscretePlot

text: I noticed the following strange behaviour: Let us first define an array of functions                   g[k_] := {Sin[k], 2*Sin[k]}         gg = g[k]      When I plot this array of functions with                   DiscretePlot[{Sin[k], 2 Sin[k]}, {k, 1, 50}]      each of the two sets of points have a different colour. But, both                   DiscretePlot[gg, {k, 1, 50}]      and                   DiscretePlot[g[k], {k, 1, 50}]      show the two sets of points in blue. I am more interested in the second case, because should the array of functions be large, it is more comfortable to use the definitions like `g` and `gg` given above. But I want to preserve the different colours. How do I do that?


title: When is Evaluate needed within function arguments?

text: I'm trying to do a simple variable substitution within a ContourPlot, but it's not working. Here's an example:               ContourPlot[x y == 1/2, {x, 0, 1}, {y, 0, 1}]      ContourPlot[x y == 1/2 /. y -> z, {x, 0, 1}, {z, 0, 1}]      The second line, although mathematically identical, produces no contour. Why? How can I do the substitution correctly? **Edit:** It looks like my initial question is solved by simply wrapping the argument in Evaluate. However, why doesn't Plot obey the same rules? The following works without Evaluate:               Plot[x, {x, 0, 1}]     Plot[x /. x -> z, {z, 0, 1}]


title: How does Plot evaluate its argument?

text: I have a list of about twenty `InterpolatingFunction`s that I'd like to plot. They are interpolations from experimental data (frequency spectra between 100 and 5000 MHz, since you asked).               In[210]:=  interps     Out[210]:= {InterpolatingFunction[{{100.,5000.}},<>],                 InterpolatingFunction[{{100.,5000.}},<>],                 InterpolatingFunction[{{100.,5000.}},<>] (* ... etc ... *)}      I tried this:               (* Through[interps[f]] threads the argument f through the list *)     Plot[Through[interps[f]], {f, 100, 999}]      ![First attempt: inline expression](http://i.stack.imgur.com/C7w3q.png) This took about thirty seconds, and as you can see the lines are all the same colour. On a whim, I tried replacing it with this:               expr = Through[interps[f]];     Plot[expr, {f, 100, 999}]      ![Second attempt: extracting a variable](http://i.stack.imgur.com/3niGz.png) This only took about two seconds, and the default colours worked this time. This was a major 'WTF' moment for me. Is this a bug? Why aren't the two versions of the code equivalent? I'm using Mathematica 9.0.1.0.


title: How can I plot the characteristic polynomial?

text: For example, I have:               CharacteristicPolynomial[m, x]      > >     0.5 + 0.1 x + x^2 >   But               Plot[CharacteristicPolynomial[m,x], {x,-1, 1}]       gives errors.


title: Why can't D[] be used in place here?

text: > **Possible Duplicate:**   >  General::ivar is not a valid variable when plotting - what actually causes > this and how to avoid it? Beginner question: Why can't I use `D[]` like that?               Plot[{Sin[x], D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]      If I assign the result of `D[]` to a variable and put that variable in the list it works.


title: Error plotting delayed expressions

text: I have defined:               Qq[T_] := Exp[-w/(2 T)]/(1 - Exp[-w/T])       Uq[T_] := T^2 D[Log[Qq[T]], T]      Can someone explain why this expression work:               Plot[Evaluate[Uq[T] /. w -> 1], {T, 0, 2}]        (As result the plot is created) But this does not?:               Plot[Evaluate[Uq[T]] /. w -> 1, {T, 0, 2}]        (As result a General::ivar error is displayed)


title: How to ContourPlot a Table?

text: > **Possible Duplicate:**   >  Why is ContourPlot not displaying this curve?   >  Why do I have to put Evaluate[] here I'm trying to plot certain contours of a function $f:\mathbb R^2\to\mathbb R$. What I tried is the following:               ContourPlot[Table[f[x, y] == a, {a, 0, 1, 0.1}], {x, -3, 3}, {y, -3, 3}]      For some reason this doesn't work. If I first evaluate `Table[f[x, y] == a, {a, 0, 1, 0.1}]` and then plug the result into `ContourPlot`, however, it does work. I've noticed that `Table[f[x, y] == a, {a, 0, 1, 0.1}]` is evaluated to `{False, False, ..., False}` somewhere in the process if evaluated inside `ContourPlot`. (Which is not the same result as when evaluated separately.) > Why does this happen? What can I do to make it work? Thanks.


title: app keeps minimizing when switching in windows 8

text: so I run mathematica on my surface pro with windows 8 pro, when I opened a notebook in it and switched to my browser and some other apps it's sometimes impossible to go back to my notebook, it doesn't reopen the window. It gives me a windows warning sound but nothing pops up or shows, I just can't switch back is this a certain setting in windows that needs to be changed or a mathematica bug?


title: When exporting text, how can I set the line separator?

text: I want to export a string for a bash script. The terminal is naturally very picky when it comes down to the "\n\r" vs "\n", Windows vs. Linux, new line issue. How can I teach _Mathematica_ to use "\n" rather than "\n\r" as the line separator when exporting text (in Windows)? I found a couple of posts regards the same issue, but they were concerned with importing files. For example, here. None of the suggested solutions worked for my case. I played with `CharacterEncoding` and `"LineSeparators"` but nothing worked. EDIT: Great thanks to Mark Adler for giving me the right clue. His suggested solution `WriteString[f, "\n"]` did not work because "\n" is interpreted by _Mathematica_ as string not as end-of-line. However, his suggested `DOSTextFormat -> False` option also works as option for `Export[]`. I got the desired result using `Export[filename,script,"Text",DOSTextFormat -> False]`.


title: What is wrong with my VectorPlot?

text: I am trying to make a simple plot of a spherical field falling off with distance from origin:               VectorPlot[{x, y} / EuclideanDistance[{0, 0}, {x, y}]^2, {x, -3, 3}, {y, -3, 3}]      I just get dots. Why do I get this? ![enter image description here](http://i.stack.imgur.com/oFgFY.png)


title: How can I plot a function that is the sum of another function?

text: I plotted `m[t]`, but actually what I want to plot is `g[t]`, which is a summation of `m[t]` from 0 to 19 seconds. But when I plot `g[t]`, I get dots. On the picture, what I want is on the right, I don't want the dots, so I guess list plot is not the way to go. How should I plot g to look like the picture I have to the right; ![enter image description here](http://i.stack.imgur.com/j6FkE.png) ### EDIT My code;               period = 1;                                          beta = 0.05;     An = List[{-1 , 1, -1, +1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1}];          sinch[t_] := (Sin[(Pi*t - t*period)/period])/(Pi* t);                                      m[t_] :=        An * sinch[t] * (Cos[(Pi*beta*t - t*period) / period] /          (1 - (4*beta^2 * (t - t*period)^2 )/period^2 ));           Plot[{m[t]}, {t , 0, 19}]                  g = Sum[m[t], {t, 1, 20}];     ListPlot[g]


title: Fill gap created by Exclusions

text: A gap appears at the locations of Exclusions at t=1,t=1+t0 when the top slider for t0 is set to Play. How can these gaps be avoided or filled in?                Manipulate[             y[t_, t0_] := 1/(1 - (t - t0));        y0[x_] := y[x, 0];        yT[x_] := y[x, t0];             Plot[{y0[t], yT[t]}, {t, -3, 7},        Exclusions -> {t == 1, t == 1 + t0},        PlotStyle -> {{Thick, Black}},        PlotRange -> {0, 3},        Frame -> True,        Axes -> False,        ImageSize -> 1.2 {500, 330},        BaseStyle -> {FontSize -> 16},        FrameLabel -> {t, x},        RotateLabel -> False,        PlotRangePadding -> {{2, 0}, {.1, .1}},        Epilog -> {PointSize[0.015], Red, Dashed,       Line[{{-4, y0[s]}, {s, y0[s]}}],         Point[{{-4, y0[s]}, {s, y0[s]}, {s + t0, yT[s + t0]}}],        Black, Dashing[{}], Line[{{-4, 0}, {-4, 3}}],        Red, Point[{-4, y1[s]}],        Black, Arrowheads[.03], Arrow[{{-4, 3}, {-4, 3.1}}],        Red, Dashing[{}], Line[{{s, y0[s]}, {s + t0, yT[s + t0]}}]}],             {{t0, 2}, -2, 5, 0.01},        {{s, 0}, -2, 0.67, 0.01}              ]


title: Why don't * and ^ work as I expected on matrices?

text: For example, this input...               {{1, 2}, {3, 4}}*{{1, 2}, {3, 4}}      produces this output...               {{1, 4}, {9, 16}}      and this input...               {{1, 2}, {3, 4}}^2      produces the same...               {{1, 4}, {9, 16}}      What I want in both cases is...               {{7, 10}, {15, 22}}      I think I know what's going on here. Mathematica doesn't seem to be discriminating between lists of lists, and matrices, and the `*` and `^` operators are just threading over the lists. I've found `.` and `MatrixPower` which do what I think `*` and `^` should. But the question still remains, is this confusing (to at least me) behavior of `*` and `^` by design, and what benefit does it confer?


title: Using spherical derivatives with NDSolve

text: I am trying to plot the path of an object around a centre of mass. Obviously this needs spherical coordinates. The problem I encounter is with the derivatives. The Derivatives in spherical coordinates are for (radial, azimuthal, polar) (r,theta,phi):               dr = r'     dϕ = r ϕ'     dθ = r Sin[ϕ] θ      Where the accelerations in theta and phi remain 0 for now. But I need values for the initial velocity, this means that when I add the sinus to the NDSolve, it can't solve the set of equations; This is the furthest I've come. In truth, I'm not sure if this is the right approach or not, but solving the equations in Cartesian coordinates brings a lot more problems.               b = 20;     ball = First@NDSolve[{r''[t] == -9.81/r[t]^2, r[0] == 5, r'[0] == 0,        WhenEvent[r[t] == 2.25, r'[t] -> -0.9 r'[t]], θ''[t] == 0,       θ[0] == 0,r[0] θ'[0] == π/4, ϕ''[t] == 0,       ϕ[0] == π,r[0] ϕ'[0] == π/4}, {r, θ, ϕ}, {t, 0, b}];      The following doesn't work (third row, added sinus):               ball = First @ NDSolve[{r''[t] == -9.81/r[t]^2, r[0] == 5, r'[0] == 0,       WhenEvent[r[t] == 2.25, r'[t] -> -0.9 r'[t]], θ''[t] == 0,      θ[0] == 0,r[0] Sin[ϕ[0]] θ'[0] == π/4, ϕ''[t] == 0,      ϕ[0] == π,r[0] ϕ'[0] == π/4}, {r, θ, ϕ}, {t, 0, b}];      I then plot with:               Manipulate[       Show[         ParametricPlot3D[{r[t] Sin[θ[t]] Cos[ϕ[t]] /. ball,            r[t] Sin[θ[t]] Sin[ϕ[t]] /. ball,            r[t] Cos[θ[t]] /. ball}, {t, 0, a},            PlotStyle -> {Gray, Dashed, Thick},            PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}],          ParametricPlot3D[{r[t] Sin[θ[t]] Cos[ϕ[t]] /. ball,            r[t] Sin[θ[t]] Sin[ϕ[t]] /. ball,            r[t] Cos[θ[t]] /. ball}, {t, a - 0.001, a},            PlotStyle -> {Black, Thickness[0.05]},            PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}],          Graphics3D[Sphere[{0, 0, 0}, 2]]],       {{a, b/100, "Time"}, b/100, b}]      Trying:               ball = First @ NDSolve[{x''[t]^2 + y''[t]^2 + z''[t]^2 ==      -9.81^2/(x''[t]^2 + y''[t]^2 + z''[t]^2)^2,       x[0] == 3, y[0] == 3, z[0] == 3, x'[0] == 1, y'[0] == 0,       z'[0] == 0,       WhenEvent[x''[t]^2 + y''[t]^2 + z''[t]^2 == 2.25^2,        x''[t]^2 + y''[t]^2 + z''[t]^2 -> -0.9 x''[t]^2 + y''[t]^2 +        z''[t]^2]}, {x, y, z}, {t, 0, b}];      Returns an under-determined error. I get that I have only one second derivative, but going all out (added row 3):               ball = First@NDSolve[{x''[t]^2 + y''[t]^2 +       z''[t]^2 == -9.81^2/(x''[t]^2 + y''[t]^2 + z''[t]^2)^2,       ArcTan[x[t], y[t]] == 0, ArcTan[z[t], Sqrt[x[t]^2 + y[t]^2]] == 0,      x[0] == 3, y[0] == 3, z[0] == 3, x'[0] == 1, y'[0] == 0,       z'[0] == 0,       WhenEvent[x''[t]^2 + y''[t]^2 + z''[t]^2 == 2.25^2,        x''[t]^2 + y''[t]^2 + z''[t]^2 -> -0.9 x''[t]^2 + y''[t]^2 +        z''[t]^2]}, {x, y, z}, {t, 0, b}];      produces the messages: > Warning: the rule (x'')[t]^2+(y'')[t]^2+(z'')[t]^2->-0.9 > (x'')[t]^2+(y'')[t]^2+(z''[t]^2 will not directly set the state because the > left-hand side is not a list of state variables. >> > > Unable to find initial conditions that satisfy the residual function within > specified tolerances. Try giving initial conditions for both values and > derivatives of the functions. >>


title: Scope within Context

text: To define some package-wide functions/variables, what approach is recommended? I tried to use contexts with the `Begin` function, but this failed:               Clear[fun];     fun[] := Module[{},        Begin["myContext`"];        x = 1;        End[];        ];     fun[]     myContext`x      I would expect `myContext'x` to be 1, but it seems to be undefined. Why does this fragment fail, what should I do instead?


title: Plotting a parametric function with three input variables

text: I want to plot a 2D parametric function of the form: $$ f_x(\theta_1,\theta_2,\theta_3) = \cos(\theta_1)+\cos(\theta_1+\theta_2)+\cos(\theta_1+\theta_2+\theta_3) $$ $$ f_y(\theta_1,\theta_2,\theta_3) = \sin(\theta_1)+\sin(\theta_1+\theta_2)+\sin(\theta_1+\theta_2+\theta_3) $$ where the ranges for the input variables are: $ \theta_1 \in [-\pi,\pi]$ and $ \theta_2 \in [-\pi,\pi]$ and $ \theta_3 \in [\frac{-\pi }{2},\frac{\pi }{2}]$ I tried to use `ParametricPlot`, but it takes only two input variables. Can any one help me with this?


title: Using an InputField to define a function to compose with a sequence

text: I am still trying to figure out Mathematica (started early August). I am trying to write a program that will accept an arbitrary function and an arbitrary sequence that can start at an arbitrary natural number in order to compose the function with the sequence so that my students can investigate the sequential criterion for the limit of a function. I cannot figure out how to get Mathematica to accept a function...below is what I have worked out so far. Any help would be greatly appreciated!               Manipulate[DynamicModule[{ a = 1 /n, b = 1},        Column[{Labeled[InputField[ Dynamic[  f[x_] :> ( x^2 - 4)/( x - 2 ) ]], "function", Left],                Labeled[InputField[Dynamic[a]],"sequence", Left],               Labeled[InputField[Dynamic[b]], "i=" , Left ],                Dynamic[If[ ( t - b ) < 11,                   TableForm[ Transpose[ {Range[b, t], Table[ N[ a, 4 ], {n, b, t} ],                     Table[ N[ f[ a ], 4], {n, b, t}]}], TableHeadings -> {           None, { "n", "\!\(\*SubscriptBox[\(a\), \(n\)]\)",            " f(\!\(\*SubscriptBox[\(a\), \(n\)]\))"}}],                  TableForm[Transpose[ {Range[t - 10, t],                     Table[ N[ a, 4 ], {n, t - 10, t} ],                     Table[N[ f[ a ], 4], {n, t - 10, t}]}], TableHeadings -> {           None, { "n", "\!\(\*SubscriptBox[\(a\), \(n\)]\)",            " f(\!\(\*SubscriptBox[\(a\), \(n\)]\))"}}]]]}]], {{t, 1, "k"}, 1, 1000, 1, Appearance -> "Labeled"}]


title: wrong use of _?NumberQ?

text: I am having trouble with a numerical exercise. Here's a simplified version of my problem. I define two functions to find the solution to two constrained maximization problems:               g[a_,b_,x_]:=NArgMax[{h2[a,b,x,y], CONSTRAINT[a,b,x,y]},{y}][[1]]     f[a_,b_,y_]:=NArgMax[{h1[a,b,x,y], CONSTRAINT[a,b,x,y]},{x}][[1]]      In the above definitions h1(.) and h2(.) are "well-behaved" objective functions, "a" and "b" are parameters and `CONSTRAINT[a,b,x,y]` is a given inequality involving the parameters and choice variables. With these functions, I would like to find a fixed point, say, `xstar`:               FindRoot[{xstar==f[a, b, g[a,b,xstar] ]}, {xstar, 0}]      When I try to run `FindRoot` with actual numbers for "a" and "b" I get an error saying that the constraint in the maximization problem is not valid. I think the problem is that it attempts to make a symbolic evaluation. I hence tried defining the functions as `g[a_,b_,x_?NumberQ]` and `f[a_,b_,x_?NumberQ]`, but it didn't work. However, when I defined:               G[x_?NumberQ]:=g[a,b,x]     F[y_?NumberQ]:=f[a,b,y]      and then fixed values for the parameters by setting them equal to a given number (e.g. `a=b=0.1`),then it did work. It seems then that I am doing something wrong when I use `?NumberQ` in the original function to avoid symbolic evaluation... Any ideas on why it is wrong and how to solve it? I would like to make a plot for different values of "a" and "b", so running the simulations one by one (as in the solution I mention above that works, by redefining the function only in terms of one variable) is extremely inefficient... and I'm sure there's a smarter way of doing it ! ;) **Here is a complete example using the above notation** :               h1[a_, b_, x_, y_] := PDF[BinormalDistribution[{a, b}, {1, 1}, .5], {x, y}]     h2[a_, b_, x_, y_] := PDF[BinormalDistribution[{a, b}, {.5, .5}, .7], {x, y}]     CONSTRAINT[a_, b_, x_, y_] := CDF[BinormalDistribution[{a, b}, {1, 1}, .5], {x, y}]     g[a_, b_, x_] := NArgMax[{h2[a, b, x, y], CONSTRAINT[a, b, x, y] < .5}, {y}][[1]]     f[a_, b_, y_] := NArgMax[{h1[a, b, x, y], CONSTRAINT[a, b, x, y] < .5}, {x}][[1]]          FindRoot[{xstar == f[1, 1, g[1, 1, xstar]]}, {xstar, 0}]


title: How does epilog position work in logplots?

text: I'm trying to use `Epilog` in my plots but the position of the `Epilog` isn't making much sense. As a minimal example consider,               LogPlot[Sin[x], {x, 0, \[Pi]}, Epilog -> {Text["x", {\[Pi], 0.2}]}]      I'd have expected this to put an "x" in the center of the graph but instead it shows up in the corner: ![enter image description here](http://i.stack.imgur.com/z1hTp.jpg) I've also tried `ListLogplot` and other graphics but they all produce similar results. How do I force `Epilog` to use the same positions as the plot? Note: I'm using _Mathematica V10_ on _Linux_.


title: How to customize the MathematicaClosingDialog.nb?

text: With _Mathematica_ 10 came the closing dialog notebook, which probably most of you deactivated. (You can bring it back by dechecking "Always exit after closing last window" in Edit->Preferences->Interface.) I just kept it, because my _Mathematica_ installation gets non-responsive (often accompanied by the pop up of the "Progress" window) in several situations including start up. However, the default closing dialog ![defaultClosingDialog](http://i.stack.imgur.com/bUNpL.png)   isn't very functional. Therefore I'd like to customize it to get, e.g. something like: ![customClosingDialog_Explained](http://i.stack.imgur.com/BLc0s.png)   Where the "Quit" button is replaced by a "Quit Kernel" button that just quits the kernel, as there is no advantage to use the default "Quit" instead of the close window X. Furthermore I'd like to extend the closing dialog by adding additional buttons, e.g. a "Evaluate Specified Notebook" button that will evaluate a notebook file, whose path is defined in some .txt file. The only way to read the default _MathematicaClosingDialog.nb_ into Mma I found is               nb = Import[FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd",                  "TextResources", "MathematicaClosingDialog.nb"}]]      The output of this import looks like a mess, though. In summary:   1. How to replace the "Quit" button with a "Quit Kernel" button?    2. How to add additional buttons, like a "Evaluate Specified Notebook" button?   3. Can the directory for the _MathematicaClosingDialog.nb_ be changed?   (I couldn't find it in the "Option Inspector".)


title: Expected graph distance in random graph

text: I am trying to use the functionality of `Expectation` and `Probability` for random graphs, in particular for percolation models. For example, I would like to be able to compute the expected graph distance between two fixed vertices in a complete graph with independent exponential edge weights. The following naive code does not work.               n = 5;     Expectation[     GraphDistance[     CompleteGraph[n,EdgeWeight -> Table[ew[m], {m,1,(n (n-1))/2}]], 1, 2],      Table[ew[m] \[Distributed] ExponentialDistribution[1], {m,1,(n(n-1))/2}]      ]//FullForm      yields               GraphDistance[Graph[List[1,2,3,4,5],List[Null,SparseArray[Automatic,List[5,5],0,List[1,List[List[0,4,8,12,16,20],List[List[2],List[3],List[4],List[5],List[1],List[3],List[4],List[5],List[1],List[2],List[4],List[5],List[1],List[2],List[3],List[5],List[1],List[2],List[3],List[4]]],Pattern]]],List[Rule[EdgeWeight,List[ew[1],ew[2],ew[3],ew[4],ew[5],ew[6],ew[7],ew[8],ew[9],ew[10]]],Rule[GraphLayout,"CircularEmbedding"]]],1,2]      indicating that the random weights are not actually assigned to the edges. A similar example would be the computation of the probability that two fixed vertices in a complete graph are in the same connected component after edges are deleted with probability $1-p$ and retained with probability $p$. Again the following naive code does not work.               n = 5; p = 1/3;     Probability[     GraphDistance[     CompleteGraph[n, EdgeWeight -> Table[ew[m], {m, 1, (n(n-1))/2}]], 1, 2] == 0,      Table[ew[m] \[Distributed] EmpiricalDistribution[{1-p, p} -> {1, 0}], {m,1,(n(n-1))/2}]     ]      Ideally, I would like to be able to compute this probability (a polynomial in $p$) for symbolic $p$. Of course I would also be grateful for other approaches to the problem, but using `Expectation` and `Probability` would feel very intuitive to me. **Update:** The problem can be circumvented by computing the probability of a generic event which is only specified after `Probability` has been applied:               Clear[f, g]     n = 5;     f[ewarray_] :=       GraphDistance[CompleteGraph[n, EdgeWeight -> ewarray], 1, 2]     Probability[     g[Table[ew[m], {m, 1, (n(n-1))/2}]] == 0, Table[ew[m] \[Distributed] BernoulliDistribution[1-p], {m, 1, (n(n-1))/2}]     ] /. g -> f // Simplify      The results are the same as @ubpdqn's MC calculations. I have experimented with `Hold` and `Release` to avoid the use of the extra function `f` but do not know enough those functions to make it work.


title: Obtain data points from a density plot

text: I have a density plot, for example               DensityPlot[Sin[x*y],{x,0,2pi},{y,0,2pi}].      Then I would like to collect points from this densityplot into a file so that I can always use ListDensityPlot to draw these points again, or I may draw these points by some other software. I read several posts on how to do that for Plot, but how can I generalize them to `DensityPlot`?


title: Making an animation which displays a rotating object

text: I want to rotate the geometry obtained whith the input:                 movil = ExampleData[{"Geometry3D", "SpaceShuttle"}]      But it shows an error message : _Graphics is not a Graphics3D primitive or directive_. I'm trying to represent the attitude of an airplane so if there is another option with similar geometry It can also be usefull. I'm using this code:               frame[α_, β_, γ_, t_] :=        GraphicsRow[         {Graphics3D[            Rotate[              Rotate[                Rotate[movil, α °, {0, 0, 1}],                β °, {0, 1, 0}],              γ °, {1, 0, 0}],             Axes -> True, LabelStyle -> 12,             PlotRange -> {{-0.6, 0.6}, {-0.6, 0.6}, {-0.6, 0.6}},             ViewPoint -> {1, 0, 0.2}],           Show[            ListPlot[{ϕctab, θctab, ψctab}, Joined -> True, LabelStyle -> 12,               AxesLabel -> {"n", "Grados [º]"}],             ListPlot[{{{t, ϕctab[[t]]}}, {{t, θctab[[t]]}}, {{t, ψctab[[t]]}}},               PlotMarkers -> {Automatic, 10}]]},          ImageSize -> 590];          frs = Table[frame[ϕstab[[t]], θstab[[t]], ψstab[[t]], t], {t,1, Length[θstab]}];     ListAnimate[frs]


title: Incomplete implementation of units?

text: I've been playing around with the new units capability in MMA9 and I'm becoming a bit frustrated with what I perceive as an incomplete implementation of this capability and I'm wondering if there are other similar examples. For example, `Histogram[]` can take a list of quantities and a `TargetUnits` specification and it will scale the plot appropriately:               data = Quantity[RandomVariate[NormalDistribution[0, 1], 100], "Meters"];     Histogram[data, AxesLabel -> Automatic, TargetUnits -> "Meters"]      ![enter image description here](http://i.stack.imgur.com/a43qZ.png)               Histogram[data, AxesLabel -> Automatic, TargetUnits -> "Centimeters"]      ![enter image description here](http://i.stack.imgur.com/7DER5.png) But the options for `Histogram[]` do not appear to allow units specifications, which seems dangerous to me and can have some (obvious but) strange results if care is not taken. As an example, specifying `bspec = {-3, 3, 0.2}` assuming that the units are in meters results in a figure that looks something like this:               Histogram[data, {-3, 3, 0.2}, AxesLabel -> Automatic, TargetUnits -> "Meters"]      ![enter image description here](http://i.stack.imgur.com/6rzen.png) If we then change the `TargetUnits` to centimeters, here's what happens:               Histogram[data, {-3, 3, 0.2}, AxesLabel -> Automatic, TargetUnits -> "Centimeters"]      ![enter image description here](http://i.stack.imgur.com/wpPSO.png) Needless to say, one could readily draw a completely different conclusion about the nature of the data even though the only thing that's changed is the output units. To me this seems like an incomplete implementation and I'm wondering if anyone else has encountered a similar issue elsewhere? If so, I'm tempted to avoid the new units capability until it's more mature.


title: Symbolic computations with already assigned variables

text: For example I have assigned some variables that could defined in terms of each other. Then I for some reason need to derive some formula using this variables. How to show the result of this computation without substituting the values and how then substitute them? It should look something like this:               computeWithOnly[expr_,vars_]:=...     substitute[expr_,vars_]:=...          a:=1;b:=2;c:=d+e;d:=3;e:=4;     computeWithOnly[Expand[(a+b+c)^3]]     (*a^3 + 3 a^2 b + 3 a b^2 + b^3 + 3 a^2 c + 6 a b c + 3 b^2 c +       3 a c^2 + 3 b c^2 + c^3*)     computeWithOnly[Expand[(a+b+c)^3],{c}]     (*a^3 + 3 a^2 b + 3 a b^2 + b^3 + 3 a^2 d + 6 a b d + 3 b^2 d +       3 a d^2 + 3 b d^2 + d^3 + 3 a^2 e + 6 a b e + 3 b^2 e + 6 a d e +       6 b d e + 3 d^2 e + 3 a e^2 + 3 b e^2 + 3 d e^2 + e^3*)     computeWithOnly[Expand[(a+b+c)^3],All]     (*1000*)     substitute[computeWithOnly[Expand[(a+b+c)^3],{c}],{a,b}]     (*27 + 27 d + 9 d^2 + d^3 + 27 e + 18 d e + 3 d^2 e + 9 e^2 +       3 d e^2 + e^3*)


title: Sound data Import Export

text: Can't regain the data after Export. Create an array of sampled amplitude values:   2\. Visualize as sound   3\. Save it   4\. Get it back   5\. ???               sound = RandomReal[1, {500}];       ListPlay[sound]       Export["test.txt", sound];       in=Import["test.txt"]       ListPlay[in]      A second example.   Take data from a WAV sound,   Export it,   reImport it,   play it.               tubadat = ExampleData[{"Sound", "Tuba"}, "Data"];       Export["TubaDat.dat", tubadat];       in = Import["TubaDat.dat"];       ListPlay[in]        It is not the original sound.


title: Precedence of defined functions

text: When I define functions in _Mathematica_ like:               f[x_] := 3      f[x_Integer] := 6      How is the value of `f[6]` determined?   It seems to be independent of the order they're defined (which would make the most sense). From my initial testing, it picks the most "restricted" definition, but the meaning of this is unclear if I used patterns like `f[x_ /; x > 3]` Can anyone point me to any documentation/specification about this issue ?   I've looked unsuccessfully for a while.


title: Output of plots from within Do[ ] Command

text: I am wondering why the following does not plot the way it's written and exactly how does the `Do[]` function operate? I think I could be using it incorrectly.               In[1]:= u[x_, t_] := (1/2) (Exp[-(x + t)^2] + Exp[-(x - t)^2])             Do[                Plot[u[x, k], {x, -5, 5},                 AxesLabel -> {x, u},                 PlotRange -> {0, 1}],                {k, 0, 3}               ]      * * * ## EDIT               In[2]:= Clear["Global`*"]             a=1;             b=1;             \[Phi][\[Xi]_,\[Nu]_,t_]:=\!\(             \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(10\)]\(             \*UnderoverscriptBox[\(\[Sum]\), \(j = 1\), \(10\)]\((             \*FractionBox[\(5\ \((\(-1\) +              \*SuperscriptBox[\((\(-1\))\), \(j\)])\)\ \((\(-1\) +              \*SuperscriptBox[\((\(-1\))\), \(i\)])\)\), \(j\ i\              \*SuperscriptBox[\(\[Pi]\), \(2\)]\)] Cos[             \*FractionBox[\(1\),              SuperscriptBox[\(\[Pi]\), \(4\)]]              \*SqrtBox[\(             \*SuperscriptBox[\(i\), \(4\)]              \*SuperscriptBox[\(\[Pi]\), \(4\)] +              \*SuperscriptBox[\(j\), \(4\)]              \*SuperscriptBox[\(\[Pi]\), \(4\)]\)] t])\) Sin[i\ \[Pi]\ \[Xi]] Sin[j\ \[Pi]\                                \[Nu]]\)\);             Do[Print@                Plot3D[\[Phi][\[Xi],\[Nu],m],{\[Xi],0,a},{\[Nu],0,b},                Mesh:>Automatic,                PlotLabel:>"Surface Plot of Solution at t = "<>ToString[m],                ColorFunction:>{"BlueGreenYellow"}],                {m,0,10,2}               ]


title: Error in setting matrix elements

text: > **Possible Duplicate:**   >  How to Set parts of indexed lists? For better organization of my code, sometime I use data objects in the form:               data["A", "1"] = {{1, 2}, {3, 4}}      instead of               dataA1 = {{1, 2}, {3, 4}};      One of the advantages is when working with `Module`, because I can declare `data` just one time, and I can use `data["A","1"]`, `data["A","2"]`, `data["B","1"]` and so on, with limited scope. Everything works fine except for one detail. With `data["A", "1"]` I can't perform operations like:               data["A", "1"] = {{1, 2}, {3, 4}}     data["A", "1"][[All, 2]] = "X"      to change `data["A", "1"]` to `{{1, "X"}, {3, "X"}}` I got the error:               Set::setps: data["A", "1"] in the part assignment is not a symbol      When I try with:               dataA1 = {{1, 2}, {3, 4}};     dataA1[[All, 2]] = "X";     dataA1      I have no problem and get `{{1, "X"}, {3, "X"}}` as expected. There is nome way to perform this kind of operation in `data["A", "1"]` object? **Update** The question indicated as duplicated do not handle the case: `data["A", "1",...]` but just `data["A"]`


title: Relational joining of tables

text: A common thing to want to do with data is to combine it (at least I thought this was a common thing). In SQL there is the idea of table joins "select id,v1,v2 from A,B where A.id=B.id" kind of thing. I'm trying to do a join like this using Mathematica, i.e. retrieve table A from the Internet, retrieve table B from the Internet, combine, do stuff with the resulting joined columns. My First effort was this:               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000}];     b = Table[{x, RandomReal[]}, {x, 1, 1000}];     (* Use this simple match function for now *)     RMatch[x_] := x[[1]] == x[[3]];     Length[Part[        Select[Flatten[Outer[Function[{x, y}, Join[x, y]], a, b, 1], 1],          RMatch], All, {1, 2, 4}]] // Timing      > >     {1.906250, 1000} >   This works, but is way too slow. Imagine if it was 100,000 rows each; the program may never finish. Also this will take up a lot of memory; creating a temporary list of rows that is NxM in size. So I tried an iterative approach instead:               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000}];     b = Table[{x, RandomReal[]}, {x, 1, 1000}];     (* Use this simple match function for now *)     RMatch[x_, y_] := x[[1]] == y[[1]];     RJoin[a_, b_, match_] := Block[       {lena = Length[a], lenb = Length[b], arow, brow, i, j},       Flatten[Reap[          For[i = 1, i <= lena, ++i,           arow = a[[i]];           For[j = 1, j <= lenb, ++j,            brow = b[[j]];            If[match[arow, brow], Sow[Join[arow, brow]]             ]            ]           ]          ][[2]], 1        ]       ]     Length[Select[RJoin[a, b, RMatch],         Function[{x}, x[[1]] == x[[3]]]]] // Timing      > >     {2.562500, 1000} >   This will use much less memory, but is even slower. Is this something that just isn't appropriate for _Mathematica_ i.e. do this using a different tool, output the table and work with that instead? That would be a shame, but it seems that it may be necessary. # Update: Thanks to the great answers below I decided to give up on the general case and focus on unique ID matching, which is the situation that arises the most. Following Verbeia and Michael E2's examples I came up with a version that is fast and readable.               (* Simulate tables *)     a = Table[{x, RandomReal[]}, {x, 1, 1000000, 2}];     b = Table[{x, RandomReal[]}, {x, 1, 1000000, 3}];          RJoin[a_, b_] := Block[{f},       Do[         f[x[[1]]] = x[[2]],         {x, a}         ];        Cases[b /. {x_, y_} -> {x, y, f[x]}, {_, _, _Real}]       ]          (* Use and time *)     Length[RJoin[a, b]] // Timing      > >     {1.750000, 166667} >   That's 1.75 seconds to join two tables with almost a million rows total. This is mildly faster than Michael E's version which took 4.2 seconds on my computer. When I need a more general case I plan to use Java to process the data, but this should handle most of my cases. # Update 2 I managed to simplify and speed up the arbitrary matching case a little bit               (*Simulate tables*)     a = Table[{x, RandomReal[]}, {x, 1, 1000, 1}];     b = Table[{x, RandomReal[]}, {x, 1, 1000, 1}];          (*Use this simple match function for now*)     RMatch[x_, y_] := x[[1]] == y[[1]];          RJoin[a_, b_, match_] :=      Flatten[       Reap[Do[           If[match[x, y],            Sow[{x[[1]], x[[2]], y[[2]]}];            ],           {x, a}, {y, b}           ];         ][[2]]       , 1]     Length[RJoin[a, b, RMatch]] // Timing      > >     {1.359375, 1000} >


title: Using MapThread on list of lists

text: Just a light weight question for learning. If you think this was asked before, please feel free to close it. I am trying to learn `MapThread` more, and wanted to use it to generate `Rule` from a list like this               lst = {{1, 2},{a, b}}      in order to obtain               (* {1 -> a, 2 -> b}  *)      Using `MapThread` works nice:               MapThread[Rule, lst]     (* {1 -> a, 2 -> b}  *)      But when the list contain more than one list in it, like this               lst = {{{1, 2}, {a, b}}, {{3, 4}, {c, d}}}      Then I could not find a way to use `MapThread` on its own on the whole list. It needs help to iterate over all the lists. So what I do now is `Map` the function `MapThread` on each list in the list. Like this               Map[ MapThread[Rule, #] &,  lst]     (*  {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}}  *)      I did not want to do this:               MapThread[Rule, ArrayFlatten[{lst}]]     (* {1 -> a, 2 -> b, 3 -> c, 4 -> d} *)      because it loses the structure I had at the start, even though I can correct things with               Partition[%, 2]     (* {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}} *)      But it seems not a good way to do it. Question is: What is the recommended way to do this type of operation? Can `MapThread` be told to do this on its own without the help of `Map`? Are there other commands to do the above that you think are better? I used `Rule` above, but you can replace that with any function `f` that takes 2 arguments. **Update 12/26/12** Fyi, I made a small addition to the solution so that it can be also used for 2D matrix, in addition to the 3D matrix (since this was not part of what I was asking originally). Here is my changes. I found that the trick is to tell `Apply` the level to use. For 2D matrix, use level 0 or {}. But for 3D matrix, use {1}. This assumes the input is either 2D or 3D. So this is how it looks now:               f[lst_List] :=Apply[Thread[Rule[#1, #2]] &, lst,If[MatrixQ[lst], Sequence @@ {}, {1}]]     f[ {{1, 2}, {a, b}} ]     (* {1 -> a, 2 -> b} *)      and               f[ {{{1, 2}, {a, b}}, {{3, 4}, {c, d}}}]     (*  {{1 -> a, 2 -> b}, {3 -> c, 4 -> d}} *)      Another way I could have done this, is by making 2 function definitions               f[lst_?(MatrixQ[#] &)] := Apply[Thread[Rule[#1, #2]] &, lst]     f[lst_List] := Apply[Thread[Rule[#1, #2]] &, lst, {1}]      But I personally never liked this type of coding much. Because now the logic is spread around, instead of all being contained in one place that is easier to see and maintain, So I normally like to have one function, and inside it, add the different logic needs for different values and types of the input, rather than define many different functions.


title: Why does using ReplaceAll twice produce a different result?

text: Why does this:               Solve[a x^4 + b x^3 + c x^2 + d x + e == 0,  x] /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F}      produce a different result from this?               Solve[a x^4 + b x^3 + c x^2 + d x + e == 0,  x] /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F} /.         {2 c^3 - 9 b c d + 27 a d^2 + 27 b^2 e - 72 a c e -> F}


title: Make Sinc'[0] return 0 instead of Indeterminate

text: I want Sinc'[0] to return 0, but instead it returns Indeterminate. I've tried               Unprotect[Sinc]     Unprotect[Derivative]     Derivative[1][Sinc][0] ^= 0      But it doesn't work. Maybe this needs to be similar to this (from the help files for Derivative)               f'[x_] := If[PossibleZeroQ[x], N[0, Precision[x]], (x Cos[x] - Sin[x])/x^2];


title: How to create a ListLinePlot with a layout analogous to ChartLayout -> "Stacked"?

text: I am using 3 checkboxes as desktops, portables and ipods in such a way that when I click to desktops it should shows `ListLinePlot` of `p1`, when I click to portables, it should show `ListLinePlot` of `p2` and in the same way, when I click to ipods, it shows `ListLinePlot` of `p3`.               p1 = {.955, .914, .956, 1.516, 1.355};      p2 = {1.462, 1.357, 1.577, 1.917, 2.054};     p3 = {0,0, 1.57, 1.619, 3.997};          Column[{CheckboxBar[        Dynamic[z], {ListLinePlot[p1, Filling -> Axis,            FillingStyle -> Blue] -> Desktop,          ListLinePlot[p2, Filling -> Axis, FillingStyle -> LightBlue] ->           Portables,          ListLinePlot[p3, Filling -> Axis, FillingStyle -> Green] -> Ipods}], Spacer[5], Dynamic[z]}]      This is working correctly. But I want when I click both desktops and portables on, it should show the plots of `p1` and `p2` in a stacked way. Here I am explaining it with the help of `BarChart` because I have no idea whether 'ListLinePlot`can do this .               BarChart[Table[{p1[[i]], p2[[i]]}, {i, 1, 5, 1}], ChartLayout -> "Stacked"]      If I click Desktops, Portables and ipods, then it should dynamically take data of p1, p2 and p3 in stacked order as               BarChart[Table[{p1[[i]],p2[[i]], p3[[i]]}, {i, 1, 5, 1}], ChartLayout -> "Stacked"]      and so on. But I want stacked `ListLinePlot` and I don't know any function like `ChartLayout` in `BarChart`. I have seen the `Accumulate` function but it does not work as I wanted. For more clarification, just have a look at http://graphics.thomsonreuters.com/12/01/US_APPLEBREAK0112_VT.html I want to do as it is, as in the product button of this link. Please help me.


title: How can I give input to an ArrayPlot

text: I would like to create a dynamic ArrayPlot so that the squares, when clicked, provide input. Can I use ArrayPlot for this? Or is there something else I should have to use.


title: How to create a notebook element that can replace itself?

text: I would like to create a notebook element that can replace itself. Here's an example to illustrate:               Panel[Column[       {Style["This is a panel", Bold],        Button["Press me!",         SelectionMove[EvaluationNotebook[], All, EvaluationCell];          NotebookWrite[EvaluationNotebook[],           "\"Now I'm just a piece of static text.\""]]}]]      This code will create a little panel: ![Mathematica graphics](http://i.stack.imgur.com/AUxce.png) If we press the button, the panel will get replaced by a piece of static text (i.e. not a dynamic expression that's shown as text, but just plain old non- dynamic text). ![Mathematica graphics](http://i.stack.imgur.com/KFkrB.png) Well, in this implementation actually it's not the panel that gets replaced, but the complete cell containing the panel, and that's my problem: I need _only the panel_ to be replaced, so this will work even if the panel is just a subexpression in a larger expression. **How can we create an UI control that is able to replace itself with an arbitrary expression in the notebook?**


title: Memory Leak while running Animate/Manipulate/Export

text: While looking into building a simulation for an ant colony, I started encountering some memory leakage issues.                ymax = 1000; xmax = 1000;      nest = {500, 500};      maxAnts = 30;      steps = 200;      maxSpeed = 20;      maxAngle = π/6;           orientation =         RandomVariate[UniformDistribution[{0, 2 π}], maxAnts];     ant = Table[        agent[∞, nest, orientation[[i]], #] & /@ Range[i], {i,          maxAnts}];          update[agent[symbol_, location_, direction_, t_]] :=      Module[{dir, speed, loc},        dir = First@         RandomVariate[          UniformDistribution[{direction - maxAngle,             direction + maxAngle}], 1];        speed = RandomVariate[UniformDistribution[{1, maxSpeed}], 1];       loc = Flatten[location + Round[{speed*Cos[dir], speed*Sin[dir]}]];       loc = Min[#] & /@ Transpose[{loc, {xmax, ymax}}];       loc = Max[#] & /@ Transpose[{loc, {0, 0}}];       agent[symbol, loc, dir, t + 1]]          display[agent[symbol_, location_, direction_, t_]] :=      Text[Rotate[symbol, direction], location]     display[list_] := Module[{lst = display[#] & /@ list}, Graphics[lst]]          history =        Join[ant[[#]],           NestList[update, Last@ant[[#]], steps - Length[ant[[#]]]]] & /@         Range[maxAnts];          Animate[Show[Graphics[display[history[[All, i]]]],        Graphics[{Red, PointSize[Large], Point[nest]}],        PlotRange -> {{0, xmax}, {0, ymax}}], {i, 1, steps, 1}]      ![Animation](http://i.stack.imgur.com/XfjZd.gif) The issue I have is that Mathematica seems to have a memory leak, as the Animate, or manipulate, or exporting to gif runs, the amount of memory allocated to Mathematica keeps growing until it just stops working. Below is a gif in which I turn the animation on and off to show that the memory keeps growing as Animate (or Manipulate) runs. A bummer because this limits the number of ants and steps to use. ![Memory Leakage](http://i.stack.imgur.com/NZJm4.gif)


title: Locator with Integer value coordinates

text: I want to get the Pixel value of an image.and here is my code               DynamicModule[{p = {50, 50}},       {Show[img, Graphics[Locator[Dynamic[p]]]],                       ImageValue[img, Dynamic[p]]}]      and it came up with a warning that p is with a non integer value, to solve the problem ,I used `Floor` to get an integer value               DynamicModule[{p = {50, 50}},       {Show[img, Graphics[Locator[Dynamic[p]]]],                       ImageValue[img,Floor/@Dynamic[p]]}]      this time it still doesnt work, with a warning:                   ImageValue::imgrng: The specified argument Floor[p$20303] should be a pair of real or      integer numbers or a list of those.      My question is ,can I strict the loactor to Integer Domain?or is there any more elegent way to deal with this problem?


title: Importing a Canon Raw file (.CR2)

text: This is a very top level question with no code examples attached. I have an interest in using Mathematica to read raw files coming from a Canon camera, before they are converted into jpg's, where data is lost. Are there any existing non proprietary mathematica scripts, which can read a CR2 file from a Canon camera and display its image as it would if a jpeg were imported. At the very least a script that can display data about the image stored in the CR2 file to include intensity, size, pixel value, LRGB histograms, etc...


title: Padding and formatting within BaseForm

text: I find using BaseForm to be a little tricky. For example, if you use BaseForm and then do some additional operation all the numbers turn back into base 10, so you have do BaseForm as the "last step". This creates the problem of how you then format the BaseForm if it is the last step. For example, given the following:               BaseForm[Grid[Partition[Map[FromDigits[#,16]&,RealDigits[FractionalPart[CubeRoot[Table[Prime[n],{n,64}]]],16,8,-1][[All,1]]],8],Alignment->Right],16]      ![enter image description here](http://i.stack.imgur.com/GO1Qa.png) Formatting problems are: (1) how to get leading zeroes for those values that are less than 8 hex digits? (2) how to get rid of the 16's (I don't want to display them) Please do not answer with copy and paste from the doc center, unless you can you show how the command in question works in the above expression inside of BaseForm. PaddedForm and other similar commands DO NOT WORK as far as I can tell. For example if you write:               BaseForm[Grid[Partition[Map[PaddedForm[FromDigits[#,16],8]&,... etc      It does NOT work.


title: Ulam's Spiral with Opperman's diagonals (quarter-squares)

text: First we craft a function to return the quadrant boundary based on Oppermann's Conjecture               a[n_] := (Mod[n, 2] + n^2 + 2 n)/4      Then we create a few lists               r = 10;     q = 1;     q1 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 2;     q2 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 3;     q3 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     q = 4;     q4 = Table[a[q + 4 (n - 1)] <-> a[q + 4 (n)], {n, 1, r}];     u = Flatten[Table[{(n - 1) <-> n}, {n, 2, a[4 + 4 r] + 1}]];      We produce the normal Ulam's Spiral               Graph[u]      ![Ulam's Spiral](http://i.stack.imgur.com/eDqsa.png) We don't get the spiral when we attempt to combine the diagonal lists by using this               Graph[Union[u, q1, q2, q3, q4]]      ![Ulam Bad Spiral](http://i.stack.imgur.com/RaRF3.png) How can we overlay the diagonals onto the spiral?


title: Specifying non-conflicting PlotTheme options

text: I am trying out Mathematica 10 on https://programming.wolframcloud.com. `$PlotTheme` interested me a lot because it finally produces nice plots (probably) without the need of fine tuning of every plot. However, the options are conflicting each other and there seems to be some hiding options. For example (figures available at https://www.wolframcloud.com/objects/0caeabc9-81ba-4c6c-a51d-64f06c644a40),               (* This get thick lines *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"ThickLines"}]          (* This get monochrome *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"Monochrome"}]          (* There is no monochrome or thick lines here *)     LogPlot[{1/x, x,2x, E^x},{x,1,10},PlotTheme->{"Monochrome","ThickLines"}]      As another example,               (* Didn't get open markers or monochrome, but at least get thick *)     ListPlot[{{{1,2},{2,4},{3,7},{4,9}},{{1,3},{2,4}}},PlotTheme->{"Monochrome","OpenMarkersThick"}]          (* After adding frame, markers completely changed *)     ListPlot[{{{1,2},{2,4},{3,7},{4,9}},{{1,3},{2,4}}},PlotTheme->{"Monochrome","Frame","OpenMarkersThick"}]      Is it possible to make those themes non-conflicting with each other? The theme seems perfect for me is as follows: (1) The lines are solid, dashed, dotted, ... ("Monochrome") (2) The lines are colored. (e.g. "VibrantColor") (3) Framed ("Frame"). (4) Larger labels ("LargeLabels"). At best thicker lines ("ThickLines"). (5) Setting apply both to `Plot` and `ListPlot` (to put in $PlotTheme instead of tuning every plot). But I am not able to get all of them satisfied -- once `Plot` looks fine, `ListPlot` looks ugly. Is it possible to get some non-conflicting fine tunings once and apply everywhere?


title: Error Using Sow in DensityHistogram with ColorFunction

text: To find the color values used in a plot, I was using `Sow` as shown here:               Short@Reap[Histogram3D[RandomVariate[BinormalDistribution[.5], 500],        ColorFunction -> (ColorData["Rainbow"][Sow[#1]] &)]      ]      ![Sow/Reap OK](http://i.stack.imgur.com/bcs6D.png) But I get an error if I simply replace `Histogram3D` by               Short@Reap[       DensityHistogram[RandomVariate[BinormalDistribution[.5], 500],         ColorFunction -> (ColorData["Rainbow"][Sow[#1]] &)]       ]      Now I get the following message:               Transpose::nmtx :  "The first two levels of the one-dimensional list"         {{{-3.5,3.},{-3.5,3.},{0.,24.}},0, ... , 1} cannot be transposed.          Transpose::argt :  "Transpose called with 0 arguments; 1 or 2      arguments are    expected."      ![error](http://i.stack.imgur.com/kK5Qz.png) It's possible to work around this problem by doing without `Sow` and `Reap` as follows:               l = {};     {DensityHistogram[RandomVariate[BinormalDistribution[.5], 500],        ColorFunction -> (ColorData["Rainbow"][AppendTo[l, #1]; #1] &)],       N@l}      But it would be nice to know **if there is an explanation** for why `Sow` doesn't work in the `DensityHistogram` example whereas it works in `Histogram3D`. The same error appears if I leave out the `Reap`. From the message it seems clear that a list of all `PlotRange` tuples is being _sown_ at some point before the `ColorFunction` actually is put to use. I tried to suppress passing that kind of argument to `Sow` by modifying the `ColorFunction` to               ColorFunction -> (If[ListQ[#1], White,       ColorData["Rainbow"][Sow[#1]]] &)      but it had no effect. As Leonid pointed out in his answer, there must therefore be a _different_ invocation of `Sow` outside the color function. Maybe someone knows another way to suppress the invalid `ColorFunction` call that seems to trip up `Sow`. However, it doesn't seem to be obvious because when I _don't_ use `Sow` as in my work-around based on `AppendTo` with a list `l`, there is no entry in the resulting list `l` that corresponds to the `PlotRange` tuples. **Edit** It seems that this is a problem specifically with `DensityHistogram`. I also noticed that the setting for `FrameTicks` is _ignored_ by `DensityHistogram`. It can be restored by wrapping the plot in `Show` with the desired `FrameTicks` option. None of these issues arise with the related function `SmoothDensityHistogram`. Leonid pointed out what the probable cause for the `Sow` error is, but since wrapping the result in another `Show`, I would for now stick with the workaround I mentioned above: ditch `Sow` and `Reap`, and use `AppendTo` to collect the desired values in a list `l` using a `CompoundExpression` of the type `AppendTo[l, #]; #`.


title: What is an "INTERNAL SELF-TEST ERROR"?

text: I got this all the time after updating to 9.0 (OS 10.8.2): !["Internal self-test error" message](http://i.stack.imgur.com/Cq6Vv.png) That's **Clipboard|c|3015** for the benefit of anyone searching. The error went away with 9.0.1, but a version has reappeared (multiple times at each launch) since updating my OS (to 10.9): ![enter image description here](http://i.stack.imgur.com/SmUdq.png) That's **SpanBox|c|2178** for the benefit of anyone searching. What does an "Internal self-test error" mean?


title: Using Boole to integrate over region

text: I have a complex and long piecewise function to integrate, so I have written a Mathematica script that cuts the whole range of integration, evaluates the integrand in each region and then integrates it. In order to integrate the evaluated function on the right range, I set the integration on the whole original range and I use Boole to define the appropriate region. Now, it happens that both the integrand and the region depends on other parameters, say `a` and `b`, so I should get an integral which depends on these, as in the following WORKING example               Assuming[0 < 2 a < 1,       Integrate[       Exp[-t] Boole[(b < 0.5 && a < t < 2 a) || (b > 0.5 &&             0 < t < a)], {t, 0, 1}]]      which gives $\begin{cases} e^{-2. a} \left(e^a-1.\right) & 0.<a<0.5\land b<0.5 \\\ e^{-1. a} \left(e^a-1.\right) & 0.<a<0.5\land b>0.5 \\\ 0\. & \text{True} \end{cases}$ However, when the range of integration becomes too complex, Mathematica stops to evaluate the integral and give me back an implicit solution. For example, consider the following code               r = (0 < b < 1/          2 && ((0 < a < b &&              b + a < z <               1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&                  0 < y < z - x))) || (a == b && b + a < z < 1 &&              z - a < x < z && 0 < y < z - x) || (b < a < 1 - b &&              b + a < z < 1 && z - b < x < z && 0 < y < z - x))) || (1/2 <=           b < 1 && 0 < a < 1 - b &&          b + a < z <           1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&              0 < y < z - x)))     int = Exp[-0.5 y1^2 y -          2 (y2^2 (z - b - a) + y1^2 (-z + b + x + a))] y1^2 Boole[r]     Integrate[int, {z, a, 1}, {x, a, z}, {y, 0, a}]      The last line gives me $\text{y1}^2 \int _a^1\int _a^z\int _0^a\exp \left(-2 \text{y1}^2 (a+b+x-z)+2 \text{y2}^2 (a+b-z)-0.5 y \text{y1}^2\right) \text{Boole}[...]dydxdz$ The same happens if I isolate intervals with respect to `a,b` , as in               r = LogicalExpand[(0 < b <            1/2 && ((0 < a < b &&               b + a < z <                1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&                   0 < y < z - x))) || (a == b && b + a < z < 1 &&               z - a < x < z && 0 < y < z - x) || (b < a < 1 - b &&               b + a < z < 1 && z - b < x < z && 0 < y < z - x))) || (1/2 <=            b < 1 && 0 < a < 1 - b &&           b + a < z <            1 && ((z - b < x <= z - a && 0 < y < a) || (z - a < x < z &&               0 < y < z - x)))]     s = Reduce[r[[2]], {x, y}]     int = Exp[-0.5 y1^2 y -          2 (y2^2 (z - b - a) + y1^2 (-z + b + x + a))] y1^2 Boole[s]     Integrate[int, {z, a, 1}, {x, a, z}, {y, 0, a}]      or if I split the `Integrate` function               Integrate[      Integrate[Integrate[int, {y, 0, a}], {x, a, z}], {z, a, 1}]      Why Mathematica cannot evaluate the integral?


title: How to enter chemical equations?

text: When I want to take chemistry notes and write down a formula such as H_2O or C_2H_5OH it enters "Math mode" which changes the font size and italicizes the letters. Is there an easy way to properly enter chemical formulas and equations in text? I'm new to Mathematica 10 and I'm really boggled by all the styles and how to change them so please keep it simple.


title: BSplineCurve Interpolation

text: Can I get interpolated values from this B-spline, (shown in red)?               points = {{-2, 2}, {2, 2}, {6, 6}, {10, 7}, {14, 11},        {18, 2}, {22, 1}, {26, 2}, {30, 1}, {34, 1}};          fn1 = Interpolation[points, Method -> "Spline"];     fn2 = Interpolation[points];          Show[ListPlot[points],      Graphics[{Red, BSplineCurve[points]}],      Plot[fn1[x], {x, -2, 36}],      Plot[fn2[x], {x, -2, 36}],      AxesOrigin -> {-2, 0}]      ![enter image description here](http://i.stack.imgur.com/kpMjw.png)


title: Plotting the solution of a vector stochastic differential equation

text: I have a vector stochastic differential equation, $$\mathrm dq = p\,\mathrm dt\qquad q(0)=0$$ $$\mathrm dp = (-q -p)\mathrm dt+\mathrm dW\qquad p(0)=10$$ This can be entered to give me the process describing **either** p or q, using               proc = ItoProcess[         {{p[t], -p[t]-q[t]}, {{0}, {1}}, XXX[t]},         {{q, p}, {0, 10}},         {t,0}     ]      where `XXX` is either `q` or `p`. The solution can be plotted using the usual method (here for `p`) of               ListLinePlot@RandomFunction[proc, {0, 10, .02}, 10]      > ![enter image description here](http://i.stack.imgur.com/bBTbp.png) However, the situation is more difficult if I want to extract **both** `q` and `p`, as for each simulation it will give me a list of the type (obtained using `Normal`, and by setting `XXX[t]` to `{q[t], p[t]}` in the `ItoProcess`)               {{{t0, {q[t0], p[t0]}}, {t1, {q[t1], p[t1]}}, ...}      i.e. the times aren't properly distributed over the p/q, and as a consequence I'm having a hard time finding a good way of getting this into a plottable form. So the questions are:   1. Is there a nice way of getting all components out of a vector stochastic differential equation to plot them alongside each other?   2. If there's none, what's the right hacky approach? Fiddling with `Transpose` and `Flatten`?


title: How to manipulate 2D plots?

text: When it comes to visual analysis, large datasets or data with intricate internal details often makes plotting in 2D useless, as the outcome is either just a fraction of the full dataset, or no details can be observed in the mess of datapoints. **How can one make the process of changing the plot range and/or zooming, panning, etc. less tedious** than doing it programmatically and iteratively, from time to time? I often meet with this issue, and developed various methods to deal with it (like this). Though I have now a working solution that I would like to share (see below), I also am highly interested in what kind of methods and tricks others invented to visualize and manipulate complex 2D data with ease.


title: Is there any simple way to zoom/magnify a selected portion of a plot (like gnuplot or xmgrace)?

text: Is there any simple way to zoom a particular portion of a plot (similar to what you can do with gnuplot or xmgrace using the magnifier and selecting a region)? Usually I do it by varying the `PlotRange[]` manually or by putting the `PlotRange[]` under `Manipulate[]`, but that is not very convenient option for heavy plotting (which involve complicated functions or large data). Is there anything like a magnifier tool or something similar?


title: Using MatrixPlot, how can I dynamically zoom in and out with my mouse?

text: I have a MatrixPlot output which I would like to zoom around in, drawing boxes that define a zoom region with my mouse. These things are all fairly standard in Labview... surely Mathematica must have a similar set of abilities? For an example matrix, we can write:               TestArray = Array[RandomInteger[{0, 1}] &, {100, 100}];     MatrixPlot[TestArray]


title: Singular integral: NIntegrate fails to converge

text: I need to calculate the following singular integral:               NIntegrate[Log[1 + y^2]/Cos[Pi y], {y, 0, 1}]      However, it is failing to converge. I have tried to specify `MaxRecursion`, `PrecisionGoal`, and `Exclusions` but neither helped. How does one calculate singular integrals in Mathematica?


title: Citation and Bibliography mac with Mathematica 9

text: Insert bibliographical note doesn't appear on the insert menu for Mac. However if I right click the mouse this option does appear: i tried to use a standard bibtex file with it, but it doesn't seem to compile and gives a strange error message. Any idea if this feature is indeed useable?


title: Why animator smoothes dynamic updates, or how to make pacman drink beer

text: How could I make a pacman drink beer in Mathematica? This is what I have so far               pacman[xposFun_, angleFun_] := {Yellow,         Disk[{Dynamic@xposFun[Clock[{0, Infinity}]], 0`}, 1`,          Dynamic[{Pi/6 Abs@Sin[2 Pi Clock[]],             angleFun[Clock[{0, Infinity}]]} /. {val_, ang_} :> {val + ang,              2 Pi - val}]]};          burp := Quiet@EmitSound@ListPlay@Upsample[ConstantArray[1, 80], 200]          xpos[t_] := \[Piecewise] {         {5 t, 0 < t < 3},         {15, t >= 3},         {0, True}        };          angle[t_] := \[Piecewise] {        {0, 0 < t < 3},        {Pi/4 (t - 3), 3 < t < 4.8},        {Pi/4 (4.8 - 3), t > 4.8}       }          angleBeer[t_] := \[Piecewise] {        {0, 0 < t < 3.5},        {Pi/4 (t - 3.5), 3.5 < t < 5.3},        {Pi/4 (5.3 - 3.5), t > 5.3}       }          beer[filling_] := {{Opacity[0.2], EdgeForm[Directive[Thick, Gray]],          Polygon[{{0`, 0`}, {1`, 0`}, {1.2, 1.5}, {-0.2, 1.5}}]},        Opacity[0.8], filling, EdgeForm[Directive[White, Thickness[0.01]]],         Scale[{Polygon[{{0`, 0`}, {1`, 0`}, {1.2, 1.3}, {-0.2, 1.3}}],          White,           Polygon[{{-0.2, 1.3}, {1.2, 1.3}, {1.3, 1.6}, {-0.3, 1.6}}]},          0.9],        {Opacity[0.], EdgeForm[Directive[Gray, Thickness[0.01]]],          Disk[{1.1`, 0.7`}, 0.3, {-Pi/2 - 0.2, Pi/2 - 0.2}]}};          Graphics[{pacman[xpos, angle],        Translate[        Rotate[beer[          Dynamic[If[Clock[{0, 5.4}, 5.4, 1] < 5.4, Darker@Yellow,             If[Clock[{0, 7.4, 1}, 7.4, 1] == 7.4, Refresh[burp, None]];             Opacity[0.]]]],          Dynamic@angleBeer[Clock[{0, Infinity}]]], {16, -0.2}]},       PlotRange -> {{0, 20}, {-1.2, 2}}, Background -> Black]           Animator@Dynamic@anything      ![enter image description here](http://i.stack.imgur.com/xbDcN.gif) Now, this serves as an excuse to ask the real question. This is an issue I've also had with version 8 but that I didn't have a reproducible small code for it. I see the dynamic animation is choppy but it gets fixed while any `Animator` is running on display dynamically updating something, like the `Animator@Dynamic@anything` that the code above displays after the pacman. For testing, you can get the animation to restart, by copying and pasting the cell in the same place. Once the pacman is moving, try starting and stopping the animator to see the difference in choppiness. Furthermore, changing the `DynamicUpdateInterval` in the `SystemOption`s can make this improve but it's always choppier without the animator, as if without it it always missed some frames... Do you see this behaviour too? How could I tell the front end "heyy, an animation is happening even if I'm not using an animator"?


title: How to "ReplaceAll" using a set of conditional expressions instead of a list of rules

text: Suppose that I have two linear functions               f[x_] := f0 + f1 x     g[x_] := g0 + g1 x      and a (possibly rather complicated) set of conditional expressions, obtained through Reduce. For example, we might have something like this:               conditions = (f0 == f1 && g0 == 0) || (f0 == g1 && g0 == f1)      What I would like to do is write something like               {f[x],g[x]} /. conditions      and receive as output the set of pairs of $f$ and $g$ adhering to that formula. In this case we'd have               {{a + ax, bx}, {a + bx, b + ax}}      (or maybe `{{f0 + f0x, g1x}, {f0 + f1x, f1 + f0x}}` to stick with original variable names). How can I do this?


title: Find the slope between adjacent points in a list

text: I have a list of two dimensional points that are ordered by their x-coordinate. I would like to calculate the slope between all adjacent points. I'm familiar with the use of pure functions in Sort for example that can compare adjacent elements. Is there a way to perform a function on all adjacent elements in a list?


title: Style markers in strings

text: I'm dealing with strings in _Mathematica_ and I would love to handle their stylling in the most cenvenient way. Without loss of generality, let's assume I want to make some parts of string `Bold`. Example of desired output: > to **be** or **not** to be I know I can achieve that by for example:               StringForm["to `` or `` to be", ##] & @@ (Style[#, Bold]& /@ {"be", "not"})       but I want single function `bold` and some kind of markers (here `#`):               bold @ "to #be# or #not# to be"      > to **be** or **not** to be * * * It is **my approach** :               bold = Module[{x},                    With[{patt = "#" ~~ x : Except["#"] .. ~~ "#"},            StringForm @@ ({                           StringReplace[#, patt :> "``"],                           Sequence @@ StringCases[#, patt :> Style[x, Bold]]                           })]                  ] &      and I have **couple of questions** about it:   * do you feel that `#` is not the best choice too? :)   * is this: `{patt = "#"~~...}` a proper way of storing patterns?   * maybe some other ideas? I like this way but I'm not sure if it is bulletproof. It is quite handy because `StringCases` etc do not look for overlaps by default. Notice that _mixed-style-string-form_ tends to produce some kind of error If you want to edit that cell. This is also what I to want to ask about: > >     INTERNAL SELF-TEST ERROR: MathEditCells2|c|1384 >     Click here to find out if this problem is known, and to help improve >     Mathematica by reporting it to Wolfram Research >


title: How to output an expression as a Dot[] product

text: How to force _Mathematica_ to **output** an expression such as $a1u1+a2u2+a3u3$ as a `Dot` product like this one:               {a1,a2,a3}.{u1,u2,u3}       or A.U


title: A palette of accumulated expertise

text: I've been trying to put together a palette of useful functionality garnered from this site. There is useful stuff scattered all over the place, for example:   * Post an image   * Copy code   * Duplicate a notebook   * Paste a table As an ugly, yet functional, way of putting them together, I have something like:               CreatePalette[Column[{         OpenerView[{"Duplicate Active Notebook", duplicating}, True],         OpenerView[{"Pasting a table", pasting}, True],         OpenerView[{"Copy for StackExchange", copyForStackExchange}, True]         (* etc *)         }],       WindowTitle -> "mathematica.stackexchange.com"];      where the definitions inside each `OpenerView` are slight modifications of the code from the above links. (Usually just stripping off any existing palette stuff is all that is required. I did find that a single button seemed to require `ImageSize -> Automatic` so it would display properly.) So the question is, what else can I add to this? **Are there any procedures _you_ use regularly that are suitable for a palette?** Things that have made your mathematica experience easier and more productive?   **Is there any enlightening information that could be continually displayed on a palette?** E.g. progress bars, memory usage, cursor position?   **Are there any tips and hints for beginners that could be nicely presented on a palette?**


title: How to scale edge length and keep layout of edge-weighted Graph?

text: I love using `Graph` as structure to store and visualize my data in _Mathematica_. Consider the following simple example for creating a `Graph` object with weighted directed edges. I already laid out the graph in a tree structure using the options `{"LayeredEmbedding", "Orientation" -> Top, "RootVertex" -> 1}` I found in the documentation of `GraphLayout`, since this representation is useful for my particular needs.               vertices={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,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100};     edges={1\[DirectedEdge]2,3\[DirectedEdge]4,5\[DirectedEdge]6,7\[DirectedEdge]8,9\[DirectedEdge]10,11\[DirectedEdge]12,13\[DirectedEdge]14,15\[DirectedEdge]16,17\[DirectedEdge]18,19\[DirectedEdge]20,21\[DirectedEdge]22,23\[DirectedEdge]24,25\[DirectedEdge]26,27\[DirectedEdge]28,29\[DirectedEdge]30,31\[DirectedEdge]32,33\[DirectedEdge]34,35\[DirectedEdge]36,37\[DirectedEdge]38,39\[DirectedEdge]40,41\[DirectedEdge]42,43\[DirectedEdge]44,45\[DirectedEdge]46,47\[DirectedEdge]48,49\[DirectedEdge]50,51\[DirectedEdge]52,53\[DirectedEdge]54,57\[DirectedEdge]58,59\[DirectedEdge]60,61\[DirectedEdge]62,63\[DirectedEdge]64,65\[DirectedEdge]66,67\[DirectedEdge]68,69\[DirectedEdge]70,71\[DirectedEdge]72,73\[DirectedEdge]74,75\[DirectedEdge]76,77\[DirectedEdge]78,79\[DirectedEdge]80,81\[DirectedEdge]82,83\[DirectedEdge]84,85\[DirectedEdge]86,87\[DirectedEdge]88,89\[DirectedEdge]90,91\[DirectedEdge]92,93\[DirectedEdge]94,95\[DirectedEdge]96,97\[DirectedEdge]98,99\[DirectedEdge]100,2\[DirectedEdge]3,2\[DirectedEdge]5,6\[DirectedEdge]7,6\[DirectedEdge]9,10\[DirectedEdge]11,10\[DirectedEdge]13,14\[DirectedEdge]15,14\[DirectedEdge]17,4\[DirectedEdge]19,4\[DirectedEdge]21,22\[DirectedEdge]23,22\[DirectedEdge]25,20\[DirectedEdge]27,20\[DirectedEdge]29,28\[DirectedEdge]31,28\[DirectedEdge]33,34\[DirectedEdge]35,34\[DirectedEdge]37,30\[DirectedEdge]39,30\[DirectedEdge]41,42\[DirectedEdge]43,42\[DirectedEdge]45,40\[DirectedEdge]47,40\[DirectedEdge]49,24\[DirectedEdge]51,24\[DirectedEdge]53,54\[DirectedEdge]55,54\[DirectedEdge]56,26\[DirectedEdge]57,26\[DirectedEdge]59,60\[DirectedEdge]61,60\[DirectedEdge]63,58\[DirectedEdge]65,58\[DirectedEdge]67,8\[DirectedEdge]69,8\[DirectedEdge]71,72\[DirectedEdge]73,72\[DirectedEdge]75,76\[DirectedEdge]77,76\[DirectedEdge]79,74\[DirectedEdge]81,74\[DirectedEdge]83,70\[DirectedEdge]85,70\[DirectedEdge]87,88\[DirectedEdge]89,88\[DirectedEdge]91,86\[DirectedEdge]93,86\[DirectedEdge]95,12\[DirectedEdge]97,12\[DirectedEdge]99};     weights={18,53,50,53,51,96,129,47,47,55,68,75,74,82,65,87,76,10,10,57,99,4,4,46,46,81,81,64,74,7,7,17,17,61,86,64,70,17,17,23,23,64,104,8,8,48,48,80,80,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};          Graph[vertices, edges, EdgeWeight -> weights,        EdgeLabels -> MapThread[Rule, {edges, weights}],        GraphLayout -> {"LayeredEmbedding", "Orientation" -> Top,          "RootVertex" -> 1}, EdgeLabelStyle -> Directive[Blue, 20]]      The graph that I get with these options looks like the following: ![enter image description here](http://i.stack.imgur.com/VwaHH.png) Edge weights are put as labels but all edges have the same length due to the options specified. What I would like to obtain now is a `Graph` object with edges scaled according to the edge weight while keeping the tree-like layout of the graph. I have read the documentation of `GraphLayout` and several other documentation pages on `EdgeWeight`, `TreeGraph`, _etc_. The only possibility I found so far is to use the options `{"SpringElectricalEmbedding", "EdgeWeighted"->True}` for the `Graph` object. However this destroys the tree- like layout I want to keep:                Graph[vertices, edges, EdgeWeight -> weights,       EdgeLabels -> MapThread[Rule, {edges, weights}],       GraphLayout -> {"SpringElectricalEmbedding", "EdgeWeighted" -> True},EdgeLabelStyle -> Directive[Blue, 20]]      And the `Graph` object looks like this: ![enter image description here](http://i.stack.imgur.com/yEtuS.png) **Question: Is there a way to combine the tree-like layout of`Graph` with weight-scaled edges in Mathematica?** I think one would have to change the `VertexCoordinates` that are embedded in the `Graph`. It is easy to access the current `VertexCoordinates` using `GraphEmbedding` but I can't figure out how to change them appropriately.


How to simplify the following trigonometry expression such that the number of used characters is minimal?               (13*Cos[t] - 5*Cos[2*t] - 2*Cos[3*t] - Cos[4*t])/4      The question sounds weird because I ask for the minimal number of used characters, but it is not a typo. The number of used characters must be minimal because the plotter needs short expression. Please ignore the computation performance for this case.


title: Please explain this code (contains Append, Do, Coefficient)

text: I am a graduate student using a past student's Mathematica program. Will someone please explain to me exactly what this piece of code is doing? Specifically the `Do[c[j] = {}, {j, 0, k}]`, `Append` command, and the `Coefficient` command. Thanks in advance.               inttstar[1] = (1/8)*(tstar[2] - tstar[0]);     (* Eq 2.31 *)          inttstar[i_] := inttstar[i] = (tstar[i + 1]/(i + 1) - tstar[i - 1]/(i - 1))/         4 - (-1)^i*tstar[0]/(2 (i^2 - 1));    (* Eq 2.30 *)     inttstar[k];          Do[c[j] = {}, {j, 0, k}]     Do[Do[c[j] = Append[c[j], Coefficient[inttstar[j], tstar[i], 1]], {i,         0, k}], {j, 0, k}]          r = {};          Do[r = Append[r, c[i]], {i, 0, 15}]          r


title: Connect to Windows kernel from Linux computer

text: I've seen many questions regarding the connection to a Linux machine from a Windows one, but I need to do the opposite. **Situation:** I have Mathematica on my Linux laptop (`A`) and I want to run a remote kernel on my Windows desktop (`B`) (which also has Mathematica) **Current solution:** On `A` I have a kernel that opens in `LinkMode` so when I execute something it gives me a port and IP address of my machine. Then on `B` I use the `LinkConnect` function that allows me to run my computations on `B`'s kernel. **Things to improve:** I want to be able to do this automatically. One annoying part of this solution is that the numbers `N,M` that I use in the `LinkConnect` function (`LinkConnect["N@IP-address,M@IP- address",LinkProtocol->"TCPIP"`) always change, so I have to retype them every time. The other problem is that sometimes I use parallel functions e.g. `ParallelTable[]` but using this solution doesn't allow me to execute multiple kernels on `B`. **Questions:** I think Mathematica comes with a way to do this connection in the background using Remote Kernels, but I don't know how to connect `A` with `B` using that.   * Is it possible to connect from Linux to Windows using Remote Kernels? if so, how?   * Will this allow me to execute parallel kernels in `B`?


title: Why does DominantColors keep shuffling the order of the results?

text: This graphic is produced by running `DominantColors` (new in _Mathematica_ 9) with different values, using the Lena image as the source: ![lenna strips](http://i.stack.imgur.com/7qAoA.png) Each row is a list of the dominant colours in an image, when asking for between 2 and 60. However I'm surprised that the order of the colors keeps changing: why would the order depend on how many you asked for? Have I done something daft in my code? Or I have failed to grasp something obvious in the online documentation? (Either is likely.)               With[{l = ExampleData[{"TestImage", "Lena"}]},         Graphics[          Table[{colorList = DominantColors[l, d];            {Table[{                 colorList[[x]],                  Rectangle[{x - 1, 10 - d},{x, 10 - (d + 0.7)}]                   },                 {x, 1, Length@colorList}]}},           {d, 2, 60}]]     ]


title: How to plot rectangles aligned by their center?

text: Supose I have a rectangle which area is $x^2$. In some cases I may not know what is the size of each side, for $x=12,$ we have several possibilites:               {{144, 1}, {72, 2}, {48, 3}, {36, 4}, {24, 6}, {18, 8}, {16, 9}, {12,        12}, {9, 16}, {8, 18}, {6, 24}, {4, 36}, {3, 48}, {2, 72}, {1, 144}}      I want to plot each one of these rectangles, all them aligned by their center. Until now, I did this:               n = 144;     a = Select[n/Range[1, n], IntegerQ];     b = Reverse[a];     c = Table[{a[[x]], b[[x]]}, {x, 1, Length[a]}]      Which finds all the sizes of the sizes which satisfy $a\cdot b=x^2$. But I can't figure out how to do the next part, can you help me?


title: How do I add a color bar to a 3D plot?

text: I tried               Plot3D[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2},      ColorFunction -> (ColorData["TemperatureMap"][#3] &),      PlotLegends -> Automatic]      in an attempt to add a colorbar legend to the plot, but this did not work. It did work here:               DensityPlot[Exp[-x^2 - y^2], {x, -2, 2}, {y, -2, 2},      ColorFunction -> "SunsetColors",      PlotLegends -> Automatic]      Any suggestions in how I can get it to work in the first bit of code? Thanks.


title: Why does my matrix lose rank?

text: I want to check the rank of a matrix for observability, but _Mathematica_ loses a rank if the matrix contains very large numbers. Let's say my matrix is               myM = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {5.4 10^0, 1, 1, 1}};      with this matrix I get a rank of 4               MatrixRank[myM]      but if I change the matrix to               myM = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {5.4 10^12, 1, 1, 1}};      (first entry in the last row) the rank of my matrix is only 3. Can somebody explain it to me please?


title: Use of Manipulate in CDF documents

text: I am trying to publish a cdf document, but I'm having some problems with the function `Manipulate` with this code:               Manipulate[x + 1, {x}]      In _Mathematica_ , when I set `x = d + d^3` in the input field, I get this output: > `Manipulate[x + 1, {{x, d + d^3}}]` This is what I want. However, it seems that the cdf player is only able to evaluate the expression `x + 1` when `x` is a number and not a more complicated expression. Is this true or I am doing something wrong?


title: How to stop Manipulate changing view point

text: When using the following manipulate I can rotate the plot and manipulate the value without my view point changing;               Manipulate[Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}], {a, 1, 5}]      If I rotate one of these plot in the following manipulate the value the view point changes back to the default.               Manipulate[GraphicsRow     [{Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}],     Plot3D[Sin[a*x + y^2], {x, -3, 3}, {y, -2, 2}]}],      {a, 1, 5}]      I have a much more complex plot that contains a GraphgicsRow and a Column and I want it to keep the view point of the plot while I manipulate it. Is there a simple way to do this? Is the problem the GraphicsRow or is that just a coincidence? Thanks.


title: intersection between two curves in Mathematica

text: I have two curves (drawn from points) in a plane, one is drawn with `ListLinePlot` and the other drawn with `ParametricPlot`. How can I determine the intersection between both curves? I cannot use (don't know how to) interpolation directly, since the curves are not graphs. Let's say we have                r[\[Phi]_] = 1 + 1/20 Sin[20 \[Phi]];       tb = Table[{r[\[Phi]] Cos[\[Phi]], r[\[Phi]] Sin[\[Phi]]}, {\[Phi], 0, 2 \[Pi], 0.1}];      ListLinePlot[tb]       and we interpolate data stored in `tb`. E.g. at `x = 0.95` there are 4 (or 5) different values for `y`. How can I plot interpolating function? I am sure I am missing something. Theoretically, I could use interpolation across segments of points on a curve but this is something I want to avoid. Any ideas?


title: How to run Mathematica using Mac Terminal

text: My question is so trivial and I'm sure most people in here know exactly how to do this, however I still don't know how to run Mathematica in Mac terminal! I need to use all the cores of my computer in order to get faster results. I open Mathematica in terminal using this command:               /Applications/Mathematica.app/Contents/MacOS/MathKernel      Then when I type `math -run "<<test.m"` (test is my file's name), nothing happens! Can anybody guide me what to do or refer me to a good refrence with some examples at this?


title: Using DSolve to solve for x[t,parameter]

text: I'm trying to solve an ODE with two independent variables (a cannon firing from a cliff incorporating wind resistance dependent on velocity). I've tried the following for the x-component:               NDSolve[{x''[t, θ] == -0.2*x'[t, θ]/2.30, x'[0, θ] == 10.8*Cos[θ], x[0, θ] == 0},       x[t, θ], t]      Assuming my algebra is correct, how do I properly phrase this input to give me `x[t, θ]`?


title: Why does Plot3D omit parts of the surface at kinks?

text: When doing               Plot3D[Max[p^2-q^2,0],{p,0,1},{q,-1,1},PlotStyle->White]      the result looks like this (with Mathematica 8.0.0.0): ![enter image description here](http://i.stack.imgur.com/uhghv.png) As you can easily see, at the "kink" where the function starts going above 0, Mathematica leaves a gap in the surface. Why does it do that, and more importantly, what can I do about it?


title: How do I eliminate the breaks in a 3D plot with a Max or Min function?

text: Whenever I make a 3D plot using the `Max` or `Min` functions, I get breaks in the plot when it switches from one expression in `Max` or `Min` to the other. How can I eliminate these breaks to get one continuous surface? The particular example I want to make work is this:               ParametricPlot3D[{r Cos[t], r Sin[t],       Max[r^2 Cos[t]^2 - 1.06^2, 0] + Max[r^2 Sin[t]^2 - 1.92^2, 0]},       {t, 0, 2 \[Pi]}, {r, 0, 3.4}, Mesh->None, Boxed->False, Axes->None]      which produces this: ![surface showing breaks in plot](http://i.stack.imgur.com/QTZ9H.png) but it is possible to reproduce the effect with simpler expressions like `Plot3D[Max[x, 1], {x, 0, 2}, {y, 0, 2}]`. * * * I've checked that occurs with Mathematica 7 and 8 on Windows and Linux.


title: Exporting Mathematica expression as SVG

text: I was thinking it would be nice if I could export Mathematica expressions as svg, but I am having some issues. At first blush everything seems to work fine. This piece of code does produce a svg file:               res = Solve[x^2 + a x + 1 == 0, x]     Export["res.svg", res]      The problem with the svg file are the fonts. If I try to open the file in Adobe Illustrator I get this message:               SVGMathematica2Mono:          Font not found on the system; missing font has been substituted.     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -           SVGCourier:          Font not found on the system; missing font has been substituted.     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -      The end result looks like this: ![SVG issues](http://i.stack.imgur.com/DpEev.png) It looks bad in several other svg viewers as well. Is there some way to either embed the needed fonts in the svg file or convert the expression to a graphic and export it as such?


title: How can this image (optical illusion) be created with Mathematica?

text: I came across this image the other day: ![enter image description here](http://i.stack.imgur.com/ttcii.jpg) and liked the sensation of it pulsing. I was wondering if anyone would know how to create something similar with Mathematica (without the Pink Floyd Dark Side of the Moon logo). **Edit** Very nice work from @halirutan, @Silvia, and @J.M -- you've given me headaches -- literally :)


title: Possible to use Manipulate in GUIRunModal?

text: Is it possible to use the widget created by `Manipulate` within `GUIRunModal`? I intend to run the file using `MathematicaScript -script <filename>`.


title: Better use of Mathematica's PolynomialReduce[]?

text: I've been using               scPhiDecomp[expr_]:= PolynomialReduce[expr, {x^2-y^2,2 x y}, {x,y}]      which works great on               scPhiDecomp[a x^2 + 2c x y -a y^2]     >> {{a,c},0}      but doesn't do what I want on               scPhiDecomp[y (a x^2 + 2c x y -a y^2)]     >> {{0,(a x)/2+c y},-a y^3}      How do I use `PolynomialReduce[]` to produce `{{a y, c y}, 0}` on the second expression, while still producing the desired result on the 1st? Thanks, Keith


title: Strange message appearing when using Wolfram Alpha in Mathematica

text: I have Mathematica 9.0.1.0 and I've recently noticed that whenever I press the equals sign and type something like Sech[x]^2, I get the message: ![enter image description here](http://i.stack.imgur.com/dFYfV.png) I then tried other search queries, such as p^2, Hamiltonian, and 40 degrees 39'44''. I keep getting the same message, though. What's strange is that, regardless of the search query, Mathematica still correctly interprets the input. Does anyone know why this message appears? I only started seeing it a week or two ago. Thanks.


title: Graphics elements in a 2D lattice

text: I'm trying to write a small piece of code that will take the RHS of a first order linear ODE and return a slope field sampled at a few points. I have written:               (* Direction fields for 1st order linear equations y' = f(y,t) *)          grid = 10;          supt = 2; inft = -2; supy = 2; infy = -2;          tlist = Table[inft + n (supt - inft)/grid, {n, 0, grid}];     ylist = Table[infy + n (supy - infy)/grid, {n, 0, grid}];          Ggrid = Partition[Flatten[Outer[{#1, #2} &, tlist, ylist]], 2];          f = #1 + Exp[-2 #1] - 3 #2 &;          slopes = f[#[[1]], #[[2]]] & /@ Ggrid // N;       slopes is a `Table` of function values evaluated on the 2 dimensional array `Ggrid`. I would like to plot a small line with the given slope at the corresponding point in `Ggrid`.


title: How to stack matrices: one on top of another?

text: I have over 10 thousands matrices each with n by 3 size. For example, M[1]={{1,2,3},{4,5,6},{7,8,9}}, M[5]={{10,11,12},{13,14,15}} and M[20]={{16,17,18},{19,20,21},{22,23,24},{25,26,27}}. I want to form Mfinal={{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}}. I have tried like this mylist={5,20}; Do [Mfinal=Join[M[1],M[i],1],{i,mylist}]. It does not give me the results I desire.


title: non-linear trend reduction using thresholds

text: Doing some mappings of the earth magnetic field results in the left-hand figure below (which consists of 181 profiles): ![Non-linear trend reduction without threshold](http://i.stack.imgur.com/oKzCe.jpg) To improve this I tried a non-linear trend reduction using, for example,               lm = LinearModelFit[data, {a, a^2,a^3,a^4,a^5,a^6,a^7,a^8,a^9},a];      (middle figure) and               lm = LinearModelFit[data, {a, a^2,a^3}, a];      (right-hand figure), respectively. Data was defined as `data = Import[#1, "Table"];` within a `Scan` environment. Because of the occurrence of artifacts I feel that I have to consider something like thresholds, so that the reduction will be only considered within a threshold (for example -20 <= t <= 20) and the data outside of this range should not be affected by these calculations. I have no idea how to handle this effectively. My idea first was to use a lot of `IF`'s and to separate each profile into several parts. But this will be ineffective and time-consuming... I would like to handle all those 181 profiles separately before combining them. * * * @R.M.: This is the code I used so far:               SetDirectory[SystemDialogInput["Directory"]]     listOfFileNames = ReadList["listing.txt", Word];          Scan[      (data = Import[#1, "Table"];        newfile = StringReplace[#1, ".dat" -> "-red.dat"];        wfile = OpenWrite[newfile, FormatType -> StandardForm];        Clear[lm]; Clear[a]; Clear[neu]; Clear[aha];         start = First[First[data]]; mdim = Length[data];        lm = LinearModelFit[          data, {a, a^2, a^3, a^4, a^5, a^6, a^7, a^8, a^9}, a];        Do[aha = Last[Take[data, {m, m}]]; ywert = Last[aha];          xwert = First[aha]; neu[m] = ywert - lm[xwert], {m, mdim}];        Do[WriteString[newfile, start + (m - 1)*0.05  , "  "];          Write[newfile,    neu[m]], {m, mdim}];        Close[wfile];        Clear;        ) &,      listOfFileNames      ]      With listing.txt: 09500.dat 09525.dat 09550.dat 09575.dat 09600.dat 09625.dat 09650.dat 09675.dat etc * * * @belisarius: ![example 2](http://i.stack.imgur.com/Ij5Ru.jpg) This shows the quality of data outside of the pipeline I want to achieve @Mr.Wizard: With VSNR there is no effect on the data: ![enter image description here](http://i.stack.imgur.com/X7RyQ.png)


title: Creating a table/Matrix during a For loop

text: I have a `For` loop (with `i` as a counter), which calculates different values (`y1`, `y2`, `y3`,...) as a function of the variable `x`. How can I create a table/matrix which contains `i` lines, each line containing the variable `x_i` and the values (`y1_i`, `y2_i`, `y3_i`,...)?


title: Create a (maybe nested) list of nminimize solutions in a loop

text: I'm a total newbie in mathematica, so need some help. I understand that my question is about basics, but i couldn't find the answer in docs, google and here. Here is what i'm trying to do.               For[i = 1, i < 10, i++,      Quiet[s =          NMinimize[{Abs[x1] + Abs[x2] + Abs[x3] + Abs[x4] + Abs[x5],            Abs[0.055*(x1 + 11) + 0.065*(x2 - 13) + 0.068*(x3 - 47) +                0.071*(x4 - 50) + 0.07*(x5 - 43) + 0.852] <= 0.30 * i &&             Abs[-8.567*(x1 + 11) - 9.057*(x2 - 13) - 9.154*(x3 - 47) -                8.937*(x4 - 50) - 8.608*(x5 - 43) - 1359.469] <= 6 &&             Abs[55.818*(x1 + 11) + 62.22*(x2 - 13) + 64.286*(x3 - 47) +                64.945*(x4 - 50) + 63.306*(x5 - 43) + 4747.69] <=              1650}, {x1, x2, x3, x4, x5},           Method -> "DifferentialEvolution"]]            AppendTo[sols_nested_list, s]???      ]      Here AppendTo is wrond, but i need something like {{f,x1,x2,x3,x4,x5},{f,x1,x2,x3,x4,x5}...} How can i do this? Thanks in andvance.


title: Specifying an array that may have an unknown number of entries

text: Say I'm running some process of unknown duration, and during the process, I need to periodically record the state of some variable. If we knew exactly how long the process took, we could simply specify an array of appropriate size, and know that when the array is filled, we'll be finished. However, if this is not the case, it seems one has to resort to operations like:               testArray = Append[testArray,dataPoint];      Which becomes both computationally intensive and memory intensive at the limit of large array sizes. Is there a better way to proceed? Or should I simply specify a very large version of `testArray` and then chop it down after I've finished my procedure and filled it to some limited extent? Let me provide an example of the kind of process I'm thinking of (using the horrible `Append` strategy just to make things clear):               randVar=0;     storage={};          While[randVar<=0.99,     randVar=RandomReal[];     storage = Append[storage,randVar];     ];     Length[storage];      How do we use e.g. Sow/Reap to deal with the array updates?


title: get while loop output into a list

text: I would like to get the output from this while loop and use it as a list so I can count the frequency of the various tuples..               n = 1;     While[n < 10,       Print[RandomSample[Join[Table["a", {2}], Table["b", {2}]], 2]]; n++]      I'm thinking it should be easy but I haven't been able to do it? Thanks in advance for any suggestions!


title: Assign the output of a loop

text: > **Possible Duplicate:**   >  Creating a table/Matrix during a For loop Yet another simple question.               For[i = 1, i < 3, i++,      For[j = 1, j < 3, j++,        Print[{i, j}]      ]     ]      I want to assign the output to a list, for example like:               tts = {{1, 1}, {1, 2}, {2, 1}, {2, 2}}      All my efforts did not gave me the desired result, but I am sure it is possible. Any suggestions are welcome.


title: Dispatch displays rules incorrectly and evaluates when displaying

text: Consider this               a = 3;     disp = Dispatch[Unevaluated[{a -> 2}]]      > ![enter image description here](http://i.stack.imgur.com/E8Eg8.png) We see the rule `3 -> 2`, rather than `a -> 2`. However, we have               Unevaluated[a] /. disp      > >     2 (*not 3*) >   So that indeed the rule in the dispatch table was `a -> 2`. Note however that               Unevaluated[a] /. Normal[disp]      > >     3 >   As `Normal[disp]` intermediately evaluates to `a -> 2` which evaluates to `3 -> 2`. `a` does not match 3, so there is no replacement. So at first sight it may seem reasonable that `Dispatch` displays the table this way. However, this may lead to side effects **Side effects** Consider the following example. First we just set `disp2`, without displaying it.               disp2 = Dispatch[Unevaluated[{Print["hello"] -> 2}]];      > >      Null (*prints nothing, note the semicolon*) >   but when we do display the `Dispatch` table, the message is printed. ![enter image description here](http://i.stack.imgur.com/7fUqK.png) Note that we can still use the `Dispatch` table however.               Unevaluated[Print["hello"]] /. disp2      > >     2 >   This seems quite weird to me. To me it seems reasonable to put any expression in a `Dispatch` table. But it is not nice at all that such expressions would be evaluated when we display the `Dispatch` table. I suppose the way around this is to use `HoldPattern`, but that is disappointing to me, because really this should not be necessary. **Comparison with Association** To see why this is disappointing, consider `Association`. Here it is crucial that we use `Unevaluated`, as it is not an option to use `HoldPattern`, as the following does not work.               (*b has no value*)     Association[HoldPattern[b] -> 2][b]      > >     Missing["KeyAbsent", b] >   For `a`, which does have a value, we would have to do               Association[Unevaluated[a -> 2]][Unevaluated[a]]      > >     2 >   **Quick fix** Note that evaluating the following will prevent this issue.               Unprotect[Dispatch];     Clear@Dispatch;     Protect[Dispatch];      This only clears the rules that determine how `Dispatch` tables are displayed. **Question** So all in all it's nothing too major, I just wanted to share this. It is not nice that `Dispatch` can have side effects when used in this reasonable way. Is this a bug? A perfect answer would "spelunk" to where to code is evaluated.