title: What is so special about variable s$?

text: I found a nice bug in _Mathematica_ 9.0.1.0. Could anyone check to reproduce it? Create a file `temp.txt` with one line:               Attributes[s$] = {Temporary}      Load it into _Mathematica_ with `<<`. Now calculate:               Sum[x^(-n)*y^n, {n, 0, Infinity}]      _Mathematica_ stops responding and the only option is to quit the kernel. You can't interrupt or abort. Now change `s` to `a` or `b` in the file and repeat the above. It works! Next put the line               Attributes[s$] = {Temporary}      directly into the notebook and calculate the sum. It works! What is so special about temporary variable `s$` loaded from the file? I used a temporary variable `s$` in one of my functions and then saved the function to the file. _Mathematica_ added the above line to the file. Everything stopped working.


title: Non-Solvable PDE?

text: I would like to know whether this PDE is solvable and if yes, for which values of $a$.               2 (y Cos[a] + x Sin[a]) - 4 (y Sin[a] - x Cos[a]) f[x, y]     - 2 (y Cos[a] + x Sin[a]) (f[x, y])^2      + ((x^2) Cos[a] - 2 x y Sin[a] - (y^2) Cos[a]) D[f[x, y], x]     - ((x^2) Sin[a] + 2 x y Cos[a] - (y^2) Sin[a]) D[f[x, y], y] == 0      I have tried to solve it for the case where $a=0$               2 y + 4 x f[x,y] - 2 y f[x,y]^2 -      2 x y Derivative[0,1][f][x,y] + (x^2-y^2) Derivative[1,0][f][x,y] == 0      on _Mathematica_ but after 3 hours it gave me no result. Then I utilized the method of characteristics and expressed the $a=0$ case as a system of three ODEs \begin{eqnarray} \frac{dx}{dt} &=& (x^2 - y^2) \\\ \frac{dy}{dt} &=& (-2xy) \\\ \frac{df}{dt} &=& 2yf^2 - 2y - 4xf \end{eqnarray} but _Mathematica_ still gave me no results. So I suspect that this PDE might not have an analytic solution. Is this PDE solvable, and if not could you please indicate a reference which indicates which cases of PDEs are non solvable? I am only interested in Analytic solutions. Any kind of help will be most appreciated. Thank you in advance.


title: NIntegrate::ncvbr: How should we interpret and handle this error not mentioned in any documentation?

