title: Advanced Tupling

text: I had asked this question before but I guess I did not make the question clear enough and I apologize for that. Here is the problem: `Tuples` gives me more data than I want. A very bright user gave me a solution to restrict the output using a mechanism of filtering results as they are selected by his algorithm. The problem was even though it was efficient, it could not render data very well even on a machine with a lot of memory. Memory was the bottleneck and nothing else. It also tuples from all the lists and puts them in any of the positions. So let me present the problem hopefully more clearly, with some actual data I am trying to analyze. Suppose the following, I have the following lists:               a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 21, 22, 23, 25, 26, 28}          b = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 30, 31, 33, 37, 41}          c = {6, 10, 13, 14, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 35, 37, 39}          d = {17, 19, 25, 30, 31, 33, 34, 35, 36, 38, 44}          e = {31, 41, 45, 47}          f = {23, 26, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53}      What I am trying to achieve: A tuple of length of 6 integer digits The first digit can only be a tuple of list a, second digit can only be tupled from list b, and so on. No number in any of the tupled outputs should be the same from any list, for example, `{2,2,25,25,31,31}` is not a desired combination and should be excluded. Order does not matter in this problem and should be excluded, for example, `{2, 1, 10, 9, 42, 41}` would be considered the same as `{1, 2, 9, 10, 41, 42}` and would be uneeded. Obviously we have a large set of possible combinations, and as previously mentioned, M! loves to use memory and is not at all processor dependent, so limiting the memory footprint would be a priority. Notice that the lists are of different lengths. For large numbers of combinations, M! has difficulty rendering such a potentially large dataset on even a highend consumer grade computer, it would probably be advantageous to write these out to a text file as they are generated so the data can be viewed with an external text editor like Ultraedit. Hope this is a detailed enough explaination and someone can share their thoughts! Thanks in advance!


title: Determining sample size with no replacement for a given confidence and reliability when there are x failures observed during sampling?

text: I am trying to follow the procedure of a Sandia Labs report found here to determine the required sample size, for various population sizes, with no replacement for a given confidence and reliability. The authors provide Mathematica code but I chose to write my own based on their procedure. The procedure described on page 13 is “The second SNL technique can be extended for any number of defective units in the sample by using the CDF for the hypergeometric distribution. This extension is referred to as the third technique. To find the minimum n given a specific x required for given N, γ, and R, the following technique can be used. Note that D is (1 - R) N rounded to the nearest integer. For the hypergeometric distribution HyperDist(n, D, N), find the minimum n for which CDF(HyperDist(n, D, N), x) does not exceed γ”. I believe I’m able to reproduce the corrected results in Tables 1 & 2 of the above report with my code below. There are columns labeled “INCORRECT” which I don’t plan to confirm. These tables however are based on observing _zero_ failures in the sample taken while I would like to be able to specify an arbitrary number of x failures. But when I use an x value (number of failures) other than zero I get an error message. Can someone shed any insight into this ? Thanks. My code is :               c=0.9;         (* Confidence *)     r=0.9;       (* Reliability *)     x=0;           (* Number of failures in the sample *)     pop=10;   (* Population size *)     n=0;            (* Sample size, iterated *)          d=Round[(1-r)*pop]     gamma=1-c     Do[{        Label[iterate];        n=n+1;        dist=HypergeometricDistribution[n,d,pop];        cdf[z_]:=CDF[dist,z];        cdfvalue=N[cdf[x]];        If[cdfvalue>gamma,Goto[iterate],Print["Solution:"]];        Print["n = ",n];        Print["CDF[x] = ",cdfvalue];        Break[]},      {pop+2}]


title: Variable location for intial value in ParametericNDSolve

