title: Speeding up multilinear PRA branch-and-bound algorithm with worst-case exponential time scenario with respect to basic events

text: The algorithm is a branch-and-bound algorithm that calculates dominances for PRA, probalistic risk assessment. The task was to find faster ways to do it in numerical software such as Matlab but we found it extremely hard, more here. Now I am trying to find ways to speed it up in symbolic softwares such as Mathematica. The algorithm uses multilinearity but not with respect to constant term. The worst case time scenario with respect to basic events is exponential. This does not mean that it is exponential with respect to minimal cut sets. It is a method to analyse the impact of epistemic uncertainty about event probabilities in fault tree analysis. The algo is based on a theorem in multilinear optimization according to which the extreme values of multilinear function $f: HR \rightarrow \mathbb R$ are attained at the vertices of HR where HR is a hyperrectangle in $\mathbb R^n$. Basically the idea of this algo is to traverse the corners in the hyperrectangle. So: > **what kind of methods would you use to speed up this kind of recursive > algorithm?** **Algorithm**               Algo[f0_, lb0_, ub0_] :=        Module[{f = f0, lb = lb0, ub = ub0, monomials, fp, fm, bvar, blb,          bub}, If[f == 0 || f == 0.0, Return[True]];        monomials = f // MonomialList;        fp = Select[monomials*1.0*D, (First[#] >= 0) &] /. {D -> 1};        fm = Select[monomials*1.0*D, (First[#] < 0) &] /. {D -> 1};        If[Plus @@ (fp /. lb) + Plus @@ (fm /. ub) >= 0, Return[True]];        If[Plus @@ (fp /. ub) + Plus @@ (fm /. lb) < 0, Return[False]];        bvar = Variables[f] // First;        blb = Select[lb, ((# // First) == bvar) &];        bub = Select[ub, ((# // First) == bvar) &];        Algo[(f /. blb), lb, ub] \[And] Algo[(f /. bub), lb, ub]];      **Example how to use this function**               Algo[Subscript[p, 1] + Subscript[p, 2] - Subscript[p, 1] Subscript[p, 2],       Table[Subscript[p, i] -> 0.01, {i, 7}], Table[Subscript[p, i] -> 0.04, {i, 7}]]


title: Replace one order of derivative inside higher one

text: How could I replace for example:               Derivative[2][f][x]      by               Derivative[1][g][x]      where               g[x]=Derivative[1][f][x]      ? But doing this in a manner that work for all cases (all combinations of mixed derivates and multiple variables)?


title: Adding subscripts to variables

text: I know I can define               vars = Map[Subscript[x, #1] &, {"tem", "pressure", "hum", "lat", "alt", "space", "corner"}]      and               vars = Array[Subscript[x, #1] &, {8}]      But how can I add both kinds of subscripts in my "x"s to get something like x"tem""1", x"tem""2", and so on? Based on the answer I got here, I tried to write general form in this way.I am quite sure there would be much better interactive way to do that.This is just starter version of mine:               Outer[Subscript[x, Subscript[#1, #2], Subscript[#3, #4],      Subscript[#5, #6], Subscript[#7, #8]] &, {"a", "b"}, {1, 2, 3,      4}, {"i", "j"}, {1, 2, 3, 4}, {"m", "n"}, {1, 2}, {"A", "B", "C",      "D"}, {1, 2, 3, 4, 5, 6, 7}];


title: double integration

text: I want to evaluate a double integral, but the limits of one integral is a function of the second. Like this               A[(b_)?NumberQ] :=        Pi - 2*b*g*         NIntegrate[          1/Sqrt[g^2 - b^2*g^2*y^2 - 4*y^12 + 4*y^6], {y, 0,            Solve[g^2 - b^2*g^2*y^2 - 4*y^12 + 4*y^6 == 0, y, Reals][[2]] -             0.00001}];      NIntegrate[2*(1 - Cos[A[b]])*b, {b, 0, 100000}]      The upper limit of the first integral is an polynomial equation that depends on `b` and the second integral is in `b` for `g = Sqrt[0.1]`, I have the value `5.3`.


title: DynamicModule inconsistent behavior; was: DynamicModule persistent UI changes

text: **Update** : I'll restate the question in hopefully more terse and clearer terms. To illustrate the issue, run this and save the resulting notebook:               CreateDocument[       DynamicModule[        { ultimateAnswer = 42,         x = False},        Pane@Row@{           Checkbox[Dynamic[x]], " Notebook modified ",Checkbox[Dynamic[Refresh["ModifiedInMemory" /. NotebookInformation[], UpdateInterval -> 0.1]]]}]       , WindowSize -> {320, 80}, WindowElements -> {}, WindowToolbars -> {}, WindowFrameElements -> {"CloseBox", "DocumentIcon", "ResizeArea"}];      ![saved](http://i.stack.imgur.com/Es4KC.png) Add a cell and close the notebook: ![modified](http://i.stack.imgur.com/zNsxZ.png) Reopen it, play a few with the checkbox: ![re- modified](http://i.stack.imgur.com/p9b2c.png) Lastly, be sure the checkbox is on, and close the notebook. Note that there's no external or internal clue about the notebook saved state. What will the _Front End_ do? What should it do? Shouldn't the checkbox remain checked when you re-open the notebook? **Primary question** : Should the _Front End_ close the window without any warning the notebook has been modified? Note that in this contrived example, the flag var is there to illustrate the issue, but perfectly could also be another near it with the result of a 7.2 billion years computation. **Secondary-- nice-to-have,-- question** : in case this issue bothers you, how would you resolve the problem in a nice, elegant, concise Mathematica way? **Bonus question** : you classify this as   1. you're-very-very-picky-and-a-little-paranoid, irrelevant   2. very minor   3. mild curiosity   4. serious  Now seriously, I've actually been bitten by this, and have spent significant time looking for a solution. If you attempt any involved GUI work, it's probable you won't notice this during development because the notebook morphs a lot. Only at the end, you clean up nice to discover all your persistent changes aren't being saved. You must then notify users that they have to save even though the window says nothing has changed. * * * **Old post** : The documentation of `DynamicModule` states: > Symbols specified in a DynamicModule will by default have their values > maintained even across Mathematica sessions. So, any change in `DynamicValues` vars able to persist should be reflected somehow. In particular, notebook saved state should be modified in this case, as if the user had created a new cell. As a contrived example, evaluate this:               CreateDocument[       DynamicModule[{x = False},        Pane@Row@{           Checkbox[Dynamic[x]],            " Notebook modified ",           Checkbox[            Dynamic[Refresh["ModifiedInMemory" /. NotebookInformation[], UpdateInterval -> 0.1]]]}]       , WindowSize -> {230, 80}, WindowElements -> {}, WindowToolbars -> {},       WindowFrameElements -> {"CloseBox", "DocumentIcon", "ResizeArea"}];      Observe the resulting notebook, in particular the **close button** and **document icon**. The first `Checkbox` is backed by a `DynamicModule` var, second one monitors if there're unsaved changes. ![Toying with DynamicModule backed UI](http://i.stack.imgur.com/kNciz.png) Adding a new cell (1st-2nd images) triggers the normal **UI** clues of unsaved data: in OSX, the filled **close button** and the **grayed-out document icon.**   Changing the checkbox (3rd-4th images), though, doesn't change the **UI** nor, more importantly, the internal document state. In fact, you can close the document without **FE** prompting to save it and observe subsequently that the first checkbox doesn't remember its setting. If you want **UI** persistence, you must force the saving. Other widgets behave similarly. The culprit here is surely `DynamicModule`, not the widgets or `Dynamic`. This is probably well known, and I see two explanations here. One, a bug/glitch (tested on Mathematica 9.0.1/OSX 10.9.2); two, this behavior is by design or tough to implement by the **FE**. Note that window resizing or zoom doesn't modify the notebook saved state also, even though the document metadata has changed. My take is the second case seems somewhat inconsistent from a **UX** point of view. The old controversy of data vs metadata remains unresolved and impractical, but in my opinion `DynamicModule` vars should be considered full data citizens. `DynamicModule` _raison d'être_ is session persistence. Some the strong points of **Mathematica** are the homoiconic, literate programming aspects, the unholy mix of code/data/metadata/application/IDE/document, and arguably `DynamicModule` vars are so data as any user-entered expression. If you make a Cell/Show Expression, it's easily observable that the `DynamicModule` vars are being modified and do change the cell expression:               Cell[BoxData[      DynamicModuleBox[{$\     CellContext`x$$ = True},        PaneBox[        TemplateBox[{CheckboxBox[       ...      Whether it's a bug or designed behaviour, I believe **WRI** won't change this in the near future. But I like my notebooks reflecting `DynamicModule` state changes. As a newbie, I see two quick'n'dirty very unsatisfactory solutions:   * Track the vars and save programmatically the document,              Checkbox[Dynamic[x,(x=#;FrontEndTokenExecute["Save"])&]]      or              Checkbox[Dynamic[x,(x=#;NotebookSave[])&]]      But, it's the user who should choose how and when to save the document, not the application.   * Create/delete ghost content, e.g.,              With[{nb = EvaluationNotebook[], scr = AutoScroll -> False},         SelectionMove[nb, After, Cell, scr];         NotebookWrite[nb, Cell["", "Text"], All, scr];         NotebookDelete[nb, scr]];      Ugly, and ungainly, and error-prone, not only for the fake changes, but for the selection resetting. I haven't found a way to fully restore the selection state (and this is something the **FE** does well: dynamic interactivity usually respects the selection point.) My question, then: is there a more elegant (concise, convenient) way to mark the notebook as changed so both UI and internal notebook state reflect the fact?


title: Creating a list from other lists and varying the number of elements that get added

text: Suppose I have                listA = {M, F}      and               ListB = {a,b,c}      I want to make a new               listC = {{Ma, Mb, Mb, Mb, Mc, Mc}, {Fa, Fb, Fb, Fb, Fc, Fc}}       Where I tell Mathematica how many copies of a particular element to make in listC. `Outer[]` seems like a good start but it returns the combined elements as a two item list. For example I get `{M, a}` instead of `M a`.


title: How does one get Mesh lines at 0 in ParametricPlot3D?

text: The following is in the documentation (MMA 10) under ParametricPlot3D -> Options -> Mesh :               ParametricPlot3D[{(2 + Cos[v]) Cos[u], (2 + Cos[v]) Sin[u],        Sin[v]}, {u, 0, 2 Pi}, {v, 0, 2 Pi}, Mesh -> 10]      You'll see that the lines for u=0 and for v=0 are missing. These can be restored by using `Mesh->Full`, but then the number of lines will be the default, 15. I'd also like to have the number of lines be different in the two directions, with each one containing 0, but Mesh->{Full,10}, e.g., gives an error. Here is the image in the documentation: ![missing mesh lines](http://i.stack.imgur.com/rYXpt.jpg) **Update:** While the answer below works as requested, it does not work for tubes. See this example:               ParametricPlot3D[{(2 + Cos[v]) Cos[u], (2 + Cos[v]) Sin[u],        Sin[v]}, {u, 0, 2 Pi}, {v, 0, 2 Pi}, Mesh -> 10,       BoundaryStyle -> Tube[.03], MeshStyle -> Tube[.03]]      ![enter image description here](http://i.stack.imgur.com/DVX9N.jpg)


title: Question about InputAutoReplacements

text: I have a question about `InputAutoReplacements`.               SetOptions[$FrontEndSession,         InputAutoReplacements -> {"spa" ->                  RowBox[{"〚", "\[SelectionPlaceholder]", "〛"}] } ]      It works, but always adds in spacing automatically. How can I get it fixed? Thanks! ![enter image description here](http://i.stack.imgur.com/wL9wy.jpg) Xiang Li


title: Numerical partial derivative

text: For a one-variable numerical function, it's simple to calculate the derivative at a point with `Derivative` as Szabolcs has pointed out before:               f[x_?NumericQ] := x^2     f'[3.]     (* 6. *)      But this fails for partial derivatives:               g[x_?NumericQ, y_?NumericQ, z_?NumericQ] = x y z + x^2 y^2 z          Derivative[1, 0, 0][g][1., 1., 1.]     (* 3. *)          Derivative[1, 1, 1][g][2., 3., 4.]     (* Unevaluated: Derivative[1, 1, 1][g][2., 3., 4.] *)      `ND` seems to only handle the one-dimensional case. Using `SeriesCoefficient` simply returns the (scaled) `Derivative` expression:               SeriesCoefficient[g[x, y, z], {x, 2., 1}, {y, 3., 1}, {z, 4., 1}]     (* Derivative[1, 1, 1][g][2., 3., 4.] *)      I'd prefer not to clutter my code with finite difference formulas, since this functionality must be in _Mathematica_ somewhere; where is it? **EDIT:** The closest I've found so far is `NDSolve`FiniteDifferenceDerivative`, but that works on grids and it's a hassle to use for other purposes. Anyone know of a convenient C/Java library that links well with _Mathematica_ and handles all kinds of numerical differentiation? **EDIT2:** Does `Derivative` have accuracy control? (step size or anything)               Clear @ f     f[x_?NumericQ] = Exp[x];     Array[Abs[Derivative[#1][f][1.] - E] &, {8}]      $$\left( \begin{array}{c|c|c} \text{n} & \text{seconds} & \text{error} \\ \hline 5 & 0.123 & 6.77\times 10^{-7} \\ 6 & 0.297 & 0.0000484 \\ 7 & 0.592 & 0.0127 \\ 8 & 1.05 & 1.11 \\ \end{array} \right)$$


title: How to define a vector with automatically added symbolic elements with subscripts

text: I want to define a vector lets say **k** containing elements Symbolize[Subscript[ _k_ , 1]], _k2_ , _k3_ ... etc. When I define lets say _k4_ . I want the symbol automatically added to vector k. Something like below but not working at all.               k /: {k, Symbolize[      ParsedBoxWrapper[      SubscriptBox[      StyleBox["v", FontFamily -> "Courier New", FontWeight -> "Plain",         FontSlant -> "Italic"], "_"]]]} :=      AppendTo[k, Subscript[v, _]];      My Question is; 1) How can I symbolically define elements (with sub scripts) automatically added to a vector. 2) If I assign values to symbols, How can I get elements values only and symbols only. **EDIT 1**               Symbolize[Subscript[k, _]]       Command Symbolizes all subscripts of **k** e.g. _k1_ (`Subscript[k, 1]`), _k2_ (`Subscript[k, 2]`) etc. This is fine. What I want is collect _k1, k2 k3_ in a set (List) **k** with out additional commands or additional functions. Just as soon as sybolize sub scripted ones it should add it self to set k (sort of pattern maching as in `Subscript[k, _]`). When I call k it should give me the list { _k1, k2, k3_ }. @Mr. Wizards answer gives the list but as calling function `ksym`. Sort of what I need but not exactly. @halirutan answer is also interesting but I don' t want to define additional functions or operators (may be as minimum as possible). **EDIT 2** Its sort of bag or set; no order is required, only _k1,k3_ can be given and _k2_ can be missing. **EDIT 3**               << Notation`     (*below line symbolizes all subscripted k_]*)     Symbolize[ ParsedBoxWrapper[        SubscriptBox["k", "_"]]]      somewhere here I need additional code that all _k_ _ are added to k once its been defined. For example:               {Subscript[k, 1], Subscript[k, 2], Subscript[k, 3]} = {1, 2, 3}      after that when I ask k it should give me `{Subscript[k, 1], Subscript[k, 2], Subscript[k, 3]}` as @Mr.Wizard suggested `ksym[] := HoldForm @@@ UpValues[k][[All, 1]]` and for values `kval[] := UpValues[k][[All, 2]]` should work. But, what I' m missing in @Mr.Wizard example is that one needs to define symbols as;               k /: Subscript[k, 1] = "val1";     k /: Subscript[k, 2] = "val2";     k /: Subscript[k, 3] = "val3";      what I need is once I write `{Subscript[k, 1], Subscript[k, 2], Subscript[k, 3]} = {1, 2, 3}` I should be able to get k vector and `{Subscript[k, 1], Subscript[k, 2], Subscript[k, 3]}` is appended automatically to k.


title: Is there a way to "lock" some cells in a notebook?

text: Is there a way to "lock" some cells in a notebook so they can't be edited? It's usually input cell that's documenting some functionality. I'd like other readers of the notebook to be able to execute them but not changing them.


title: Export animation of a Manipulate autorun sequence?

text: I've got a Manipulate that does a vector field plot. Basically a function that returns a list of Graphics objects and a couple of sliders:               Manipulate[      Show[ReleaseHold[s[v, r1, r1 + s2] ]]      , {{r1, 1.}, 1., 2.5 }      , {{s2, 1.}, 1., 2.5 }      , {{v, 1.}, 0., 2.5 }      ]      Once I set the sliders in a position that I like, I discovered the neat feature "Paste Snapshot" that samples my slider position values, that I can use to save the resulting image to a file. I've just discovered the autorun feature of Manipulate, which is a neat visualization tool. Is there a way save the autorun output showing the image and the sliders all animated in a list, so that I can run Export[ "filename.avi", %] as if I had a plain old table of images?


title: How to solve a Differential Equation with DSolve with Function Coefficient?

text: Suppose I have               v[x_] = (1.453 Sech[x + 1])^2 + I  Sech[x + 1] Tanh[x + 1]      And I have to solve the equation:               mu1 u1[x] - u1''[x] - v[x] u1[x] == 0      for `u1[x]`. The conditions that are given are:               u1[-2] == 1, u1'[-2] == 0 .      I have tried `DSolve` but it shows errors: > Solve::inex: Solve was unable to solve the system with inexact coefficients > or the system obtained by direct rationalization of inexact numbers present > in the system. Since many of the methods used by Solve require exact input, > providing Solve with an exact version of the system may help. How can I Solve this equation in Mathematica symbolically?


title: Extracting a range of data from a table

text: I have text file with data in 2 columns. I have imported it using the following line               c = Import["ab", "Table"];      This text file has a large amount of data, and I need only a certain range. What I mean is, if my data runs for example from `-10 to +10`, I need only from `-5 to +5` and its corresponding values. So I naively tried this               Plot[c, {-5, 5}]      which is clearly wrong, and its little wonder that I am getting an error message. Not sure what to do. Please help!


title: Is it possible to print more than last line with Get (<<) without using Print commands?

text: I want to run my _Mathematica_ scripts from the terminal and I want it to print lines like MATLAB would. That is, suppress output by ending a line with `;`, and otherwise print the output of the line. `Get` (`<<`) only prints the last line. Without using Print[var] and saving variables after every line... Is this possible?


title: How to find 4 unknowns?

text: There are 4 unknowns constants: `a`,`b`,`c`,`p`. The variable is `phi` and the result is `d`. For `phi={13,23,45,73}` the results are `d={32.08754292290807,32.1136624112758,32.1728430675844,32.2430287624866}` The equation is:               (c/0.3048*((1+(a*p/(b*c))*(sin(phi*pi/180))^2))/sqrt(1-sqrt(1-b^2/a^2)*     ((sin(phi*pi/180))^2))) = d      How can I solve it in Mathematica?


title: Lowering the degree of an polynomial with an assumption that the polynomial has a factor x^2+ax+b

text: Let's assume $ x^{10}+x^5+1 $ has a factor $x^2+ax+b$ Then, If $x^2=-ax-b$, $ x^{10}+x^5+1 =0$. If we successively apply $x^2=-ax-b$ to $ x^{10}+x^5+1 $, we can make $ x^{10}+x^5+1 $ to degree 1, such as $ mx +n $ and it should be that $m=0, n=0$ So having it on my mind, I tried,               x^10+x^5+1 //. x^2-> -a x -b      Didn't work.               x^10+x^5+1 //. x_^2-> -a x -b      Didn't work. So, any suggestions? Thanks ahead!


title: FourierTransform and Partial Derivatives?

text: I have a function of three variables $f(x,y,z)$, and it obeys a linear partial differential equation. I'm checking my by-hand calculations with Mathematica. I want to convert the PDE into the Fourier-spectral domain, but Mathematica isn't playing nice. I find the following behavior baffling.               FourierTransform[D[f[x, y, z], x], {x, y, z}, {kx, ky, kz}]      > `-I kx > FourierTransform[FourierTransform[FourierTransform[f[x,y,z],x,kx],y,ky],z,kz]`               FourierTransform[D[f[x, y, z], y], {x, y, z}, {kx, ky, kz}]      > `FourierTransform[Derivative[0, 1, 0][f][x, y, z],{x,y,z},{kx,ky,kz}]`               FourierTransform[D[f[x, y, z], z], {x, y, z}, {kx, ky, kz}]      > `FourierTransform[Derivative[0, 0, 1][f][x, y, z],{x,y,z},{kx,ky,kz}]` Essentially, it's like Mathematica uses $\mathcal{F}\left[\frac{\partial f}{\partial x}\right]=-i k_x \mathcal{F}\left[f\right]$ for the first argument $x$, but does not use the same rules/identities for partials w.r.t. second and third arguments, i.e. $\mathcal{F}\left[\frac{\partial f}{\partial y}\right]$ and $\mathcal{F}\left[\frac{\partial f}{\partial z}\right]$ are not simplified. What's going on here? **How can I force Mathematica to do this simplification for the other variables?**


title: Keeping Quotation Marks in Output

text: I am running into the following seemingly simple problem. I have this code:               testphrase="i love you";     input=ToLowerCase[StringSplit[testphrase, Whitespace]]      It outputs, `input={i,love,you}` However, I want to use input elsewhere in my program as `"i","love","you"`. So the behaviour I am looking for is as such: `input={"i","love","you"}` I know if I paste input, the quotation marks show up around it. I know the issue resides somewhere in `ShowStringCharacters`, as I've read that documentation, but I'm getting mixed up in the different behaviour between pasting it, manually inputting it, and calling on it in Mathematica. My program will only work if the output is formatted in three words with quotation marks, and won't work if the quotation marks aren't there. --- edited to add --- The solution below looks like it should work, but I am still getting odd behaviour. Here is my whole code. The follow example outputs to count the number 111, as it should.               trigrams={{{"i", "don", "t"}, 211}, {{"i", "can", "t"},        186}, {{"you", "don", "t"}, 175}, {{"don", "t", "know"},        137}, {{"oh", "oh", "oh"}, 111}};     Clear[trigramHash];     (trigramHash[Sequence @@ #1] = #2) & @@@ trigrams;     count = trigramHash["oh","oh","oh"]; trigramHash[___] = 0;       Yet this still outputs zero.               test = InputForm[ToLowerCase[StringSplit["oh oh oh", Whitespace]]];     trigrams = {{{"i", "don", "t"}, 211}, {{"i", "can", "t"},          186}, {{"you", "don", "t"}, 175}, {{"don", "t", "know"},          137}, {{"oh", "oh", "oh"}, 111}};     Clear[trigramHash];     (trigramHash[Sequence @@ #1] = #2) & @@@ trigrams;     count = trigramHash[test]; trigramHash[___] = 0;      Even though, on the face of it, test should work - it is outputting as "oh","oh","oh".


title: Unexpected behavior of subtraction with approximate numbers

text: I'm using the `Table` command to generate a list of values:               FullForm /@ Table[10. - x, {x, 2.7, 2.8, .1}]      and I get the following result:               {7.3`,7.199999999999999`}      Why do I get `7.199999999999999'` instead of 7.2? Moreover, if I try to calculate the `Complement` of `{7.2}` in this list, I get `{7.2,7.3}`, which is not what I would expect. At the same time, using the `Complement` option `SameTest->(#1==#2&)` gets me `{7.3}`. This behavior is observed in Mathematica 7/8/9, and even on WolframAlpha. P.S. I know that using `Range[7.3,7.2,-0.1]` would be clearer, I'm just curious about the aforementioned problem.


title: Frame or EdgeForm disappearing out of PlotRange

text: I am trying to obtain a thin frame around the bars in this chart but it's proving rather tricky. Can anyone suggest a solution?               size = {3, 12, 8, 0.5, 7, 5, 6, 7, 3, 4, 2};          bar[i_] := Inset[Graphics[{EdgeForm[{Thin, Black}],         FaceForm@LightBlue, Rectangle[{0, -1/2}, {size[[i]], 1/2}]},        PlotRange -> {{0, size[[i]]}, {(-1/2), 1/2}}],       {1, -(Length[size] - i + .5)}, {Left, Center}, size[[i]]];          Graphics[{LightYellow, Rectangle[{0, 0}, {15, -(Length[size] + 1)}],       Array[bar, Length[size]]},      PlotRange -> {{0, 15}, {0, -(Length[size] + 1)}}]      ![enter image description here](http://i.stack.imgur.com/mmzBt.png) A second version has the same problem:               bar[i_] := Inset[Graphics[{LightBlue,         Rectangle[{0, -1/2}, {size[[i]], 1/2}]},        PlotRange -> {{0, size[[i]]}, {(-1/2), 1/2}},        Frame -> True, FrameTicks -> None, ImagePadding -> 0],       {1, -(Length[size] - i + .5)}, {Left, Center}, size[[i]]];      **Edit** Thanks to Heike's comment I have something I can use:               size = {3, 12, 8, 0.5, 7, 5, 6, 7, 3, 4, 2};          bar[i_] := Rectangle[{1, -(i - 1)}, {size[[Length[size] + 1 - i]] + 1, -i}];          Graphics[{LightYellow, Rectangle[{0, 0}, {15, -(Length[size] + 1)}],       EdgeForm[{Thin, Black}], FaceForm@LightBlue,       Array[bar, Length[size]]},      PlotRange -> {{0, 15}, {0, -(Length[size] + 1)}}]      ![enter image description here](http://i.stack.imgur.com/eLgDK.png)


title: String replacement to make the TeXForm output beautiful

text: This question is inspired by this question: How to convert the symbol $d$ in Integrate into $\mathrm{d}$?. Although it’s not a big problem, the `TeXForm` can be modified manually to “standard” form, I’m curious why _Mathematica_ ’s `TeXForm` won’t change the differential d to $\mathrm{d}$ automatically. There are some detailed situations to pay attention to.   * The integrand or the integration argument may contain some variables having letter “d”(Such as: det, adcda, etc.) or even “d” itself.(Although it’s ugly to do so.)   * Mathematica will automatically change alpha to $\alpha$.   * Single-character symbol names are given in _italic_ font, while multiple character names are given in roman font. I’ve written some lines of codes to do this. But I think the code is ugly and can’t handle the situation with integration argument’s name exactly “d”. Here is my code.               cTeXForm[expr_, arg__] := Module[{       (*temp saves the original TeXForm*)       temp = ToString@TeXForm@HoldForm[Integrate[expr, arg]],      (*var saves the integration argument and reverse the order to keep up with the integral symbol*)       var = ToString /@ TeXForm /@ Reverse@(Flatten /@ ({#} & /@ {arg}))[[;; , 1]], pos, range, betweenQ, loc},       (*locate the position of differential d*)       pos = StringPosition[temp, "d"][[;; , 1]];       range = StringPosition[temp, var];       betweenQ[n_] := Catch@(Scan[If[#[[1]] <= n <= #[[2]], Throw[0], n] &, range];Throw[1]);       loc = {#, #} & /@        Pick[pos, betweenQ[#] & /@ pos, 1][[-Length@var ;; -1]] ;       (*replace and output*)       CopyToClipboard@OutputForm@StringReplacePart[temp, "\\mathrm{d}", loc]]      Here is the test (although no beautiful):               cTeXForm[x^2 alpha d baded, {x, 1, 2}, {alpha, 2, 3},baded]      And here is the output of my code $$\int _1^2\int _2^3\int \alpha \text{baded} d x^2\mathrm{d}\text{baded}\mathrm{d}\alpha \mathrm{d}x$$ So the question is how to **precisely** change the differential d to $\mathrm{d}$? Are there any other ways to do this? (`RegularExpression`, rule- based replacement etc. I’m not familiar with these.) Any advice about the string manipulation or using `TeXForm` is welcomed.


title: Count and plot the number of solutions in an interval

text: I have equations depending on one or more parameters and I want to find and plot regions in the parameter space in which there is a specific number of solutions. For definiteness let's consider a simple case               -3 + 3 mu2 - 6 q mu2 - 8 q^3 mu4 + 4 q^4 mu4 + q^2 (3 mu2+ 4 mu4) == 0      where I want to find and/or plot regions in the space `(mu2,mu4)` in which the equation has `0, 1,...,4` solutions with `0 < q < 1`. Note that I want to use the same method also for non-polynomial equations (and possibly systems of equations).


title: How can I add any points in Manipulate?

text: (* 5.3  1 *)     X = {x, 1 - x}     Y = {y, 1 - y}     A = {{2, -1}, {0, 1}}     B = {{-3, 3}, {1, -2}}     f1[x_, y_] = X.A.Y     f2[x_, y_] = X.B.Y     (* Print["Pago del Row Player en Eq-> ",f1[3/5,1/2]]     Print["Pago del Col Player en Eq-> ",f2[3/5,1/2]] *)     Manipulate[           ParametricPlot[{f1[x, y], f2[x, y]}, {x, 0, 1}, {y, 0, 1},        PerformanceGoal -> "Quality",            Epilog -> {Red, PointSize -> .036, Point[{f1[p, q], f2[p, q]}]}],           Style["Representación de los pagos de Prisionero 1(abscisas) y \     Prisionero 2 (ordenadas) en el Dilema del Prisionero", 11, Bold],      Delimiter,           Style["Prisionero 1 juega la estrategia mixta(p,1-p), con el valor \     de p indicado a continuación", 10, Darker@Blue],      {{p, 0}, 0, 1, Appearance -> "Open"},      Delimiter,           Style["Prisionero 2 juega la estrategia mixta(q,1-q), con el valor \     de q indicado a continuación", 10, Darker@Orange],      {{q, 0}, 0, 1, Appearance -> "Open"},      Delimiter,           Style["Valores MAXIMIN", 11, Bold, Darker@Black],      (*Style["Valor Maximin para Norm: 5/6",10,Darker@Gray],      Style["Valor Maximin para Cliff: 5/6",10,Darker@Gray],*)           Delimiter,      Style["Estrategias de Equilibrio", 11, Bold, Darker@Black],      Delimiter,      Style["Nota.- Los años de carcel son los valores absolutos de lo \     indicado en los ejes. Se indican en negativo porque es algo \     malo/negativo", 10, Darker@Black],      Style["Creado por Rafael Sanmartín( rafaorly@gmail.com )", 10,        Darker@Black],           ControlPlacement -> Left, SaveDefinitions -> True           ]      ![Mathematica graphics](http://i.stack.imgur.com/OVg3t.png) I tried to add any point after `Epilog`, but I can't. I want to add, for example, the points $(2,-3)$, $(-1,3)$, and $(0,1)$ or $(f_1(0.5), f_2(0.5))$ and $(f_1(0.4), f_2(0.3))$.


title: Unset variable by its name given as a string

text: Unlike the function Clear, the function Unset does not work for string patterns. Given the name of a variable as a string, how can you unset the corresponding variable? Example: Given:               x = 10;      trying to unset later:               Unset[Symbol["x"]]      results in               Unset::write: Tag Symbol in Symbol[x] is Protected. >>      Using `With`:               With[{var = Symbol["x"]}, Unset[var]]      results in               Unset::usraw: Cannot unset raw object 10. >>      Note that `Clear["x"]` is not an option, because it also removes all `DownValues` associated with `x`.


title: Symbolic manipulation of functional form

text: I have a functional polynomial expression of the form:               expr = f[x] + f[x] g[w] + Conjugate[f[y]] g[z] +            Conjugate[g[z]] + g[w] + f[x] f[y] g[w] + 1 +            Conjugate[a] f[t] + Conjugate[b] Conjugate[c]      I would like to write a function that selects terms that are up to linear (i.e. zero and first order) in the functions `f` and `g`, eg. in my case the correct output would be:               1 + f[x] + Conjugate[g[z]] + g[w] + Conjugate[a] f[t] +     Conjugate[b] Conjugate[c]       Note that the functions are complex, and the conjugate terms are also considered. I basically just want to neglect second-order terms and higher.


title: Organise data in table

text: I have a large amount of data available (in excel), which is not very organised. I can do this by copy paste, but I am trying to do this using mathematica. Hopefully someone can help me. I imported the data, and it is now organised in a matrix that looks like this:               test = {{{dog, 5}, {"", ""}, {"", ""}}, {{cat, 7}, {dog, 2}, {"", ""}}, {{dog,3},{horse, 2}, {cat, 1}}, {{horse, 7}, {cat, 2}, {dog, 1}}};     TableForm[test]      So on day one, they counted 5 dogs, but no other animals, on day 2 they counted 7 cats, and 2 dogs, day 3: one horse, 2 cats etc.. To analyse this data I want to create a table that gives for each day, the amount of animals but then organised in columns per animal (even if the animal is not present at that day) like this:               result = {{"dog", "cat", "horse"} , {5, "", ""}, {2, 7, ""}, {3, 1, 2}, {1, 2, 7}};     TableForm[result]      I tried somethings using `pick` and `sort` but could not figure out how to do this. Of course this example is very simple, but the real data are for a 978x15 table (and does not involve animals ;) )


title: Check if integer has even number of digits

text: I want to check if a number has an even or odd number of digits. `10` would be even because it has 2 digits `300` would be odd because it has 3 digits `986786` would be even, because it has 6 digits Seems like I would be dividing it by a power of 10, is that right?


title: Finding fourier transform of data and hence frequencies

text: I looked at all the other questions related to mine before posting this, and they didn't solve my problem. I have a large data set which can be downloaded from here. I'm using the following code to plot the DFT:               data = ToExpression @ Import["http://ge.tt/api/1/files/3dvZMs61/0/blob?download"];     ListPlot[Abs[Fourier[data]], Joined -> True, AxesOrigin -> {0, 0}]      ![enter image description here](http://i.stack.imgur.com/apHNw.gif) As far as I can tell, there is no pronounced single or countable number of frequencies in this data set. However, if I just plot the data, I get:               ListPlot[data, AxesOrigin -> {0, 0}]      ![enter image description here](http://i.stack.imgur.com/3CPpJ.gif) Here it is evident that there is a subtle periodic character, whose frequency is what I want. Why am I not getting that frequency as a peak in the first plot?


title: How to collect expressions from cells created by Print?

text: I have a notebook where evaluation of a certain cell produced hundreds of adjacent output cells using `Print`. I need to create a list containing all expressions from those output cells as elements, and assign the list to a variable **without re-running the evaluation**. Could you suggest a way to automate this process to avoid manually copying all expressions?


title: No menu in Mathematica 10 under Ubuntu 14.04

text: I have recently installed latest _Mathematica_ 10 on Ubuntu 14.04. **Problem:** no menu available in global menu. Is there are any fix for this? The problem appear only when run from Unity launcher. When new window created via `Ctrl` + `N` the menu shows normally. Screenshot: ![enter image description here](http://i.stack.imgur.com/Thdrm.png)               AbsoluteOptions[EvaluationNotebook[], WindowElements]      > >     {WindowElements -> {"StatusArea", "MemoryMonitor", >        "MagnificationPopUp", "HorizontalScrollBar", "VerticalScrollBar", >        "MenuBar"}} >


title: Logic behind Flatten and Append to in Module

text: I have a list(kicks), and a function(fix). I am aware of the problem using Loop and Append or AppendTo. My question is why does the Flatten produce the desired output. List:               kicks = {6.28992, 1.78953, 4.67832, 3.85717, 4.15561, 7.9862, 8.02365,              2.62077, 5.89348, 6.50246}      Function:                fix[list_] := Module[{xos, comp, ct},         comp = {};         xos = If[list > 7, AppendTo[comp, list]];         ct = Flatten[comp]]          fix[#] & /@ kicks               Output: {{}, {}, {}, {}, {}, {7.9862}, {8.02365}, {}, {}, {}}      Desired output:               {7.9862, 8.02365}      I want to understand why Flatten in this case does not work, and how to solve it while using Module.


Are there any plans to develop Wolfram OS? Google has developed Chrome OS/Chromium OS dedicated to easy and fast access to the web. Valve has developed Steam OS that created primarily for playing video games and provide huge performance boost because of tight integration of the OS with a computer's hardware. Both of the OS's are delivered as pre-installed OS on the special machines such as Chromebooks and Valve Machines. Since Mathematica is "integrated all-in-one platform", there can be a lot of benefits to have own OS - Wolfram OS that can be the defacto platform for computations and research and provide significant performance improvements over the standard OS's. I think a lot of hardware manufacturers will be interested in delivering scientific-oriented computers - Wolfram Machines.


title: Communication between local kernels

text: this is my first post but you have already helped me so many times that I have to start by saying thanks a lot! I have a really long calculation to do, and I have used the Evaluation->Kernel configuration options to create 2 new local kernels and divided the task in three groups of little ones. The problem is that I don't know how to share the information between different notebooks running on different local kernels. Can you help me? Thanks again anyway.


title: Is there a free version of the Springer book "Mathematical Statistics with Mathematica"?

text: Is there a free version of the Springer book: $$\text{Mathematical Statistics with Mathematica}$$ by Rose and Smith ... available on the internet?


title: WhenEvent for several variables

text: I want to solve a system of nonlinear two differential equations (say, in $\theta(x,t)$ and $\phi(x,t)$ with `NDSolve`, but I want to stop the evaluation when one of the functions ($\phi(x,t)$) reaches zero, or, for instance, a certain value $\bar{\phi}$. Because then I would like to study how, where and (of course) when this pinch- off happens. What is the best way of doing this, in your opinion? Putting a constraint before running `NDSolve`? I tried with WhenEvent, adding a line `WhenEvent[\\[Phi][x, t] == 0, Plot[\\[Phi][x, T], {x, 0, L}]` in the code, but it gives me               NDSolve::litarg:     To avoid possible ambiguity, the arguments of the dependent variable in  WhenEvent     (...)should literally match the independent variables      Here is the link to the shortest code I can manage to give: https://www.dropbox.com/s/4t5o53lppb2itk8/mma3.nb


title: How to connect a checkbox with part of the graphics?

text: I'd like to have a checkbox in a `Manipulate` expression, governing whether part of the graphics is displayed or not. For instance, assume that I have a surface with two planes:               Show[Plot3D[x^2+y^2,{x,-1,1},{y,-1,1},PlotStyle->Opacity[0.5]],       ParametricPlot3D[{0, u, v}, {u, -1, 1}, {v, -1, 1}, PlotStyle -> Opacity[0.5], Mesh -> None],       ParametricPlot3D[{u, 0, v}, {u, -1, 1}, {v, -1, 1}, PlotStyle -> Opacity[0.5], Mesh -> None]]      Now I'd like to wrap it in a `Manipulate` with two checkboxes, enabling or disabling the planes. Currently, I'm doing something like this:               Manipulate[      Apply[Show,        Join[{Plot3D[...]},         If[xzero, {ParametricPlot3D[{0, u, v}, {u, -1, 1}, {v, -1, 1},            PlotStyle -> Opacity[0.5], Mesh -> None]}, {}],         If[yzero, {ParametricPlot3D[{u, 0, v}, {u, -1, 1}, {v, -1, 1},            PlotStyle -> Opacity[0.5], Mesh -> None]}, {}]]],     {{xzero, True, "x=0"}, {True, False}}, {{yzero, True, "y=0"}, {True,         False}}]      but somehow feel it's overly complicated. What is the right way to do this?


title: Catching and debugging numerical errors in compiled functions

text: I have a compiled function (that was created using the second method of this question). Basically it's using a compiled closure. The problem is that for some parameter values it does not evaluate. Here is a small example:               (*just some function that has a singularity at x=5*)     f = Compile[{{x, _Real, 0}, {a, _Real, 0}}, Sin[a*x*Pi/180]/(x - 5)        , RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False}];          (*The wrapper just increments the x values by diff. Aa is the      variable that is supposed to be inlined in the closure*)     Block[{Aa},       With[{wrapper =           Compile[{{x, _Real, 0}, {diff, _Real, 0}},            Evaluate@f[x + diff, Aa]]},        min = Compile[{{xs, _Real, 1}, {Aa, _Real, 0}, {diff, _Real, 0}},          First@Sort[wrapper[#, diff] & /@ xs]          , CompilationOptions -> {"InlineCompiledFunctions" -> True,             "InlineExternalDefinitions" -> True,             "ExpressionOptimization" -> True},           RuntimeOptions -> {"Speed"}](*compile*)        ]       ];          (*The warning is harmeless*)     (*CompiledFunction::cfsa:Argument diff+x at position 1 should be a machine-size real number. >>*)          (*The function is compiled*)     Needs["CompiledFunctionTools`"]     CompilePrint[min]                       3 arguments             9 Integer registers             11 Real registers             3 Tensor registers             Underflow checking off             Overflow checking off             Integer overflow checking off             RuntimeAttributes -> {}                  T(R1)0 = A1             R0 = A2             R1 = A3             I7 = 0             I6 = -5             I3 = 1             R6 = 3.141592653589793             I5 = 180             Result = R7          1   I2 = Length[ T(R1)0]     2   I8 = I7     3   T(R1)1 = Table[ I2]     4   I4 = I7     5   goto 20     6   R3 = GetElement[ T(R1)0, I4]     7   R2 = R1     8   R5 = R2 + R3     9   R4 = R0     10  R8 = I5     11  R9 = Reciprocal[ R8]     12  R8 = R6 * R9     13  R9 = R4 * R5 * R8     14  R8 = Sin[ R9]     15  R9 = I6     16  R10 = R5 + R9     17  R9 = Reciprocal[ R10]     18  R8 = R8 * R9     19  Element[ T(R1)1, I8] = R8     20  if[ ++ I4 < I2] goto 6     21  T(R1)2 = Sort[ T(R1)1]]     22  R7 = Part[ T(R1)2, I3]     23  Return      But then here are the use cases:               (*everything works OK even though the singularity is in the arguments*)     min[{1,5,5},1,0]     (*=> -0.0043631*)      But for some arguments it does not:               (*But if all the arguments are singularites: BLAM!*)     min[{5,5,5},1,0]          (*=> CompiledFunction[{x,a},Sin[(a x \[Pi])/180]/(x-5),-CompiledCode-][5,Aa] *)      > >        CompiledFunction::cfne: Numerical error encountered; proceeding with > uncompiled evaluation. >> >        CompiledFunction::cfse: Compiled expression Aa should be a machine- > size real number. >> >        CompiledFunction::cfex: Could not complete external evaluation at > instruction 2; proceeding with uncompiled evaluation. >> >   Questions:   * Why is this working if some of the arguments give division by zero, but does not evaluate if all of the arguments are incorrect?   * **How can one debug such problems?** There is nothing obviously wrong at instruction 2 in the compiled output...   * How to guard against and/or catch such errors in compiled code?


title: The dangers of SaveDefinitions --- should this really happen?

text: I have been bitten hard by `SaveDefinitions -> True`. I'll describe in detail what happened below. My questions are: Is this a bug? What is the most convenient workaround? * * * Consider a definition issued like this:               Block[{x, y}, f[x_, y_] = x + y;]      Why didn't I use `:=` instead? Because the expression that stands in place of `x+y` in my actual problem is computed (symbolically) within the `Block` so (numerical) evaluations of `f` are going to be sufficiently fast. We can check the definition:               ?f      > f[x_,y_]=x+y Now let's give `x` a value ...               x = 1      ... and test that `f` still works as expected:               f[0, 0]      > 0 (* as expected *) Let's use `f` in `Manipulate` with `SaveDefinitions -> True` ...               Manipulate[f[a, b], {a, -1, 1}, {b, -1, 1}, SaveDefinitions -> True]      ... and check that it works again:               f[0, 0]      > 1 (* oops!! *)               ?f          f[x_, y_] = 1 + y      The definition of `f` has been rewritten _and changed to something else_ as a side effect of `SaveDefinitions`. What is the morale? Probably that `SaveDefinitions` and `Set` are not safe to use together. Note that what happened here is different form the situation when the definition of `f` is overwritten just because a notebook containing a manipulate with SaveDefinitions has been opened. * * * My current workaround is to use the following hack to "neutralize" the `HoldAll` attribute of `SetDelayed`:               Block[{x, y},      (f[x_, y_] := #) &[x + y];]      Alternative suggestions are welcome.


title: Accessing files in different directories

text: I have a problem that I am trying to work on. My Folder structure is like this.   * Application(MainDirectory)   * AppData( Secondary directory where files are Design.m, Layout.m, and Evaluation.m)   * Data(Another directory where datafiles are excel cheets, csv sheets, etc) The design.m file calls for an `listTabValues = Import[FileNameJoin[{DirectoryName[NotebookDirectory[], 1], "data", "VariableNames.xlsx"}]]` to access data in the files of the Data folder. I have a notebook in the Application(Main Directory) where I do `Get[FileNameJoin[{NotebookDirectory[], "AppData", "Design.m"}]]` to get the contents of the Design.m file. The problem is when I evaluate in this manner, the `NotebookDirectory[]` is set to the Application(Main Directory) and the design takes the same value and not the AppData directory as the `NotebookDirectory` where the Design.m files resides and the data access fails. Any way to wok around this?


title: Mathematica automaticly evaluates some cells

text: Is there a command or a trick to tell Mathematica to not automaticly evaluate some cells? I use the `NMinimize` function to calculates some coordinates and then use that data with `Manipulate`. When I run `NMinimize`, Mathematica automaticly runs `Manipulate`.


title: PDF exports of ArrayPlot's are fuzzy (OS X)

text: [The following problem occurs on OS X; I don't know if it also occurs with other OS's.] If I produce a `Graphics` object with `ArrayPlot`, right-click on it, choose "Save Graphic As...", and save it as a PDF file, the resulting PDF graphic is absurdly fuzzy/blurry (which is particularly perverse, considering that it is among the simplest kind of graphics (all solid-color squares with vertical and horizontal edges). For example, in the PNG screenshot below, one such figure is shown in the Mathematica GUI (on the left), and the PDF file exported as described above (and displayed at "Actual Size" magnification with the Preview app) is shown on the right: ![original vs PDF](http://i.stack.imgur.com/iJDtl.png) (Actually, the screenshot of the original on the left looks fuzzier to me than what I actually see on the screen, but that degree of fuzziness is nothing compared to what the PDF looks like.) As I understand it PDF is the native graphics format for OS X. It should be possible (not to say trivial) to save this _very_ simple graphic as a PDF in a way that preserves all the edges and corners to infinite resolution. Does anyone know how? PS: FWIW, I did try displaying the `Graphics` object above with `Style[#, Antialiasing->False]&`, but this change had no effect, either on the resulting PDF nor on the object's appearance in the Mathematica GUI.


title: Defining a function that handles Dynamic arguments similar to Built-ins

text: Firstly please note that I'm using simply `Dynamic` behavior to illustrate my question, I'm not asking how to move a `Disk` or make a `Slider`. When defining custom functions that allow interactive changing of variables I have almost always gotten by with just setting the attribute `HoldFirst` and giving the variable as a first argument and wrapping `Dynamic` where appropriate in the code defining the controller for example:                SetAttributes[mySlider, HoldAll]       mySlider[var_, range_] := Slider[Dynamic[var], range]       DynamicModule[{a = 0.4},       {mySlider[a, {0, 1}], Dynamic[a]}      ]      But I feel that this is somewhat clashing compared to the interfaces of the build-in controllers and would like to have a similar interface such as those, namely changing such a definition to:                mySlider2[var_Dynamic, range_] := Slider[var, range]      DynamicModule[{a = 0.4},      {mySlider2[Dynamic[a, Temporary], {0, 1}], Dynamic[a]}]      Which in a sense allows the full specification of Dynamic to be used, here showing for example the use of a `Temporary` setter. For this simple example the change is rather painless, however the problem arises in situations where the code doesn't just pass on variables but needs to split them out in some way, for instance this manual implementation of a movable disk:                myMovableDisk[Dynamic[r_, {fstart_, f_, fend_}]] :=        EventHandler[Dynamic@Disk[r, 1],{        {"MouseDown", 1} :> fstart[MousePosition["Graphics"], r],        {"MouseDragged", 1} :> f[MousePosition["Graphics"], r],        {"MouseUp", 1} :> fend[MousePosition["Graphics"], r]       }]      Now this matches the longest definition, but I would rather like not to have to provide multiple definitions for `myMovableDisk[Dynamic[r_, { f_, fend_}]]`,`myMovableDisk[Dynamic[r_, f_]]` and such. So my way of doing this was to set `HoldAll` and just provide rewriting calls to other definitions:                myMovableDisk[Dynamic[r_]] := myMovableDisk[Dynamic[r, {None, Automatic, None}]]      myMovableDisk[Dynamic[r_, {f_}]] := myMovableDisk[Dynamic[r, {None, f, None}]]      myMovableDisk[Dynamic[r_, f_]] := myMovableDisk[Dynamic[r, {None, f, None}]]      myMovableDisk[Dynamic[r_, {f_, fend_}]] := myMovableDisk[Dynamic[r, {None, f, fend}]]      myMovableDisk[Dynamic[r_, Temporary]] := myMovableDisk[Dynamic[r, {None, Temporary, Automatic}]]      To me this seems like a less elegant solution to allow normal dynamic interactivity, and I have yet to actually define how for instance a Temporary setter should work. I was wondering if there was an easier way to carry out such definitions, something akin to just accepting a `_Dynamic` argument and then query it to get the values of `fstar`,`f` and `fend` in the code actually defining `myMovableDisk`? Additionally I wonder if there is a write up of something like an interface definition for `Dynamic`, in essence answering what a function accepting `Dynamic[var]` should live up to of expectations in order to mirror a build-in function, since I'm really just working against the help page.


title: Poor quality Rasterize output when Background -> None

text: I am attempting to generate partially transparent images for PNG `Export`, but seem to run to the following issue. If I `Rasterize` a simple piece of `Graphics` with `Background -> None` (transparent) it looks worse:               rings = Image[         Rasterize[          Graphics[{Black, Disk[], White, Disk[{1, 1}/64, 1 - Sqrt[2]/64]}],            Background -> #, RasterSize -> 400, ImageSize -> 400]] & /@ {None, White}      > ![enter image description here](http://i.stack.imgur.com/ho1BD.png) First version appears jagged, as a circle drawn using a too simple polygon would do. I can verify this with `ImageDifference`:               ImageAdjust[ImageDifference @@ (RemoveAlphaChannel[#, White] & /@ rings)]      > ![enter image description here](http://i.stack.imgur.com/JZsO6.png) Jagged pattern is clearly visible. How to use `Rasterize` with `Background -> None` (or anything similar generating an alpha-channel image) and achieve good output quality without resorting to generating primitives such as `Disk` using hand-crafted code? **Clarification:** I want alpha channel on the output to behave as it does on `Rasterize[..., Background -> None]`. That is, the image having conceptually three regions: transparent background, black outer disk and white (non-transparent) inner disk. (These screenshots were taken on Mathematica 9.0.1.0 running on OS X 10.8.4.)


title: Solve differential equation with undetermined constants making the assumption that the constants are positive

text: I want to solve:               eqn = D[f[w], {w,2}] + (3/2 c^2 k Exp[c w] - 9/4 c^2  k^2  Exp[2 c w]) f[w] +  m^2 f[w]          sol = DSolve[eqn == 0, f[w], w]      with the assumption that `m`, `c` and `k` are positive. How do I add this assumptions?


title: How to find (numerical) value of a derivative at point?

text: I have the following function:               f[0, 0] = 0     f[x_, y_] := Exp[-(x^2 + y^2)^(-1)]      How do I find its partial derivatives at any given point, including $(0,0)$? This doesn't work (obviously, I guess):               point={0,0}     D[f[x, y], x] /. x -> point[[1]] /. y -> point[[2]]


title: Import[] exception possibly caused by ToString[] behaviour which I cannot explain

text: Let me just start by pointing out I'm a new StackExchange user as well as a new Mathematica user (started today!) I mention this as a context to my ineptitude :) I am attempting to read through a list with the names of files I want to open, import data from them and plot that data. Here is the code I'm trying to use:               testfiles = ({"aspirina.txt", "silicio.txt", "silicio20.txt",         "silicio20luz.txt", "tio2.txt", "vidro.txt", "vidro2.txt"})          Do[{data = Import[path <> ToString[i, StandardForm], {"Table"}],        Print[path <> ToString[i, StandardForm]],        Print[ListLinePlot[data]]}, {i, testfiles}]          (*     Out[500]= {aspirina.txt, silicio.txt, silicio20.txt, silicio20luz.txt,       tio2.txt, vidro.txt, vidro2.txt}     *)      > >     Import::nffil: File not found during Import. >> >     ~/Desktop/TCOEM/Espetros Raman/aspirina.txt >   etc. The directory and file names are correct, so much so that when I try this directly by just typing the exact same directory I get the desired result. Firstly, I changed the `FormatType` setting of `ToString[]` to `StandardForm` because the default (`OutputForm`) would give me an extra whitespace on either side of the full stop in the file names. Why does it do this? Secondly, why is it that even when `Print[]` seems to indicate the directory is correct I get the exception saying the file cannot be found during Import? I specifically did not format the names of the files in the testfiles list individually as strings (using "" around each one) to allow for the case where I have hundreds of such files and just want to copy and paste their names via whatever file manager I happen to be using. Any help will be greatly appreciated!


title: How to use NIntegrate in a function using parameters from a list

text: I would like to use `NIntegrate` in a function with some parameters from a list. I simplified my problem for this forum. The list of parameters is as follows:               aH = {aH1, aH2};     pars = {aH1 -> 2., aH2 -> 3.};      Normal integration works fine. The next function gives numerical output for numerical values of t and T.               f[t_, T_, k_Integer]:=Exp[-Integrate[aH[[k]],{u,t,T}]]      Now I would like to define the function using `NIntegrate`               f[t_?NumericQ, T_?NumericQ, k_Integer, aH1_?NumericQ] := Exp[-NIntegrate[aH[[k]], {u, t, T}]]      Unfortunately, this does not give numerical output when trying to evaluate by:               f[0., 1., 1, 2.]      Does anyone know how to solve this? Your help is much appreciated. Best regards, Frits


title: (Centered) Automatic Numbering of Figures

text: I want to create a figure caption cell style that prefixes a **centred** figure caption with Figure X, where X is an incremental number I have seen two methods for automatically numbering figures: Method 1: Use a CellDingbat to place the label in the left margin of the notebook               Cell[StyleData["FigureCaptionLeft"],      CellDingbat->Cell[        TextData[{"Figure ",           CounterBox["FigureCaptionNumbered"], "."}]],      TextAlignment->Left,      CounterIncrements->"FigureCaptionNumbered",      CellMargins->{{115,0},{0,0}},      MenuSortingValue->10000]      Method 2: Use CellFrameLabels to place the label above, below, left or right of the cell frame. Using this method I have not been able to obtain cell frame label and the caption on the same line.               Cell[StyleData["FigureCaptionCentred"],      CellMargins->{{65, 0}, {0, 0}},      CellHorizontalScrolling->True,      CellFrameLabels->{{None, None}, {None,          Cell[          TextData[{"FIGURE ",             CounterBox["FigureCaptionNumbered"], "."}]]}},      CellFrameLabelMargins->{{0, 0}, {0, 0}},      TextAlignment->Center,      CounterIncrements->"FigureCaptionNumbered"]      The image should illustrate the captions created from the described styles and my desired caption ![Screenshot of the two methods and my desired caption](http://i.stack.imgur.com/Ki19V.png) Any ideas on how to create a style which prefixes centred text with a automatically generated number (with the number and text on the same line)?


title: How to write equal subset

text: I have a unique set `S={1,1,3,3,3}` but from this unique set I can create many combinations like `{1,3,3,3,1}, {3,3,1,3,1}, ...` I want to write a generalized formula to represent this. From the below formula I have already tried to find the total combinations:               5!/(2!*3!)      where 5 is the total number of elements in the set and number of 1's are 2 and number of 3's are 3. But I want to write this formula in a generalized way.


title: How can I create a class of matrices programmatically?

text: I am trying to figure out how to create a function that can create the matrix pattern below, where: `f[1]` returns `{{1}}` `f[2]` returns `{{1,2,2}}`, i.e., inserts 2 cells to the back `f[3]` returns `{{3,3,3}, {{1,2,2}}}`, i.e., inserts a row of size 3 in front `f[4]` returns `{{4,4,3,3,3}, {4,4,1,2,2}}`, i.e., inserts 2 new cells in front of both rows `f[5]` returns `{{4,4,3,3,3}, {4,4,1,2,2}, {5,5,5,5,5}}`, i.e., inserts a row of size 5 at the back and `f[12]` returns               {      {12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11},      {12, 12, 8, 8, 7, 7, 7, 7, 7, 7, 7, 10, 10},      {12, 12, 8, 8, 4, 4, 3, 3, 3, 6, 6, 10, 10},      {12, 12, 8, 8, 4, 4, 1, 2, 2, 6, 6, 10, 10},      {12, 12, 8, 8, 5, 5, 5, 5, 5, 6, 6, 10, 10},      {12, 12, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10}     }      The function attaches `n` number of cells to the current matrix at every iteration in a counter clockwise direction. The odd number cells can be done by inserting a row of size `n`. for example `Insert[{{1, 2, 2}}, ConstantArray[3, 3], 1]` However I am stuck on the even numbered blocks because they would need to be inserted on multiple rows. Can someone please point me to where I can find how to create such a function?


title: Create set of equations by replacing constant values

text: Say I have an equation:               eq = ax + by + c == 0      and I want to run `NSolve` on a set of equations of this form, for example:               NSolve[{5x + 7y - 6, 9x - 2y + 3}]      How can I use the single definition of `eq` above to do this, by replacing `a`, `b` and `c` with the required values? It is ok to write it manually in NSolve for a simple example as above, but the real equation I will be doing this with has many more terms, and I will be solving a set of 8 equations! Overall it'd be great if I could take a single equation like `eq` above, and then a list of the values that I want to be used (eg. a list of values for `a`, a list of values for `b` and a list of values for `c`) and then generate a list to pass to `NSolve`. This is probably a fairly simple question, but I'm a beginner with Mathematica (although an experienced programmer in many other languages), so I'm not sure how to approach it. I suspect there may be a built-in function that will do this (or something like it) - is that the case?


title: Apply UpValues before Listability

text: I'm trying to modify `Plus` but am running into trouble with it being `Listable`:               ClearAll[f, g, h]     Attributes[f] = {Listable};     h /: f[x_h, l_List] := 0     h /: g[x_h, l_List] := 0     f[h[1], {1, 1}]   (* {f[h[1], 1], f[h[1], 1]}, not OK I want 0 *)     g[h[1], {1,1}]    (* 0 as expected *)      How can I make the UpValue (or equivalent) have higher priority than the listability? **EDIT:** I ended up wanting to do this again and figured I'd fix the `Plus` properly. Here it is working using Sashas answer and Mr.Wizards `$Pre` method:                   $Pre =.         ClearAll[myPlus]; Attributes[myPlus] = {Orderless};         Unprotect[InterpolatingFunction]; UpValues[InterpolatingFunction] = {};         InterpolatingFunction /:           myPlus[y_InterpolatingFunction[t_Symbol], l_List] :=           Interpolation[            MapThread[List, {y["Grid"], l + # & /@ y["ValuesOnGrid"]}],             InterpolationOrder -> First[y["InterpolationOrder"]]][t]         myPlus[other__] := +other         $Pre = Function[x, Unevaluated@x /. Plus -> myPlus, HoldAllComplete];         Protect[InterpolatingFunction];              y = Interpolation[Table[{i, RandomReal[{0, 1}, 2]}, {i, 1, 10}]];         ParametricPlot[{y[t], y[t] - {1, 1}}, {t, 1, 10}]


title: From notebook,how can I change variable value with in .m file dynamically?

text: I wrote a function named `Testing`.               BeginPackage["TestPackage`"]     Testing[tabNames_] :=            (               DynamicModule[                             {                                 tabIndex = 0,                                 displayPanel = 0                             },                             (                                 {                                 Column[{                                         (*Setter Bar Part*)                                         (                                             Dynamic[                                                     SetterBar[                                                                                Dynamic[tabIndex],                                                               (Table[(i -> tabNames[[i]]), {i, 1, Length[tabNames]}]),                                                               {ImageSize -> {110, 50}}                                                              ]                                                     ]                                         ),                                     (*Setter bar IS Closed here*)                                     (*middle Panel Part*)                                     Dynamic[                                                 Panel[                                                          displayPanel                                                     ]                                                ]                                     }                                 ], Dynamic[tabIndex]}(*Final PAnel IS Closed here*)                             )                     ]       )       EndPackage[]      I saved the above code in `.m` file. `.nb` file code                  functionCalling = Testing[{a, b, c, d}];        notebookList = {1, 2, 3, 4, 5};        TestPackage`displayPanel =Dynamic[(Part[notebookList, (TestPackage`tabIndex + 1)])];        Dynamic[Part[functionCalling, 2, 1]]      I want to track the `TabIndex` value dynamically,If you click on any `setterButton`. depending upon the `TabIndex`value,I will find the element from the `notebookList` and assign to `displayPanel`. after assignment,the updated `displayPanel` value should be displayed dynamically in notebook. for this purpose,I wrote the above code in a `.nb` file.But that code is not working How can I solve this issue? Please help me?


title: Numerical Integration as Model for Nonlinear Fit

text: I'm trying to do a fit for parameters of a function within an integral but I'm getting errors when I try and run it. Essentially I want the following fit to work out:               model[a_, b_, x_] := Sum[NIntegrate[totalνLayer[p, m] (a (1 - b^-p)),                                        {p, 0.2, 10}], {m, x - .45, x + .45, .02}]          nlm = NonlinearModelFit[data, model[a, b, x], {a,b}, x, Weights -> 1/errors^2]      Where `totalνLayer` is a function I defined earlier. I just want the fit values for `a` and `b` and their covariance matrix, but I'm clearly doing something wrong. Any help is much appreciated! For those who care, all of the necessary code is below:               amp[x_] := 47.5111 - 1.79354 Abs[x]     μ[mrad_] := 5.449517720787487 Exp[-0.0693211022591832 Abs[mrad]]     σ[mrad_] := 1.7679270770338407 Exp[-0.12510841305113626 Abs[mrad]]     γ[x_] := 2.5587996836804026 Exp[-0.20766051151975093 Abs[x]] + 0.5696086481954964     ω[mrad_] := 7.63444841081276 Exp[-0.08637416159312404 Abs[mrad]]     lin[mrad_] := 0.9648001654360766 - 0.10434481940699446 Abs[mrad] + 0.003062473453032527 Abs[mrad]^2          crossSection[x_] := -600.089 + 1201.5577451256304 x - 1751.9101332336447` x^2 + 1899.988095515613` x^3 - 1556.709382526493` x^4 + 974.3641634962205` x^5 - 468.5129814014657` x^6 + 172.90071370757002` x^7 - 48.48328424613457` x^8 + 10.067733931487915` x^9 - 1.4558045159248463` x^10 + 0.1215353564558521` x^11 -0.00009554527467999401` x^12 - 0.001211849211458331` x^13 + 0.00009244381215772915` x^14 + 6.85533417357146`*^-6 x^15 - 1.3215490607411126`*^-6 x^16 - 1.213701585221995`*^-8 x^17 + 1.4963340473233928`*^-8 x^18 - 6.405376189932708`*^-10 x^19 - 1.3047056106410797`*^-10 x^20 + 2.0016864863803638`*^-11 x^21 - 1.2643359066392302`*^-12 x^22 + 4.036927989211094`*^-14 x^23 - 5.368234695690585`*^-16 x^24 + 214.8882519560799` x^-1 - 54.26505937368572` x^-2 + 9.480463574208194` x^-3 - 1.1135829819290948` x^-4 + 0.08354380635765371` x^-5 - 0.0036045838406917876` x^-6 + 0.0000678896567028218` x^-7      And the definition of `totalνLayer`:               totalνLayer[x_, mrad_] := .3*3.78*10^-5*810^2*5 (amp[mrad] Exp[-(x - μ[mrad])^2/(                               2 σ[mrad]^2)] + lin[mrad] x + (amp[mrad] γ[mrad]^2)/(                               4 (γ[mrad]^2/4 + (x - ω[mrad])^2)))/(                               crossSection[x] 10^-38*1*6300*6.022*10^23)      And the data:               data = {{0, 1185.2847069383793`}, {4, 780.6026466248076`}, {8, 493.5502399832769`},              {12, 312.1838499130911`}, {16, 193.16881196193143`}, {20, 113.41366552793787`},             {24, 64.20654682074144`}};          errors = {132.12627600307064`, 90.55918065608893`, 60.884899393246535`,              41.88064141772561`, 29.076284534300132`, 20.049728493077968`,               13.950371635495452`};      And last but not least the model and fit:               model[a_, b_, x_] := Sum[NIntegrate[                                totalνLayer[p, m] (a (1 - b^-p))*10^-38*1.4*150*6.022*10^23,                                {p, 0.2, 10}],                              {m, x - .45, x + .45, .02}]          nlm = NonlinearModelFit[data, model[α, β, x], {α, β}, x, Weights -> 1/errors^2]      I apologize for all of the weird numbers and functions; this is neutrino data from my research.


title: What is the best way to save a large graph object, allowing it to be reloaded quickly in a new kernel?

text: I generated a very large graph, too large to simply display and manipulate with copy/paste operations. How can I somehow save the graph to a file to allow it to be rapidly reloaded after I quit out of the kernel and restart Mathematica?


title: How to create an interactive map of the 50 states showing certain data in tool tips boxes for health care policy development?

text: To create a means of displaying information about the distribution of primary care providers, the population density and the average yearly Medicare expenditure per enrollee for each state, I would like to create a US map with the state boundaries indicated, and then display a tool tip box containing the data for that state when the cursor hovers over that state. `CountryData["UnitedStates"]` does not have a map that includes the state boundaries. In addition, I would like to colorize the states to indicate the value of a given parameter for that state, such as age-adjusted average yearly cost per Medicare Enrollee, by reference to a color scale. I have not been able to find the _Mathematica 9_ code for an interactive US map in the Mathematica demonstrations and I am interested in suggestions or working code that I could use. My level of proficiency with _Mathematica 9_ is somewhere between beginner and intermediate, so I appreciate the details that might not be necessary for explaining the solution to an experienced user.


title: Function to preserve evaluation on display?

text: I'm looking for a function that applies the following behavior to an expression: -When the expression is given as the full input, or as part of a function that cannot be evaluated, it remains in unevaluated form. -When the expression is used for a function, it is evaluated.  `Defer[]` won't evaluate it in a function. `Unevaluated[]` leaves itself in evaluated when used directly as output. Essentially, I need a function `F[]` that will output the following:   * `F[1-1/2]` outputs `1-1/2`, NOT `1/2`   * `Times[F[1-1/2],5]` outputs `5/2`, NOT `(1-1/2)5`   * `Times[F[1-1/2],x]` outputs `(1-1/2)x`, NOT `x/2` If the solution only works for a specific internal expression, that works, because I only need this for one function.


title: How to get the total intensity of a certain frequency range in an audio file?

text: Does anyone know how to get the total intensity of a certain frequency range in an audio file? Let's say an audio file has a frequency range from 0Hz to 20KHz, and I want to extract the total intensity of every 100Hz, then I can have the intensity of 0 to 100Hz, 100 to 200Hz....etc.


title: Modify this code using Module and While

text: I have written a recursive function and would like to re-write the code using **Module** _AND_ **While** to compare the timings. Here is my recursive function for f[n], where 6 n f[n] = f[n-1] + n! for n>0 and f[0]=7.               Clear[f]       f[0] = 7;       f[n_Integer /; n>0] := f[n-1]/(6 n) + n!        Now I want to write it using **Module** AND **While** , I could write using **Module** ONLY, but I am struggling when I need to combine it using **While** loop.   Here is my code using **Module** only:                fm[n_] := Module[{f}, f[0] = 7; f[i_] := f[i-1]/(6 i) + i!; f[n]]      Then if I want to use **Module** AND **While** , I get into trouble, here is my code:                fm[n_] := Module[{fw}, While[n>=0, fw[0] = 7; fw[i_] := fw[i-1]/(6 i); fw[n] ] ]        The code is not working and I couldn't figure out where does it go wrong. Do I still need to write recursively inside the While loop? And how could I write the correct code?   Any detailed explanations are greatly appreciated. Thanks in advance!


title: Pulling out common terms when simplifying complicated equations

text: I have a complicated expression where common terms are apparent but Simplify[] and FullSimplify[] don't appear able, even with plenty of assumptions added, to reduce down to a simpler form with common terms recognised so that I can give them a symbol and simplify the expressions acordingly. A simpler example which demonstrates is               h (140 + Current -         lastU1 + (lastV1 +            1/2 h (140 + Current - lastU1 + (5 + 0.04 lastV1) lastV1)) (5 +            0.04 (lastV1 +               1/2 h (140 + Current - lastU1 + (5 + 0.04 lastV1) lastV1))))      with obvious common terms being               140 + Current - lastU1   -> Alpha     (5 + 0.04 lastV1) lastV1 -> Beta      With these and one further common term which contains them both recognised               (lastV1 + 1/2 h (Alpha + Beta)) -> Gamma      this expression can be reduced to               h (Alpha + Gamma (5 + 0.04` Gamma))      I have played with Factor[], Collect[] and many others but nothing seems to do what I need. I am sure that Mathematica is capable of doing what I am looking for, so I am asking the experts here for tips for how best to go about it. As a matter of interest, these expressions are going to be compiled into C eventually and I have found this to produce output of interest in terms of structuring the algebraic reduction               Experimental`OptimizeExpression[ expression , OptimizationLevel -> 2]      but I would still like more control over the manipulation before I get to this stage. Many thanks in advance Michael


title: Tricky selection of elements based on their position

text: I need to make a list of some elements from a 4D array with dimensions 4x4x4x4. I need to select the elements based on their position in the following way: name an element e(x,y,z,w); I need all the elements where x≥y and z≥w. This basically excludes all the upper triangular part of each submatrix and all the submatrices in the upper triangular part of the tensor. The array in question is this one:               b={{{{12, 0, 0, 0}, {-18 Sqrt[2], 0, 0, 0}, {12 Sqrt[3], 0, 0, 0}, {-6,      0, 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0,      0}}}, {{{-18 Sqrt[2], 0, 0, 0}, {84, 0, 0, 0}, {-48 Sqrt[6], 0, 0,      0}, {54 Sqrt[2], 0, 0, 0}}, {{0, 0, 0, 0}, {0, 60, 0,      0}, {0, -90, 0, 0}, {0, 18 Sqrt[10], 0, 0}}, {{0, 0, 0, 0}, {0, 0,      0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0,      0}, {0, 0, 0, 0}, {0, 0, 0, 0}}}, {{{12 Sqrt[3], 0, 0,      0}, {-48 Sqrt[6], 0, 0, 0}, {276, 0, 0, 0}, {-186 Sqrt[3], 0, 0,      0}}, {{0, 0, 0, 0}, {0, -90, 0, 0}, {0, 240, 0,      0}, {0, -90 Sqrt[10], 0, 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0,      168, 0}, {0, 0, -84 Sqrt[6], 0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0,      0, 0, 0}, {0, 0, 0, 0}}}, {{{-6, 0, 0, 0}, {54 Sqrt[2], 0, 0,      0}, {-186 Sqrt[3], 0, 0, 0}, {648, 0, 0, 0}}, {{0, 0, 0, 0}, {0,      18 Sqrt[10], 0, 0}, {0, -90 Sqrt[10], 0, 0}, {0, 600, 0, 0}}, {{0,      0, 0, 0}, {0, 0, 0, 0}, {0, 0, -84 Sqrt[6], 0}, {0, 0, 504,      0}}, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 360}}}}      I tried in many ways but I can't figure it out. Thanks in advance.


title: Integer partitions in all orderings

text: I want to partition an integer into $k$ integers all possible orderings. This can be done in the following way               integerPartitions[n_, {k_}] := Select[FrobeniusSolve[Table[1, {k}], n], FreeQ[#, 0] &]      For example,               integerPartitions[4, {2}]      gives               {{1, 3}, {2, 2}, {3, 1}}      But this is very slow if the partition number is large as compared to `IntegerPartitions`, which gives partitions in reverse lexicographic order. For instance, `integerPartitions[60, {5}]` will take more than 4 seconds in my laptop in contrast to 0 seconds of `IntegerPartitions[60, {5}]`. So my question is: what would be the most efficient Mathematica code for this problem?


title: How to express an integer number in English words?

text: How do I convert a number to a readable string? I would like to implement a function, `inWords[]`,                   inWords[n_]:= ?      which should return a readable English string. A few expected results:               inWords[123456]     " one hundred twenty three thousand four hundred fifty six"          inWords[1000000001]     "one billion one"          inWords[123456789123456789]          "one hundred twenty three quadrillion four hundred fifty six trillion \     seven hundred eighty nine billion one hundred twenty three million \     four hundred fifty six thousand seven hundred eighty nine"      On the other hand, how do I implement a function to do exactly the reverse of this? That is, to read and parse string and convert the string to a number? **Note** The Stack Overflow post _Express a number using words in Mathematica_ tries to answers second part of my question. However, it uses `WolframAlpha` which expects one to be connected to the Internet, and there are restrictions on number of calls made so, a non- WolframAlpha answer would be much nicer.


title: Efficient way to solve equal sums $x_1^k+x_2^k+\dots+x_5^k=y_1^k+y_2^k+\dots+y_5^k$ with Mathematica?

text: I need to solve the system of equations, call it $S_1$, in the integers $$x_1x_2x_3x_4x_5 = y_1y_2y_3y_4y_5$$ $$x_1^k+x_2^k+\dots+x_5^k=y_1^k+y_2^k+\dots+y_5^k,\;\; k= 2,4,6$$ I used a very primitive code using _KSubsets_ [], _Table_ [], _Sort_ [], and _Do_ [], and with $x_i, y_i\le 50$ found one, $$2\cdot16\cdot25\cdot45\cdot48 =3\cdot9\cdot32\cdot40\cdot50$$ $$2^k+16^k+25^k+45^k+48^k = 3^k+9^k+32^k+40^k+50^k$$ Using this single example, I managed to find a parametrization, so $S_1$ has an infinite number of primitive solutions. However, I would like to find other small solutions to $S_1$, perhaps $x_i, y_i\le 300$, (which hopefully belongs to other families). Is there an efficient way to do it with _Mathematica_? The code I used takes forever if I extend the range > 50. :( P.S. The system $S_1$ leads to an $11$th degree identity, in case one is wondering why I am interested in it.


title: Converting polygon to graph in V7

text: I've unsuccessfully tried many ways of converting polygon points into a graph using _Mathematica_ 7, and I am frustrated. I looked at this post, but it doesn't work:               Needs["Combinatorica`"];     crds = {{1, 10}, {2, 4}, {10, 5}, {20, 10}};     vertices = Range[Length[crds]];     edges = Thread[vertices \[DirectedEdge] RotateLeft[vertices]];          Graph[vertices, edges]      produces errors:               Syntax::sntxf: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!     \(vertices\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" cannot be followed by \\\\\\\"     \\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\(\(\\[ DirectedEdge]\)\) \(\(RotateLeft[vertices]     \)\)\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\".\\\"\", \"MT\"]\)\!\(\*StyleBox[\!     \(\"\"\), \"MT\"]\)"          Syntax::tsntxi: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\\[      DirectedEdge]\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" is incomplete; more input is      needed.\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\"\"\), \"MT\"]\)"          Syntax::sntxi: Incomplete expression; more input is needed.      Any ideas?


title: CorrelationTest small bug?

text: Consider two Normally distributed random variables:               x1 = RandomVariate[NormalDistribution[], {1000}];     x2 = RandomVariate[NormalDistribution[], {1000}];      I want to test $H_0 : \rho = 0$ against $H_1 : \rho \neq 0$. If I use               CorrelationTest[Transpose[{x1, x2}], 0, {"TestDataTable", All}]      I get, for instance, > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Pearson Correlation} & 0.00505234 & 0.873251 \\ \text{Spearman Rank} & > 0.00983509 & 0.756138 \\ \end{array} However, if I use               PearsonCorrelationTest[x1, x2, "TestDataTable"]      I get > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Pearson Correlation} & 0.00505234 & 0.87322 \\ \end{array} and, finally, if I use               SpearmanRankTest[x1, x2, "TestDataTable"]      I get > \begin{array}{l|ll} \text{} & \text{Statistic} & \text{P-Value} \\ \hline > \text{Spearman Rank} & 0.00983509 & 0.756081 \\ \end{array} Now **compare** the P-Values of the tests... they are slightly different, although they are supposed to be exactly the same test. Can anyone confirm this? If yes, could it be a small bug in _Mathematica_?


title: What kind of hypergeometric function is it?

text: I found a formula for an integral of a product of three Bessel functions at The Wolfram Functions Site: ![Bessel function integral](http://functions.wolfram.com/Bessel- TypeFunctions/BesselJ/21/02/02/0007/MainEq1.gif) I cannot understand what kind of hypergeometric function it is. The _Mathematica_ code given for it is:               HypergeometricPFQ[{{(α + λ + μ + ν)/2, (α + λ + μ - ν)/2}, {}, {}},                       {{}, {λ + 1}, {μ + 1}}, a^2/c^2, b^2/c^2]      When I try to evaluate it in _Mathematica_ 9, the last argument is highlighted in red and I get an error message: > HypergeometricPFQ::argrx: HypergeometricPFQ called with 4 arguments; 3 > arguments are expected. >>


title: Computing a series in terms of exponential function

text: Is there any way to compute the following series in terms of exponential function ? $$\sum_{k=0}^\infty Y_1(k)\;x^k$$ where $$Y_1(k) = \frac{(k - 1)!}{k!}Y_3(k - 1)$$ $$Y_2(k) = \frac{(k - 1)!}{k!}Y_4(k - 1)$$ $$Y_3(k) = \frac{(k - 1)!}{k!}(1/2Y_3(k - 1) + 1/2Y_1(k - 1))$$ $$Y_4(k) = \frac{(k - 1)!}{k!}(1/2Y_4(k - 1) + 1/2Y_2(k - 1))$$ such that: $\;Y_1(0)= 2 + r,\; Y_2(0) = 4 - r,\; Y_3(0) = 2 + r,\; Y_4(0) = 4 - r$               Y1[0] := 2 + r;     Y2[0] := 4 - r;     Y3[0] := 2 + r;     Y4[0] := 4 - r;     Y1[k_] := (k - 1)!/(k!)*(Y3[k - 1]);     Y2[k_] := (k - 1)!/(k!)*(Y4[k - 1]);      Y3[k_] := (k - 1)!/(k!)*(1/2*Y3[k - 1] + 1/2*Y1[k - 1]);      Y4[k_] := (k - 1)!/(k!)*(1/2*Y4[k - 1] + 1/2*Y2[k - 1]);          Sum[ Y1[k] x^k, {k, 0, Infinity}]


title: Where do those nulls come from?

text: I have seen discussions of unwanted nulls in the output in the context of building lists with conditions on the elements, but that is not involved here. I would like to know where the nulls come from and how to avoid generating them.               Clear["Global`*"]          localGroup =       AstronomicalData["LocalGroup"];          properties = {        "AlphanumericName",        "StandardName",        "AlternateStandardNames",        "NGCNumber",        "ApparentMagnitude",        "Constellation",        "Declination",        "RightAscension",        "DistanceLightYears",        "GalaxyType",        "HubbleType",        "RadialVelocity",        "Redshift"        };          lgTable = {#, Table[           {            properties[[n]],            AstronomicalData[#, properties[[n]]]            },           {n, 1, Length[properties]}           ]          } & /@ localGroup;               displayTable[record_] := Module[{},       Print[          #[[1]] <> ": ", #[[2]]          ] & /@ record[[2]];       Print["\n"]       ]          (* display two records for illustration *)          displayTable[#] & /@ lgTable[[1 ;; 2]]


title: Is it possible to specify the direction of rotation in VectorAngle function?

text: If I use the function VectorAngle[{1,0},{1,-1}], is it possible to obtain the angle generated by rotating around the axis counter clock wise? In other words, I would move from the first vector to the second in the positive direction. My output would be (7/4)*Pi instead of Pi/4.


title: Calling Mathematica from Visual Studio - example

text: I am trying to set up a connection between Visual Studio 10 and _Mathematica_ 8.0 on a Windows system. I found several sources of information on the Wolfram website, but I get entirely lost. Most of the info deals with calling C++ functions from within _Mathematica_ , but I would like it the other way round. I have quite a lot of functionality in my C++ code and I just call _Mathematica_ to make some integral calculations. Is there a good step-by-step approach to set up this connection? What files should I include in my project? What settings need to be changed? Does anyone have a complete example of pieces of code that gives insights in the general approach? That would be a great help. I followed the standard instructions to add the `lib`, `bin` and `include` to the Visual Studio directories. More specifically, I was also wondering whether in this case I also need to make a `.tm` file? Should it be empty then? The example here looks very clear, but this is approached from a Linux/Mac perspective. I hope someone could bring me some guidance. * * * Taking into account your suggestions, I have developed the following program, but there seems to be a problem with retrieving the packages. I have put the entire code here. The program first sends some variables to _Mathematica kernel_ and then it should perform the integral calculation. I am only interested in the final payoff that is calculated by Mathematica. While debugging, it seems to be that the program gets stuck in the removal of all the packages (in the loop just after sending the integral function). There is no problem with the function, I guess, because it performs the calculation perfectly when I just use _Mathematica_.               #include <stdio.h>     #include <stdlib.h>          #include "mathlink.h"          static void init_and_openlink( int argc, char* argv[]);     static void error( MLINK lp);               MLENV ep = (MLENV)0;     MLINK lp = (MLINK)0;               int main(int argc, char* argv[]){         int pkt;         float payoff;              init_and_openlink( argc, argv);      Now, I send the different parameters and the final function of interest:                   MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "mue");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "mui");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "lambdae");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "lambdai");             MLPutReal(lp,0.25);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "sigmap");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "betae");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "betai");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "gammae");             MLPutReal(lp,0.05);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "gammai");             MLPutReal(lp,0.10);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "d");             MLPutReal(lp,0.2);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "experience1");             MLPutInteger(lp,2);         MLEndPacket(lp);              MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"SetDelayed",2);             MLPutString(lp, "experience2");             MLPutInteger(lp,3);         MLEndPacket(lp);              MLPutFunction( lp,"EnterTextPacket",1);             MLPutString(lp,"expectedpayoff1bis[i1_, b1_,i2_,b2_] := NIntegrate[PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)* Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100), (1 +  betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x]), {x, 0, 2}]*(NIntegrate[(x*PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)* Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100), (1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x])/NIntegrate[PDF[NormalDistribution[(1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100), (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1]))*(1 + b1/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience1])^2 + (gammai*Exp[-lambdai*i1])^2]], x]*(1 - CDF[NormalDistribution[(1 + betae*Exp[-mue*experience2] +betai*Exp[-mui*i2])*(1 + b2/100), (1 + betae*Exp[-mue*experience2] + betai*Exp[-mui*i2])*(1 + b2/100)*Sqrt[sigmap^2 + (gammae*Exp[-lambdae*experience2])^2 + (gammai*Exp[-lambdai*i2])^2]], x]), {x, 0, 2}]), {x, 0, 2}] - (1 + (betae*Exp[-mue*experience1] + betai*Exp[-mui*i1])) - d*i1/100) - (1 - d)*i1/100");         MLEndPacket(lp);      I don't need any of the information retrieved from the above packages, so I try to get rid of everything. This is were the debugging is in a loop (When I pause the debugging, I get the screen with "no source available".                   while ((pkt=MLNextPacket(lp),pkt)&&pkt!=RETURNPKT) {             MLNewPacket(lp);             if (MLError(lp)) error(lp);         }         MLNewPacket(lp);      Afterwards I want to evaluate the function and the result needs to be printed on the screen. This is the only output I am interested in:                   MLPutFunction( lp,"EnterExpressionPacket",1);             MLPutFunction(lp,"expectedpayoff1bis",4);             MLPutInteger(lp,2);             MLPutInteger(lp,10);             MLPutInteger(lp,4);             MLPutInteger(lp,12);         MLEndPacket(lp);              while( (pkt = MLNextPacket( lp), pkt) && pkt != RETURNPKT) {             MLNewPacket( lp);             if (MLError( lp)) error( lp);         }         MLGetReal( lp,&payoff);                   printf( "payoff: %f", payoff);                   MLPutFunction( lp, "Exit", 0);              return 0;     }      The rest of the code is retrieved from the examples               static void error( MLINK lp){         if( MLError( lp)){             fprintf( stderr, "Error detected by MathLink: %s.\n",MLErrorMessage(lp));         }         else{             fprintf( stderr, "Error detected by this program.\n");         }         exit(3);     }               static void deinit( void){         if( ep) MLDeinitialize( ep);     }               static void closelink( void){         if( lp) MLClose( lp);     }               static void init_and_openlink( int argc, char* argv[]){         #if MLINTERFACE >= 3         int err;         #else         long err;         #endif /* MLINTERFACE >= 3 */              ep =  MLInitialize( (MLParametersPointer)0);         if( ep == (MLENV)0) exit(1);         atexit( deinit);              #if MLINTERFACE < 3         lp = MLOpenArgv( ep, argv, argv + argc, &err);         #else         lp = MLOpenArgcArgv( ep, argc, argv, &err);         #endif         if(lp == (MLINK)0) exit(2);         atexit( closelink);      }


title: Deleting selected rows from data table

text: I'm an intermediate Mathematica user and the _select_ function presented on Data Table Manipulation in Mathematica: Step 2 was very useful in helping me manipulate a 36Mb data file - 13 columns and 180k rows. The challenge I'm having is writing a similar function that will remove rows based on selected column entities, returning the subset of data as a new data table. Any assistance will be appreciated. Thanks.


title: TableForm behavior change

text: In an older version NoteBook, I was able to specify some options for `TableForm`, which enabled the printing of an expression in a simple fashion:               MyExpression//TableForm      I used this:               optsinit1 := SetOptions[TableForm,       TableHeadings -> {rowHeadings, columnHeadings},       TableAlignments -> Left,       TableSpacing -> 1]      where rowHeadings and columnHeadings were defined. Before using `TableForm` I would evaluate optsinit1:               optsinit1;          MyExpression//TableForm      would print the array (MyExpression) with the headings defined by rowHeadings and columnHeadings. In V9Ii have to issue               TableForm[MyExpression,optsinit1]       to get the previous behavior. I prefer the old behavior. Any hints on how this is done? Note that when I issue `Options[TableForm]` the return is               {TableAlignments -> Left, TableDepth -> \[Infinity],       TableDirections -> Column,       TableHeadings -> {rowHeadings, colHeadings}, TableSpacing -> 1}


title: Triggering actions when a variable is set

text: Some built-in variables trigger actions when their values are changed:               In[17]:= $Assumptions=1         During evaluation of In[17]:= $Assumptions::bass: 1 is not a well-formed assumption. >>     Out[17]= 1          In[18]:= $Assumptions:=2         During evaluation of In[18]:= $Assumptions::bass: 2 is not a well-formed assumption. >>      (Interestingly the message doesn't trigger if it's set again to the _same_ value.) How can we safely implement something like this? Are the any built-in hooks for value changes? * * * This is what I currently have. Does it look safe? Does anyone foresee problems? (There's always the least expected thing that goes wrong with these...)               $var /: Set[$var, value_] :=         Block[{$in = True},               Print["$var set to ", value];  $var = value] /; Not@TrueQ[$in]          $var = 6          (*       $var set to 6       6      *)      `$in` would of course be in a private context and the same needs to be done for SetDelayed as well.


title: Runaway MathKernel!

text: I was running a simulation and everything went south (my fault, stupid coding error). So I quit the kernel. Everything was running very slowly, as if it were doing some kind of large calculation. Eventually I quit Mathematica. Everything continued to run slowly. So I opened up the terminal to see what processes are running (I'm on Mac OS 10.6.8, Mathematica 9.01) and observed that there was a "Mathkernel" process, using about half (and sometimes more - 57.2% in the sceenshot) of my CPU. I tried the "Kill" command, and even "sudo Kill" but it didn't even blink. I tried logging out and back in, but it was still there. Finally, I restarted my computer, and it was gone. My question: is there a more elegant way of recovering from such a runaway process? ![enter image description here](http://i.stack.imgur.com/xfm4Z.png)


title: Registering/detecting an importer by file name extension

text: I've developed an importer and exporter for FreeSurfer's `MGH`/`MGZ` file format; the specific format isn't important, but I was wondering if there is a 'correct' way to tell _Mathematica_ that file names ending with ".mgh" should be automatically imported using my MGH importer? _Mathematica_ obviously does this for its built-in importers (e.g., `Import["abc.csv"]` is equivalent to `Import["abc.csv", "CSV"]`), so it seems like it should be possible, but I haven't been able to find any information about this in _Mathematica_ 's documentation. One solution, which seems inelegant to me, is this:               Unprotect[Import];     Import[name_String /; StringMatchQ[name, __ ~~ ".mgh" ~~ EndOfString]] :=        Import[name, "MGH"];     Import[name_String /; StringMatchQ[name, __ ~~ ".mgz" ~~ EndOfString]] :=        Import[name, {"GZip", "MGH"}];     Protect[Import];      Is there a more principled way of going about this?


title: What do these error messages mean when numerically solving differential equations?

text: I am using _Mathematica_ to numercially solve the following equations:               2 D[f0[r], r]/r + D[f0[r], r, r] == -2 A f1[r]/r^4 +  2 A D[f1[r],      r]/r^3 -2 f1[r]/r^2 + 2 D[f1[r], r]/r + D[f1[r], r, r] == 2 A D[f0[r], r]/r^3      And my boundary condition is               f0[10] == 0.01, f1[10] == 0.01,      (D[f0[r], r] /. r -> 1) == 10^-3 A,      (D[f1[r], r] /. r -> 1) == 0      When I take A to be small, say 1, everything is fine. However, if I take A to be large, e.g. 100, _Mathematica_ complains and gives me crazy results. Here are the error message I get: > NDSolve::bvluc: The equations derived from the boundary conditions are > numerically ill-conditioned. The boundary conditions may not be sufficient > to uniquely define a solution. The computed solution may match the boundary > conditions poorly. >> > > NDSolve::berr: There are significant errors {-5.55116*10^6,-7.26312*10^6,0., > 0.} in the boundary value residuals. Returning the best solution found. >> Can anyone help me to deal with this issue? I appreciate your help!


title: How to remove duplicates from set of machine precision 2D points?

text: I have a set of 2D points with machine precision coordinates. I need to remove all duplicates. Performance is important. This is the most obvious fast solution:               Union[points]      Unfortunately it turns out that unlike `Equal` and `SameQ`, `Union` has no tolerance for any difference with machine precision numbers, which makes it unusable for this purpose.               In[1]:=      a = 1.;     b = a + $MachineEpsilon;          In[3]:= a == b     Out[3]= True          In[4]:= a === b     Out[4]= True          In[5]:= Union[{a, b}]     Out[5]= {1., 1.}      Using the `SameTest` option of `Union` works, but it is not a good option because it makes the complexity $n^2$ again. So what is the fastest way to get rid of duplicates while allowing for a tolerance of comparisons, and preferably being able to control it (`Internal`$EqualTolerance`, `Internal`$SameQTolerace`)?


title: Adjacency List representation of a graph

text: I am looking to draw a graph knowing a simple adjacency representation of the graph like:                A = {{1, 3}, {2, 3}, {3, 4, 5}, {4, 5}, {5}}      Where `A` is my Adjacency List. I was thinking I could use `Graph[]` and maybe some kind of pattern matching:                Graph[{_\[DirectedEdge]_}]      I am also not familiar with patterns in mathematica (the "_" that gets used a lot but has been hard for me to understand).


title: Define a color function using Piecewise

text: How can I define a `ColorFunction` for my `ContourPlot` using `Piecewise`? For example after making a `ContourPlot` for such this function:               p[x_,y_]:=1-Sin[x]^2*Sin[y]^2;      I want to define my `ColorFunction` in a way that for example for `0<p<0.1` the plot have a different color than `0.1<p<0.2`. An example of what I need is in the following plot: ![enter image description here](http://i.stack.imgur.com/c3hUs.png) Which the color column at the right shows that each color corresponds to what value of `p`.