text: I have some user-defined module describing my integrand which has to be computed numerically (it's much more complicated than this but bear with me):               foo[x_?NumericQ, y_?NumericQ, z_?NumericQ] := Module[{f}, f = x+y+z; Return[f]];      Then I have a `region` I am defining with a rotated, truncated polyhedron, and using that as my integration domain which is a new V10 feature:               << PolyhedronOperations`     polys = Flatten[Normal[Truncate[PolyhedronData["Octahedron", "Faces"], 1/3]], 1];     p1 = Polygon[{{0, 0, 0}, {0, Sqrt[3/2]/2 - 1/(2 Sqrt[6]), 1/Sqrt[3]}, {-(1/(2 Sqrt[2])), -(1/(2 Sqrt[6])), 1/Sqrt[3]}, {1/(2 Sqrt[2]), -(1/(2 Sqrt[6])), 1/Sqrt[3]}}];     p2 = Polygon[{{0, 0, 0}, {1, 1, 0}/2, {0, 1, 1}/2, {1, 0, 1}/2}];     m = Last@FindGeometricTransform[p1, p2];     rot = Flatten[Table[m[polys[[i, 1]]], {i, 1, 14}], 1];     region = ConvexHullMesh[rot];      Then when I `NIntegrate` over it, I get an error which _doesn't exist yet_ in the Wolfram documentation, or on Google, or anywhere:               NIntegrate[foo[x, y, z], {x, y, z} ∈ region]          NIntegrate::ncvbr: NIntegrate failed to converge to prescribed accuracy after 5 refinements. NIntegrate obtained 0.35562326340448547` and 0.03672493677717351` for the integral and error estimates. >>      (Those numbers will change if you use the simple foo function.) The link in the error (>>) just takes me to the NIntegrate documentation. So my question is: **What precisely does the`ncvbr` error mean?** The error tag which seems related is `ncvb`, for example this is from the `NIntegrate` documentation:               NIntegrate::ncvb: "NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in x near {x} = {9.43625271977563}. NIntegrate obtained 10.3032-6.74255i and 0.3168981771605228` for the integral and error estimates. >>      which is actually informative, and says I need to crank up `MinRecursion` and `MaxRecursion`. However since I am using a `ConvexHullMesh` to specify my domain, could the way Mathematica "tetrahedralizes" my `region` be the problem instead, since `ncvbr` specifically mentions "refinement?" Would playing with `Min/MaxRecursions` even access this new feature, or do I have to manually refine my own mesh to prepare my integration domain? It seems like an unnecessary pain that should be accessible through the `NIntegrate` options.


title: Implementing a LineStyleFunction for line plots

text: I have data in the form:               {{0, 3, 4}, {1, 3, -1}, {2, 4, -1}, ...}      and I would like to implement something similar to ColorFunction for the style of a line. Basically I would like to plot a standard line plot using the first two entries of each point `{x, y, ..}`, and then decide on the line style using the 3rd `{.., .., z}`. Specifically I would like to plot dashed lines when the 3rd entry is positive and filled lines when negative, formed as one continuous curve. **EDIT** : to clarify, there will be large regions where the 3rd entry is consistently positive or negative, so its purpose is to set the style for those regions. This method wouldn't really work for situations where the 3rd value oscillates between the two. Many thanks, Hemmer


title: Eigenvalue / Eigenvector Calculation

text: I'm currently trying to compute the three smallest eigenvectors for a 34 by 34 matrix. While I was expecting this to take some time, Mathematica has been running for the past 3 hours, which seems maybe slightly disproportional to the task at hand. The matrix is a laplacian matrix, so it is relatively sparse. Here is my input (G is the graph itself):               A1 = AdjacencyMatrix[G];     D1 = DiagonalMatrix[VertexDegree[G]];     NL1 = IdentityMatrix[34] - MatrixPower[D1, -1/2].A1.MatrixPower[D1, -1/2];     EvecsNL1 = Eigenvectors[NL1,-3]      Any help is much appreciated. Edit: Sorry about that:               G = ExampleData[{"NetworkGraph", "ZacharysKarateClub"}]      I'm trying to get accustomed to working with graph laplacians in mathematica, so I'm messing around with some included datasets. Edit 2: Wow, I feel foolish. Thank you for your help.


title: Fourier transform an expression to obtain a distribution?

text: I have this expression for the correlation function for a rigid rotating molecule: $G(\tau) = 4 \pi \int \omega ^2 P_2[\cos (\omega \tau)] P(\omega) \, \mathrm{d}\omega \quad [1]$ where $P_2$ is a second order Legendre polynomial, and $P(\omega)$ is some distribution function. and they say "$P(\omega)$ can be solved either by a Fourier transform of Eg. 1 or by choosing an appropriate model for $P(\omega)$" An example of this 'done' in the book is: ![fft](http://i.stack.imgur.com/cTYSC.png) They say "(bottom graph) Angular velocity distribution functional $P(\omega)$ obtained from a Fourier Transform of $G(\tau)$ (the top graph)" I am quite confused how I go about obtaining this distribution via a Fourier transform. I tried a few functions in mathematica but got no where. Any help would be great. Thanks


title: Forcing efficient numerical arrays

text: I encounter strange behaviour of _Mathematica_ when evaluating multi- dimensional arrays of double-precision data. _Mathematica_ can express large arrays of machine-precision numbers using a specialized internal data-format, which optimizes memory usage and speeds up operations. However, _Mathematica_ does not always recognize when it can use such optimized arrays. Below are three cases that would ideally yield the same optimized data structure upon evaluation:               arr1 = Table[1.23, {1}, {100000}];     ByteCount[arr1]     (* 800168 *)          ncols = 1000;     arr2 = Table[1.23, {1}, {ncols}];     ByteCount[arr2]     (* 3200088 *)          ncols = 1000;     arr3 = Table[1.23, {1}, Evaluate[{ncols}]];     ByteCount[arr3]     (* 800168 *)      For some reason, the second case gives sub-optimal behaviour. My question is this: If I end up with a case where _Mathematica_ does not use its optimized numeric array data structure (such as `arr2`, above), how can I explicitly force a conversion?


title: Generate Chaotic Time Series using CellularAutomaton[]

text: If possible, How could I generate a chaotic Time series using `CellularAutomaton[]`. I am especially interested in Rule 30. A friend told me it was possible but I have yet not found the way to do so.


title: How to add vertex/edge labels to existing graph

text: If I have already created a graph using `Graph`. Later, I want to add to the graph some vertex and/or edge labels, how can I do that? Thank you.


title: How to assign up-values for `Derivative`?

text: I have defined several custom analytic functions. Here is the simplest example:               ln[x_, a_?NumericQ] := Piecewise[{{Log[x], Re[a] > 0}, {-Log[1/x], True}}]      Now I would like to let Mathematica know how to carry out derivatives on this: I need to make `D` and `Series` work on `ln` as if it were `Log`:               ln /: D[ln[f_, g_], x_] := D[Log[f], x];      Works wonderfully: ![enter image description here](http://i.stack.imgur.com/mafR8.png) But `Series` doesn't work because it is using `Derivative` instead of `D`. ![enter image description here](http://i.stack.imgur.com/pq3VH.png) So, now I try `TagSetDelayed` on `Derivative`: ![enter image description here](http://i.stack.imgur.com/lEy4E.png) But as you can see, it doesn't work because `ln` is too deep. What can I do to make `Series` work?


title: Arranging connector lines

text: Heike gave an absolutely wonderful answer to my question about arranging subplots around a main plot and including connector lines. This is the result: ![Mathematica graphics](http://i.stack.imgur.com/esMNn.png) Starting from Heike's answer, what is the best order to arrange the subplots in so the connector lines are as easy to follow / as aesthetically arranged as possible? To have something concrete to test with, let's say we have 12 points in the unit square. These are the starting points of the lines.               start = RandomReal[1, {12, 2}];      The set of endpoints is fixed (due to the subplot positions):               end = With[{dx = 0.1, dy = 0.1},             {{-dx, 1 + dy}, {.25 - dx/4, 1 + dy}, {.75 + dx/4, 1 + dy},              {1 + dx, 1 + dy}, {1 + dx, .75 + dy/4}, {1 + dx, .25 - dx/4},              {1 + dx, -dy}, {.75 + dx/4, -dy}, {.25 - dx/4, -dy},              {-dx, -dy}, {-dx, .25 - dy/4}, {-dx, .75 + dy/4}}];      Then the plot will look similar to this:               Graphics[{       FaceForm[Lighter@Orange], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}],       Line@Transpose[{start, end}],       AbsolutePointSize[18], Lighter@Orange, Point[end],        Black, MapThread[Text, {Range[12], end}]},        Frame -> True, FrameTicks -> None, PlotRange -> {{-.2, 1.2}, {-.2, 1.2}}]      ![Mathematica graphics](http://i.stack.imgur.com/bv87S.png) **Given the starting points in the orange square, how can we automatically reorder the labelled endpoints so the lines cross as little as possible (or generally: the figure looks as good as possible)?** Please try to make your answers complete, with a sample output figure using the code above. When it is not possible to avoid that the lines cross, what the "best" arrangement is is admittedly somewhat subjective. * * * **Note:** This is a question that I thought others would be interested in too. It is not a practical problem I am facing (I ordered the subplots manually in my figure), but of course if there are any good solutions, I will use them. I will be working on solutions as well. **Note 2:** Given two lists, `l1` and `l2`, containing the same elements in different orders, the permutation that re-orders `l1` to `l2` is `Part[Ordering[l1], Ordering@Ordering[l2]]`. This may be useful for reordering points.


title: Euler's method for system of differential equation

text: I need to program Euler's method to solve a system of two diffferential equations of first order. Fist, I have programmed the Euler's method for just one differential equation:                euler[f_, ini_, int_, h_] :=       Module[{x, y, l}, l = {ini};       y = ini[[2]];       For[x = int[[1]], x <= int[[2]] - h, x = x + h,       y = y + h*f[x, y]; l = AppendTo[l, {x + h, y}]];l]      And it works fine.               f[x_, y_] := 3 (1 - y);     euler[f, {0, 0.01}, {0, 10}, 1]     {{0, 0.01}, {1, 2.98}, {2, -2.96}, {3,8.92}, {4, -14.84}, {5, 32.68}, {6, -62.36}, {7,127.72}, {8, -252.44}, {9, 507.88}, {10, -1012.76}}      Now, changing a little the previous function I want to solve a system of two differential equations of first order. I programmed the following:               euler2[f_, g_, inif_,inig_, int_, h_] :=       Module[{x, y, t, list1, list2}, list1 = {inif}; list2 = {inig}; x = inif[[2]];      y = inig[[2]]; For[t = int[[1]], t <= int[[2]] - h, t = t + h,      x = x + h*f[x, y, t]; y = y + h*g[x, y, t]];      list1 = AppendTo[list1, {t + h, x}];      list2 = AppendTo[list2, {t + h, y}]; {list1, list2}]          But I got an error. What am I doing wrong? For example, I define f anf g in this way: f[x_, y_, t_] := y; g[x_, y_, t_] :=0.5x+0.5y; inif= is a set of the initial value of x (x(0)=1$\to$ inif={0,1}) and inig= is a set of the initial value of y (y(0)=1 $\to$ inig={0,1}) int is the interval where I want to calculate the solution int={0,10} and h the lenght of each step h=1 Thank you for your help.


title: Locators, lists of variable length, all in Manipulate

text: I'm trying to implement a complicated Manipulate[] interface. I'm not really interested in working code, but for those interested, I would like the program to   * allow you to drag around a variable number of locators,    * and have it output the motion of an object traveling from one locator to the next in straight line segments at constant velocity (just the function of time; no actual animation needed), and graph of the motion (i.e. connect the locators on the screen via ParametricPlot[]).   * One last thing: the times at which the object passes each of the locators are needed to specify a unique solution. But rather than manipulating the times themselves, I'd like to have input fields for the average velocity in each segment, and have the program infer the times. Here is a schematic that describes how I've tried to accomplish this: ![enter image description here](http://i.stack.imgur.com/ueqYn.png) However, I have been stumped as to how to implement this. Manipulate[] doesn't seem to have enough flexibility, and Dynamic[] seems to come with its own issues. **_All I'd like to know is if this is a dead end, or if not, some rough outline of how I could complete this implementation._** Here is how far I've gotten, with the help of a few answered stack exchange questions: GLOBAL PARAMETERS:               Row[{SetterBar[Dynamic@\[CapitalNu], Range[1, 10, 1]],"     Sets Length of X,Y,V"}]      INTERFACE VARIABLES -> INTERNAL VARIABLES:               Internalize[{V_, {X_, Y_}}, N_] := Module[{T},       T = Table[0, {i, 1, N + 2}];       For[i = 2, i <= N + 2, i++,        T[[i]] =           T[[i - 1]] + Norm[{X[[i - 1]], Y[[i - 1]]} - {X[[i]], Y[[i]]}]/           V[[i]];];       T       ]     X := Table[        ToExpression["x" <> ToString@i], {i, 0, \[CapitalNu] + 1}];     Y := Table[        ToExpression["y" <> ToString@i], {i, 0, \[CapitalNu] + 1}];     V := Table[        ToExpression["v" <> ToString@i], {i, 1, \[CapitalNu] + 1}];     T := Internalize[{V, {X, Y}}, \[CapitalNu]];      MANIPULATE INTERFACE               Procedure[T_,{X_,Y_}]:= Piecewise@      position=Table[{{X[[i]]-(t-T[[i]])/(T[[i+1]]-T[[i]]))(X[[i]]-X[[i-1]]),Y[[i]]-(t-T[[i]])/(T[[i+1]]-T[[i]]))(Y[[i]]-Y[[i-1]])},          T[[i]] <= t <= T[[i + 1]]}, {i, 1, \[CapitalNu]}]          (*The rest would look like this:      Manipulate[ParametricPlot[Procedure[Dynamic@T,{Dynamic@X,Dynamic@Y}][t],  {t,T[[1]],T[[-1]]}],     Table[{X[[i]],Y[[i]]},Locators],Table[Silders[V[[i]]]]],] *)      Does anyone know if Mathematica is capable of something like this? (I must emphasize, the Manipulate interface has to adjust automatically to changes in N; no retyping code permitted). The key issue I haven't been able to figure out is **_how to apply Manipulate[] controls, including locators, to the elements of variable length lists._** While this question may seem unnecessarily long, context really helps.


title: Using Apply inside Compile

text: In this great answer a compiled version of the Nelder-Mead algorithm is presented. Since it works on arbitrary dimensions (i.e. arbitrary number of arguments), it has to use apply on the objective function. The problem is that `Apply` is not directly supported inside `Compile`. To overcome this limitation the following code is used:               (* Produces compiled code for the Nelder-Mead algorithm with the objective function inlined *)     ClearAll[apply];     SetAttributes[apply, HoldAll];     apply[f : (_Function | _CompiledFunction), vars : {__Symbol}] :=         With[{applied := f @@ vars},           Function[arglist, Block[vars, vars = arglist; applied]]          ];      This seems to work (inside the package), but I have no idea, how it works. **Could somebody explain the techniques behind this code snippet?** Specifically:   * What does `SetDelayed` do inside `With`?    * Why does `vars` appear twice in the arguments to `Block`?    * Why doesn't this minimal example work? (I believe it mimics what is done in the mentioned answer...)              Clear[a, b, c, x, y, z, objectiveFunction, cfunc];     objectiveFunction = Compile[{a, b, c, x, y, z} ,        (a - x)^2 + 50 (b - y)^2 + (c - z)^2];          cfunc = With[{f = apply[objectiveFunction, {a, b, c, x, y, z}]},       Compile[ {{pts, _Real, 1}}, f@pts]       ]     << CompiledFunctionTools`     CompilePrint[cfunc]      **EDIT:** Here is the working snippet. Note that `"InlineCompiledFunctions"` must be set to `True` to avoid the call to `MainEvaluate`.               ClearAll[a, b, c, x, y, z, apply, objectiveFunction, cfunc];     (* Produces inlinable code for use inside Compile (where Apply is not \     supported directly) *)     SetAttributes[apply, HoldRest];     apply[f : (_Function | _CompiledFunction), vars : {__Symbol}] :=            Function[arglist, Block[vars, vars = arglist; f @@ vars]];          objectiveFunction = Compile[{a, b, c, x, y, z} ,        (a - x)^2 + 50 (b - y)^2 + (c - z)^2];     apply[objectiveFunction, {a, b, c, x, y, z}]     cfunc = With[{f = apply[objectiveFunction, {a, b, c, x, y, z}]},       Compile[ {{pts, _Real, 1}}, f@pts,         CompilationOptions -> {"InlineCompiledFunctions" -> True}]       ]     << CompiledFunctionTools`     CompilePrint[cfunc]


title: NMinimize memory consumption problem in Mathematica 9 vs. 7 & 8

text: I am having trouble using `NMinimize` in _Mathematica_ 9 - Memory consumption overflows. The same `NMinimize` command, with the same function to minimize, in _Mathematica_ 7 and 8, gives acceptable results. Is this a bug? Anyone else has had similar issues? Any workarounds ?


title: Selectively updating individual graphics in a dynamic, multiple-plot Show

text: Suppose `Show` contains multiple graphics objects that differ markedly in the amount of computation needed for their display. Hence, when dynamically updating only those individual graphics changed by any underlying variable change should be redrawn. For example (and with apologies to Dutch patriots), in the following dynamic `Show`, "pulling the red down" (by dragging the l.h.s locator) should take longer than "pulling the blue up" (by dragging the r.h.s. locator) since it is a more computationally intensive graphic (as simulated here by `Pause@0.1`). Dragging the r.h.s. locator however, is equally sluggish due to the overarching `Dynamic` wrapper causing both graphics to update whenever either locator is dragged. The logical solution would seem to be to wrap each inner `Plot` graphic in a `Dynamic` but `Show` doesn't like this apparently expecting a pure graphic for each of its shown components.               DynamicModule[{top = {.02, 0.15}, bottom = {.08, 0.08}},      Dynamic@       Show[        Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top,FillingStyle -> Red],        Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis,FillingStyle -> Blue],        Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],        Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],       PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/IB3od.jpg) `Overlay`, on the other hand, has no such qualms as indicated by the following graphic being much more responsive to the r.h.s. `VerticalSlider` "pulling the blue up".               DynamicModule[{top = {.02, 0.15},bottom = {.08, 0.08}},      {VerticalSlider[Dynamic[top[[2]]], {0, 0.15}],       Overlay[{        Dynamic@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top,FillingStyle -> Red, Axes -> False,PlotRange -> {0, .2}],        Dynamic@Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis,FillingStyle -> Blue, Axes -> False, PlotRange -> {0, .2}]}],        VerticalSlider[Dynamic[bottom[[2]]], {0, 0.15}]}]      ![enter image description here](http://i.stack.imgur.com/oUyHj.jpg) This is not a permanent solution as `Overlay` doesn't enjoy `Show`'s more natural way of combining plots (more intuitive formatting, locator usage, ability to set common graphics options etc) so the question is; how can `Overlay`'s selective updating be replicated in `Show`? **Answer Update:** The following answer is a hybrid taking from both Jens and Mr Wizard's responses which I think help to nicely illustrate some more general points about dynamic interface design. First, the combined answer:               SetAttributes[{DynamicShow, DynamicPlotRed, DynamicPlotBlue}, HoldAll];          DynamicShow[p_Plot] := Graphics[Dynamic@p[[1]], p[[2]]];          DynamicPlotRed[top_] := DynamicShow@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top, FillingStyle -> Red]          DynamicPlotBlue[bottom_] := DynamicShow@Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis, FillingStyle -> Blue]          DynamicModule[{top = {.02, 0.15},bottom = {.08, 0.08}},      Show[       DynamicPlotRed@top,       DynamicPlotBlue@bottom,       Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],       Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],      PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/8UOn2.jpg) This includes the desired, lower level (indirect) use of `Dynamic` to maintain the usefulness of its automatic, targeting updating as captured in Mr Wizard's answer. This is important as it allows a more general, more numerous adding of interface components (note the relevant `Dynamic` sits in `DynamicShow` to which I'll return). The approach in Jens' answer - having each `Locator` directly update the corresponding plot, while working perfectly for the quoted two-element example, doesn't generalize in the sense that all plot updating now needs to be done "by hand" or via `Dynamic`'s second argument _without_ harnessing `Dynamic`'s automatic updating (in full generality "Plot" can be an arbitrarily complex interface component with multiple, not-immediately-obvious dependencies). There is a potential issue in that this solution relies on a consistent `FullForm` being generated by `Plot` but this can be addressed by adding a helper function. For example, using the `PlotLegend` option changes the `FullForm` structure but this can be handled as follows:               SetAttributes[{DynamicShow, DynamicShowLegend, DynamicPlotRed, DynamicPlotBlue}, HoldAll];          DynamicShow[p_Plot] := Graphics[Dynamic@p[[1]], p[[2]]];          DynamicShowLegend[p_] /; (! FreeQ[Hold@p, PlotLegends]) := Legended[Graphics[Dynamic@p[[1, 1]]], p[[2]]];          DynamicPlotRed[top_] := DynamicShow@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top, FillingStyle -> Red]          DynamicPlotBlue[bottom_] := DynamicShowLegend@Plot[{x, bottom[[2]]}, {x, 0, .1}, Filling -> {1 ->{Axis, Green}, 2 -> {Axis, Blue}}, PlotLegends -> True]               DynamicModule[{top = {.02, 0.15}, bottom = {.08, 0.08}},      Show[       DynamicPlotRed@top,       DynamicPlotBlue@bottom,       Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],       Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],       PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/tvUOT.jpg) The functions introduced in Jens' answer also illustrate a fundamental principle for building more complex dynamic interfaces. While introduced here to make `Dynamic`'s second argument more readable, this improved readability assumes much greater proportions as interfaces' complexify (essentially implementing modularization with all its attended advantages, as, for example, enumerated in Tom Wickham-Jones white paper). There is a wrinkle in performing such modularization when it comes to dynamic interfaces however, which can be illustrated by seeing how Mr Wizard's solution modularizes (in fact generalizes). Essentially his insight was that `Show` apparently (mostly) expects `Graphics` heads in its arguments (with exceptions noted as above) so that wrapping one of these in a `Dynamic` upsets this obstinance (which I regard as a design oversight). This can now however, at least be accommodated by giving `Show` its cherished `Graphics` head and instead wrapping `Dynamic` around `Graphic`'s first argument via `Graphics[Plot[...][[1]], AspectRatio->1/GoldenRatio]`. The `AspectRatio` option corresponds to that generated automatically in this plot but in fact any generated option value can be included by defining               DynamicShow[p_Plot]:=Graphics[Dynamic@p[[1]],p[[2]]]      (n.b. The `FullForm` of a `Plot` output is `Graphics[comps, opts]` ) The wrinkle is that in order to apply `DynamicShow` in this way, its argument, `p`, needs to avoid evaluation prior to being wrapped in `Dynamic` to maintain its own "lexical scoping" (a form of code generation/injection). Consequently, this dynamic variable needs to be held right through to its final placement nestled inside a `Dynamic` thereby requiring a chain of `HoldAll` attributions. In a fuller generality, the passed-through variable need not just be a local `DynamicModule` variable holding a pair of numbers like `top` and `bottom` but instead can potentially hold an arbitrary large dataset. This suggests an updated, less-emulative, idiom for answering an earlier question about realizing such modularization in dynamic interfaces; that is, there appears to now be a sufficient level of mutability in the new associations/datasets for expressions like `top[[2]]` to be fruitfully extended to expressions like `interfaceData[[ ...]]`.


title: Is it possible to pass a "shared" integer in librarylink?

text: MTensor supports shared pass, where the argument can be modified in the library function and that modification can be seen in Mathematica side. Is it possible to do the same thing to a integer or double type? For example, in the following code, the library function takes an integer and set it to 2.               MMASrc = "#include <WolframLibrary.h>       #include <WolframCompileLibrary.h>            DLLEXPORT mint WolframLibrary_getVersion(){            return WolframLibraryVersion;       }            DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){            return 0;       }       EXTERN_C DLLEXPORT int test(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){            int  a = MArgument_getInteger(Args[0]);       a=2; //library function set a to 2       return LIBRARY_NO_ERROR;       }";               Needs["CCompilerDriver`"];     lib = CreateLibrary[MMASrc, "test", "Debug" -> True,         "TargetDirectory" -> "/tmp"];     testFunc = LibraryFunctionLoad[lib, "test", {Integer}, "Void"];     a = 3;     testFunc[a];     a          (*3*)      However, I get 3 as output. So it is possible to have shared pass so that I Mathematica can reflect the modify of a by the library function, except making it into a MTensor with one element?


title: Can Tuples help simplify this?

text: I have a list `{1, 2, 3, 4}` and wish to form                {{{1,2},{3,4}},       {{1,3},{2,4}},       {{1,4},{2,3}}}      I ended up doing it manually like this:               a={1,2,3,4}     {{{a[[1]],a[[2]]}, {a[[3]],a[[4]]}},     {{a[[1]],a[[3]]}, {a[[2]],a[[4]]}},     {{a[[1]],a[[4]]}, {a[[2]],a[[3]]}}}      Is there a way to do this more simply? Of course this is a simplified question from the actual problem which is more complicated. An answer to this can be generalized to my actual problem. Thanks.


title: Help needed with Simple equations

text: take a simple formula like Ohm's law u=i*r... is it possible to solve for i without values??, something like Solve[u=i*r, i] and expect an output like i=u/r which gives me: Solve::naqs: i r is not a quantified system of equations and inequalities. >> Solve[i r, i] sol = Solve[u == i*r, i] which gives me {{}} Any help would be greatly appreciated


title: Using more than one set of Locators in a Manipulate

text: I need to add locators dynamically to different sets. With one set this works OK:               Manipulate[      Graphics[{Point@pts}, PlotRange -> {{0, 1}, {0, 1}}],      Control[{{pts, {RandomReal[1, 2]}}, ControlType -> Locator}],       Row[{        Button["Add L1", pts = pts~Join~{RandomReal[1, 2]}]}],      Dynamic@pts]      But when I try to use more than one set, it doesn't:               Manipulate[ (*fails*)           Graphics[{Point@pts, Point@ptsNA}, PlotRange -> {{0, 1}, {0, 1}}],      Control[{{pts, {RandomReal[1, 2]}}, ControlType -> Locator}],      Control[{{ptsNA, {RandomReal[1, 2]}}, ControlType -> Locator}],           Row[{        Button["Add L1", pts = pts~Join~{RandomReal[1, 2]}],         Button["Add LNA", ptsNA = ptsNA~Join~{RandomReal[1, 2]}]}],      Dynamic@pts, Dynamic@ptsNA]      I could work out my way by adding all locators to the same set and manually assigning them to one "set" or another, but in my real application I have to add a different number of locators to each set at a time and also be able to delete them, so that complicates the code. **Edit** Thanks to Sjoerd's comment in another question, I found this limitation is covered in the documentation: > Due to internal limitations, it is not possible to combine individual > Locator variables with a variable that is a list of multiple Locator > variables: you can have only one multipoint Locator variable in a > Manipulate. However, in exchange, it is possible to add the option > LocatorAutoCreate->True to that one Locator multivariable specification, and > thereby allow you to create and destroy Locator points interactively > (changing the length of the list of points stored in the variable). So, no hope using `Manipulate[]`, accepting jVincent's answer.


title: Blurred frontend text in Mathematica 10, Windows, High-DPI Display

text: So I have recently upgraded to a Windows ultrabook with a high-res display. All my software seems to cope just fine with the high resolution, except for Mathematica 10. Mathematica seems to pretend the screen resolution is lower, and blurs both frontend text and graphics output. How can I configure the interface to display crisp text, as it did on my old MacBook Air? Thanks!


title: Question about collections of custom GUI controls for Mathematica

text: Background: I have only recently begun programming GUIs in Mathematica, so I have a continuous need for custom controls. I needed a scrollable list control and with the help of Google I found a beautiful one in this MathGroup post (One of Sjoerd, if I am correct.) The point being: there is a lot of excellent Mathematica code shattered all over. Most matured languages have libraries of custom controls. I am not aware of any existing for Mathematica. **Question(s): What is the best _managed_ collection of (open source) custom GUI controls for Mathematica that you know of? Where do you get your custom GUI controls? Should there be a collection of custom GUI controls for Mathematica?**


title: How can I use list processing functions on data in a file?

text: How might I work with the following functions on a list, if the list is a disk based file?               Partition[]     DeleteDuplicates[]     Split[]       SortBy[]      The file is too large to `ReadList[]` or `Import[]` the data in the first place.


title: Expectation Maximization Algorithm

text: I would like to use the expectation maximization algorithm within Mathematica. The issue is that I am very basic user and progress slowly with understanding functional programming.. I have found this "featured example" on Wolfram web page, where an algorithm for a mixture of 2 normal distributions is demonstrated. Now I would like to understand what is going on in order to change it later to be applicable to my problem (My problem is to estimate a mixture of 3 distributions, given the real data) Could please anyone explain line by line (or more coarsely) what is going on in this code? (And how would one go to use the real dataset (excel file)) Thanks a lot!               {Manipulate[      Module[{d1, d2, sim, updates},       SeedRandom[sr];       d1 = NormalDistribution[\[Mu]1, \[Sigma]1];       d2 = NormalDistribution[\[Mu]2, \[Sigma]2];       sim = With[{musAndsigmas =            RandomChoice[{p1,               1 - p1} -> {{\[Mu]1, \[Sigma]1}, {\[Mu]2, \[Sigma]2}},             numsamples]},         musAndsigmas[[All, 2]] RandomReal[NormalDistribution[],             numsamples] + musAndsigmas[[All, 1]]];       updates =         NestList[em[#, sim] &, {{-10, 5}, {5, 5}, {.2, .8}}, numiterations];       Grid[{{Show[{Histogram[sim, Automatic, "PDF",              PlotRange -> {{-30, 30}, {0, Automatic}}],             Plot[{updates[[-1, 3, 1]]*               PDF[Apply[NormalDistribution, updates[[-1, 1]]], x],               updates[[-1, 3, 2]]*               PDF[Apply[NormalDistribution, updates[[-1, 2]]],                 x]}, {x, -30, 30},              PlotStyle -> {{Red, Thick}, {Blue, Thick}},              PerformanceGoal -> "Speed", PlotRange -> All]},            ImageSize -> {400, 275},            AxesOrigin -> {-30,              0}]}, {Grid[{{Panel[              TableForm[updates[[-1, 1 ;; 2]],                     TableHeadings -> {updates[[-1, 3]], {"\[Mu]",                   "\[Sigma]"}}]]}}]}}]       ],      Style["first distribution", Bold],      {{\[Mu]1, 8}, -20, 20, ImageSize -> Tiny, Appearance -> "Labeled"},      {{\[Sigma]1, 5}, 1, 10, 1, ImageSize -> Tiny,        Appearance -> "Labeled"},      Delimiter,      Style["second distribution", Bold],      {{\[Mu]2, -12}, -20, 20, ImageSize -> Tiny, Appearance -> "Labeled"},      {{\[Sigma]2, 3}, 1, 10, 1, ImageSize -> Tiny,        Appearance -> "Labeled"},      Delimiter,      Style["probability", Bold],      {{p1, .3, "p"}, .1, .9, ImageSize -> Tiny, Appearance -> "Labeled"},      Delimiter,      Style["number of samples", Bold],      {{numsamples, 100, ""}, 50, 200, 10, ImageSize -> Tiny,        Appearance -> "Labeled"},      Style["number of iterations\nof EM algorithm", Bold],      {{numiterations, 3, ""}, 1, 20, 1, ImageSize -> Tiny,        Appearance -> "Labeled"},      Delimiter,      {{sr, 326, "random seed"}, 1, 9999, 1, ImageSize -> Tiny,        Appearance -> "Labeled"},      ControlPlacement -> Left,      Initialization :> (        problists[\[Theta]_, y_] := Block[{probs, totalprobs},          probs =            Table[\[Theta][[3, i]]*             Map[PDF[Apply[NormalDistribution, \[Theta][[i]]], #] &,               y], {i, 2}];          totalprobs = Total[probs];          Map[#/totalprobs &, probs]];        pi[j_, p_] := Mean[p[[j]]];        emu[sim_, j_, p_] := Total[sim*p[[j]]]/Total[p[[j]]];        emstd[sim_, j_, u_List, p_] := Total[(sim - u[[j]])^2*p[[j]]]/         Total[p[[j]]];        em[params_, sim_] := Module[{theprobs, mus, vars, probs},          theprobs = problists[params, sim];          mus = Map[emu[sim, #, theprobs] &, {1, 2}];          vars =            Map[emstd[sim, #, params[[1 ;; 2, 1]], theprobs] &, {1, 2}];          probs = Map[pi[#, theprobs] &, {1, 2}];          Append[Transpose[{mus, vars^.5}], probs]];        )]}


title: How to generate patterns by a list of integers

text: I have a list of integers `{3,4,2,2}`. This list will give patterns `{x_,_,y_,y_,_,_,z_,z_,w_,w_,x_}` and `{0,0,0,1,1,1,1,0,0,1,1}`. Notice that I want to assign successive `0,1` with the same symbol. How to make this? *edit Compare the patterns               {x_,_,y_,y_,_,_,z_,z_,w_,w_,x_}     {0, 0, 0,1, 1,1, 1,0,  0,1, 1 }     {1, _, 2,2, _,_, 3,3,  4,4, 1 }      Suppose I have symbols `{x_,y_,z_,w_}` (you may use `{a_,b_,c_,d_,...}`). To transform `lst={3,4,2,2}` to `{x_,_,y_,y_,_,_,z_,z_,w_,w_,x_}`, begin with `{x_,_,_,_,_,_,_,_,_,_,_}`. Then put `y_` at positions `lst[[1]]` and `lst[[1]]+1`. Then put `z_` at positions `lst[[1]]+lst[[2]]` and `lst[[1]]+lst[[2]]+1`. Then put `w_` at positions `lst[[1]]+lst[[2]]+lst[[3]]` and `lst[[1]]+lst[[2]]+lst[[3]]+1`. And finally put `x_` at the last position.


title: Image Processing: Finding Orientation and Position of Symmetry Axes

text: **Background** I'm currently toying with Principles of Design by Charlotte Jirousek in order to learn some basics of image processing. As main principals she suggests Balance, Proportion, Rhythm, Emphasis and Unity. I'm particularly interested in **Balance**. According to her definition: Balance is the concept of visual equilibrium, and relates to our physical sense of balance. It is a reconciliation of opposing forces in a composition that results in visual stability. Most successful compositions achieve balance in one of two ways: symmetrically or asymmetrically. Balance in a three dimensional object is easy to understand; if balance isn't achieved, the object tips over. To understand balance in a two dimensional composition, we must use our imaginations to carry this three dimensional analogy forward to the flat surface. ![Sample 2](http://i.stack.imgur.com/hw3vM.gif) Symmetrical balance can be described as having equal "weight" on equal sides of a centrally placed fulcrum. It may also be referred to as formal balance. When the elements are arranged equally on either side of a central axis, the result is Bilateral symmetry. This axis may be horizontal or vertical. It is also possible to build formal balance by arranging elements equally around a central point , resulting in radial symmetry. ![Sample 2](http://i.stack.imgur.com/lSEfx.gif) There is a variant of symmetrical balance called approximate symmetry in which equivalent but not identical forms are arranged around the fulcrum line. ![Sample 3](http://i.stack.imgur.com/ImbiH.gif) **Question** How can I find Orientation and Position of Symmetry Axes of the given figures? **Solution Directions** In fact this question meant to be a toy example for image processing. However, after some investigation this turns out to be a challenging subject in it self.See the link for related papers submitted and published in both computer vision and computer graphics as well as changing test images.   * Jens has a quite inspiring approach explained in his post.   * An alternative approach is suggested by Changming Sun, Deyi Si Fast Reflectional Symmetry Detection Using Orientation Histograms. In this approach Gradient Orientation Histogram is used.               o = Flatten@ImageData@GradientOrientationFilter[imag, 3];     w = Flatten@ImageData@GradientFilter[imag, 3];     \[ScriptCapitalA] = WeightedData[o, w];     \[ScriptCapitalD] = HistogramDistribution[\[ScriptCapitalA]];     t = Table[{x, PDF[\[ScriptCapitalD], x]}, {x, -\[Pi]/2, \[Pi]/2, 0.05}];     Max[t\[Transpose][[2]]]      As explained in the paper this gives the axes. Also available in Mathematica GradientOrientationFilter examples.   * Another approach could be based on component in Mathematica which may require additional image processing.


title: Can you recommend an efficient method for finding the least integer satisfying my inequality?

text: I tried find the minimum make $\frac{1}{2}+\frac{1}{2+\sqrt{2}}+\frac{1}{3 +\sqrt{3}}+...+\frac{1}{n+\sqrt{n}}>15$ Following code is so slow when I use condition               NestWhile[# + 1 &, 1, NSum[1.0/(i + Sqrt[i]), {i, #}] < 15 &]          Catch@Fold[If[#1 > 15, Throw@#2, #1 + 1.0/(#2 + Sqrt[#2])] &, 0.0,         Range[10^7]] // Timing      but these two are fast without condition               NSum[1.0/(i + Sqrt[i]), {i, 10^7}]          Fold[# + 1/(#2 + Sqrt[#2]) &, 0.0, Range[10^7]]      How can I improve my code make it efficiency if dont't use compilation? # Update: Use Bisection_method               num = 15;     f[x_] := NSum[1/(i + Sqrt[i]), {i, x}];     n = NestWhile[# + 1 &, 1, f[10^#] < num &]     min = 10^(n - 1);     max = 10^n;     mid = Round[(min + max)/2];     While[Abs[f[mid] - num] > 10^-6,        If[f[mid] >= num, max = mid - 1];       If[f[mid] <= num, min = mid + 1];       mid = Round[(min + max)/2];     ];     {min, mid, max}     Clear["`*"]


title: How does Plot work?

text: I considered the following function:               sin[x_] := Module[{},       Print["x=", x];       Sin[x]     ]      in _Mathematica_. Next, I tried to plot it using:               Plot[sin[t], {t, 0, 2 Pi}]      Surprisingly, the first three lines of output are:               x=0.000128356     x=t     x=1.28228*10^-7      Can someone explain this behavior? In this case it doesn't cause a problem, but in my "real" case it does. ### Summary acl's answer below offers, at its very beginning a solution to the specific problem. In very-short, the reason that this `x=t` appears is hidden somewhere in the way _Mathematica_ evaluates the functions. The answers below provide interesting insight into the way it works. The interested reader _should_ read all the answers and details below, they are invaluable, although might be behind the reach of some of the readers (like, partially, in my case).


title: Failing to import an .eps file

text: I have an .eps file which was created using GLE. There is nothing wrong with the file, GS View can read it correctly. However, when I use Mathematica to read it using               Import["dcl.eps"]      it returns `$Failed`. The particular .eps file can be found here EPS file I want to read this eps file so as to rasterize it, thus reducing its size. I'm using Mathematica v 9.0 under Win XP. Any ideas why Mathematica cannot read this file?


title: Extract data from WeatherData as a list of associations

text: Given weather data for 2013 and 2014 as follows:               t =        QuantityMagnitude[         WeatherData["California", "MeanTemperature", {{2013, 1, 1}, {2014, 1, 1}, "Day"}]          "Values"]];      how can I get the average temperature for each day during 2 years as a list of associations, for example: > >     January 1 -> 12 >      ... >      December 31 -> -20 >


title: How to count the integer grid numbers defined by inequalities?

text: I have the following code to show a red area defined by inequalities:               ClearAll["Global`*"];     p = Reduce[y <= 3/10 x + 18 && y > x^2/8, {x, y}]     r = RegionPlot[p, {x, -15, 18}, {y, -5, 25},         GridLines -> {Table[i, {i, -15, 18}], Table[j, {j, -5, 25}]},         PlotStyle -> Directive[{Opacity[0.5], Red}]];     bg = Graphics[{Opacity[0.2], Yellow, Rectangle[{-16, -6}, {19, 26}]}];     range = First /@        Differences /@ (PlotRange /. Options[r]); target = 1; Show[{r, bg},       AspectRatio -> (Last[range]/First[range]/target)]      which shows: ![enter image description here](http://i.stack.imgur.com/7KHXQ.png) How can I count those integer grids and highlight them with colored dots?


title: If statement condition based on variable without value does not cause error

text: This code works as expected:               isDefined = 2;     x = 1;     For[i = 1, i <= 3, i++,         If[x + i > isDefined, x = 100];         Print[StringJoin["i = ", ToString[i], ", x = ", ToString[x]]];     ]      It produces output:               i = 1, x = 1     i = 2, x = 100     i = 3, x = 100      This code does not work as I would expect it to:               x=1;     For[i=1,i<=3,i++,         If[x+i>notDefined,x=100];         Print[StringJoin["i = ",ToString[i],", x = ",ToString[x]]];     ]      It produces output:               i = 1, x = 1     i = 2, x = 1     i = 3, x = 1      In both, it starts with `x = 1`, so when `i = 2`, `x + i = 3 > 2`. Since 2 is the value assigned to the variable `isDefined`, `x` is set equal to 100. The second example is the same code, except instead of comparing `x + i` with the variable `isDefined`, it compares `x + i` with the variable `notDefined`, a variable I never defined. Instead of giving an error message and stopping, or somehow indicating that I told it to compare the value of `x + i` with something that has not been assigned a value, it keeps right on going and never gives any indication that anything is wrong. In the real code on which this example is based, I have lots of input data and I create output data based on calculations and conditions using the input data. I changed a variable name but accidentally left the old name in an if statement. The result was output that looked like the condition had never been met, when actually Mathematica just did what it did in the example above. Some programming languages won't compile/run if you try to do something like this, and if they don't do this by default, there's an option to specify that they shouldn't compile/run. I've looked through the preferences and online and can't find anything about this. I'd like to avoid the incorrect output that results from this problem. Does anyone have any ideas (other than the obvious solution of not making mistakes in the first place)?


title: Mathematica list element sort

text: I have a list, say,               cc = {{0.16441114380905922, 1}, {0.16441114380905922, 2},           {-0.16441114381135857, 4}, {0.3469323902621586, 3},           {-0.3469323902254179, 2}, {-0.26126804383825986, 3},           {0.2612680438599802, 2}, {-0.28969854537720147, 3},           {0.28969854538168743, 2}, {-7.968690709137364, 3},           {7.968690708910122, 2}, {-4.000091496006696, 3},           {4.000091495616817, 2}, {4.729024444062355, 3},           {-4.72902444452141, 2}, {4.729024444062355, 1}}      I want to get the following information:   1. all the $2\times1$ sub-lists with the same first element should be together (e.g., {x,y} and {x,z} should be together)   2. multiplicity of the first elements I am using `Tally` and `Sort` (also used `GatherBy`) but not much help so far. Thanks in advance.


title: how to use Tooltip with a Dynamic point

text: consider this example:               LocatorPane[Dynamic[pt],      Plot[Sin[x], {x, 0, 10},        Epilog -> {PointSize[Large], Point[Dynamic[pt]]},        PlotLabel -> Dynamic@pt], Appearance -> None]      I am trying to add `Tooltip` to the `pt` but without any success. the only thing I got is using `Tooltip` with the point like this: `Tooltip@Point[Dynamic[pt]]` but this will show the word `Point` also. any solution to use Tooltip with the point `pt` thanks


title: Solve[polynomial, x, Reals] doesn't get all real roots or correct ones?

text: _My main confusion is about the difference between the two code blocks at the end of this long spiel, but the spiel contains the code to create the polynomial if its coefficients are helpful for explaining the difference. Thanks in advance!_ I have this polynomial, `eu1-eu2`, of degree `n` (where `n` is a multiple of `3` between `3 and 93`, inclusive).               solutions = Simplify[Solve[eu1 == eu2]];     solutions = p /. solutions;     Select[solutions, Element[#, Reals] &]      and               p /. Simplify[Solve[eu1 == eu2, p, Reals]]      should return the same roots, from what I can tell. And they do, for lower values of `n`. But as `n` increases, at some point they start returning slightly different roots, and later on, the first code block returns a bunch of different roots while the second one usually returns one root repeated many times. As `n` increases, the second one's repeated root seems to be farther away from any of the roots gotten from the first one. The first one probably gets the true roots, since the size of "solutions" (which includes complex roots) equals `n`. But then what number is the second one getting? * * * Edit: `30` is the smallest `n` for which the number of roots is the same but the roots themselves are slightly different. Here the first method produces `{0.333794}` whereas the second produces `{0.333788}`. `33` is the smallest `n` for which the number of roots is different for each method. Here the first method produces `{0.251609, 0.251683, 0.273157, 0.274114, 0.3336}` whereas the second produces `{0.33363}`. * * * Edit: The code that sets up the polynomial is as follows:               n = 93;     q1 = (n - Mod[n, 3])/3;     q2 = q1;     upperbound = 0.5;          (mat1 = Array[0, {n, 3}];     prob1 = Array[0, {n, 1}];     prob2 = Array[0, {n, 1}];     prob3 = Array[0, {n, 1}];     For[m = 0, m <= n - 1, m++,     If[m + 1 - q1 != 0,      prob1[[m + 1, 1]] = q1/(m + 1);     prob2[[m + 1,      1]] = ((q2 - (n - m - 1))/(m + 1 - q1))*(1 - q1/(m + 1));     prob3[[m + 1, 1]] = 1 - prob1[[m + 1, 1]] - prob2[[m + 1, 1]];     mat1[[m + 1]] = {prob1[[m + 1, 1]], prob2[[m + 1, 1]],      prob3[[m + 1, 1]]},     mat1[[m + 1]] = {0, 0, 0}]])          (mat = Array[0, {n, 3}];     For[m = 0, m <= n - 1, m++,     If[m + 1 <= q1,      mat[[m + 1]] = {1, 0, 0},     mat[[m + 1]] = mat1[[m + 1]]]])          (mat3 = Array[0, {n, 3}];     prob4 = Array[0, {n, 1}];     prob5 = Array[0, {n, 1}];     prob6 = Array[0, {n, 1}];     For[m = 0, m <= n - 1, m++,     If[m + 1 - q2 != 0,      prob4[[m + 1,      1]] = ((q1 - (n - m - 1))/(m + 1 - q2))*(1 - q2/(m + 1));     prob5[[m + 1, 1]] = q2/(m + 1);     prob6[[m + 1, 1]] = 1 - prob4[[m + 1, 1]] - prob5[[m + 1, 1]];     mat3[[m + 1]] = {prob4[[m + 1, 1]], prob5[[m + 1, 1]],      prob6[[m + 1, 1]]},     mat3[[m + 1]] = {0, 0, 0}]])          (mat2 = Array[0, {n, 3}];     For[m = 0, m <= n - 1, m++,     If[m + 1 <= q2,      mat2[[m + 1]] = {0, 1, 0},     mat2[[m + 1]] = mat3[[m + 1]]]])          u = {{1 - p}, {p}, {0}};          (eu1 = 0;     For[m = 0, m <= n - 1, m++,     eu1 = eu1 + (mat[[m + 1]].u)*(p/upperbound)^     m*(1 - p/upperbound)^(n - m - 1)])     eu1 = Simplify[eu1];          (eu2 = 0;     For[m = 0, m <= n - 1, m++,     eu2 = eu2 + (mat2[[m + 1]].u)*(p/upperbound)^(n - m - 1)*(1 -      p/upperbound)^m])     eu2 = Simplify[eu2];      Also note that the following code results in the same solutions as the first code block:               Simplify[Solve[eu1 - eu2 == 0 && p < 15000, p, Complexes]]      Whereas this code results in the same solutions as the second code block:               Simplify[Solve[eu1 - eu2 == 0 && p < 15000, p, Reals]]      So it's something about allowing the function values to be complex vs. not allowing them to be complex. But I don't understand why my function would ever be complex when p is restricted to be real, since all of the coefficients are real. Also, how exactly does it restrict function values to be real while it's solving for the roots? And why are the roots different from the case where complex function values are allowed? Sorry that this is kind of a mess, but I would really appreciate any help you can provide!


title: How to "merge" various graphics 2d into one 3d graphic?

text: I did some calculations and as result got a 2D graphic, but at the beginning of the work I used a constant parameter. What I want is to make a 3D graphic with this parameter as an axis, varying from 1 to 100. How to proceed?


title: Input[] inside DynamicModule causing a kernel crash

text: I have those few lines of code causing a crash and I can't figure out why:               DynamicModule[{openNothing},      EventHandler[       Panel@Row@{          Button["Built In Funct", openNothing[]]}, {}],           Initialization :> (openNothing[] := (Input["bla", 1];))]      _Mathematica_ freezes for a few seconds and then says: > The kernel is not responding to a Dynamic Evaluation. [...] **WARNING:** It did make _Mathematica_ not responding at all. After the **force quit** the list of the recently opened notebooks were removed (I assume that the `~/.Mathematica/FrontEnd/init.m` has been removed.) I'm on _Fedora 19_ , _Mathematica_ 8.0.4. The same issue has been noticed under _Windows 7_ , _Mathematica_ 9.


title: Parametric Equation with restrictions on the independent variable

text: I'm sorry if this question was answered but I am completely new to _Mathematica_ , really learning as I go (background in Java). The questions I looked at that were suggested didn't make much sense with all the advanced parts being thrown around. For a Pre Calculus class I need to graph parametric equations. However, one of the questions is:               x = 2t     y = t + 5      with `-2 ≤ t ≤ 3`. How would I do this? So far I know the basic equation but I don't get the part with having the piecewise               ParametricPlot[{ 2 t, t + 5}, {t, -10, 10}]


title: Why is Plot3D giving me a surface with gaps?

text: I am trying to get plot for the band structure for graphene.               d = 10; (*Plot range*)      coupling := {{0, 2 Cos[Sqrt[3]*(#1)/2]*Cos[#2/2] + Cos[#2] +      I (2 Cos[Sqrt[3]*(#1)/2]*Sin[#2/2] - Sin[#2])},      {Conjugate[ 2 Cos[Sqrt[3]*(#1)/2]*Cos[#2/2] + Cos[#2] +         I (2 Cos[Sqrt[3]*(#1)/2]*Sin[#2/2] - Sin[#2])], 0}} &;     Plot3D[Eigenvalues[coupling[kx, ky]][[1]], {kx, -d, d}, {ky, -d, d}] (*Discontinuous*)     Plot3D[(Eigenvalues[coupling[kx, ky]][[1]])^2, {kx, -d, d}, {ky, -d, d}] (*Continuous*)      I am not able to understand why the surface in the first plot is coming out discontinuous; i.e., it has some gaps in the surface plot, whereas there are no gaps in the second plot, which simply plots the square of the function shown in the first plot. There is no physics that explains the gaps. Also, the effect is not periodic/predictable. By that I mean that on changing `d`, I am getting very different patterns of gaps all over the place. Is there some problem with my code or is 3D plot working incorrectly? How do I get rid of this error? ### Edit I am NOT talking about the spike at (0,0). I am attaching a picture of my plot for clarity. I am talking about the "ribbons" missing from the surface. ![enter image description here](http://i.stack.imgur.com/BdqjN.jpg) There are no "ribbons" in the case of the squared plot. ![enter image description here](http://i.stack.imgur.com/4T04v.jpg)


title: RandomVariate does not fill range of PDF of distribution

text: I've declared my own probability distribution as follows               dist[a_, b_] := ProbabilityDistribution[Cos[(b x)/2]^2 Sinc[a x]^2, {x, -400, 400}];      When I try to create a random variate using this probability distribution I only get data points in a range (-400, -245).               data = RandomVariate[dist[200, 500], 10^4];     Histogram[data, 200, "ProbabilityDensity"]      ![Histogram of prob. dist.](http://i.stack.imgur.com/suMFe.png) Just to clarify, this isn't an issue with the histogram, when I look at `data` it does only contain numbers in the range seen above.


title: Restrict SystemDialogInput to open certain file types

text: The documentation for `SystemDialogInput` shows how to restrict the types of files shown.               SystemDialogInput["FileOpen",".nb"]      ...only shows _Mathematica_ notebook files. This also works for other file extensions such as ".txt", ".html", etc., but doesn't work for other file types. If I have a tab delimited file that with extension ".data" and try:               SystemDialogInput["FileOpen",".data"]      ...the dialog box defaults to all files. Is there a way to only show other "non-standard" file types?


title: Evaluate outer function first

text: I'm new in Mathematica so this is maybe super easy to do, but I can't figure out how. I've got a function `plus[a,b]` that sums two numbers and I need to implement a function `derivation[a]` that will derive the input like this:               derivation[e_Integer] (* returns 0 *)     derivation[x] (* returns 1 *)      I've got a problem with this rule:               derivation[plus[a, b]] := plus[derivation[a], derivation[b]];      When I implement it this way, it doesn't work because plus is evaluated before derivation. I.E. `derivation[plus[x, 3]]` should return `1`. Is there some other way how to implement it?


title: How to batch rename a directory of files?

text: I have a directory of files with the pattern: `"some_number.some_name.pdf"` I want to remove the `"some_number."` part from all the files. How to do that? There are a few commands in my head: `FileNames`, `Map`, etc. But I don't know how to chain them together to achieve the task. Thanks in advance.


title: Exported graphics texture to eps is too dark

text: Why is the exported graphics eps file so dark? It looks much lighter (and better) as the Mathematica output appearing the notebook. After running               Map[SetOptions[#,       Prolog -> {{EdgeForm[], Texture[{{{0, 0, 0, 0}}}],         Polygon[#, VertexTextureCoordinates -> #] &[{{0, 0}, {1,            0}, {1, 1}}]}}] &, {Graphics3D, ContourPlot3D,       ListContourPlot3D, ListPlot3D, Plot3D, ListSurfacePlot3D,       ListVectorPlot3D, ParametricPlot3D, RegionPlot3D, RevolutionPlot3D,      SphericalPlot3D, VectorPlot3D, BarChart3D}];      and then trying to export               contourPotentialPlot2 =       ContourPlot[-3600. h^2 + 0.0297 h^4 - 5391.9 s^2 + 0.275 h^2 s^2 +       0.375 s^4, {h, -400, 400}, {s, -300, 300},       PlotRange -> {-1.4*10^8, 2*10^7}, Contours -> 15,       ContourStyle -> AbsoluteThickness[1], Axes -> True, Ticks -> None,       AxesStyle -> AbsoluteThickness[3], PlotPoints -> 30,       PlotRangePadding -> 0, Frame -> False,      ColorFunction -> "BrassTones"];          potential2 =        Plot3D[-3600. h^2 + 0.0297 h^4 - 5391.9 s^2 + 0.275 h^2 s^2 +        0.375 s^4, {h, -400, 400}, {s, -300, 300},        PlotRange -> {-1.4*10^8, 2*10^7}, ClippingStyle -> None,        MeshFunctions -> {#3 &}, Mesh -> 15,        MeshShading -> {{RGBColor[1, 1, 0]}, {RGBColor[1, 1, 1]}},        Lighting -> "Neutral"];          level = -1.4 10^8;      gr = Graphics3D[{Texture[ImageData[Rasterize[contourPotentialPlot2]]],        EdgeForm[], Polygon[{{-400, -300, level}, {400, -300, level}, {400, 300,        level}, {-400, 300, level}},        VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]},        Lighting -> "Neutral"];          pot2 = Show[potential2, gr, PlotRange -> All, BoxRatios -> {1, 1, .5},       FaceGrids -> {Back, Left}, Axes -> None, Boxed -> True,        Lighting -> "Neutral"]     Export["pot2.eps", pot2]      It looks like the first image below in the notebook file, but as an exported eps file, looks much darker as in the second image. How do I fix this? ![Mathematica output](http://i.stack.imgur.com/I19s3.png) ![Output file](http://i.stack.imgur.com/83T8z.png)


title: Function WeatherData fails

text: If I use WeatherData[] only some of my requests work. For example if I use               WeatherData[{"Chicago", 3}]      I get the correct output:               {"C3175", "KCGX", "C8163"}      But if I try               WeatherData["Chicago", "Temperature"]      I get:               $Failed      Other Collections of Curated Data like ChemicalData[] work fine, so I don't think it's a connection problem.


title: Strange phenomenon with Outer

text: Outer[Plus, ##] & @@ Array[{1, 2, 6, 24, 120, 720, 5040, 40320, 362880} &, 6]; // AbsoluteTiming     (* {0.979056, Null} *)          Outer[Plus, ##] & @@ Array[Range[9]! &, 6]; // AbsoluteTiming     (* {0.952055, Null} *)          Outer[Plus, ##] & @@ Array[Gamma[Range@9 + 1] &, 6]; // AbsoluteTiming     (* {0.010001, Null} *)      See the elapsed time, I used v9 on Win7 32bit. On v8, both of them are slow. How to explain this? Is it possible to make it faster on v8?


title: Construct a sum that evaluates its arguments but doesn't evaluate further

text: I'm trying to construct a sum like this:               Sum[body, range]      where `body` is $$\frac{1}{\sqrt{n!}}+\frac{1}{\sqrt{(n+1)!}}+\frac{1}{\sqrt{(n+2)!}}+\frac{1}{\sqrt{(n+3)!}}$$ and range is $\\{n,0,\infty \\}$.               body = 1/Sqrt[n!] + 1/Sqrt[(1 + n)!] + 1/Sqrt[(2 + n)!] + 1/Sqrt[(3 + n)!];      range = {n, 0, Infinity};      This can be done by               Sum[Evaluate@body, Evaluate@range]      Out==>$$\sum _{n=0}^{\infty } \left(\frac{1}{\sqrt{n!}}+\frac{1}{\sqrt{(n+1)!}}+\frac{1}{\sqrt{(n+2)!}}+\frac{1}{\sqrt{(n+3)!}}\right)$$ But _Mathematica_ takes a long time attempting to compute the sum, which I don't need it to do. Is there a way to prevent the computation of the sum but still evaluate the `body` and `range` parts? I tried the Trott-Strzebonski in-place evaluation trick:               HoldForm[Sum[body, range]] /. Sequence[x__] :> RuleCondition[Evaluate[x]]      But it didn't work. Where did I do wrong?


title: Compact form for domain ranges of many variables

text: When one sets up an equation to solve one often needs to specify conditions on the variables such as               { x>0 && y>0 && z>0 }      This is not a problem if only a few variables are involved. However, it is another matter when say, 50 are required. Is there a compact form one can use? Using               (...) && Table[x[[i]], {i,50}] > 0      within `Reduce[]` or `Solve[]` will not work.


title: Wrapper for inexact numeric complex numbers that maintains polar form

text: Related question: How can I convert a complex number a+b I to the exponent form A Exp(I phi)? _Mathematica_ insists on displaying complex number in form `a+I b` when `a` or `b` are not exact:               Clear["Global`*"]     z = 3 + 4 I;     Abs[z] Exp[I Arg[z]]      ![Mathematica graphics](http://i.stack.imgur.com/bDDfo.png)               z = 3.0 + 4 I;     Abs[z] Exp[I Arg[z]]      ![Mathematica graphics](http://i.stack.imgur.com/bbKpq.png) What I'd like is a `polarForm` wrapper that keeps the polar form even when `a` or `b` are not exact, like this:               Clear["Global`*"]     (z = 3.0 + 4 I) // polarForm      ![Mathematica graphics](http://i.stack.imgur.com/VSOB1.png)               (z = 3 + 4 I) // polarForm      ![Mathematica graphics](http://i.stack.imgur.com/LT0Dp.png) In the above, `polarForm` is the wrapper needed.


title: ParallelTable not firing

text: In[42]:=      ParallelTable[onePathList[s, parametri], {s, {1, 2, 3, 4}}]; // AbsoluteTiming          Out[42]= {14.771845, Null}          In[43]:=      Table[onePathList[s, parametri], {s, {1, 2, 3, 4}}]; // AbsoluteTiming          Out[43]= {14.649838, Null}      I am also watching on the ParallelKernelStatus window and on the TaskManager (I am on a Windows 7 machine with 8 physical cores) and there is zero sign of the parallel kernel running. On the other hand, 4 of them do start up when evaluating the ParallelTable cell the first time. (I have default options in config, and limited to 4 cores by licence). The function onePathList is defined in a package (see below for details) The vector "parametri" is a vector of real numbers, e.g. `parametri={333.333,333.333,116.667,1,0,1,18,0.001}` Any help greatly appreciated, thanks PS Function definitions from package               onePathList[\[Sigma]_, params_] :=      With[{Tmax = params[[7]], dt = params[[8]]},     RandomFunction[proc[\[Sigma], params], {0, Tmax, dt}]["PathStates"]]          proc[\[Sigma]_, params_] := With[{x0 = params[[6]]},     ItoProcess[{totForce[x, t, params], \[Sigma]}, {x, x0}, t]]          totForce[x_, t_, params_] :=      With[{a = params[[1]],      b = params[[2]], \[ScriptCapitalA] = params[[3]], \[Omega] =      params[[4]], \[Alpha] = params[[5]]}, (a x -      b x^3 + \[ScriptCapitalA] Sin[\[Omega] t + \[Alpha]])]


title: How to release $Mathematica$ from the $Pre HoldAllComplete lock

text: Not sure if posted before, but I'm asking this question from a _Mathematica_ fellow user who tried to load expressions, whose problem soon turned into a prison break game featuring the following code.               SetAttributes[hold, HoldAllComplete];     GetOut /: hold[GetOut] := Unset[$Pre];          $Pre = hold;      After executing this code, all subsequent evaluations are hold, including the GetOut "key" and the reset expression.               GetOut     $Pre = .      Are there any ways to unhold subsequent evaluations, in addition to rebooting _Mathematica_?


title: Curvature Manipulation: Vector Evaluation Error

text: I am building a mathematical simulation of curvature that will show the Osculation circle at each point on a curve. However my code keeps coming up with errors and `Manipulate` doesn't evaluate `r[[1]]`. I believe it keeps it as just an expression. It says: > Part::partd: Part specification r[[1]] is longer than depth of object. >>               r[t_] := {Cos[t], Sin[t]}     uT[t_] := Simplify[r'[t]/Norm[r'[t]], t \[Element] Reals]     x[t_] := r[[1]]     y[t_] := r[[2]]     OlcusionPoint[t_] :=       x[t](*-((((x'[t])^2+(y'[t])^2)*y'[t])/((x'[t]*y''[t])-(x''[t]*y'[       t])))*)// Evaluate     OclusionPoint2[t_] :=       y[t](*+((((x'[t])^2+(y'[t])^2)*x'[t])/((x'[t]*y''[t])-(x''[t]*y'[       t])))*)// Evaluate          Manipulate[      Show[Graphics[{RGBColor[0.6, 0.6, 0.8],          Disk[{OlcusionPoint[t], OclusionPoint2[t]},           Abs[1/(uT[t]/r'[t])]]}],        ParametricPlot[{Cos[t], Sin[t]}, {t, 0, 2 Pi}],        Graphics[{PointSize[.025], Point[{Cos[t], Sin[t]}]}]], {t, 0, 2 Pi}]


title: Plot isn't outputting a plot

text: I am trying to plot the magnitude complex function (f) with respect to w. For some reason, Plot is just displaying a set of axes, with no points. Any Idea what's going on here?               z02 = 50*2^.5     z01 = 50     z1 = 100     zin = z02*(zl + \[ImaginaryJ]*z02*tan (w))/(z02 + \[ImaginaryJ]*zl*tan (w))     gamma = (zin - z01)/(zin + z01)     f = abs[gamma]          Plot[abs[gamma], {w, 0, 6.28}]      Thanks!


title: RLink Java(TM) platform has stop working

text: I am trying to send to R a big function,it has only three variables but output is quite big.So when i "translate" that code from mathematica to look like R code and input it in REvaluate i get the popup window thats telling me that java(tm) platform se binary has stopped working.I succeeded the similar thing with same amount of code length but with this one I can't and I can't figure out what's wrong. Here is the code that's making trouble:               ClearAll[sigmasqr, a, ll, sll];     s = FinancialData["^gspc", "FractionalChange", {"2005/01/01", "2009/12/31"}][[All, 2]];          R[t_] := s[[t]]          sigmasqr[1, w_, a_, b_] = Variance[s]          sigmasqr[t_, w_, a_, b_] := w + a R[t - 1]^2 + b sigmasqr[t - 1, w, a, b]          ll[t_, w_, a_, b_] := -.5 (Log[2 \[Pi]] + Log[sigmasqr[t, w, a, b]] + R[t]^2/      sigmasqr[t, w, a, b]) // N          sll = Sum[ll[t, w, a, b], {t, 2, 100}];      So sll is a log likelihood sum for 100 returns,now I want to create a function that can be used in R's optim from this sll.Here is the code:               REvaluate["a1=function(w,a,b){" <> StringReplace[ToString[sll//InputForm], {"[" -> "(", "]" -> ")",      "L" -> "l", "*^" -> "*10^"}] <> "}"]      And here is where problem starts.. I found that the troublesome part starts from part 48 of the sum                   REvaluate["a1=function(w,a,b){" <> StringReplace[ToString[sll[[1;;47]]//InputForm], {"[" -> "(", "]" -> ")",      "L" -> "l", "*^" -> "*10^"}] <> "}"]      If you check you will see that it runs perfectly,but now if you run:                   REvaluate["a1=function(w,a,b){" <> StringReplace[ToString[sll[[48]]//InputForm], {"[" -> "(", "]" -> ")",      "L" -> "l", "*^" -> "*10^"}] <> "}"]      you will get a java platform stop working message.Is there a solution to this problem? I should say that I pasted the troublesome part in R to check did I forgat to change something in the form of code but,no it's working in R.


title: sum polynomial H(x,y)

text: I want to write and evaluate an expression something like $$H_1=\sum_{i+j=0}^3 e_{ij}x^iy^j$$ or $$H=\frac{\sum_{i+j=0}^3 e_{ij}x^iy^j}{\sum_{i+j=0}^3 a_{ij}x^iy^j}$$ with correct syntax.


title: Why does this integral have a complex component?

text: I wanted to find the probability of my normally-distributed random variable being at least 15, so I set up this integral:               Integrate[PDF[NormalDistribution[14, 3.7], x], {x, 15, Infinity}]      Imagine my surprise when I got this result:               0.393476 - 1.75334*10^-15 I      Granted, the angle is miniscule. But why is Mathematica producing this result? This happens even if I type in the PDF manually:               0.107822 E^(-0.036523 (-14 + x)^2)      My TI in rectangular mode returns a result equal to the real component of what Mathematica produces. No complex component. It doesn't make sense for a real-valued function to have complex area anyway. What's going on here? Whenever I see e's and i's in the same room I tend to blame Euler, but I'm having trouble figuring out what Mathematica is doing. Using the "proper" Mathematica command for computing this probability returns a value that agrees with my calculator.               Probability[15 <= x, x \[Distributed] NormalDistribution[14, 3.7]]      I just want to know why Mathematica thinks the integral has complex area.


title: Solve failing and not clear why

text: I define the function:                w[q_, n_, a_] := q/(4 Pi n r^2) (1 - Exp[-2 r/a] (2 (r/a)^2 + 2 (r/a) + 1))      I then want to solve:                q = 1.6*10^(-19);      n = 8.85*10^(-12);      a = 0.529*10^(-10);      Solve[w[q, n, a] == 1000, r]      This does not work and I do not understand why. I think there is a solution. Any ideas?


title: Unexpected Plot3D behaviour

text: The following illustrates what appears to be an incorrect `Plot3D` for this polynomial. I have forced the function to complex argument, changed ranges. In contrast, `ListPLot3D` behaves as expected. Is there something I am missing?               pol1 = x + 1 - x^2 - 2 + 3 x + 4 x^2;     pol2 = -2 Sqrt[x (1 - x^2)];     h[u_] := pol1^2 - pol2^2 /. x -> u      2D plots:               GraphicsColumn[{Plot[h[x], {x, -3, 1},         PlotLabel -> TraditionalForm[h[x]]],       Plot[Abs[h[x]], {x, -3, 1},         PlotLabel -> TraditionalForm[Abs@h[x]]]}, Frame -> All]      ![enter image description here](http://i.stack.imgur.com/ncYWL.png) `Plot3D`:               Plot3D[Abs@h[x + I y], {x, -3, 1}, {y, -1, 1}, Mesh -> None,       PlotPoints -> 100, PlotRange -> {0, 20},       PlotLabel -> Row[{"Plot3D of ", TraditionalForm[Abs@h[z]]}]]      ![enter image description here](http://i.stack.imgur.com/OvpPA.png) This appears to just be a translation of the real valued function along the y-axis and **not** the (or perhaps my) intended outcome...this can be easily confirmed by looking at adding even the smallest imaginary component to any of the 4 real roots. In contrast `ListPlot3D`:               sol = Solve[h[x] == 0, x];     pts = {#, 0, 0} & /@ (x /. sol);     Show[ListPlot3D[       Flatten[Table[{i, j, Abs@h[i + j I]}, {i, -3, 1, 0.1}, {j, -1, 1,           0.1}], 1], MeshFunctions -> (#2 &), Mesh -> {{0}},        MeshStyle -> {Red, Thick}, PlotRange -> {-1, 20}],       Graphics3D[{PointSize[0.04], Point[pts]}],       PlotLabel -> Row[{"ListPlot3D of ", TraditionalForm[Abs@h[z]]}]]      ![enter image description here](http://i.stack.imgur.com/sSfkM.gif) This nicely shows the four real roots and behaves as expected.


title: Sequence and boolean And

text: I'm trying to figure out if a calculation result it's a valid result. As it return a matrix, I need to test that every element it's a number, so I thought this could work...               numericTable = Range[12] ~Partition ~ 4;     check=( NumberQ/@Flatten@numericTable) /.List->Sequence ;     And[check]      This should return `True` or `False` depending if exist or not a non-numerical element in the matrix. But it returns               Sequence[True,True,True,True,True,True,True,True,True,True,True,True]      So I don't understand anything, because...               In[]:= Sequence[True,True,True,True,True,True,True,True,True,True,True,True]===check     And[Sequence[True,True,True,True,True,True,True,True,True,True,True,True]]     Out[]= True     Out[]= True      Where's the catch ???


title: Applying a general formula

text: We are a group of students who are struggling with transforming this formula to run in mathematica. In fact there are many formulas that we are struggling with, but if we are able to see how this is solved we should be able to see how it is done and apply it to the other formulas ourself. We tried using spares Array but was not able to compute it. ![enter image description here](http://i.stack.imgur.com/XCcXf.png)               Subscript[x, 1]={{1,2}}     Subscript[x, 2]={{1,3}}\[Transpose]     Subscript[x, 3]={{1,4}}\[Transpose]     e={{2,4,5}}\[Transpose]          T is set to 3. and Subscript[w, j]= 1-j/H               1/T\!\(     \*UnderoverscriptBox[\(\[Sum]\), \(t = 1\), \(T\)]     \*SuperscriptBox[     SubscriptBox[\(e\), \(t\)], \(2\)]\)Subscript[x, t]Subscript[x, t]\[Transpose]+1/TUnderoverscript[\[Sum], j=1, H-1]Subscript[w, j]Underoverscript[\[Sum], s=j+1, T]Subscript[e, s]Subscript[e, s-j](Subscript[x, s]Subscript[x, s-j]\[Transpose]+Subscript[x, s-j]Subscript[x, s]\[Transpose])


title: Plotting multiple curves with multiple axes (>2) on the same plot

text: I'm attempting to generate a graph that depicts mulitple time series, measured in different units (but with a common time scale) on the same graph. This is a generalization of the familiar 1-plot/scale (1 Plot, 2 Scale/Axis) question. Here is an example of what I'm trying to duplicate: http://home.trainingpeaks.com/athlete/workout/RKDN7DHUWEWZHGI6TCCMKNUSAU By way of background, this graph was data collected by a cycling computer used by a racer in an early stage of the 2014 Tour de France. Briefly, every t seconds, the cycling computer collects and calculates a set of measurements, including speed, temperature, distance traveled, power (in watts), rpm's, elevation, location, etc., along with a time stamp. These are then overlayed onto a single plot, using one of the variables (distance or time usually) as a common x-axis, and with a y-axis reflecting the units specific to that measurement. Doing any pair of these in Mathematica on a 2-scale plot is straightforward, but I'm stumped on how to depict more than 2 in the format shown above. Any suggestions would be most welcome! Cheers, Mark


title: Measuring execution time of code

text: How one can measure the execution time (time that is spent for code to finish) of a program in _Mathematica_? I understand that there are general timing functions (Timing, AbsoluteTiming, TimeUsed, etc.) that can be used for measuring CPU or wall time, but I don't know the pros/contras (and caveats) of the different methods.


title: Permanently set options such as metric units for W|A queries

text: Mathematica lets me be so lazy that I don't even have to switch to a browser to check the weather report: ![](http://i.stack.imgur.com/ZmUx4.png) The only problem is that it will automatically display the temperature and wind speed in Fahrenheit and miles per hour. Unfortunately I don't speak Fahrenheit and I'd like to see it in Celsius. When using W|A online, it is possible to create a user account and set W|A to metric permanently. Is it possible to set preferences such as this one permanently (at least for the duration of a session) when using W|A from within Mathematica?


title: How to put Labels in of a list of number in a chart?

text: I can´t put the labels 0,....,31 in this simple chart on the usual place, or better just over the Top of each bar How should I do?               f1[x_] := 12 x^5 - 975 x^4 + 28000 x^3 - 345000 x^2 + 1800000 x     a = Table[i, {i, 0, 31}]     fa = f1[a]          amix = Table[{i, f1[i]}, {i, 0, 31}]          atext = Table[ToString[i], {i, 0, 31}]     atext     BarChart[amix, ChartStyle -> "DarkRainbow",       ChartLabels -> {atext, Top}]


title: Is it possible to cause a notebook to be hidden when pressing the close button?

text: Is it possible to cause a notebook to be hidden (`Visible -> False`) instead of closing it when pressing the close button in the title bar? The `Messages` window seems to work this way. The `Notebooks[]` function will list it even when it is not visible (or it has been "closed"). Is this special behaviour, or is it possible to make any notebook window behave like this? * * * Motivation: As part of a user interface, I would like to gradually collect some information into a notebook (lets call it a "log-notebook"). The visibility of the log-notebook would be toggled with a button. This log- notebook should persist across kernel sessions, but not across front end sessions (it will never be saved).


title: How can I obtain more significant digits?

text: I type               f1[x_] := 12 x^5 - 975 x^4 + 28000 x^3 - 345000 x^2 + 1800000 x     N[f1[15.5], 15]      and obtain 3.74112*10^6 BUT It´s not true!!! the result is larger than this solution, I think... BACAUSE...                RealDigits[f1[15.5]]      gives me, the result {{3, 7, 4, 1, 1, 2, 0, 6, 8, 7, 5, 0, 0, 0, 0, 0}, 7} So,... I can´t understand that I tell Mathematica that I want to view 15 significative digits, and Mathematica DON´T show me 15 sgnificative digits!!!, only 6!! How I can obtain more digits???? with N[...] or with //N ??? * * * I can´t understand any differneces in precision with Mathematica               m1 = {15, 4, 8, 23, 10, 9, 5, 18, 30, 21}     m2 = {15`9, 4`9, 8`9, 23`9, 10`9, 9`9, 5`9, 18`9, 30`9, 21`9}     f1[x_] := 12 x^5 - 975 x^4 + 28000 x^3 - 345000 x^2 + 1800000 x     x0 = f1[m1]     x1 = N[f1[m1], 9]     x2 = N[f1[m2], 9]      In the last element of x_ you can see diferrences, and... I don´t know what is the best way to obtain an an result with a concrete number os significative digits. In x2, I tell Mathematica that I want 9 significative digits but the result is different from the last element of x1 and x0 and I don´t know what result is the correct! What´s the best way to obtain the good result with a given precision??, in this concrete situation? If you replace in the las line of code in x2 9 for 12 or 15, you obtain the same result!! I can´t understand the behaivour!!


title: ToExpression an array

text: I have a .dat file. I would like to convert a big array of strings(that's what I havein the .dat file) into an array of numbers, for example               a = {{"3,-3,0,5,5,0.000208"}, {"-3,-3,0,5,5,0.000208"},{"3,-3,0,5,5,0.000208"}};      into               b = {{3,-3,0,5,5,0.000208}, {-3,-3,0,5,5,0.000208},{3,-3,0,5,5,0.000208}};      I tried to do               ToExpression[a]      but it does not work. How can I do it? Thanks


title: Padding of matrix

text: I want to do padding of matrix               a = {{x,x},{x,u}};       to               b = {{x, x, x}, {x, u, u}, {x, x, x}}          c = {{x, x, x, x}, {x, u, u, u}, {x, x, x, x}, {x, x, x, x}}      and soon... How I can automatically do this?


title: Controlling output of graphics, the role of ";" and code structure/formatting

text: ";" is described under Compound Expression as a delimiter, such that only the output of the last item in the compund expression is given. Situation: 1/ Print[] produces output whether followed by ";" or not. [Clearly an override is desirable so this makes sense for compound expressions] 2/ When combining graphics using Show[], appending ";" still suppresses output. Since "Show" is as conceptually active as "Print", is there a principle at work here (are there other instances)? 3/ If in procedural code a syntactically complete line is _not_ terminated with a ";", the following line is indented... which means Show[] in the middle of several lines of code upsets indentation and code legibility **Question** : if one has several graphics that one wishes to display without combining them what is the recommended approach, given that multiple Show[] should be separated by ";" but doing so suppresses output. * * * PS There is an incredibly minor-but-irritating-to-the-beginner "quirk" of commenting: semi-colon before comment at the end of code before a closing "]" is marked as a syntax error - is it really? If so, what is the nature of the _error_ (it might just be redundant)?               Block[{a},       Print[a];(*the ; preceding is magenta, but is it really a syntax error?*)]      One is tempted to say the ";" is superflous because the expression is terminated by "]", in which case why is it not still an error when extra line breaks are inserted?               Block[{a}, Print[a];      (*the ; preceding is not magenta, so why is this not a syntax error?*)      ]


title: How Simplify and Assume can be combined on matrix products?

text: What I am trying to do is to simplify some expressions involving matrices! The problem is that Simplify[] considers the simplifications based on alphabetical order and everything is Commutative. For instance, let               f[e_] := df*(e^1 + Subscript[C, 2]*e^2 + Subscript[C, 3]*e^3 +       Subscript[C, 4]*e^4 + Subscript[C, 5]*e^5 + Subscript[C, 6]*e^6);      and               fe = f[e]; f1e = f'[e];     u = Simplify[e - (2/3) Series[fe/f1e, {e, 0, 4}]];     f1u = f'[u]; J = (3 f1u + f1e)/(6 f1u - 2 f1e);     v = Simplify[e - J*(f[e]/f'[e])]      In fact, when I call Simplify[] in the above piece of code, Subscript[C, 2], ..., Subscript[C, 6] must be considered as matrices. I mean, Simplify[], assume that all muliplications are Commutative, while there is no such thing for matrices. To tackle this, I also added NonCommutativeMultiply[Subscript[C, 2], Subscript[C, 3], Subscript[C, 4], Subscript[C, 5], Subscript[C, 6]] at the beggining of my code, but once again I could not obtain reliable outputs! For example, we must have $C_2C_3\neq C_3C_2$, or the code must not simplify $C_2C_3C_2$ to $C_2^2C_3$. I also used the way described by Mr.Wizard in http://mathematica.stackexchange.com/questions/17926/why-does-simplify- ignore-an-assumption?newsletter=1&nlcode=83941%7cfd18, but once again the matrix products are commutative? So, is there any way to use Simplify or FullSimplify on matrix expressions involving matrix products to have reliable output simplified expression? Any tips or help will be fully appreciated.


title: Controlling page breaks

text: I'm writing a bunch of cells to a new notebook nb and am trying to control the pagebreaks. That is, I want a pagebreak after each `Length[listOef]` number of cells. But sometimes, I get two pagebreaks, depending on which random permutatation of `listOef`.               listOef      contains `"aantalVragen"` number of cells given by the user. Then I use the following code:               nb = CreateDocument[Null, Magnification -> 1.5, ShowCellTags -> False,                                PageHeaders -> {{None, None, None}, {None, None, None}},                               ShowCellLabel -> True];          (*Initialize exported notebook*)     SelectionMove[nb, Next, Cell];     NotebookDelete[nb];          allPermutations = Table[RandomPermutation[aantalVragen], {aantalToetsen}];          Do[      NotebookWrite[nb, Cell["Toets 1." <> ToString[toetsNummer], "Title",                              PageBreakAbove -> True]];      NotebookWrite[nb, Cell[datumToets, "Text"]];      NotebookWrite[nb, Cell["Wiskunde", "Text", TextAlignment -> Right]];      NotebookWrite[nb, Cell["G. Hollander", "Text", TextAlignment -> Right]];           (* Test toetsNummer *)        Do[         NotebookWrite[nb, Permute[listOef, allPermutations[[toetsNummer]]][[vraagNummer]]];         SelectionMove[nb, Previous, Cell];         SetOptions[NotebookSelection[nb],                     CellLabel -> "Vraag " <> ToString[vraagNummer] <> "."];         SelectionMove[nb, After, Notebook])         ,         {vraagNummer, aantalVragen}];           **SelectionMove[nb, Previous, Cell];      SetOptions[NotebookSelection[nb], PageBreakBelow -> False];      SelectionMove[nb, Next, Cell];**      ,      {toetsNummer, aantalToetsen}]          Export[exportAddress, nb];      Why does I sometimes get two pagebreaks? I then check if the last cell of the page has a pagebreak with the code               SelectionMove[nb,Previous,Cell];     Options[NotebookSelection[nb]]      at the end of every inner `Do[]` (which is for every page), but I get an empy list of options, so I don't know if there is a pagebreak or not. Also, I'm not quite sure of the part of the code in ** Bold **: I'm trying to suppress pagebreaks at the end of a page, as I'm doing that with                NotebookWrite[nb,        Cell["Toets 1." <> ToString[toetsNummer], "Title", PageBreakAbove -> True]];      at the beginning of the code. But that doesn't seem to prevent double page breaks, sometimes. Any help/advice on this? Thanks!


title: How to plot planar graphs as such?

text: A planar graph is a graph that can be drawn in the plane such that no two edges cross. For example, the graph `Graph[{{1, 2}, {2, 3}, {3, 1}, {1, 4}, {3, 4}, {2, 4}}]` is planar, and can be shown in both of these ways: ![enter image description here](http://i.stack.imgur.com/wQa6X.gif) The layout in the left doesn't have crossing edges and it's immediately obvious that the graph is planar. The layout on the right is what Mathematica gives me by default. **Question:** How can a planar graph be shown without any crossing edges in Mathematica? * * * I expect `Combinatorica`` might have this feature as it has a `PlanarQ` function, but unfortunately the documentation is not included with Mathematica and I have not been able to find out how to do this. Testing whether a `Graph` is planar is possible like this:               << GraphUtilities`     PlanarQ@ToCombinatoricaGraph[someGraph]      Note: The above way of testing planarity is for version 8 or earlier. The `PlanarGraphQ` built-in function was introduced in version 9. * * * Here's a random set of planar graph of different sizes to test on:               << ComputationalGeometry`     graphs = DeleteDuplicates[        Flatten@Table[          Graph@           Union[Sort /@              Join @@ (Thread /@                 DelaunayTriangulation@RandomReal[1, {j, 2}])],          {10}, {j, 4, 10}          ], IsomorphicGraphQ];      * * * To avoid confusion, I'd like to note that the `ComputationalGeometry`PlanarGraphPlot[]` function does not do what I need. It does not lay out a graph. One needs to provide an explicit list of vertex coordinates to it. I have a graph as the input, I know that it's planar, and need a layout algorithm that will draw the graph without intersecting edges.


title: How to force Compile to return multiple results?

text: I would like to return two separate values from a compiled function, but _Mathematica_ refuses to use the compiled version. Here is a narrowed-down example:                   cFunc = Compile[{{a, _Integer, 1}}, {a, a.a}];          (*        ==> CompiledFunction::cfex: Could not complete external evaluation at instruction 3; proceeding with uncompiled evaluation. >>            ==> {{1, 1, 1}, 3}     *)      Here `a` and `a.a` are hypothetic intermediate results of some long computation, that must be externalized in order for computation to go on outside the compiled function. I assume it is not possible to return lists that are not uniform (data type and dimensions). Is there any way to return more than one results from a compiled computation?


title: Setting up TextStyle with initialization cells in Mathematica 6+

text: It used to be quite straightforward to change the default settings of a notebook in terms of inputs, outputs, text styles and font sizes in previous versions of _Mathematica_ using initialization cells with commands such as `$TextStyle` and `$FormatType`. However, as of _Mathematica_ version 6, functions have been superseded by `BaseStyle`. May I know how to use this new function to accomplish the same?


title: Workbench Profile[] question

text: I previously posted this question on Mathgroup but received no response I am using Workbench to profile my code. Suppose I have 2 modules, let's call them A, B (they are too long to replicate here). While running my code, Module B is called repeatedly from A, say in a `Do` loop. Module A is called once. I would like to profile total usage of B (not just one instance), which rules out embedding each call to B in a `Profile[]` statement (as this generates a Profile output for each call). I could, of course, profile A, but the information produced on B would be buried in between timing data pertaining to other parts of A (which for my long module A makes it virtually impossible to understand what's happening in B). Is there a way to accomplish this?


title: Deploying Mathematica Content Online

text: I have the following program at home, which draws on a batch of pre-processed files (that are word frequency text files, compiled using `ToLowerCase`, `Tally` and `Sort`. Here is an example of the file that it draws on: `{{"i", 3073}, {"you", 2860}, {"the", 1741}, {"and", 1518}, {"a", 1218}, {"me", 1209}, {"to", 1153}, {"my", 913}, {"t", 855}, {"that", 843}...` and so on. Each file is about ~ 50KB, and it's been generated using `Put` and is thus grabbed using `Get`. I use them for the following program, which essentially plots word frequency for a given year (each year has its own file). It's along a similar lines as the Google ngram viewer, but on a very specific historical dataset.               Manipulate[viewerCount1 = {};      viewerCount2 = {};      SetDirectory["/users/myNAME/desktop/DB/Put/"];      filenames = FileNames["*.txt"];      Do[       input = Get[file];       yearLength = Length[input];       AppendTo[viewerCount1,         If[Length[Flatten[Cases[input, {word1, _}]]] == 0, 0,           Flatten[Cases[input, {word1, _}]][[2]]]/yearLength];       AppendTo[viewerCount2,         If[Length[Flatten[Cases[input, {word2, _}]]] == 0, 0,           Flatten[Cases[input, {word2, _}]][[2]]]/yearLength];       , {file, filenames}];      DateListPlot[{Tooltip[viewerCount1, word1],         Tooltip[viewerCount2, word2]}, {1964}, Joined -> True,        PlotLabel -> "Number of Total Word Appearances by % of All Words",        PlotStyle -> {{Red}, {Blue}}], {{word1, "war",         "First Word (Red)"}}, {{word2, "peace", "Second Word (Blue)"}}]      ![enter image description here](http://i.stack.imgur.com/LDvKW.png) Here's the crux of the question, however. **Is there a good way to deploy this online so other people can access it?** I assume this is too big for the CDF format? Alternatively, _WebMathematica_ sounds promising, but before I upgrade my _Mathematica_ purchase I would love to hear if the community thinks that would be useful. I know that there have been discussions elsewhere about sharing dynamic content with non-Mathematica users, but these seem to not rely on specific external files. Or, am I using the wrong language to deploy the final version of this?


title: Solving differential equation - initial condition

text: I want to solve the differential equation:               DSolve[{R''[ρ] + 2 /ρ R'[ρ] + (1 - (l (l + 1))/ρ^2) R[ρ] == 0}, R[ρ], ρ]      This works fine and outputs:               {{R[ρ] -> C[1] SphericalBesselJ[l, ρ] + C[2] SphericalBesselY[l, ρ]}}       But when I add the condition:               R[0] ==0      i.e.               DSolve[{R''[ρ] + 2 /ρ R'[ρ]] + (1 - (l (l + 1))/ρ^2) R[ρ] == 0,     R[0] == SphericalBesselJ[1, 0]}, R[ρ], ρ]      The output is:               { }      Why is this the case?


I constantly find myself with multiple Windows Explorer windows open and it would be wonderful to be able to close them all at once using a Mathematica command. Is it possible to close Windows Explorer from within Mathematica ? The post here makes me think it must be possible: http://stackoverflow.com/questions/7644881/calling-a-command-line-program


title: HOG descriptor for image processing

text: I did not find in _Mathematica_ a function for Histogram of Oriented Gradients (HOG) descriptors. Is there any similar function? Do you have an implementation you are willing to share?


title: How to express Polynomial in a certain format with Mathematica?

text: **Equations**               A = {{-0.03333, 0, 0}, {0.0667, -0.6799, 0.6667}, {0,     0.3399, -0.3467}};     B = {0.0333, 0, 0};     CC = {1, 1, 1};     myInverse = Inverse[s*IdentityMatrix[3] - A];     P = CC*myInverse*B;     P = P[[1,1]];      **Goal** > Express the polynomial $P$ in the format $\frac{1}{1+\text{something}}$. **Trials** > **1\. Trial:** tried to play with denominator and numerator, FAIL, here. > > **2\. Trial:** tried Solve command but errs, the code here fires the error > with a transfer function $G(s)$ and the picture here. I try to express the > line 146 i.e. the equation $G(s)$ in the form $\frac{1}{1+C}$. How can I > simplify this? Why do I get the error? How can I get the equation for the > $G(s)$ in the requested form? Err report "Solve::ivar: ... is not a valid > variable". > > **3\. Trial:** fixing the preserved-variable problem revealed by Artes's > answer, I get very peculiar answer -- I get empty set!? Why? I should get > some non-empty equation. Notice the line 336 in the picture here.


title: Calling external commands without showing command prompt on windows

text: I'm playing around with some code that's calling external command-line commands on a windows platform, and when doing this, the command prompt will pop up quickly and then disappear. This is not a huge bother, if you are calling something once, however if you have a loop running and each call takes some time, it becomes a major annoyance. Consider the following code:                Table[Pause[1/2]; Run[ "dir" ];, {3}];      Is there any way to avoid this behavior, or calling an external program though other methods then by `Run[]`.


title: Plot A Function Of A Stochastic Process

text: I am trying to do something very simple in Mathematica 9. I want to play around with option pricing and for that I thought it best to use the new stochastic process functionality. So, first of all I simulate one instance of a geometric brownian motion: $$ \frac{dX_t}{X_t} = \mu dt + \sigma dW_t\\\ dW_t \sim N(0, 1) $$ Which in Mathematica is:               proc = ItoProcess[        \[DifferentialD]x[t]/         x[t] == \[Sigma] \[DifferentialD]w[t] + \[Mu] \[DifferentialD]t,         x[t],         {x, x0},        t,        w \[Distributed] WienerProcess[]];      And here's an example of what I get, when I plot it, assuming $X_0 = 100$. ![Example of a GBM](http://i.stack.imgur.com/UFebR.png) So, okay, when I create a plot of a `RandomFunction` of the process, then I actually plot the `TemporalData` for $X_t$ and not $dX_t$. Cool, whatever. But now I want to plot, say $f(dX_t)$ or $f(X_t)$, where I would like to define $f$ as I see fit. And this is where I hit a brick wall. I have tried looking for hints in the docs or for answers here, but there are no definitive ones or the ones that seem to work. I also feel, that I'm missing something fundamental here. Could somebody kindly suggest an answer or the venue of inquiry?


title: TreePlot with centered vertexes

text: I want to draw a tree plot for Euler totient function for this question like the following: ![enter image description here](http://i.stack.imgur.com/N64Zx.jpg) I generate the EulerPhi for first 20 numbers into a list:               list = Map[# -> EulerPhi[#] &, Range[2, 20]]      Then I plot it using this:               TreePlot[list, Bottom, 1, VertexLabeling -> True,  DirectedEdges -> True ]      And the output: ![enter image description here](http://i.stack.imgur.com/bsM9R.jpg) But I want the layout of tree become like the above one so that numbers of form $2^n$ are centered and branches to the left or right. How can I do this? By manually editing the graph the output looks like the following ![enter image description here](http://i.stack.imgur.com/zpmip.jpg) **Updated** I've managed to centralize the powers of $2$ but now the branches aren't placed well.               y = 0; coordinates =       Map[First[#] -> {0, y++} &,       Select[Prepend[list, 1 -> {0, 0}], IntegerQ[Log[2, First[#]]] &]]          {1 -> {0, 0}, 2 -> {0, 1}, 4 -> {0, 2}, 8 -> {0, 3}, 16 -> {0, 4}}      and using `GraphPlot`:               GraphPlot[list, VertexLabeling -> True, DirectedEdges -> True,         VertexCoordinateRules -> coordinates]      ![enter image description here](http://i.stack.imgur.com/3vEvt.jpg) Now, If the branches are placed upper than the root, then the result would be OK.


title: Home edition: Updates and installing it on a new computer

text: I cannot find any info concerning the Home Edition on the eligibility   * to receive updates (so e.g. from 9.0.0 to 9.0.1)   * to install it on a more than one computer or on a new computer (I am planning to buy a new one in due time). Could you give me some references or user experience?


title: TextCell going awry due to ImageResolution (in Mathematica 7)

text: Can anyone see how to fix this text display? The example is from a larger project. I need to export the graphic at high resolution, but the text is going wrong.               text = StringTake[        ExampleData[{"Text", "DonQuixoteIEnglish"}], {110600, 110914}];          a = Graphics[{{LightBlue, Rectangle[{0, -0.21}, {1, -0.04}]},        Inset[Graphics[{{LightYellow, Rectangle[{0, 0}, {450, 40}]},           Inset[            TextCell[text, LineSpacing -> {0, 16}, TextJustification -> 1],            Center, Center, {450, 40}]},          BaseStyle -> {FontSize -> 12}, PlotRange -> {{0, 450}, {0, 40}}],         {0.5, -0.155}, Center, {0.9, Automatic}]},       PlotRange -> {{0, 1}, {-0.21, -0.04}}, ImageSize -> 600]      ![enter image description here](http://i.stack.imgur.com/Is0fv.png)               Rasterize[a, ImageResolution -> 300]      ![enter image description here](http://i.stack.imgur.com/gZioC.png) N.B. This problem is happening on Mathematica 7. I just checked on Mathematica 9 and it works ok, but I need to run it on version 7.