text: I am trying to figure out if _Mathematica_ allows a variable location for a known initial value for `ParametricNDSolve`. I haven't been able to find an example where this is done. In the following I set `w[5.7] == 0` as an initial condition, but I would rather set `w[p] == 0`, or in some other way find the largest `p` for which the solution of interest exists. The solution of interest requires `w[y] >= 0` in the range `{ y, 1, p}`, so I plot `Sqrt[w]` there. Sorry about all the initial variables etc. The adjustable parameter `c` is to be anything in the range `{ 0, 1}` but here `0.2` is used.               {la, ra, ta, sa} = {0.06, 0.00002, 298., 5.6705*10^-8};      {roa, rex} = {5.6*10^(-8), 1.209} ; ro[y_] = roa*y^rex;      {ka, kc, kex} = {179., 0.9624, -0.2792}; k[y_] = ka*kc*y^kex;     {ga, g0, g1, g2, g3, g4} = {   0.0237,    1.09104, -0.751912,                                   0.792915, -0.0862438,  0.0029868};          g[y_] = ga*(g0 + g1*y + g2*y^2 + g3*y^3 + g4*y^4);     {fa, f1, f2} = {1.001, -0.001076, -0.0000635};      f[y_] = fa + f1*y + f2*y^2;     r[y_] = ra/f[y];     a[y_] = kex/y - 2.*(f1 + 2.*f2*y)/f[y];     b[y_, c_] = ((c^2)*ro[y]/Pi^2/r[y]^3 - 2.*sa*(ta^4)*g[y]*(y^4 - 1.))* la^2/ta/r[y]/k[y];          wsol = ParametricNDSolveValue[{ w'[y] + 2*a[y]*w[y]^2 + 2*b[y, c] == 0,                                     w[5.7] == 0}, w, {y, 1, 12}, {c}];     Plot[ Sqrt[wsol[0.2][y]], {y, 1, 12}, PlotRange -> {{1, 12}, {-1, 10}},           AxesOrigin -> {0, 0}, Frame -> True]      I get a nice graph with a $2$-branch solution, and it varies with parameter `c`, but I'd like to include the parameter `p` to be used in the initial condition `w[p] == 0`. At the largest `p = pmax`, the solution approaches a double root, somewhere between $5$ and $6$ in this example. That number is needed for further work - basically, what is `pmax[c]`?


title: 2D Plotting of triplet data set with third axis as variation of thickness of curve

text: I have similar question like mentioned at representing triplet data set with color on 2d plot but this time instead of color I need to represent variation of third axis with the thickness of the curve


title: Solve trigonometric equation

text: I'm looking for a solution (graphic, numeric or analytic) for a function of the form: $$a^2\tanh(x)=\tan(ax),\quad a ≥ 1,\ x > 0$$ preferably using _Mathematica_. Any advice?


title: Image of first quadrant under $f(z)=(z+i)/(z-i)$

text: I'm able to plot the region where `Im[z] > 0` and `Re[z] > 0`:               RegionPlot[Re[x + I y] > 0 && Im[x + I y] > 0, {x, -2, 2}, {y, -2, 2}]      But now I'd like to apply the function $f(z)=(z+i)/(z-i)$ to this region and view the result. Can you give me suggestions?


Integrate[x^(1/3) AiryAi[x], {x, 0, ∞}]     (* Integrate[x^(1/3) AiryAi[x], {x, 0, ∞}] *)          Integrate[x^a AiryAi[x], {x, 0, ∞}] /. a -> 1/3     (* Gamma[1/3]/(3^(1/9) Gamma[1/9]) *)        * Why do I need to generalize/parameterize an integral sometimes to get a closed form result? Should cases like this be considered as bugs?   * How can I tell what kinds of generalization may help in a particular case? Do you know any other tricks besides replacing a constant with a parameter?


title: SolveAlways rejects inequality

text: I have two functions of `x`, `f` and `g`. `f[x] = g[x] + 2`, but the exact form of `g[x]` is unknown. It is known that `g[x]` is well-formed, positive, continuous, differentiable, etc., but an exact representation is unknown. What I would like to find are the conditions under which `f[x]` is positive. This is clearly whenever `g[x] > -2`, however, when I use `SolveAlways`:               f[x_] = g[x] + 2     SolveAlways[f[x] >= 0, x]      I get: > SolveAlways::eqf: 2 + g[x] < 0 is not a well-formed equation. >>


title: Use Initialization Cells to open a CellGroup

text: I would like to use "Evaluate Initialization Cells" to open a CellGroup in a notebook. However, the following code doesn't work if placed in an initialization cell:               SelectionMove[SelectedNotebook[], Previous, CellGroup];     FrontEndTokenExecute["SelectionOpenAllGroups"]      When I manually press shift-enter (on the closed CellGroup), then it works as expected by opening the CellGroup. Unfortunately, if I place this code in an initialization cell (in the appropriate location before or after the CellGroup I wish to have opened), the CellGroup doesn't open. Alternatively, is there an option I can set for CellGroups as there is for a single cell such as using `SetOptions` with `CellOpen -> True`?


title: DeleteCases that match partially

text: Say I have a list of strings L , L2= "some_text-to-delete" and I want to delete all the Li that match with "text" or "delete" DeleteCase only gives the ones that match exactly...


title: Reducing exponential inequalities fails

text: I am quite stumped by this problem :               Reduce[ N^(x-y) <1 && N > 0 , x, Reals]      gives the expected result               (N>1 && x<y) || (N<1 && x>y)      but               Reduce[ N^(x-y) <1 && N > 1 , x, Reals]     Reduce::nsmet This system cannot be solved by the methods available to Reduce      and more importantly               Reduce[ N^x < N^y && N > 0 , x, Reals]     Reduce::nsmet This system cannot be solved by the methods available to Reduce      Now this would not be a problem but I am trying to apply `Reduce` automatically to large quantities of inequalities, and I would rather avoid having to rewrite each and every one by hand. Especially considering that some will be multiple inequalities like               N^x < N^y < N^z      Do you have any idea why `Reduce` fails and how to go around this ? Thanks in advance.


title: Symbolic integral with distributions

text: Why is               Integrate[ HeavisideTheta[1 - x^2] DiracDelta[1 - x^2] , {x, 0, 1} ]     (*0*)      It should be `HeavisideTheta[0]`?


title: eigenvalues and eigenvectors without Root answers

text: I'd like to find eigen values and vectors of parametric 21*21 Matrix and i cant solve the root problem.please help me to find the answers without Root. My Matrix is:                {{-100 d, 0, 2 Sqrt[190] e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,                0, 0, 0, 0}, {0, -81 d, 0, 6 Sqrt[57] e, 0, 0, 0, 0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0}, {2 Sqrt[190] e, 0, -64 d, 0, 6 Sqrt[102] e,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 6 Sqrt[57] e,        0, -49 d, 0, 8 Sqrt[85] e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,        0}, {0, 0, 6 Sqrt[102] e, 0, -36 d, 0, 60 Sqrt[2] e, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 8 Sqrt[85] e, 0, -25 d, 0,        42 Sqrt[5] e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0,        60 Sqrt[2] e, 0, -16 d, 0, 28 Sqrt[13] e, 0, 0, 0, 0, 0, 0, 0, 0, 0,        0, 0, 0}, {0, 0, 0, 0, 0, 42 Sqrt[5] e, 0, -9 d, 0, 104 e, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 28 Sqrt[13] e, 0, -4 d,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0,        12 Sqrt[78] e, 0, -d, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0,        0, 0, 0, 0, 6 Sqrt[330] e, 0, 0, 0, 6 Sqrt[330] e, 0, 0, 0, 0, 0,        0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -d, 0, 12 Sqrt[78] e, 0,        0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4 d, 0,        28 Sqrt[13] e, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,        12 Sqrt[78] e, 0, -9 d, 0, 42 Sqrt[5] e, 0, 0, 0, 0, 0}, {0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 28 Sqrt[13] e, 0, -16 d, 0, 60 Sqrt[2] e,        0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42 Sqrt[5] e,        0, -25 d, 0, 8 Sqrt[85] e, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 60 Sqrt[2] e, 0, -36 d, 0, 6 Sqrt[102] e, 0, 0}, {0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8 Sqrt[85] e, 0, -49 d, 0,        6 Sqrt[57] e, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,        6 Sqrt[102] e, 0, -64 d, 0, 2 Sqrt[190] e}, {0, 0, 0, 0, 0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 6 Sqrt[57] e, 0, -81 d, 0}, {0, 0, 0, 0,        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2 Sqrt[190] e,        0, -100 d}}


title: Partition data and plot each set as a different color

text: data = { {2, 60}, {4.5, 62}, {6.5, 64}, {8, 65}, {9, 65}, {10,        65}, {11, 65}, {12, 67}, {13, 67}, {14, 67}, {16, 67}, {17,        67}, {18, 67}, {19, 65}, {20, 64}, {21, 70}, {22, 75}, {23,        80}, {24, 80}, {25, 82}, {26, 82}, {27, 79}, {30, 80}}          ListPlot[data, Joined -> True,      AxesLabel -> {"T(Celcius)", "Volume Collected"}]      I want to partition the data into three pieces, and the plot produced should have the points joined with a line that corresponds to the color of the point.


title: Palette to set Cell Options such as Background Editable and Initialization property?

text: Hello I have found examples of codes that generate palettes to format the text of a cell (or a portion of it). I have also found codes for palettes that change the style of a cell. The latter is described in the Help for instance and gives a nice palette               CreatePalette[      Column[Button[Style[#, 12, FontFamily -> "Times"],           FrontEndTokenExecute[InputNotebook[], "Style", #],           Appearance -> "Palette", ImageSize -> 120] & /@ {"Title",          "Subtitle", "Subsubtitle", "Section", "Subsection",          "Subsubsection", "Text", "Code", "Input"}, Spacings -> 0],       WindowTitle -> "Format"]       Other questions here on MSE such as this do similar things, but still change the text style only. So I am stuck as I do not find how to modify this function to affect the `Background` of the Cell. I would also like to change properties such as the Cell being `Editable` or `Initialization`. Again I cannot find the proper command to put in the button to do this. Eventually I would like to have a button that takes a cell and makes several changes at once, for instance makes the cell initialization, non-editable, and LightGreen background. Is there a way to edit these properties with a palette? Thanks for helping, Roberto


title: Gaps in plots of equation solution from parameter

text: I'm trying to plot solution of system of equations as a function of parameter               Manipulate[{       Quiet[sol = Solve[{Ka*P*L*L == PLL, P0 == P + PLL, r*P0 == L + 2*PLL}, {P, L, PLL}]][[3]];       complex[x_] := PLL /. sol[[3]] /. r -> x;       Plot[{          Hold[Evaluate@D[complex[r], r]],          Hold[Evaluate@D[-complex[r], {r, 2}]]          } // Release,        {r, 0.1, 4},        PlotStyle -> {Red, Blue}        ]},      {Ka, 10000, 10000},      {P0, 0.5, 1}      ]      My plot has gaps! Why and how I can eliminate them? ![enter image description here](http://i.stack.imgur.com/3Frhi.png)


title: How can I create a table of sliders?

text: I'm trying to do the following: I have a table:               w = Table[ToExpression[ToString[h] <> ToString[i]], {i, 1, Length[c]}]      This table is suposed to generate variables, like the following list:               {h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11}      I'm trying to create a table of vertical sliders with this by adding this to the code:               w = Table[VerticalSlider[Dynamic[ToExpression[ToString[h] <> ToString[i]]]], {i, 1, Length[c]}]      It create a it gives me an error:               Set::write: "Tag ToExpression in \!\(ToExpression[\"hi\"]\) is Protected.      I'm aware that this may not be the best way todo this but it's all I can imagine, I guess the other feasible way would be with loops, I don't know. Can you help me?


title: How to make the coordinate indicator in a plot bigger?

text: I want the little vertical line which indicate the coordinate of the system in plot bigger. For example, in the picture below I marked those lines I am talking about with a blue rectangle. How can I make all such a indicators bigger? ![enter image description here](http://i.stack.imgur.com/zxPta.jpg)


title: Exporting numbered equations to HTML/TeX using conversion rules

text: This question is a follow up from this one. It may also be considered a duplicate since I have already asked this question in stackoverflow almost a year ago. For a background on using numbered equations see my post from SO. Since then I had not messed with the question till today. Consider the following:               ExportString[         Cell[             BoxData[                 FormBox[RowBox[{RowBox[{"f", "(", "x", ")"}], " ", "=", " ", "x"}],             TraditionalForm]         ],         "NumberedEquation",         CellTags -> "eq:myEq"         ]         , "HTML",         "FullDocument" -> False,         "ConversionRules" -> {             "NumberedEquation" -> {                 "\\begin{equation}\n", Convert`TeX`BoxesToTeX[#] &,  "\n\\end{equation}"             }         }      ]      The output is:               \begin{equation}          f(x) = x     \end{equation}      Notice how it was able to detect the cell tag using html. But if you were to export it using latex, it just doesn't. What we want is this output when using latex:               \begin{equation}\label{eq:myEq}     f(x) = x     \end{equation}      The question is, how we can use the conversion rules to take advantange of the cell tag.


title: What are the default TransformationFunctions used in Simplify and FullSimplify?

text: If I do               Simplify[(c^3 - s^3)^2 - (s^3 + c^3)^2,       TransformationFunctions -> Automatic]      (i.e. a verbose version of default behaviour), what transformation functions actually get applied? Similarly for FullSimplify. The documentation says `By default FullSimplify does not use Reduce:`. Well how would I know? What else doesn't it use? What does it use?


title: Helio chart for canonical correlation

text: I'm trying to create a chart usually called "Helio chart". It's a chart type very suited for canonical correlation analysis involving several dependent and independent variables. However, it is a little bit difficult to find good examples of for this chart on the web and the best example I have can be found on the 6th page of this paper on the NASA website: http://ti.arc.nasa.gov/m/profile/adegani/Canonical%20Correlation.pdf It is possible to create such a chart in Mathematica? ![enter image description here](http://i.stack.imgur.com/1fPk3.png)


title: How to apply a function of several arguments to a list?

text: I have a list of triplets:               list = {{1, 3, 5}, {4, 5, 1}, {4, 9, 2}}      How can I apply a function f to the last element of each triplet when f the last and second-to-last elements of each triplet as arguments? The result should look like: > >     {{1, 3, f[3, 5]}, {4, 5, f[5, 1]}, {4, 9, f[9, 2]}} >   I tried:               list /. {a_, b_, c_} :> {a, b, f[b, c]}      But the result comes out as > >     {{1, 3, 5}, {4, 5, 1}, {f[4], f[9], f[2]}} >


title: How to set up new types for pattern matching strings?

text: Consider the following toy example: I have a set of language sounds, which I partition into two exclusive subsets, consonants and vowels. I want to set up string patterns for e.g. `StringMatchQ` that may contain restrictions based on the sound specification. For sake of simplicity, I used letters instead of sounds, as for now it does not matter.               (* Define domains *)     vowels = {"a", "e", "i", "o", "u"};     consonants = {"b", "c", "d", "f", "g"};          (* Define predicates *)     VowelQ[x_] := MemberQ[vowels, x];     ConsonantQ[x_] := MemberQ[consonants, x];          (* Use predicates in pattern matcher *)     StringReplace["badge",       Shortest[pre__] ~~ c : __?ConsonantQ ~~ v_?VowelQ ~~ EndOfString :>        pre <> "-[" <> c <> "]-[" <> v <> "]"]      > `"ba-[dg]-[e]"` My question is: **How to set up domains that can be used like e.g.`DigitCharacter` in the pattern matcher**, that is, how to define `Consonant` and `Vowel` in the following (putative) application to yield the same result as the above code?               StringReplace["badge",       Shortest[pre__] ~~ c : Consonant .. ~~ v : Vowel ~~ EndOfString :>        pre <> "-[" <> c <> "]-[" <> v <> "]"]      I can define new data structures, like `Consonant["c"]`, that is displayed as `"c"`, but is nevertheless interpreted as `Consonant["c"]`, though I have the feeling that this is not the way to do it.


title: Differential geometry add-ons for Mathematica

text: I need a differential geometry tool for Mathematica. Is there any add-on? Unfortunately, Mathematica does not include such functionality or I can not find it.


title: How to make an arbitrary number of plots have different labels/colors/etc?

text: I'm sorry but I'm not sure how to phrase this question well. Frequently I have a function that produces and returns a Plot[] or array of Plot[]'s, which I can then display with Show[], or combine with Plot[]'s from another function and then use Show[]. Normally to tell which curve is which on a graph with many curves, you have a legend. Except here, the function produced an arbitrary number of plots, and also I maybe later want to combine them with other Plot[]'s in Show[], so they all have the same color in the legend. Is there a way to make Show[] give them different colors so I can tell them apart? I can think of some very contrived ways to do this (make some sort of global variable that keeps track of how many plots have been created, and uses this as a counter to change the color to be used for the next plot), but they're very ugly and I imagine there must be a better way in elegant MM. Does anyone know of one? Thank you! Edit: An example of the code:               (*Creates and returns a plot.*)     PlotSomething[freq0_] := (     Plot[Sin[freq0*x], {x,0,3.14}])          (*Call the above plotting function several times, create and return an array of Plots.*)     MakePlotArray[numplots_] := (     plottable = {};For[i = 1, i <= numplots, i++,     AppendTo[plottable, PlotSomething[i]];     ];     Return[plottable];)          (*How can I make these plots have different colors and labels?*)     Show[MakePlotArray[5]]


title: ParametricNDSolve and ProcessEquations

text: I have a question regarding NDSolve`ProcessEquations and ParametricNDSolve. When using the regular NDSolve we have the option to divide the integration into the three steps ProcessEquations, Iterate and ProcessSolutions. My question is: When using ParametricNDSolve, is the ProcessEquation stage only done one time (when we create the ParametricFunction) or is it done every time we call the object with new parameter values? /Jacob


title: Constraining some rows from LeastSquares to lines

text: For two matrices, `A` and `B`, with dimensions `{n,p}` and `{n,2}` respectively, `LeastSquares[A,B]` returns an matrix, `R`, with dimensions `{p,2}`. But any row of `R` could be anywhere in the real plane. I want to constrain `R[[1]]` and `R[[-1]]` to two different lines. How should this be done? The system is overdetermined, `n>p`


title: Compile for deployment

text: Is there any way (other than the manual one) to grab all the functions a notebook uses from the different user-defined packages and putting everything into one file to deploy the code for e.g. CDF? I understand that this involves a recursive search through a possibly large number of package files, and the discovery of heavy interrelations between functions, but it is definitely not impossible to be done (I've done it myself many times by hand), and thus _Mathematica_ should be able to do it. Perhaps Wolfram Workbench?


title: Avoiding the re-evaluation of a RegionPlot3D

text: Is there a simple way to save the output from `RegionPlot3D` so as to avoid re-evaluating when the notebook is re-opened and `Show` is used to re-display the plot? The re-evaluation takes in excess of 30 mins of run time.


title: Convert logical relational expression to / from disjunctive and conjunctive forms?

text: I would like to convert logical relational expressions in disjunctive form, e.g., $$(x \lt -1) \lor (-1 \lt x \lt +1) \lor (x \gt +1)$$ into conjunctive form, e.g., $$(x \ne -1) \land (x \ne +1)$$ I have some machinery in place that converts a logical relational expressions in disjunctive form into a union of intervals:               ClearAll[mxInterval];                                                                                mxInterval::unrecognized = "The expression `` is not an Inequality, Less, LessEqual, GreaterEqual\      or Greater operator or the logical Or of one or more of the operators.";                                   mxInterval[HoldPattern[Inequality[valueLeft_, ropLeft_, var_, ropRight_, valueRight_]]] :=                 mxInterval[ropLeft, valueLeft, valueRight, ropRight];                                                   mxInterval[(rop:(Less|LessEqual))[var_, value_]] :=                                                        mxInterval[LessEqual, "-\[Infinity]", value, rop];                                                      mxInterval[(rop:(Greater|GreaterEqual))[var_, value_]] :=                                                  mxInterval[rop, value, "\[Infinity]", GreaterEqual];                                                    mxInterval[HoldPattern[Or[x__]]] :=                                                                        Or @@ Replace[HoldComplete[x], elem_ :> mxInterval[elem], {1}];                                         mxInterval[expr_] := (Message[mxInterval::unrecognized, expr]; Return $fail;)                               mxIntervalSymbol[op_, side_] := Switch[                                                                    op,                                                                                Less|Greater, Switch[side, l, "[", r, "]"],                                                            LessEqual|GreaterEqual, Switch[side, l, "(", r, ")"]];                                                  mxInterval /: MakeBoxes[mxInterval[ropLeft : (Less|LessEqual|Greater|GreaterEqual),                                                   valueLeft_, valueRight_,                                                                           ropRight : (Less|LessEqual|Greater|GreaterEqual)], form_] :=            RowBox[{mxIntervalSymbol[ropLeft, l], MakeBoxes[valueLeft, form], ",",                                         MakeBoxes[valueRight, form], mxIntervalSymbol[ropRight, r]}];         Using `mxInterval` on the sample expression produces a disjunction of intervals,               In[]: mxInterval[x < -1 || -1 < x < +1 || x > +1]          Out[]: Or[mxInterval[-\[Infinity],LessEqual,Less,-1],               mxInterval[-1,Less,Less,+1],               mxInterval[+1,Greater,GreaterEqual,\[Infinity]]      which display as: $$(-\infty, -1] \cup [-1,+1] \cup [+1,+\infty)$$ or, as the number line: oops, which is actually of $(-\infty,-1] \cup [+1,+1\infty)$: ![NumberLine](http://imgur.com/QlUqb51.png) ( _Note_ : Maybe I should produce Union instead of Or here. Would that eliminate the needs for a `MakeBoxes` definition for `Or[mxInterval ..]`? The only use for that function is to get the $\cup$ operator instead of $\lor$ in the display). What I would really like is the function `mxInterval[Or[mxInterval ..], And]` which would take the disjunctive form of intervals and produce the conjunctive form. And, of course, `mxInterval[And[mxInterval ..], Or]` that would do the reverse. If I were using a more procedural language, I would sort and then iterate over the intervals constructing the result along the way. However, I feel like the best way to implement the function in Mathematica is to rely heavily on pattern matching, but I'm having trouble formulating a solution using that paradigm. Or, maybe there is a Mathematica incantation that will do the conversion on the original logical relational expression? That would be sweet.


title: getting Mathematica messages in .NET

text: For example, equation Sin[10*x]-Log[x]==0 can't be solved by NSolve. Mathematica returns message "NSolve::nsmet". How can I get messages in my c# program?               IKernelLink kl = MathLinkFactory.CreateKernelLink();     kl.WaitAndDiscardAnswer();     kl.ComplexType = typeof(Complex);     kl.Evaluate("x/.NSolve[" + equation + ",x]");     kl.WaitForAnswer();     Complex[] res = (Complex [])kl.GetComplexArray();     //some code     kl.Close();


title: What does "EquationalLogic`FindCounterexample[]" do?

text: I found the undocumented `EquationalLogic`FindCounterexample[]` by browsing the lists of available symbols, but I have no clue about its purpose. The name is intriguing! So far I found the following:   * Accepts 2 or 3 arguments    * Returns an `Integer` (1, 10, 15, 31, 100 ...)   * For the first two arguments it seems to need equalities and boolean expressions (I didn't try quantifiers yet). Like in               EquationalLogic`FindCounterexample[r == r + 1  && r == 2, b == 1]        * For the third argument, almost anything is allowed   * The numeric result seems to be connected to some feature of the equation system, but not sure to which one.  For example:               EquationalLogic`FindCounterexample[r == a + 1  , a == 1]     (*     -> 31     *)          EquationalLogic`FindCounterexample[r == a + 1  , r == a]     (*     -> 100     *)      Any suggestions or ideas about how to use this? **Edit** Some additional info, mostly provided by @Rojo:               Names["EquationalLogic`*"] // Column     (*      "EquationalLogic`FindCounterexample"      "EquationalLogic`FindProof"      "EquationalLogic`Prove"      "EquationalLogic`$MaxCounterexampleSearchSize"          "EquationalLogic`$ProverOptions"     *)      All interesting names! Now, look at this:               EquationalLogic`FindProof[y == x, y == 2 && x == 2]     (*     {ProofObject[       InitialLemma[1, 2 == x],       InitialLemma[2, 2 == y],       InitialHypothesis[3, y == x],       OrientRule[4, 2 -> x, Reason[1, Identity, 1]],       ApplyLemma[5, 2 -> x, 2 == y, 0, 1, DeducedLemma[5, x == y, SupportingReason[2, x, x, 4, 0]]],       OrientRule[6, x -> y, Reason[5, Identity, 2]],       ApplyLemma[8, y -> x, y == x, 0, 1, SufficesToShow[8, True, SupportingReason[3, x, x, 6, 1]]],       FinalGoal[9, True, EndReason[8]]       ], True}      However, hold your expectations:               EquationalLogic`FindProof[2 y == 2 x, y == 2 && x == 2]     (*     {ProofObject[], False}     *)      If you run               Trace[EquationalLogic`FindProof[x == 0, x == 0], TraceInternal -> True]      among a lot of non human gibberish, you will find a lot of references to               EquationalLogicDump`skolem____$      And just for your reference, there is the **Skolem normal form**


title: How to create this four-dimensional cube animation?

text: This is a tesseract, a four-dimensional cube, which contains two cubes. Here, each side length of the smaller one is 1, while the side length of the bigger one is 2. How do make I it? I am still working on it, and I wish to see different approaches. ![rotating tesseract](http://i.stack.imgur.com/NIxpn.gif)


title: How can I specify a numerical order for variables?

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


title: Draw tangent to point in ListLinePLot

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


title: Nested NIntegrate of vector function

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


title: Is it possible to use Composition for polynomial composition?

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


title: Calculate with units

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


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

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


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

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


title: Jumps in NDSolve results

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


title: Is there a command returning information about a particular object?

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


title: NDSolve error when solving pde

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


title: Mixing Text and Formulas

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


title: Dispatch not behaving like a normal expression in Mathematica 10

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


title: Nest Replace Function with different rules

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


title: Optimizing a functional using variational calculus

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


title: How does Mma compute Confidence Intervals?

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


title: ReplaceAll a list of rules to an equation

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


title: Time derivative of unit vector in spherical coordinates

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


title: Excluding region with `RegionDifference`

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


title: Possible JLink memory leak (during) object creation

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


title: Integrating a function forcing parameters to be real and positive

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


title: Higher order periodic interpolation (curve fitting)

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


title: Ideas for NDSolve?

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


title: Memory handling by ConstantArray

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


title: FindRoot Domain restriction

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


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

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


title: Reproducing Image Patterns with Mathematica

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


title: fragment loss with ContourPlot3D

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


title: Detecting and counting signals in list data: checking pulse rate

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


title: Detecting change of a variable (detect mouse clicks)

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


title: Fastest way to do vector / matrix multiplication with constant matrix

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


title: Dynamically show usage

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


title: Trig angles simplifying in worksheet

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


title: Formatting numbers for sending to the WolframAlpha[] function

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


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

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


title: How to determine all cases consistent with constraints

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


title: Does Mathematica support collaborative filtering and recommendation systems?

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


title: Finding Limits in several variables

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


title: Drawing minor gridlines

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


title: Precise cropping with ImageCrop

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


title: Looking for better way of plotting families of functions

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


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

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


title: Using NestWhileList to determine smallest prime value in series

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


title: Parallel evaluation and memory use

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


title: How do I remove Wolfram Branding in a CDF?

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


title: How to migrate or export projects with Workbench

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


title: ContourPlot - plot only one connected component

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


title: Reduce on equations involving integrals

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


title: Efficiently filling area with disks located at certain points

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


title: Efficient by-element updates to SparseArrays

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


title: How to add equations' left and right sides together?

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


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

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


title: Generating an Airy disk on a plane

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


title: How to determine cluster membership using FindClusters?

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


title: Series expansion of a complex function

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


title: Assigning several values inside DynamicModule

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


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

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


title: Create filling between two trig functions

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


title: Making a list of terms ordered by product order

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


title: Clearing a specific definition

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


title: Overlaying a Plot within a Manipulate Control Panel

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


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

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


title: Write C/C++ programs calling Mathematica functions

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


title: Prevent text from wrapping in a notebook

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


title: Finding a fit to a multi-dimensioned function

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


title: Minimise a function taking a vector as an input directly

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


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

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


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

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


title: Producing cleaner Mathematica output

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


title: How to export transparent raster plots?

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