title: How to sum matrix elements based on finding the first (and second) non-zero elements of each row?

text: I have a matrix: ![enter image description here](http://i.stack.imgur.com/omnrx.png) I would like to sum all the first non-zero elements of each row so that I get a value of $$25.5317 + 8.85471 + 6.90018 + 32.9436 + ... $$ and so on and simply ignore zero rows. Similarly I would like to do the same again for the second non-zero elements from each row so that I get: $$29.1235 + 11.0472 + 41.2639$$


title: ArcTan[z] and ArcTan[x,y], Restriction and Conversion

text: In _Mathematica_ there are two different forms for the arctangent (inverse tangent), namely               ArcTan[x,y]      which gives the arc tangent of $y/x$, taking into account which quadrant the point $(x,y)$ is in, and               ArcTan[z]      which gives the arc tangent $\tan^{-1}(z)$ of the complex number $z$. I am not sure about the exact conversion rule, but as far as I understand it is not simply               ArcTan[z] == ArcTan[x+I y] == ArcTan[x,y]      How do I restrict _Mathematica_ to use only one of the two forms for `ArcTan`, or convert between the two? **EDIT** Maybe I should elucidate on the problem at hand. I am trying to solve the equation $$ a \cos(x) + b \sin(x) = c $$ which can be done with the _Weierstrass substitution_ to yield $$ x_{\pm} = 2 \arctan\left[ \frac{b \pm \sqrt{a^2+b^2 - c^2}}{a+c}\right] $$ which is of the type `ArcTan[z]`. But if instead I use _Mathematica_               Solve[a Cos[x] + b Sin[x] == c, x]      Then I get an ugly expression of the type `ArcTan[x,y]`: $$ \arctan\left[\frac{a c-\sqrt{a^2 b^2+b^4-b^2 c^2}}{a^2+b^2},\frac{\frac{a \sqrt{-b^2 \left(-a^2-b^2+c^2\right)}}{a^2+b^2}-\frac{a^2 c}{a^2+b^2}+c}{b}\right] $$ How do I tell _Mathematica_ to convert this expression into an `ArcTan[z]` or vice versa? (I purposely neglected the periodicity of the solutions.) **EDIT 2** I just saw, that `Reduce` yields an `ArcTan[z]`. Where is the logic behind this?


title: Derivation after substitution not working

text: I have a code that will output an expression in form of a functions like this               (Λ[θ]^3 Ω[θ] - 4 (3 Derivative[1][Λ][θ] Derivative[1][Ω][θ] + Ω[θ] ( Λ′′)[θ]) -       4 Λ[θ] (Ω[θ] + 3 (Ω′′)[θ]))/(4 G J Λ[θ] Ω[θ]^3)      Now, I have functions $\Lambda(\theta)$ and $\Omega(\theta)$, that I'd like to replace with some values of theta. I tried with `->` and `:>` and none of the replacement rules will differentiate my replacement. I can differentiate the variables separately, and then specify replacement rule `Λ'[θ] -> value(θ)`, and then use `/. Derivative[1][Λ][θ]-> value[θ]`, but that seems kinda redundant. Why isn't _Mathematica_ doing it on it's own, recognising that it is the same expression, and just evaluating the derivative? This way _Mathematica_ is treating differentiated lambdas or omegas as something not connected to original lambda and omega. Why is this so, and can it be circumvented?


title: Why is my Dynamic expression so much slower than the same in Manipulate?

text: I'm trying to do some optimization based on interactive parameters, then compute and present stuff based on the optimized results. In trying to do that, I came across some strange behavior I can't figure out. When I write either:               Manipulator[Dynamic[y], {0, 1}]     Dynamic[NMinimize[(z - y)^2, z]]      or even:               DynamicModule[{y},       Manipulator[Dynamic[y], {0, 1}]       Dynamic[NMinimize[(z - y)^2, z]]     ]      it runs incredibly slower than:               Manipulate[       NMinimize[(q - p)^2, q]     , {p, 0, 1}]          The first two are much, much slower, to the point they slow down my whole session, and I can't figure out why. Any ideas on how to speed it up?


title: How to change the number of markers in Plots?

text: Two questions, but I am not sure whether they are already answered or not.   * How can I create `PlotMarkers` (in `ListLinePlot`) with less points (less markers)? Or markers with some intervals. I have tried the Mesh option, but it does not work; it messes up all the plots.    * Is it possible to create `PlotMarkers` for normal `Plot`, not `ListPlot`? One way is to export the data to the list, but I would like to do it directly. More information: Suppose `ListLinePlot` of a number of data lists with legends. based on the suggestions, I have changed my plots into this, but honestly I cannot understand how it works!               style = Sequence @@ {Frame -> {{True, False}, {True, False}},         FrameTicks -> {{0, 1, 2, 3}, {0, 0.4, 0.8, 1.5}, None, None},         FrameStyle -> Directive[Black, 16, FontSlant -> Plain],         LabelStyle -> Directive[FontSlant -> Plain],         AxesStyle -> Lighter@Gray, TicksStyle -> Black,         LabelStyle -> {GrayLevel[0], 14, FontSlant -> Plain,           FontFamily -> "Helvetica"}, ImageSize -> 300,         AspectRatio -> 1/GoldenRatio}            ListLinePlot[{c1, c2, c3, c4}, PlotRange -> Full,        Evaluate@style,        PlotLegends -> Placed[{Long, S_Short, Short, Flexible}, Below],        PlotStyle -> (Directive[            AbsoluteThickness[2], #] & /@ (ColorData[81] /@ Range[6])),        MeshFunctions -> {Abs[#1] &, Abs[#1] &, Abs[#1] &, Abs[#1] &},        Mesh -> 6, PlotMarkers -> {Automatic, 20},        MeshStyle -> {ColorData[81] /@ Range[6], ColorData[81] /@ Range[7],          ColorData[81] /@ Range[8], ColorData[81] /@ Range[9]}]      The output is something like this, where as you can see each Markers has all the colours together. How can I solve this problem and improve it? Another problem is the distribution of the Markers which is not good. ![the output!](http://i.stack.imgur.com/y53h9.jpg)


title: Question about Replacements and String Manipulations

text: I'm trying to get better at _Mathematica_ and in the book I'm using (by **Nancy Blachman** ) is the following question (which apparently was taken from another book: **_The Art and Science of C_** ) which reads: On a standard telephone keypad, the digits are mapped onto the alphabet (minus the letters Q and Z) as shown below:                       ABC     DEF      1       2       3     GHI     JKL     MNO      4       5       6     PRS     TUV     WXY      7       8       9      Write a function `phoneSpell` that generates all possible letter combinations that correspond to a given number, represented as a string of digits. For example, if you call `phoneSpell[652]`, your function should generate the 27 possible letter combinations corresponding to that prefix, namely               {"MJA", "MJB", "MJC", "MKA", "MKB", "MKC", "MLA", "MLB", "MLC",      "NJA", "NJB", "NJC", "NKA", "NKB", "NKC", "NLA", "NLB", "NLC", "OJA",     "OJB", "OJC", "OKA", "OKB", "OKC", "OLA", "OLB", "OLC"}      Note that if the argument passed to `phoneSpell` contains a 0 or 1, that position in the output should simply be displayed as that digit, since there are no letters that correspond to it. I've tried various things like first converting the number to a `String` using `ToString` and getting the `Length` using `StringLength`. I've tried a combination of `Outer` and `Tuples` to get the different combinations, but I'm not getting much luck. Any pointers in the right direction will be appreciated. Thanks.


title: How to deal with too much recursion

text: I have put together a very simple climate model based around four equations which define the state at time `t` based on time `t-1`, along with a initial state at time `t = 0`. The problem arises when I wish to evaluate, say, the temperature at year 2000 (`t = 2000`) or higher. I hit the recursion limit. I could keep increasing the `$RecursionLimit` all the time, but I wonder if there is a better way to deal with the problem?               ClearAll[timeStep, waterDepth, gramsPerM3ofWater, joulesPerCalorie,        joulesToHeatWater, solarConstant, albedo, boltzmanConstant,        emissivity, temp, heatContent, incomingFlux, outgoingFlux, flux];          (*Constants*)     timeStep = 31536000;(*One year in seconds*)     waterDepth = 4000.;     gramsPerM3ofWater = 1000000.;     joulesPerCalorie = 4.186;     joulesToHeatWater = waterDepth*gramsPerM3ofWater*joulesPerCalorie;     solarConstant = 1350.;     albedo = 0.3;     incomingFlux = solarConstant (1 - albedo)/4;     boltzmanConstant = 5.67*^-8;     emissivity = 1.;          (*Initial State*)     temp[0] = 0.;     heatContent[0] = temp[0]*joulesToHeatWater;     outgoingFlux[0] = emissivity *boltzmanConstant*temp[0]^4;     flux[0] = (incomingFlux - outgoingFlux[0])*timeStep;          (*Equations*)     heatContent[t_] := heatContent[t - 1] + flux[t - 1]     temp[t_] := heatContent[t]/joulesToHeat     outgoingFlux[t_] := boltzmanConstant*temp[t]^4     flux[t_] := (incomingFlux - outgoingFlux[t])*timeStep


title: Problem setting up C compiler on a Mac

text: This is a follow up to this question. I am using Mma 10 on a MacBook-Pro with OS-X Mavericks. After reading the documentation under CCompilerDriver/tutorial/SpecificCompilers I did the following:               Needs["CCompilerDriver`"];     CCompilers[]      ![enter image description here](http://i.stack.imgur.com/ZNCx5.png) The documentations says they are the compilers that _are found on my machine_ and that the CCompilerDriver package is automatically called when using CompilationTarget->"C" inside Compile. However, I can't get Compile working with CompilationTarget->"C". I also tried the Basic example in the documentation for CreateLibrary, and $Failed was returned. That means a suitable compiler could not be found. The documentation at CCompilerDriver/tutorial/SpecificCompilers also says, " Many Unix-type operating systems such as Linux or Mac OS X come with GCC already installed. If it is not present, then it can be added with a relatively simple configuration step." Can you help me with that _simple configuration step_?


title: Confusing ReplaceRepeated & Hold

text: I've been bootstrapping myself to the very alien world of Mathematica and there came my first WTF moment:               RRP[P_, O_, Phi_, L_, M_] :=       If[d <= L, O + l2*v0, {}] //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d  -> Norm[OP - v1],         l2 -> l1 + M Sqrt[L^2 - d^2]       };      What I wanted to achieve is to recursively apply these rules(which I felt similar to a context-free grammar) to form the desired expression. There was no cyclic dependency in the rules, nor were alternatives, so I kinda expected it to expand correctly. But it didn't! * * * Edit: I'm trying to calculate the position of the internal joint in a planar RRP linkage. Expressed in procedural language it's probably like this(pseudocode):               /* P: position of external R joint      * O: reference point of P joint      * Phi: direction of P joint      * L: length of the R-R bar      * M: +1/-1      */     function RRP(P, O, Phi, L, M){         OP=P-O;         v0=[cos(Phi), sin(Phi)];         l1=dot(OP, v0);         v1=l1*v0;         d=norm(OP-v1);         l2=l1+M*sqrt(L^2-d^2);         if(d<=L) return O+l2*v0;         else return [];     }      * * * Since I haven't figured out how to even _debug_ here, I tried to output intermediate variables(or non-terminals in CFG terminology):               RRP[P_, O_, Phi_, L_, M_] :=       {d, OP, v1, OP - v1} //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d -> Norm[OP - v1],         l2 -> l1 + M Sqrt[L^2 - d^2]         };     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      And it gave me this:               {{6, Sqrt[26]}, {-5, 1}, {-5, 0}, {{0, -5}, {6, 1}}}      `OP` and `v1` were as expected. But WTF was `OP-v1`? A _Matrix_? * * * I figure I can't do much with `OP` so I tried manually substituting `v1` in the `d->` rule:               RRP[P_, O_, Phi_, L_, M_] :=       {d, OP, v1, OP - l1*v0} //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d -> Norm[OP - l1*v0],         l2 -> l1 + M Sqrt[L^2 - d^2]       };     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      Now it gives me the correct answer:               {1, {-5, 1}, {-5, 0}, {0, 1}}      * * * So now I'm VERY confused about this, I don't even know if I'm following the proper/idiomatic way of constructing complex functions, thanks to the arcane Help that came with Mathematica... Could anyone please either point out the problem, or kindly enlighten me on how I could construct a equivalent function in "The Mathematica Way"? * * * EDIT: After some lookup I figured out that the evaluation order for `OP - v1` was to blame. So I added `Hold[]` around the culprit and `//ReleaseHold` the whole thing after `//.` finishes building the expression. It works:               RRP[P_, O_, \[Phi]_, L_, M_] := (         If[d <= L, O + l2*v0, {}] //. {           v0 -> {Cos[\[Phi]], Sin[\[Phi]]},           OP -> P - O,           l1 -> Dot[OP, v0],           v1 -> l1*v0,           d -> Norm[Hold[OP - v1]],           l2 -> l1 + M Sqrt[L^2 - d^2]         }) // ReleaseHold;     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      But I am still confused: Could I know where I need `Hold[]` when I _write_ the code, not as a workaround after I found out something wrong with it?


title: Finding the optimal teams ranking based on the table of match results

text: My original question was this: > So my task is to score all the possible rankings of the 14 SEC football > teams and find the best one, using who won in head-to-head games as the sole > criterion (so not factoring in strength of schedule or homefield advantage > yet). > > RandomSample[Range[14]] gives me one random ranking of the 14 teams, then I > score that ranking by seeing how many wins and losses it actually predicted. > For example, if "1" represents Missouri (miss) and "3" represents Georgia > (ga), then if the generated ranking has 1 listed before 3, that ranking gets > +1 to its ranking score, since Missouri beat Georgia this season. If 3 is > listed before 1, the ranking score receives a -1 to its score, for > incorrectly ranking those teams with respect to each other. And so on for > every head-to-head SEC match up from last year. In the code below, the 14x14 matrix is the head-to-head football results in the SEC from last year. For example, since "1" represents Missouri and "3" represents Georgia, the entry (1,3) and (3,1) both represent Missouri vs. Georgia. Since Missouri won, there's a 1 in that spot. The code checks which number is in each entry, then if the generated list has the winning team in front of the loser, the ranking score k receives one point, minus one if not. And it works for one list at a time. Now I need a way to apply that algorithm to all 14! possible rankings (Permutations[RandomSample[Range[14]]), find the one with the highest ranking score (k) and show that ranking. (14! is like 90 billion) Here's the code               x = ({         {0, 2, 1, 1, 1, 1, 1, 8, 0, 0, 1, 0, 1, 0},         {2, 0, 3, 2, 2, 6, 2, 0, 0, 0, 0, 2, 0, 2},         {1, 3, 0, 4, 3, 3, 3, 8, 0, 3, 0, 0, 0, 0},         {1, 2, 4, 0, 4, 4, 4, 0, 0, 0, 11, 0, 13, 0},         {1, 2, 3, 4, 0, 5, 5, 0, 0, 10, 0, 0, 0, 5},         {1, 6, 3, 4, 5, 0, 6, 8, 9, 0, 0, 0, 0, 0},         {1, 2, 3, 4, 5, 6, 0, 0, 9, 0, 0, 12, 0, 0},         {8, 0, 8, 0, 0, 8, 0, 0, 8, 10, 8, 8, 8, 8},         {0, 0, 0, 0, 0, 9, 9, 8, 0, 9, 9, 9, 9, 9},         {0, 0, 3, 0, 10, 0, 0, 10, 9, 0, 10, 10, 13, 10},         {1, 0, 0, 11, 0, 0, 0, 8, 9, 10, 0, 11, 11, 11},         {0, 2, 0, 0, 0, 0, 12, 8, 9, 10, 11, 0, 12, 12},         {1, 0, 0, 13, 0, 0, 0, 8, 9, 13, 11, 12, 0, 13},         {0, 2, 0, 0, 5, 0, 0, 8, 9, 10, 11, 12, 13, 0}        });          list1 = RandomSample[Range[14]];     rank = Ordering@list1;     k = 0;     For[i = 1, i < 15, i++,      For[j = 1, j < 15, j++,       Which[x[[i, j]] == i,        If[rank[[i]] > rank[[j]], k++, k--],        x[[i, j]] != (i || 0),        If[rank[[j]] > rank[[i]], k++, k--]]]]; k


title: Different results for MaximumLikelihood depending on method?

text: When I used this command:               EstimatedDistribution[data, BinomialDistribution[n, p],                           ParameterEstimator -> {"MaximumLikelihood", Method -> "NMaximize"}]       I get: `BinomialDistribution[12, 0.00842065]` with error message:               FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations      versus:               EstimatedDistribution[data, BinomialDistribution[n, p],                           ParameterEstimator -> {"MaximumLikelihood"}]      I get: `BinomialDistribution[4, 0.0252702]` What are actually the differences between the two commands? Which answer should I use?


title: Transform x-scale of data for e.g. MatrixPlot

text: I have to transform in a nonlinear way the x-scale of some data for a `MatrixPlot` (or `ReliefImage` or `ListDensityPlot` etc.). Let me give an example to explain what I try to do. I have following fake data:               fakeData=Table[BinCounts[RandomVariate[NormalDistribution[71,1.5],1000],{0,85,0.5}],{j,1,100}];      Which I can plot easily with e.g. `MatrixPlot[fakeData]`, which gives ![Output of MatrixPlot for fakeData](http://i.stack.imgur.com/orbzy.png) Or I can plot just one line of the fake data with `ListPlot[fakeData[[3]]]`, which gives ![Output of ListPlot for fakeData](http://i.stack.imgur.com/o59c5.png) But the xscale of the data is not correct and should be transformed. The initial scale is linear:               xScaleInitially=Range[Length[fakeData[[1,All]]]];      and the transformed scale should be something like, e.g.:               xScaleTransformed=1⁄((10+Sqrt[xScaleInitially]));      Then I can try to transform all my data with e.g.:               fakeDataTransformed=Table[Transpose[{xScaleTransformed,fakeData[[j]]}],{j,1,100}];      If I use `ListPlot[fakeDataTransformed[[3]]]`, I get for these data the result I want to have: ![Output of ListPlot for transformed fakeData](http://i.stack.imgur.com/Yekx6.png) But I cannot manage to use `MatrixPlot` or `ReliefImage` on these transformed data to get a picture similar to the first one above. Could somebody of you tell me how I can transform my data correctly, so that I still can have plots as with `MatrixPlot` or `ReliefImage` etc.? I would be very happy about every hint and help!


title: Using imported data in further calculations

text: I have quite a lot of data in an Excel file, which I have to use in further calculations. The transformation should map a data point with thre coordinates into a two coordinate result. Example: $(r,g,b)\mapsto(r/2 + g, r \, tan(\pi/3)/2)$. So far I have tried the following, but it doesn't work since the result is the same as the imported data.               coords[{r_, g_, b_}] := {r/2 + g, r Tan[Pi/3]/2};     data = Import["file.xlsx"]     coords[data]      ### Edit OK, i'm sorry for not posting the data earlier:               {{{"0.1", "0.65", "0.25"}, {"0.8", "0.1", "0.1"}, {"0.7", "0.15", "0.15"},        {"0.6", "0.1", "0.3"}, {"0.5", "0.2", "0.3"}, {"0.4", "0.1", "0.5"},        {"0.3", "0.3", "0.4"}, {"0.2", "0.1", "0.7"}, {"0.1", "0.8", "0.1"}}}


title: Mathematica 9, Mavericks, Java

text: I've been trying to get a clear story regarding the interaction of these three components before upgrading my system from Lion to Mavericks --- I can't afford a Mathematica disaster. What I think is the case is: 1\. Upgrading to Mavericks removes Java from the system (or perhaps installs Java 7). 2\. MMA 9 requires Java 6, and the MMA installer gives you an option to install (downgrade?) to Java 6. 3\. Once you have Java 6 installed, MMA works fine. Does that sound correct? Does Wolfram indeed support MMA 9 on Mavericks?


title: Is there a better way to get the eight points of intersection?

text: I want to get the eight points of intersection from the equations `2 Abs[x] + Abs[y] == 1` and `Abs[x] + 2 Abs[y] == 1`. To solve these equations, I tried               Solve[{2 Abs[x] + Abs[y] == 1, Abs[x] + 2 Abs[y] == 1}, {x, y}]      but could only get the four points. I then tried               y /. Quiet@Solve[#, y] /.         Abs[x_] -> {x, -x} & /@ {2 Abs[x] + Abs[y] == 1,  Abs[x] + 2 Abs[y] == 1}          p = ({x, y} /. Solve[y == #] & /@ {{1 - 2 x, (1 - x)/2}, {(1 - x)/2, (           1 + x)/2}, {(1 + x)/2, 1 + 2 x}, {1 + 2 x, -1 - 2 x}, {-1 - 2 x,            1/2 (-1 - x)}, {1/2 (-1 - x),            1/2 (-1 + x)}, {1/2 (-1 + x), -1 + 2 x}, {-1 + 2 x, 1 - 2 x}})~       Flatten~1      > {{1/3, 1/3}, {0, 1/2}, {-(1/3), 1/3}, {-(1/2), 0}, {-(1/3), -(1/3)}, {0, > -(1/2)}, {1/3, -(1/3)}, {1/2, 0}} It works, but I don't like it. Could you recommend a better method? ![enter image description here](http://i.stack.imgur.com/0GPLC.jpg)


title: EndOfFile error

text: I have a LARGE file (14.6 GB) that I want to separate into several smaller files. Because of its size, using Import/Export is not feasible, I think the most reasonable way of handling this would be using the file as a stream               stream = OpenRead[filepath]       then with               Read[stream, String]      I can select what I want, and hold the strings in a temporary list until that is large enough to warrant being exported and cleared. The problem is that when Read[stream,String] encounters ASCII character 0x1A, _Mathematica_ interprets it as an EndOfFile, even when it's not. Any suggestions to get around this? Edit: https://www.dropbox.com/s/sm51m2s19wtnoqa/allascii.txt is a text file with all ASCII characters, if read in as a stream, this error should be reproduced


Recently I have used Mathematica to simulate the concrete structure. The most important point is generate random concrete aggregate. As you know, concrete aggregate can be looked as a polyhedron. We can use ConvexHull to generate polyhedron.               Needs["TetGenLink`"];          data3D = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};     Graphics3D[Point[data3D]];          {pts, surface} = TetGenConvexHull[data3D];     Graphics3D[GraphicsComplex[pts, Polygon[surface]]];      ![enter image description here](http://i.stack.imgur.com/SLdxs.png) Question 1: How to define two polyhedron intersect or not? I have written a Module, But its speed is very slow. Question 2: When the concrete aggregate become more and more in a cubic region, it is very difficult to add new aggregate in the region, How can deal with this problem ? The key is define the space relationship between line(segment) and plane(triangle):               HelenFormulaofTriangle[triangle_] := Module[        {a, b, c, p},             a = Norm[(triangle[[1]] - triangle[[2]])];        b = Norm[(triangle[[1]] - triangle[[3]])];        c = Norm[(triangle[[2]] - triangle[[3]])];             p = 0.5*(a + b + c);             Sqrt[p*(p - a)*(p - b)*(p - c)]             (*        triangle={{0,0,0},{1,0,0},{0,1,0}};        HelenFormulaofTriangle[triangle];        *)             ];                    PointInandOnorOut3DTriangle[point_, triangle_] := Module[        {},             If[         HelenFormulaofTriangle[{point, triangle[[1]], triangle[[2]]}] +            HelenFormulaofTriangle[{point, triangle[[1]], triangle[[3]]}] +            HelenFormulaofTriangle[{point, triangle[[2]], triangle[[3]]}] >           HelenFormulaofTriangle[triangle],         0,         1]                       ];                  triangle={{0,0,0},{1,0,0},{0,1,0}};        HelenFormulaofTriangle[triangle];        point={0,0,1};        PointInandOnorOut3DTriangle[point,triangle];      ![enter image description here](http://i.stack.imgur.com/Ka17C.png)


title: NDSolveValue: getting error concerning boundary values

text: I copied this code from the official website and I get an error when I evaluate it.               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]     uval =        NDSolveValue[{         D[u[x, y], x, x] + D[u[x, y], y, y] == Exp[-(x^2 + 10 y^2)],          u[x, -1] == u[x, 1] == u[-1, y] == u[1, y] == 0},          u, {x, -1, 1}, {y, -1, 1}]      I get the error: > NDSolveValue::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. >> Why is this happening? I copied it from: http://reference.wolfram.com/language/tutorial/NDSolvePDE.html I need this for an assignment, my problem is similar, but in this case I used the Laplace equation, but when I substitute my code I get the same error.


title: Intersection of two functions in SphericalPlot3D

text: How do I draw the intersection of these functions?               SphericalPlot3D[{Csc[ϕ], Sqrt[2]}, {θ, 0, 2 π}, {ϕ, 0, π},          BoxRatios -> {1, 1, 1}, AxesLabel -> {x, y, z}, Mesh -> None,          PlotRange -> {-1.5, 1.5}, PlotStyle -> Directive[Blue, Opacity[0.1]]]      ![](http://i.stack.imgur.com/C4IFa.png)


title: How to interpret an image histogram and plot histogram3D for an image?

text: I'm really finding many ambiguities in how I really should interpret the histogram of an RGB image? I could understand what the height denotes, but did not understand how the pixels get plotted on a single dimensional x-axis. Also, is it possible to plot the image onto histogram3D? I tried after converting it to separate RGB images but I get an error that says it is not able to calculate the "bins" the diagram. Thank you


title: Second derivative implicit differentiation using Wolfram Alpha input?

text: How would you perform second derivative implicit differentiation using Wolfram Alpha input? The reason that I'm using WA input is that it gives you step-by- step solutions and I'm a first year calculus student trying to figure things out. I've tried all of the obvious queries that I can think of without getting the desired results. If I type just the equation in it will give the results I'm seeking but without the step-by-step solution since it is not the primary output for the query. Here's an example of the results I get from just entering the equation x^2 + xy = 5 (w/desired result circled): ![equation results](http://i.stack.imgur.com/k9ZPt.png) *****P.S. Cross posted tocommunity.wolfram.com/groups/-/m/t/283665?p_p_auth=kD3FBYSv ***


title: How to write plain Greek in a text cell

text: If I create a text cell and type some greek text, most of the symbols are italics as if the cell had an _Input_ style. It doesn't happen with latin characters. I recollect that it is impossible to fix it, but I can't find the source where I read it. Perhaps someone knows a workaround ? The following screenshot is from _Mathematica_ 8/Linux. ![enter image description here](http://i.stack.imgur.com/0p2KG.png) **EDIT1** : I _just_ noticed that writing capital greek letters works fine (the letters are normal, not italics). The following screenshot is from _Mathematica_ 9.0.1/OSX Mavericks. ![enter image description here](http://i.stack.imgur.com/Qvxky.png) Does that piece of information ring any bells to anyone on what might be the underlying problem ? **EDIT2** : I also found this link describing a workaround by using custom modified unicode mapping files. I can't check it right now as I'm not near my Linux installation. **EDIT3** : I did try it though in _Mathematica_ 9.0.1/OSX (although the article talks about _Mathematica_ 7&8/Linux), and it works great! Here is the relevant screenshot: ![enter image description here](http://i.stack.imgur.com/qjjJx.png) **EDIT4** : As pointed out by @ybeltukov in comments, the workaround is to set the third column of `UnicodeFontMapping.tr` to 0 (zero) for Greek letters so that the default font is picked for them. **EDIT5** : This workaround doesn't anymore apply to _Mathematica_ 10\. I cannot find the `UnicodeFontMapping.tr` file.


title: Insert glyphs into a string using functional code

text: I asked this question few days ago: Replace For-loop with functional code Suppose I use strings instead of lists; for example               a = ToString /@ {123123, 112233};`      I want to insert first end of "4" to every possible position of given string. For elements in `a` , this give me               b = {4123123, 1423123, 1243123, 1234123, 1231423, 1231243, 1231234,           4112233, 1412233, 1142233, 112433, 112343, 1122334}       Now I Insert second end of "4" to given elements starting at first occurrence of "4". So, I get,               c = {       44123123, 41423123, 41243123, 41234123, 41231423, 41231243, 41231234,       14423123, 14243123, 14234123, 14231423, 14231243, 14231234,       12443123, 12434123, 12431423, 12431243, 12431234, 12344123, ...     }      Is there a method to insert elements into a string without splitting the string into a list of characters, (as done in Mr.Wisard's answer for the same question involving lists. See above link). This is what I came up with:               a = ToString /@ {123123, 112233};            Clear[f];       f[x_] := StringInsert[a, "4", x];       len = StringLength[         a[[1]]];(*Every string in set "a" has same length*)       b = Flatten[Map[f, Range[len + 1]], 1];            Clear[pos];       pos[x_] := Flatten[StringPosition[x, "4"], 1][[1]];       c = Map[pos, b];            result = {};       Do[Clear[g];         g[x_] := StringInsert[b[[i]], "4", x];         AppendTo[result, Map[g, Range[c[[i]] + 1, 8]]];, {i, 1, Length[b]}              ];            Flatten[result] ];      Anny comment to improve this really appreciated.


title: Combining BarChart and Grid - IPCC style

text: I would like to combine a plot with a table. Something like this famous plot/table from IPCC: ![IPCC plot](http://i.stack.imgur.com/mbOqy.png) So after reading Combining graphics & lists / tables I tried an approach using `Grid`. Pretty close but it feels quite hacked, especially the frame-ticks. The IPCC plot/table looks much nicer. Maybe they just used a graphics program and made it look nice. I wonder if it can be done nicely in Mathematica?               t1 = Table[BarChart[{{0, -0.2}, {0, 0.3}, {0, -0.1}}[[i]],     Frame -> False, PlotRange -> {{-0.45, 0.45}, {1.5, 2.5}},      BarOrigin -> Left, FrameTicks -> {Automatic, None},      GridLines -> {{0, {0.2, Dashed}, {-0.2, Dashed}}, None}], {i,      3}];     f1 = BarChart[{0, 1},       Frame -> {{False, False}, {True, False}},        PlotRange -> {{-0.45, 0.45}, {0, 0.1}}, Axes -> False,        BarOrigin -> Left, FrameTicks -> {Automatic, None},        AspectRatio -> 0.05]     reference = {"Sepp 2013", "Hans 2000", "Franz 1999"};     t2 = Thread@{{"c1", "c2", "c2"}, t1, reference};     PrependTo[t2, {"", "Plot", "Ref"}];     AppendTo[t2, {"", f1, ""}];     Style[Grid[t2, Frame -> All,        Background -> {None, {None, LightYellow, None, LightYellow, None}},        Spacings -> {Automatic, 0}], FontFamily -> "Helvetica"]      ![test2](http://i.stack.imgur.com/m4EP3.png)


title: Inconsistent display of TraditionalForm in version 9

text: After installing version 9, the default style sheet uses Arial font in text and formula cells. So far, so bad. At least one would hope this is done consistently. But now I see this: ![traditionalform](http://i.stack.imgur.com/p6cBy.png) You can see that the default font for `TraditionalForm` in output cells is Times, which will make such output look disjoint from the equations in inline or displayed maths. The $1$ on the output line has serifs, while the **1** on the third line (in the text cell) are sans-serif. This is what I would call visually disjoint, or incongruous. What would be the best way to change the default font for the `TraditionalForm` output so that it always remains consistent with Arial (i.e., is displayed as sans-serif) when the default stylesheet is chosen? I am aware that I could also try to change the default stylesheet back to version-8 style as discussed in "How to use version 8 default.nb style sheet in place of version 9 default.nb" \- but here I'm asking what to do if I don't want to go back to Times font, only trying to get a more uniform sans-serif appearance. **Edit** Sorry to say that the inconsistencies extend far beyond the above. I only realized this morning that many important math symbols **remain** in the old form that was based on Times glyphs, even when the rest of the expression is converted to Arial. Here is a screenshot where I typed the math symbol paired with a corresponding normal Arial character - first some double- struck glyphs, then $\hbar$, then some Greek. The square root also looks unchanged from Times font, which may be OK but isn't how I recall sans-serif square roots looking. One important problem in the juxtaposition between pairs of special and normal characters is not just the presence versus absence of serifs, but also the general mismatch in the heights. ![fonts](http://i.stack.imgur.com/1rDH3.png) The last comparison between $l$ and $I$ is of course just a reminder of how bad the Arial font is on general grounds, I'm not asking how to fix that... As a result, I think the inconsistencies I'm worried about can't be removed completely until a whole new set of glyphs is added to the Arial font. I'll have to give it some more time before perhaps accepting one of the answers, although I'm not at all happy and currently waiting for a miracle. **Edit 2** Two alternative titles for this question:   * How to un-xkcd `TraditionalForm` equations in version 9?   * Will Frankenformulas take over the world?


_**How to plot periodic function's graphic?_** For example, `f(t) = t` when `-5<t<5 && f(t+10) = f(t)`               f[t] := If[-5 <= t <= 5, t, f[t + 10] = f[t]];     Plot[f[t], {t, -20, 20}]      ![Output](http://i.stack.imgur.com/ylq0s.png)


title: Compute Triple Integral on spherical coords

text: I need to compute: $\int \int \int z dxdydz$ over the domain: $\\{x^2+y^2+z^2\leqslant 16,z\geqslant 0\\}$ Im trying to use spherical coords as: $$\int_{0}^{2\pi} \int_{0}^{\frac{\pi}{2}} \int_{0}^{4} r \cos(\theta )r^2\sin(\varphi ) \;dr\,d\theta \,d\varphi $$ I try this on Mathematica:               Integrate[Integrate[Integrate[r *Cos[theta]*r^2*Sin[phi], {r, 0, 4}], {theta, 0, Pi/2}], {phi, 0, 2 Pi}]      But re result is 0. What is wrong here?


title: Illustrating half life

text: I'm teaching some lessons on negative exponents and one application listed was half life since the rate of decay can be written as 2^-1 every ___ _ years. I found this nice animation on the net. http://www.absorblearning.com/media/attachment.action?quick=185&att=3167 I certainly don't need anything near that fancy, but wondered how I could model a similar kind of graphic using mathematica, where I could use a slider to represent years, and show a grid that responded by randomly choosing dots to "turn" off as time moved along. Any starting hints or answers are welcomed. Tom


title: Plot slope field in Mathematica for a difficult differential equation

text: I am trying to plot slope field for $\ddot{a}(t)$ for this differential equation but I don't know how to $\frac{d}{dt}\ddot{a}(t)=2\frac{\dot{a}(t)}{a(t)}\ddot{a}(t)$ I want to show that already accelerating solutions (with $\ddot{a}$ small and positive) are driven to accelerate even more, and already decelerating ones (with $\ddot{a}$ small and negative) are driven to further deceleration. So essentially I want to find out what $\dddot{a}(t)$ would look like with respect to time.


title: What is the correct way to use NIntegrate inside the FindMinimum function?

text: I'm having minor issues with the `FindMinimum` function when using `NIntegrate` inside. The functions work perfectly well but I get warning messages and I was wondering if maybe I could be enlightened on the correct usage of these two functions together. For the sake of illustration I provide the full set of functions I used on a simple example.               phi[t_, k_, h_] := (1/h)^3*        Piecewise[{{(h (1 - k) + t)^2 (h (1 + 2 k) - 2 t), (k - 1) h <= t <=             k*h}, {(h (1 + k) - t)^2 (h (1 - 2 k) + 2 t),            k*h <= t <= (k + 1) h}}];     psi[t_, k_, h_] := (1/h)^3*        Piecewise[{{(t - k*h) (h + t - k*h)^2, (k - 1) h <= t <=             k*h}, {(t - k*h) (h - t + k*h)^2, k *h <= t <= (k + 1)*h}}] ;     phipp[t_, k_, h_] := (1/h)^3*        Piecewise[{{2 (h (1 + 2 k) - 2 t) - 8 (h (1 - k) + t), (k - 1) h <=             t <= k*h}, {-8 (h (1 + k) - t) + 2 (h (1 - 2 k) + 2 t),            k*h <= t <= (k + 1) h}}];     psipp[t_, k_, h_] := (1/h)^3*        Piecewise[{{2 (-h k + t) + 4 (h - h k + t), (k - 1) h <= t <=             k*h}, {-4 (h + h k - t) + 2 (-h k + t),            k*h <= t <= (k + 1) h}}];     alpha[t_, k_, h_] := phi[t, k, h] + phipp[t, k, h];     beta[t_, k_, h_] := psi[t, k, h] + psipp[t, k, h];     T = Pi;     n = 2;     h = T/n;     FindMinimum[      NIntegrate[(h*beta[t, 0, h] - h*beta[t, n, h] +           a.Table[alpha[t, i, h], {i, 1, n - 1}] +           b.Table[h*beta[t, i, h], {i, 1, n - 1}])^2, {t, 0,         T}], {{a, {0.76}}, {b, {0.4}}}, Method -> "ConjugateGradient"]      I get the following warning message :               NIntegrate::inumr: "The integrand (a.{(8 Piecewise[{<<2>>},0])/\[Pi]^3+(8 Piecewise[{<<2>>},0])/\[Pi]^3}+b.{1/2\\[Pi]\(8\Power[<<2>>]\Piecewise[<<2>>]+8\Power[<<2>>]\Piecewise[<<2>>])}-1/2\\[Pi]\((8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3+(8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3)+1/2\\[Pi]\((8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3+(8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3))^2 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,3.14159}}"      I ask about this because `FindMinimum` takes unexpectedly long time to converge to the solution (which is a right one). But I thought that maybe using the functions correctly will accelerate the process.


title: Alternative to Except in StringExpression when using StringMatchQ

text: According to this answer and the documentation for StringExpression, `Except` can only be used in `StringExpression` for classes of characters or positions in strings. The referenced answer suggests using StringFreeQ in place of StringMatchQ. However, sometimes, this is not possible, if the pattern is one of many being passed to a function, like in the following situation               patt1 = WordCharacter..;     patt2 = "pattern";     patt3 = (*Some complicated StringExpression*);     ... (*more patterns*)     pattn = (*Everything except patt3*)          f[patt_, str_] := If[StringMatchQ[str, patt], (*stuff*), (*other stuff*)]      One possibility is to use               pattn = x: __ /; !StringMatchQ[x, patt3]      This seems repetitive and it could get verbose if repeated, but isn't too bad. However, my intuition is that there should be a better way. Is there?


title: Add to the last digit a number

text: I have data from a Multimeter that has a precision of 0.6%rdg+4dgt. So i want to take the last digit of, say, `12.007` and add 4 to the last digit like `12.011`. I'm doing `RealDigits[12.007,10,5][[1,-1]]`add 4 and then somehow with`FromDigits` get the result...it seems trivial but i don't see how.


title: Placing many arrowheads on curves

text: I can't find anything anywhere on the web to help me with this. My plot:               Plot[{(u (u + d) (1 - u))/u, u, 0}, {u, 0, 1},       PlotStyle -> {Orange, Green, Green}, PlotRange -> {-0.1, 1},       Frame -> True, Axes -> None, GridLines -> {{0}, {}},       GridLinesStyle -> Directive[Green]]      I would like to be able to put vertical arrows on the orange lines and horizontal arrows horizontal arrows on the green curve. If it helps, this is a plot of the nullclines of a system of ODEs and i need to draw the direction of the arrows of the vector field on each nullclines.


title: Multinomial logistic regression

text: Has anyone done multinomial logistic regression in _Mathematica_? The binomial case is essentially done on the `LogitModelFit` documentation page and works fine. I am following this formulation to obtain the outcome probabilities for k classes with k-1 calls to `LogitModelFit`. I am getting normalized probabilities out, but they depend on how the classes are encoded for each independent regression. I can post what I have on request but it's a lot of code for something that isn't working. Either multiple-binary or true multinomial would be fine for my purposes, but bonus for both implementations.


title: how to generate functions with changing array size?

text: I want to write a function in Mathematica which has two inputs 'n' and 'd', and the output should be (in Latex notation) $$F(n,d) = \sum_{i[1],...,i[n] =0; i[1]+...+i[n]\leq d}^{d} C[i[1],...,i[n]] f[i[1],x[1]] f[i[2],x[2]] ...f[i[n],x[n]]$$ n and d are integers. The problem is that I can hard code `F` for a given `n` and `d` alright. But when I want to write a generic function which take in any `n` and `d` and spits out the required right hand side, it becomes difficult as I have to keep changing the array size along the way depending on the values of `n` and `d`. Probably, there is a simpler way to do this in Mathematica?


title: Linearised Einstein equations

text: I need to compute the linearised Einstein Equations around a fixed metric $g_{μν}=\text{Minkowski metric} + h_{μν}$, which is not the flat metric. Does anyone know a _Mathematica_ package or a review paper that can help me?


title: How should a beginner figure out the context to use an expert answer provided on this forum?

text: J.M.'s answer to Extruding along a path related to custom cross-sections appears to answer a question I have been puzzling over for some time. I am interested in producing a tube with the stadium or stadion cross-section of oblong ductwork. I look at the code and am lost as to how to use it. Any suggestions?


title: Compile not correctly initializing a variable defined inside Module

text: In the following example, inside the `minimumX`'s `Module`, `x` is initialized to 1, but the results say otherwise:               solutionQ = Function[{x, d}, IntegerQ[Sqrt[(x^2 - 1)/d]] && x != 1];     minimumX =        Compile[{{d, _Integer}},         Module[{x = 1}, While[! solutionQ[x, d], x++]; x]];          minimumX[2]     minimumX[3]     minimumX[2]          (*     3          7          17     *)      If I define `minimumX` as:               minimumX =        Function[{d}, Module[{x = 1}, While[! solutionQ[x, d], x++]; x]];      or               minimumX =        Compile[{{d, _Integer}},         Module[{x = 1}, x = 1; While[! solutionQ[x, d], x++]; x]];      It works as I was expecting:               (*     3          2          3     *)      Is this expected behavior, or should I report a bug? (Mathematica 9.0.1)


title: Fast way of finding position of Interval containing an Integer

text: I have a large list (about 2.2 million) of pairs of integers. Each pair defines an `Interval[{}]`. Given some integer `x`, I need to find the position of the interval in my list that bounds `x` (or alternatively, return the element of the list). None of the intervals overlap, thus `x` can belong to only one of the intervals. You can assume the large list is sorted. The challenge is that I need to run this "look-up" millions of times, so even a small gain in speed would be very beneficial I tried a few obvious brute force approaches. First I created a list of intervals from the list of integer pairs, and then tried               Pick[myBigList,           Map[IntervalMemberQ[#, x] &, myBigList]]; //AbsoluteTiming      > >     4.196432 >   and then               Select[myBigList, IntervalMemberQ[#,x]& ]; // AbsoluteTiming      > >     8.814063 >   Assuming the list is ordered, then               LengthWhile[mySortedBigList, #[[1]] <= x &]      > >     3.556826 >   All of these methods seem too slow. Any suggestions would be much appreciated. (For those of you interested, here's the background on this problem. I need a fast way of translating an IP address to an approximate set of latitude- longitude coordinates. Each pair of integers in the list above corresponds to a range of IP addresses that have been converted from the zz.zz.zz.zz format to an integer. The interval defined by each pair of integers is associated with a set of lat-long coordinates. Again, this needs to be run millions or tens of millions of time on a regular basis. When this look-up was done on a 64-bit Windows desktop system running standard SQL, it took about 8 hours to geocode ten million IPs) Thanks, Mark


title: Time Varying Payoffs?

text: I'm trying to write some code that will return the final value of an annuity whose monthly payouts may or may not be constant each month. Right now I have working code for constant payments, but I'm not sure how to do changing payments. Would I use `Range`? Code:               vals = Function[{P, r, n}, P ((1 + r)^n)];     Total[Table[vals[200, .01, n], {n, 60}]]


title: Several questions on how to make a ListLogPlot look pretty

text: 1- I have the following curve which is the result of evaluation of some calculation. the curve should have value at zero. but in the plotting I can see there is a gap between the y-axis and the starting of the curve. how I can make the curve to reach y-axis. I already have a value of BER when x is zero, why it is not appear in the plot? 2- How I can make the value of y-axis to be like this: 10^-5, 10^-4, 10^-3, 10^-2, ... ? I mean not be like this 0.001, 0.01, ... 3- how to make the label axis position be in the centre of the axis not at the end? 4- how to show the grid in the plot background? Thanks ![Ploting BER vs SNR](http://i.stack.imgur.com/p0MFJ.jpg) **Edit:** here is a sample values of abep for the (0 to 40) SNR:               {0.263671, 0.223935, 0.186064, 0.151073, 0.119779, 0.092718, 0.0700926, 0.0517928,      0.0374553, 0.0265532, 0.0184883, 0.0126685, 0.00856004, 0.0057148, 0.00377648,       0.00247428, 0.00160959, 0.00104095, 0.000669973, 0.000429521, 0.000274496,       0.000174975, 0.000111307, 0.0000706891, 0.0000448341, 0.0000284057, 0.0000179819,       0.0000113756, 7.19252*10^-6, 4.5457*10^-6, 2.87193*10^-6, 1.81396*10^-6,       1.14549*10^-6, 7.23233*10^-7, 4.56569*10^-7, 2.88196*10^-7, 1.819*10^-7,       1.14801*10^-7, 7.24499*10^-8, 4.57204*10^-8, 2.88515*10^-8}


title: Simulation Sample Paths for Stochastic Approximation Algorithm

text: Let $X_t$ be IID random variables in $[0,1]$ and CDF $F(\cdot)$. Suppose there exists a variable $Y_t$ given by: $Y_1 = X_1$ and $Y_t = \phi(X_t, \overline{Y}_{t-1}), \forall t >1$, where $\overline{Y}_{t} = \frac{1}{t} \sum_{i=1}^{t} Y_i$ and $\phi^{\alpha} (x,y) = \left\\{ \begin{array}{l l} \alpha x & \quad \text{if $x < y$}\\\ x & \quad \text{if $x = y$}\\\ \alpha x + (1 -\alpha) & \quad \text{if $x > y$}\\\ \end{array} \right.$ I wish to run a simulation for 5 random walks (each with length 100) of $\overline{Y}_{t}$ where $X$ is drawn from a beta distribution with parameters (3,1) and $\alpha = 0.5$. Normally, we should observe a convergence to the mean of $X$, i.e. $\mathbb{E}[X]$. I have for $\phi^{\alpha} (x,y)$:               f[a_, {x_, y_}] := Piecewise[{{a x, x < y}, {x, x == y}, {1 - a + a x, x > y}}, 0]      My Beta distribution (with 100 iterations) can be expressed as:               RandomVariate[BetaDistribution[3, 1], 100]      I have difficulties to form the aggregation of data, and plot the evolution of $\overline{Y}_{t}$. Any help would be highly appreciated.               ListPlot[Table[<%simulated_data%>], PlotRange -> All, Joined -> True, Frame -> True]


title: What is the new command for AffineMap?

text: `AffineMap` was present in _Mathematica_ version 4. What is the equivalent command in the current version of _Mathematica_?


title: Generating a random sample of elements from a list that includes a subset of the list

text: Imagine I have a list: `tList = {item1,item2,item3,item4,item5,item6,...}`, and I'd like to take a random sample of `numItems` elements of the list: `RandomSample[tList,numItems]`. Is there a way to specify the random sample should contain some subset of the elements in `tList`, e.g. `{item65,item70,item2,...}`? The hope is then that all of the elements from the random sample are returned scrambled, including the order of the elements in the subset?


title: Bar chart labels disappear when PlotRange is used

text: I have used `Placed[Before]` to place labels on the labels before the bars, but when I specify a plot range, the labels disappear. I need a solution wherein I can use `PlotRange` and `Placed[Before]` without the labels disappearing.


title: Evaluating expressions stored in notebook from Java

text: The _Mathematica_ kernel can generally open a notebook and evaluate the functions present in the notebook using `UsingFrontEnd Command`. Example:               UsingFrontEnd[SelectionEvaluateCreateCell[nb];]      However, when I try from Java the following command, no action happens:               m1.evaluate("UsingFrontEnd[SelectionEvaluateCreateCell[nb];]");       Can anyone please explain how I can evaluate expressions in some notebook file through Java. Note: I have tried all options like `NotebookEvaluate`, `SelectionEvaluate`, etc. I have also tried different combinations of `SelectionMove`.


title: Combined Elliptic-Parabolic PDE in 1D

text: Here is an example of solving a system of parabolic and elliptic PDE: http://reference.wolfram.com/mathematica/tutorial/NDSolveDAE.html (see the subsection "Combined Elliptic-Parabolic PDE in 1D"). In this example the equation and the initial conditions don't depend on $x$. How can I change this solution for accounting dependence on $x$? Can this system be solved easier, just by using NDSolve? _Clarification:_ I have another problem described on the page PDE combined with ODE 1D, and in my problem the initial conditions depend on $x$.


title: Simplify Sin[x]/x to Sinc[x]

text: I have an expression in the form of $\tt \frac{Sin[x]}{x}$ that I would like to simplify to the form of `Sinc[x]`. I've tried the `Simplify`, `FullSimplify` and `TrigReduce`, but none of them work.               Simplify[Sin[x]/x]     FullSimplify[Sin[x]/x]     TrigReduce[Sin[x]/x]      all gives the result $\tt\frac{Sin[x]}{x}$. However               FullSimplify[Sin[x]/x == Sinc[x]]      gives `True`. I have two questions:   1. Is there a way to tell MMA that I prefer `Sinc[x]` than `Sin[x]/x`, so that it can simplify $\sin(x)/x$ to $\mathrm{sinc}(x)$?   2. How doees `TransformationFunctions` and `ComplexityFunction` work in `Simplify`? Could you give some examples and explanations of how to use them to control the form of the outcome expression? Can I use them to let _Mathematica_ apply my own defined simplify rules (for example in this case `Sin[x]/x -> Sinc[x]`)? I found their documents are difficult to understand for me. Thanks. * * * _**update**_ `FullSimplify[Sin[x]/x,ComplexityFunction->Composition[StringLength,ToString,InputForm]]` also doesn't work. However,               Composition[StringLength,ToString,InputForm][Sin[x]/x]      gives 8 which is larger than               Composition[StringLength,ToString,InputForm][Sinc[x]]      which gives 7.


title: MathLink c++ passing lists of real values simple example

text: So this may come down to me not being a very competent programmer but I am struggling with passing list from Mathematica via MathLink that aren't of integers. The final code I am hoping to get out of this will pass a list of values to a C++ function I have written and return a different list of values. I decided to learn slowly using the examples given in the Wolfram documentation center. I was able to write a simple function that received a list of integers...did some math on it...and returned a different list of integers. This worked great. If I tried to do this with a list of real values I kept getting a linker error. To simply things I removed the returning of a list of values and just decided to use the list as input and return a value. This resulted in the same linker error. I used the addtwo code from the MathLink examples supplied by Wolfram. The relevant portion of the code is:               #include "mathlink.h"     extern int sumlist(int *a, long alen);          int tot = 0;          int sumlist(int *a, long alen)     {                for(int i = 0;i<alen;i++)             {                 tot = a[i] + tot;                    }                return tot;      }      with a template file (*.tm)               :Begin:     :Function:       sumlist     :Pattern:        SumList[a_List]     :Arguments:      {a}     :ArgumentTypes:  {IntegerList}     :ReturnType:     Integer     :End:      This code works great and gives me my desired result. Now if instead I wish to pass a list of Real numbers as in the following.               #include "mathlink.h"     extern double sumlist(double *a, long alen);          double tot = 0.0;          double sumlist(double *a, long alen)     {                for(int i = 0;i<alen;i++)             {                 tot = a[i] + tot;                    }                return tot;      }      with a template file               :Begin:     :Function:       sumlist     :Pattern:        SumList[a_List]     :Arguments:      {a}     :ArgumentTypes:  {Real32List}     :ReturnType:     Real32     :End:      I am following the directions for the Command Line compiling for Microsoft visual studio from this page. I am using Microsoft visual studio 2013(which may be the problem as it technically isn't supported yet) Everything is fine until I run:               Link sumlist.obj sumlisttm.obj ml32i3m.lib /OUT:sumlist.exe      Which results in the follow error               sumlisttm.obj : error LNK2019: unresolved external symbol "float __cdecl     sumlist(float *,int)" (?sumlist@@YAMPAMH@Z) referenced in function "int __cdecl     _tr0(struct MLink *)"(?_tr0@@YAHPAUMLink@@@Z)     sumlist.exe : fatal error LNK1120: 1 unresolved externals      I have done some testing and determined that I get this error just by trying to pass the list of real values rather than integers regardless of what the function actually does. I have looked for examples of Mathematica/MathLink code and most of them only deal with lists of integers.


title: FrameStyle in Inset with Framed expression

text: I am creating some plots that use `FrameStyle->AbsoluteThickness@5` and `PlotStyle->AbsoluteThickness@0.5`. In my plots' `Epilog` option, I want to use some `Inset[Framed@...,FrameStyle->AbsoluteThickness@0.5]` expressions. Upon exporting the graphics to PDF, I noticed that the `FrameStyle` option does nothing. This lead me to the following question on this site: Formatting `Framed` \- Some `FrameStyle` graphics directives don't work So I tried the following, to get a feeling for what `BoxFrame` does:               Plot[Sin[x], {x, 0, 2 Pi},      PlotStyle -> AbsoluteThickness@0.5,      Frame -> True,      FrameStyle -> AbsoluteThickness@0.5,      ImageSize -> 180,      Epilog -> {Inset[         Framed["sin(x)", BoxFrame -> {{0.1, 0.5}, {5, 0}}],         {3/2 Pi, 0.5}]}]      The resulting PDF looks like this: ![enter image description here](http://i.stack.imgur.com/cZSzN.png) It seems like only integer numbers work in the `BoxFrame` option. But how can I make the frame thinner? Especially, how can I make it exactly 0.5 pt thick?


title: Importing data from Excel for DateListPlot

text: I am importing data from Excel and plotting it with `DateListPlot`. My code is               DateListPlot[{       Join @@ Import[""][[1 ;;, 3 ;;]][[All, All, 2 ;; 3]],        Join @@ Import[""][[1 ;;, 3 ;;]][[All, All, 4 ;; 5]]},        Joined -> True,        FrameTicks -> All]      But my problem is this works for just for the first sheet (year 2013) of the many in the same file. Sheet 2 is for Year 2012 and has the same format, and so forth. I want to get all the sheets for all the years; they are continuations of each other. Could you help me to figure out what code will do this?


title: How to enter arrows in Notation function?

text: It is not clear, what symbol is used in Notation function description for arrows? How to enter it in textual mode within Workbench? Here: http://reference.wolfram.com/mathematica/Notation/ref/Notation.html


title: Labeling a grid

text: I have               m = {{0, -1, -2, -3, -4}, {1, 0, -1, -2, -3}, {2, 1, 0, -1, -2}, {3,          2, 1, 0, -1}, {4, 3, 2, 1, 0}};      And a grid `Grid[m,Frame->All]` I would like to label the grid such that every column has a number above it and every row has a number to its side. This is what I've currently managed to do.               Labeled[Grid[m,Frame->All],{Y:{1,5},X:{1,5}},{Left,Top}]       How can I label the grid appropriately?


title: Write-protect documentation for self-written Add-on package

text: My package works fine so far, and now I want to add some documentation. I have put a file in `FileNameJoin[{ $UserBaseDirectory, "Applications", "myPkg", "Documentation", "English", "Guides", "TableOfContents.nb"}]`. The content of the notebook is:                   Notebook[{Cell["Table of Contents for pkgTools", "TOCDocumentTitle",             ShowGroupOpener -> False, TextAlignment -> Center], Cell[TextData[             ButtonBox["Tutorial: CodingStandards", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/CodingStandards"]]],             "TOCChapter", ShowGroupOpener -> True], Cell[TextData[             ButtonBox["Tutorial: CreateNewApplication", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/CreateNewApplication"]]],             "TOCChapter", ShowGroupOpener -> True], Cell[TextData[             ButtonBox["Tutorial: ToDoList", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/ToDoList"]]], "TOCChapter",             ShowGroupOpener -> True]}, StyleDefinitions ->            FrontEnd`FileName[{"Wolfram"}, "Reference.nb"]]      Now when I load the package, it appears in the Function navigator under "Add- Ons". When I click on it, the notebook opens. But it gets immediately the "modified" Tag, which is confusing to users of the package who just want to read the documentation. Is there a way to write-protect the documentation notebook?


title: Importing a named range of cells from Excel

text: I have a macro (is that what you call it?) set up in _Mathematica_ and it runs fine. What I want to do now is set up my notebook to look through an Excel document (.xlsx) and pick out a certain set of cells that I named in Excel using the name manager. How do I get _Mathematica_ to import that Named Range? Also I have noticed that _Mathematica_ will not recognize every excel document and I have checked to make sure that the file is an xlsx file and still _Mathematica_ tells me that the file can't be opened as an xls. So two problems.   1. _Mathematica_ doesn't accept every file name I give it and reports the it cannot be imported in XLS format.   2. How to I import a named cell from Excel without having to use row and column descriptors? Per request here is what I have tried so far               Import["NajaK5uLData.xls"]      > Import::nffil: File not found during Import. >>   >  $Failed               Import[NotebookDirectory[] <> "NajaK5uLdata.xlsx"]      > Import::fmterr: Cannot import data as XLS format. >>   >  $Failed


title: Can I use boolean parameters in LogitModelFit?

text: For example, to use `1` as `True` and `0` as `False`:               LogitModelFit[{{300, 0, 0}, {400, 0, 0}, {450, 1, 0}, {460, 1, 1}}, {x, y}, {x, y}]      where `y` is boolean parameter.


title: Change the inner color of markers

text: I would like to have a marker with white as its inner color, to be able to make this kind of graph: ![enter image description here](http://i.stack.imgur.com/OIQFn.png) If I use `PlotMarkers -> Style["\[FilledSquare]", White]`, it changes both the inner color + border color but not the inner color only. If I use `PlotMarkers -> Style["\[EmptySquare]", White]`, the line of the curve goes above the marker. How could I achieve that?


title: Fit convoluted Gaussian and Lorentzian functions to a peak profile

text: Thanks in advance for anyone who read this. I have a peak profile `data` like this:               DD = 100; theta2B = 13.742; Lamda = 0.999047433;     ϕ[DD_, theta2_] := 2 Pi DD (Sin[theta2/360*Pi] - Sin[theta2B/360*Pi]) /Lamda;     profile = 1/ϕ[DD, theta2]^2 - Sin[2 ϕ[DD, theta2]]/ϕ[DD, theta2]^3 + (     1 - Cos[2 ϕ[DD, theta2]])/(2 ϕ[DD, theta2]^4);     data = Transpose[{Table[i, {i, 7, 20, 0.01}],      Table[profile, {theta2, 7, 20, 0.01}]}];     ListPlot[data, PlotRange -> All]      And I have _Gaussian_ , _Lorentzian_ , and _Hat_ functions like this:               GUA[x_] := PDF[NormalDistribution[13.742, fwhm1/Sqrt[8 Log[2]]], x]     LUA[x_] := PDF[CauchyDistribution[13.742, fwhm2/2], x]     HAT[x_] := UnitStep[x + fwhm3/2] - UnitStep[x - fwhm3/2]      Now I want to fit the convolution of `GUA[x]`, `LUA[x]`, and `HAT[x]` to above peak profile `data`. The `fwhm1` `fwhm2` and `fwhm3` need be defined from the best fitting. Does anyone know how to do this? Thanks very much. P.S. I searched the documentation centre and found that the function `Convolve` cannot generate an analysis formula of `GUA[x] * LUA[x] * HAT[x]` (* is convolution).


title: Annoying window. How to remove it?

text: ![How do I remove this wondow from my mathematica?](http://i.stack.imgur.com/1CRkn.jpg) How do I remove this window from my _Mathematica_?


title: Integrate returns unexpected result

text: Consider the following function $$g(x,y):= \frac{1}{( (1+y)^2+x^2 )( 1+ax^2y^2 )^2}$$, where I assume that $y\geq 0$ and $a\in (0,1]$ is a parameter. When I try to evaluate the integral $\int g(x,y)\,dx$ using Mathematica I get the following result: $$ \frac{\frac{axy^2(-1 + ay^2(1 + y)^2)}{(1 + ax^2y^2)} + \sqrt{a}y(-3 + ay^2(1 + y)^2)\arctan(\sqrt{a}xy) + \frac{2\arctan(\frac{x}{1 + y} )}{ 1 + y} }{2(-1 + ay^2(1 + y)^2)^2} $$ This result cannot be the correct primitive of $g(\cdot,y)$, since on the one hand the denominator is always has a positive root but the numerator is positive, and on the other hand we have that $$0\leq g(x,y)\leq \frac{1}{1+x^2 }$$ which implies that $g(\cdot,y)$ is Riemann integrable for all $y\geq 0$. Could someone please tele me how to obtain a correct answer to the problem? This would be very much appreciated! Code:               Integrate[1/(((1+y)^2+x^2)*(1+a*x^2*y^2)^2),x]      Output: > ((a x y^2 (-1 + a y^2 (1 + y)^2))/(1 + a x^2 y^2) + Sqrt[a] y (-3 + a y^2 (1 > + y)^2) ArcTan[Sqrt[a] x y] + ( 2 ArcTan[x/(1 + y)])/(1 + y))/(2 (-1 + a y^2 > (1 + y)^2)^2)


title: Deploy a dynamic report

text: What does it take to deploy a report to the Wolfram Cloud? I would like to deploy _the generated notebook_ (not the notebook with the slots) to a public URL so my customer can access it. Every time the URL is accessed the data within the slots should be updated. All of this works on my desktop but I don't see the documentation regarding the deployment of the dynamic report.


title: Benefit of using Dataset to collect SQLSelect output

text: Considering a `DatabaseExample` included with _Mathematica_ :               Needs["DatabaseLink`"]     conn = OpenSQLConnection["publisher"];     SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True]//Short      > > `{{TITLE_ID,LORANGE,HIRANGE,ROYALTY},{BS1011,0,5000,0.1},<<49>>,{PY2008,0,50000,0.1}}` Now with the introduction of v10 and functions such as `Association` and `Dataset`, we can convert this data to a `Dataset`:               sqltodataset[fields_, data_] /; Equal @@ Join[{Length@fields}, Length /@ data] :=      Dataset[Association[Thread[fields -> #]] & /@ data]               data = SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True];     ds = sqltodataset[First@data, Rest@data];      Querying should now be much faster:               Do[SQLSelect[conn, "ROYSCHED", {"ROYALTY"}, SQLColumn["TITLE_ID"] == "BS1001"], {100}] // Timing     Do[Normal[Select[ds, #"TITLE_ID" == "BS1001" &][[All, "ROYALTY"]]], {100}] // Timing      And it seems to be. Although not quite a fast as I expected: > `{0.171601,Null}` > > `{0.093601, Null}` But at the expense of RAM:               ByteCount[ds]      > `35644` Is there a real upside to converting to a `Dataset`, or should I just stick to SQL to query? And is there a more direct way to convert straight to a `Dataset`?


title: How to change the font of a color bar?

text: When using `DensityPlot` or similar, I want to change the font size of both frame labels and the color bar legend, but I can only get the frame labels to work. Example:               DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, PlotLegends -> Automatic,      BaseStyle -> {FontSize -> 30}]      ![enter image description here](http://i.stack.imgur.com/pSXx0.png)


title: Export dataset to JSON

text: I'm experiencing a weird issue. Consider a dataset defined like this:               dataset = Dataset[{<|"a" -> 1, "b" -> 2|>, <|"a" -> 3, "b" -> 4|>}];      Now I would expect `Export["test.json", dataset]` to create a JSON file with these contents:               [{"a": 1, "b": 2}, {"a": 3, "b": 4}].      Instead, the command returns > Export::badval: The element Data contains invalid values. >>. A workaround is to run               Export["test.json", Normal[Normal[dataset]]]       but that seems merely a workaround. Is there anyone here who knows a neat solution?


title: Median of Dataset in Mathematica 10

text: I'm having trouble calculating the median of a `Dataset[]` in Mathematica 10. The situation is as follows. Consider a dataset that was defined as follows:               dataset = Dataset[{<|"a"->1,"b"->2|>,<|"a"->3,"b"->4|>}];      The mean and variance of columns `a` and `b` can now be calculated by               mean = dataset[Mean, {"a","b"}]     var = dataset[Variance, {"a","b"}]      That works pefectly, but               med = dataset[Median, {"a","b"}]      returns a `Failure[]`! Somehow, `Median[]` is not compatible with a list of associations as its argument and the other functions are. Can someone explain why this happens and maybe help with a solution?


title: Is it possible to save an interrupted computation?

text: I've got this really time consuming factoring problem. To decouple things a bit, I decided to start _Mathematica_ using the command line interface (under screen).               $ math      So my code is running, and I know that I can interrupt it with `Ctrl`-`C`, but what I want to do is interrupt it, and then write the state of the process to disk, so that I can reboot. On Linux, there is a program called CryoPID which might work. Unfortunately, my computation is running on OS X. I can detach from the screen session and re-attach to it, but if I reboot the machine I know it'll lose memory and the computation progress so far. My question is: can you save the state of a _Mathematica_ computation that you interrupt (to disk and reloadable after a restart). Thanks.


title: Solving a two point boundary problem for a piecewise system of equations

text: I'm trying to solve a two point boundary value problem with a piecewise system of equations like:               dx[t_] := Piecewise[{{0, y[t] <= 0}, {x[t]^(3/4) - x[t], y[t] > 0}}]     dy[t_] := Piecewise[{{0, y[t] <= 0}, {(1 - y[t])/x[t]^(1/4) + y[t], y[t] > 0}}]          NDSolve[{x'[t] == dx[t], y'[t] == dy[t], x[0] == 1, y[10] == 2}, {x, y}, {t, 0, 10}]      which produces the error                NDSolve::bvdisc: NDSolve is not currently able to solve boundary value problems with discrete variables.      I tried the answers here by entering               funs = ParametricNDSolveValue[{x'[t] == dx[t], y'[t] == dy[t], x[0] == 1, y[10] == yt}, {x, y}, {t, 0, end}, yt]          FindRoot[funs[yt][end], {yt, 2}]      which yields the same error. Is there any way to solve this system? Thanks for the help.


title: Clear inside a loop

text: I want to solve a system of differential equations and each time I want to change two parameters. To prevent wrong result I want to clear every assignment after solving the equations in each iteration. I have a `Do`-loop with two iterator. The problem is that if I use `Clear["Global`*"]` then the outer iterator will not be accessible to the code inside the loop. Here is an example:               Do[{Print[a]; Clear["Global`*"];}, {a, 1, 2}, {b, 1, 2}]      Result: > >     1 >   >     a >   >     2 >   >     a >   As you can see the iterator `a` is erased for the inner iterator `b`. How can I resolve this issue? I expect the outer iterator to be printed each time. There are 4 iteration in total, so I expect to get: > >     1 >     1 >     2 >     2 >   I want both iterators, a and b, in spite of using Clear command to be accessible to the code inside loop. I want to clear everything after each iteration except iterators a and b.


title: How do I union graph properties?

text: I have two graphs               g1 = Graph[{"1", "2", "3"}, {{2, 1}, {3, 1}},VertexLabels -> {"1" -> Placed["One", Tooltip], "2" -> Placed["Two", Tooltip], "3" -> Placed["Three", Tooltip]}]      and               g2 = Graph[{"5", "2", "3"}, {{2, 1}, {3, 1}}, VertexLabels -> {"5" -> Placed["Five", Tooltip], "2" -> Placed["Two", Tooltip], "3" -> Placed["Three", Tooltip]}]      Each of which displays the appropriate label when doing a mouseover. Then I do               GraphUnion[g1,g2]      and get the desired graph, but the tooltips for the vertex names are gone. If I do               GraphUnion[g1,g2,Options[g1]]       then as expected I get the tooltips for the vertices of g1. But how can I get the tooltips for ALL the vertices (i.e. vertices for both graphs)? Thanks much!


title: Problem with ContourPlot3D

text: The following line works fine:               ContourPlot3D[2 x - y == 0, {x, -10, 10}, {y, -10, 10}, {z, -10, 10},                   ContourStyle -> Opacity[0.5], Mesh -> False]      But when I bind the equation `2 x - y == 0` to a variable `eq`:               eq = 2 x - y == 0     ContourPlot3D[eq, {x, -10, 10}, {y, -10, 10}, {z, -10, 10},                    ContourStyle -> Opacity[0.5], Mesh -> False]      it fails. I also noticed that values are assigned to variables x and y after executing ContourPlot3D. There's something that I don't understand about workings of `ContourPlot`. Could anyone explain what's going on and how should I pass the equation in a variable? **UPDATE** As **m_goldberg** wrote in his answer, in a bug-free Mathematica it is not necessary to defer evaluation so `eq = 2 x - y == 0` works fine. The call to `Evaluate` is still required. But it seems to me that `eq` and `2x - y == 0` should evaluate to the same expression:               In[33]:= eq === 1 + 2 x == 0     Out[33]= True      So what's difference between these two expressions, which causes them to behave differently in `ContourPlot3D`? How can I see this difference in Mathematica environment?


title: Use different ColorFunction for each function plotted

text: When plotting two curves on one plot, you can specify different colors for each function:               Plot[{Sin@x, Cos@x}, {x, 0, 4π},       PlotStyle -> {Red, Blue}]      ![Mathematica graphics](http://i.stack.imgur.com/S9XKP.png) To plot the curves using different `ColorFunction`s, you can manually combine the plots:               Show[      Plot[Sin@x, {x, 0, 4 \[Pi]},       ColorFunction -> ({x, y} \[Function] Opacity[y, Red])],      Plot[Cos@x, {x, 0, 4 \[Pi]},       ColorFunction -> ({x, y} \[Function] Opacity[y, Blue])]      ]      ![Mathematica graphics](http://i.stack.imgur.com/ZZeIM.png) But if you try to combine them into one `Plot[]` expression, it doesn't work:               Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]},      ColorFunction -> {({x, y} \[Function]           Opacity[y, Red]), ({x, y} \[Function] Opacity[y, Blue])}]      ![Mathematica graphics](http://i.stack.imgur.com/hN4mF.png) How can you easily plot multiple curves, specifying the `ColorFunction` to use for each?


title: Implementing local complements of graphs

text: I'm trying to write a routine which generates the local complement of a graph at a vertex. For those who don't know, the local complement for a singly- connected, undirected graph is defined as the graph where for all vertices adjacent to the selected one, two of them have an edge exactly if they don't have in the original one (in other words, the subgraph containing only the adjacent edges). All other edges, including those connecting the selected vertex with its adjacent vertices, are unchanged. For example,               LocalComplement[Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1}], 1]      should give > >     Graph[{1 <-> 2, 3 <-> 1}] >   and               LocalComplement[Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 1}], 1]      should give > >     Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 1, 2 <-> 4}] >   Here's what I've tried:               LocalComplement[g_,v_]:=Module[{h=VertexDelete[NeighborhoodGraph[g,v],v]},       GraphUnion[GraphDifference[g,h],GraphComplement[h]]]      The idea is simple: First I determine the neighbourhood of the selected vertex. Since Mathematica includes the vertex in the NeighborhoodGraph, I remove that. Then I remove the original subgraph `h` from `g` and add the complement of `h`. This works well with the first example above, but for the second example, the same graph is returned, without the additional edge. Therefore I'd like to know:   * Why does my code not work as expected?   * And of course: How can I fix it?


title: Easiest Way to Use ShowGroupOpener in Mathematica

text: I currently edit manually the cell contents of a notebook (Ctrl+Shift+A or Cmd+Shift+A) to "recycle" cells containing the ShowGroupOpener option. Is there an easier way to create documents hiding contents under that type of icon?


title: Export different simulation parameters and results to same file

text: I have a simulation, and I would like to export the parameters and results to a same spreadsheet without overwriting the previous values. if I have:               parameter1 = {0.1};     parameter2 = {0.2};     result1 = {10};     result2 = {20};      And if I export it I get that. But then if I change the parameters and run the simulation again, I would like these new values to go right after the ones I had previously exported.               parameter1 = {0.1,0.3};     parameter2 = {0.2,0.2};     result1 = {10,25};     result2 = {20,30};      As a spreadsheet or a list with headings would be best. I saw an answer to a similar question recommended creating a spreadsheet beforehand and then defining the cells where the values should be exported to, but this would still rewrite the cells. I guess I could always manually change the location after each simulation. Maybe mathematica has some built-in function to do something like this? I am still very new, I apologize if this question is elementary or doesn't make sense. Any help is much appreciated!


title: Efficient export of complex graphics to PDF

text: So I have 2D plot, made with DensityListPlot. Mathematica just cannot export them properly to PDF, so what I want to do is 1) export the plot itself, without axes, labels, etc, as a jpg image, and 2) Inset this image in an empty graphics containing only axes, labels etc. So far so good. The problem is that when I export the final graphics to PDF, the image are not compressed at all -- and the file end up weighing 400k instead of 30k. The question is: how do I specify the format and compression factor of images embedded in a pdf?


title: How to calculate partial derivative of an unknown function

text: How can I force Mathematica to calculate symbolically the partial derivative of a function `u[x,y]` with respect to a variable `z = f(x, y)`, where f(x, y) is known? `u` is a function, defined on reals, taking real values. Same thing holds for `f`. I want to try different changes of variables in PDEs. An example of what I'm trying to achieve and why it's failing:               z = 2*x + y       > 2 x + y               D[u[x, y], z]      > General::ivar: 2 x+y is not a valid variable. >> > > D[u[x, y], 2*x + y] **EDIT** : It appears I have failed to convey the essence of the question. I am not asking _how_ to solve a PDE with Mathematica. I am asking how, given a transformation of the original variables, to calculate the partial derivatives with respect to the new variables. The PDE part is merely some context as to why I want to do this.


title: Why does NSum fail here?

text: I want to evaluate a sum of integrals; each integral has a pole on the real axis and I handle this via the Cauchy Principal Value $ f(E)=-\frac{a^2}{2q}\sum^{\infty}_{n=-\infty}\int^{\infty}_{-\infty}dr \exp{(-2iEr/q)}\frac{1}{\left[\sinh^2{(r)}-(\frac{rp}{q}+\frac{npP}{2})^2\right]} $ $a,p,q, E$ are constants. I should say first of all the following applies for $n\neq 0$, for zero $n$ I handle differently. For each $n$ and $E$ the denominator of the integrand has two poles on the real axis (amongst others in the complex plane I shall not be concerned with). I will use Mathematica's `FindRoot` to get the locations of these poles, since the equation whose root we need is transcendental. I will then use `NIntegrate` with the `CauchyPrincipalValue` method to evaluate the principle parts of my integral. To get the additional contribution from the $i\pi \times \text{residue}$ at each pole, I first use partial fractions on my integrand to obtain $ f(E)=-\frac{a^2}{4q}\sum^{\infty}_{n=-\infty}\int^{\infty}_{-\infty}dr \frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\left(\frac{1}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}-\frac{1}{\left[\sinh{(r)}+(\frac{rp}{q}+\frac{npP}{2})\right]}\right). $ Now the two poles for each $n,E$ are simple poles and providing we know their location (numerically via `FindRoot`) the residue is easy to compute for each. For example, considering the first term in the integrand $-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{1}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}$ and say we have numerically found the root to be at $r_0$ for this piece, then $\text{Res}=\lim_{r\to r0}\left[-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{(r-r_0)}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}\right]$ $\text{Res}=\lim_{r\to r0}\left[-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{1}{\left[\cosh{(r)}-\frac{p}{q}\right]}\right]$ the second equality following from L'Hopital's rule. Note the zeroes of $\left(\frac{rp}{q}+\frac{npP}{2}\right)$ are not really poles when the full expression is considered together as further above. There will be a similar residue from the other piece, and we must add $i\pi\times$ both of these residues to our PV. **Mathematica Implementation**               (*some constants and definitions*)     M = 1;     R = 10 M;     wp = 40;     ag = wp - 8;     pg = wp/2;     a = 1/(4 M) Sqrt[R/(R - 2 M)];     p = 1/(4 M) Sqrt[(M R)/((R - 2 M) (R - 3 M))];     q = 1/(4 M) Sqrt[R/(R - 3 M)];     P = 2 Pi Sqrt[(R^2 (R - 2 M))/M];          (*find the poles for each n,E*)          findNroots[n_?IntegerQ, x0_?NumericQ] := Block[{rM, rP, roots},      rP = r /. FindRoot[Sinh[r] + ((r p)/q + (n p P)/2) == 0, {r, x0}, PrecisionGoal -> pg, WorkingPrecision -> wp][[1]];     rM = r /. FindRoot[Sinh[r] - ((r p)/q + (n p P)/2) == 0, {r, x0}, PrecisionGoal -> pg, WorkingPrecision -> wp][[1]];     roots = {rP, rM};     roots       ]          (*integrate for given n, E, summing PVs and residues*)           integrator[n_ /; n != 0, En_?NumericQ] := Block[{rtM, rtP, lowRoot, highRoot, mid, tmp1, tmp2, tmp3, tmp4, sum},           rtP = findNroots[n, 0][[1]];      rtM = findNroots[n, 0][[2]];      lowRoot = Sort[{rtM, rtP}][[1]];      highRoot = Sort[{rtM, rtP}][[2]];      mid = (highRoot + lowRoot)/2;  (*const somewhere in middle of two poles on real line*)           tmp1 = -a^2/(2 q) NIntegrate[ Exp[-2 I En r /q] (1/((Sinh[r])^2 - ((r p)/q + (n p P)/2)^2)), {r, -Infinity, lowRoot, mid}, Method -> {"PrincipalValue"}];      tmp3 = -a^2/(2 q) NIntegrate[Exp[-2 I En r /q] (1/((Sinh[r])^2 - ((r p)/q+ (n p P)/2)^2)), {r, mid, highRoot, Infinity}, Method -> {"PrincipalValue"}];           (*add residues too:*)      tmp2 = I Pi ( -a^2/(4 q) Exp[-2 I En rtM /q] 1/((rtM p)/q + (n p P)/2) ) Limit[1/( Cosh[r] -  p/q), r -> rtM];      tmp4 = I Pi ( -a^2/(4 q) Exp[-2 I En rtP /q] 1/((rtP p)/q + (n p P)/2) ) Limit[-1/( Cosh[r] +  p/q), r -> rtP];           sum = tmp1 + tmp2 + tmp3 + tmp4;      {sum}      ]      This seems to work OK, I can do `Table[integrator[n,1],{n,1,100}]` and Mathematica seems to compute this list just fine. However if I do just`NSum[integrator[n,1],{n,1,2}]` then Mathematica will give all manner of complaints such as `NIntegrate::deorela`. Why is this when it is perfectly happy to compute the values of `integrator` in a list individually? Is there another way I should be performing this sum? A separate issue: I also find that at certain values of $n,E$ for example `integrator[1, 24]` I also get errors like `NIntegrate::deodiv: DoubleExponentialOscillatory returns a finite integral estimate, but the integral might be divergent` and I can't even compute the result individually let alone in `NSum`. I suspect this is because things become too oscillatory at higher values of $E$.


title: Simplify with Assumptions Sqrt[(expr)^2]

text: While trying to simplify expressions in the form `Sqrt[(expr)^2]` when `expr>0` I noticed a peculiar behavior that was not resolved with code from this Q&A.               Simplify[Sqrt[(x - y + a b c)^2], x - y + a b c > 0]      > >     Abs[a b c + x - y] >   When I remove any of the `a`, `b`, `c`, `x` or `y` it returns the result without the `Abs`:               Simplify[Sqrt[(x - y + b c)^2], x - y + b c > 0]      > >     b d + x - y >   I loose faith when I meet such behavior with Mathematica :-( Even though               Simplify[Sqrt[expr^2], expr > 0] /. expr -> (x - y + a b c)      does fix the first issue how could I simplify this:               Simplify[Sqrt[(x - y + a ^2 b^2 c^2)^2], x > y]      Anyway, can anybody explain why this happens and propose a way to fix it for general expressions?


title: Noticeable slowdown in graphical performance when using manipulate

text: I have been making these mathematica 3D objects that involve a molecule with some sort of surface displayed above them. This is done fairly easily by:               Molecule=Graphics3D[{{x,y,z},...},Sphere[1, .24]...,Cylinder[{1, 2}, .15]]     PES=ListPlot3D[{{x,y,z},...}]     Show[Molecule,PES]      A python script was pretty easy to whip this up for molecules; for me its better then the wolfram chemistry database because it is in better units (angstroms) and can be oriented easier. It works great, the objects manipulate smoothly. Now I wanted to do something that would have a very nice end product. Following the work of an online demonstration I started with the initialization code:               Molecule[coord_, conf_, col_, rad_, bondstyle_] :=        Module[{intconf, atomplot, tuples, bonds, bondplot},         intconf =          ReplacePart[conf,           Flatten@Table[# -> ii & /@ (Flatten@               Position[conf, DeleteDuplicates[conf][[ii]]]), {ii, 1,              Length@DeleteDuplicates[conf]}]];        atomplot = {col[[intconf[[#]]]],             Sphere[coord[[#]], rad[[intconf[[#]]]]]} & /@           Range[Length[intconf]];        tuples =          Select[Subsets[           Range[Length[             coord]], {2}], ((conf[[#[[1]]]] =!= "H" ||                conf[[#[[2]]]] =!= "H") &&              Norm[coord[[#[[1]]]] - coord[[#[[2]]]]] <=               bondstyle[[1]]) &];        bonds = coord[[#]] & /@ tuples;        bondplot =          Table[{col[[intconf[[tuples[[#, ii]]]]]],              Tube[{bonds[[#, ii]], .5*Total[bonds[[#]]]},               bondstyle[[2]]]} & /@ Range[Length[bonds]], {ii, 1, 2}];        {atomplot, bondplot}];     coord["Acrolein"] := {{-1.4373, -1.1224, 0.4127}, {0.1565,          0.3728, -0.3457}, {-1.1456, -0.2881, -0.399}, {1.0519, 0.0649,          0.6058}, {0.4003,          1.1146, -1.0773}, {-1.8435, -0.0263, -1.1667}, {0.8173, -0.6754,          1.3418}, {2.0003, 0.5599, 0.6283}};     conf["Acrolein"] := {"O", "C", "C", "C", "H", "H", "H", "H"};      I decided to use this since I can use Map to manipulate the position and scale of the object. Its really just a way to replace my python script. Surfaces were again easy to create with the Map just used to duplicate quadrants:               AcrWater=Import["xyzlist.csv"     surface["Acrolein", "Water"] =        ListPlot3D[Union[AcrWater, Map[#*{1, -1, 1} &, AcrWater]],         Mesh -> 3, ColorFunction -> "Rainbow", PlotStyle -> Opacity[0.9]];      This next part was just done in my experiments to make the graphics smoother:               graphic["Acrolein", "Water"] =        Show[          Graphics3D[{Specularity[White, 100],           Molecule[coord["Acrolein"], conf["Acrolein"],            ColorData["Atoms", #] & /@             DeleteDuplicates[             conf["Acrolein"]], {.4, .4, .4, .4}, {1.5, .193}]}],             surface["Acrolein", "Water"],             ImageSize -> {600, 600}, Background -> White, ViewPoint -> Top,         Axes -> True, Lighting -> "Neutral"];      Finally the manipulate argument:               Manipulate[      graphic[substance,        solvent], {{substance, "Acrolein", "Molecule"}, {"Acrolein"}},      {{solvent, "1C", "Solvent"}, {"Water"}}]      All of this works great together! The only problem is that manipulating the final product is incredibly slow even on a new, well equipped machine with the antialiasing all the way down. There in total will be about 30 different combinations and only implementing a single one shows significant degradation in the overall feel of the demonstration; adding more is even worse. This seems strange when it is done the previous way there is no noticeable lag even with much larger systems. My question is where is the major slowdown in this. It was my understanding that the vector objects were first evaluated then simply displayed by the manipulate command. If there is not an easy workaround is there another way to do this that can avoid the slowdown problem. Edit: Thank you for the tips so far dynamic and tracked symbols certainly made marked improvements. Here is a chunk of working code that will mimic what I am trying to do. This is a single example with with only 25 points for the surface (real surfaces will have 1000-2000). I am not entirely sure how to do it but a better way to recreate the surface using the proper notation of the data is [x,y,sin[x+y]] where and x and y run from 0-3 in steps of .1. Instead of Dynamic I also tried the Refresh command to no avail.:               Molecule[coord_, conf_, col_, rad_, bondstyle_] :=        Module[{intconf, atomplot, tuples, bonds, bondplot},         intconf =          ReplacePart[conf,           Flatten@Table[# -> ii & /@ (Flatten@               Position[conf, DeleteDuplicates[conf][[ii]]]), {ii, 1,              Length@DeleteDuplicates[conf]}]];        atomplot = {col[[intconf[[#]]]],             Sphere[coord[[#]], rad[[intconf[[#]]]]]} & /@           Range[Length[intconf]];        tuples =          Select[Subsets[           Range[Length[             coord]], {2}], ((conf[[#[[1]]]] =!= "H" ||                conf[[#[[2]]]] =!= "H") &&              Norm[coord[[#[[1]]]] - coord[[#[[2]]]]] <=               bondstyle[[1]]) &];        bonds = coord[[#]] & /@ tuples;        bondplot =          Table[{col[[intconf[[tuples[[#, ii]]]]]],              Tube[{bonds[[#, ii]], .5*Total[bonds[[#]]]},               bondstyle[[2]]]} & /@ Range[Length[bonds]], {ii, 1, 2}];        {atomplot, bondplot}];     coord["Acrolein"] := {{-1.4373, -1.1224, 0.4127}, {0.1565,          0.3728, -0.3457}, {-1.1456, -0.2881, -0.399}, {1.0519, 0.0649,          0.6058}, {0.4003,          1.1146, -1.0773}, {-1.8435, -0.0263, -1.1667}, {0.8173, -0.6754,          1.3418}, {2.0003, 0.5599, 0.6283}};     conf["Acrolein"] := {"O", "C", "C", "C", "H", "H", "H", "H"};          AcrWater :=       Table[Sin[j + i] + 2, {i, 0, 2 Pi, Pi/4}, {j, 0, 2 Pi, Pi/4}]          surface["Acrolein", "Water"] :=        ListPlot3D[AcrWater, Mesh -> 3, ColorFunction -> "Rainbow",         PlotStyle -> Opacity[0.9]];          graphic["Acrolein", "Water"] :=        Dynamic[Show[         Graphics3D[{Specularity[White, 100],            Molecule[coord["Acrolein"], conf["Acrolein"],             ColorData["Atoms", #] & /@              DeleteDuplicates[              conf["Acrolein"]], {.4, .4, .4, .4}, {1.5, .193}]}],          surface["Acrolein", "Water"], ImageSize -> {600, 600},          Background -> White, ViewPoint -> Top, Axes -> True,          Lighting -> "Neutral"], None];          Manipulate[      graphic[substance,        solvent], {{substance, "Acrolein",         "Molecule"}, {"Acrolein"}}, {{solvent, "Water",         "Solvent"}, {"Water"}}, TrackedSymbols :> {substance, solvent}]


title: Making cells group

text: After reading rcollyer's post I'm still not able to understand how grouping rules work. Here is a problem I'm facing. What I want is to create a new title, section and subsection styles. I want the title to group everything below till the next title. The section should group everything below till the next section. To see what I mean, open up a new notebook. Go to `Format > Edit Stylesheet...`. On this stylesheet make a new cell. Then select this cell and go to `Cell > Show Expression`. Here enter the following:               Cell[StyleData["MyTitle"],      CellGroupingRules->{"MyTitleGrouping", 0},      CounterIncrements->"MyTitle",      CounterAssignments->{{"MySection", 0}, {"MySubsection", 0}},      FontSize->26,     ]       Once this has been entered now go to `Cell > Show Expression` to revert back. Let us create two more cells in the same fashion, one for the section and subsection.               Cell[StyleData["MySection"],      CellGroupingRules->{"MyTitleGrouping", 10},      CounterIncrements->"MySection",      CounterAssignments->{{"MySubsection", 0}},      CellFrameLabels->{{         Cell[          TextData[           CounterBox["MySection"], " -"], CellBaseline -> Baseline], Inherited}, {        Inherited, Inherited}},      FontSize->20,     ]      Finally, the subsection:               Cell[StyleData["MySubsection"],      CellGroupingRules->{"MyTitleGrouping", 20},      CellFrameLabels->{{         Cell[          TextData[           CounterBox["MySection"], ".",            CounterBox["MySubsection"], " -"], CellBaseline -> Baseline],          Inherited}, {Inherited, Inherited}},      CounterIncrements->"MySubsection",      FontSize->16,     ]      After creating those new styles, now we can use them, here is a screenshot of what I obtained if I use the "MyTitle", "MySection" and "MySubsection" styles. ![enter image description here](http://i.stack.imgur.com/zh8fg.png) Don't mind the text I entered there. The main point here is that there is no grouping. How can I make it behave as the regular "Title", "Section" and "Subsection" styles? ![enter image description here](http://i.stack.imgur.com/t7Rxh.png)


title: How to Export Data from Mathematica into Excel specific cell

text: for import,we can do like this Import["XXX.xlsx", {"Data",1,2,3}],Mathematica will get the cell {2,3} of the "sheet1" in "XXX.xlsx". But if we want to export data from Mathematica to one Excel specific cell,How to realize?


title: Define a function with a function for an input

text: I want to create the functions $even[f]$ and $odd[f]$ which will apply the formula $even[f(x)] = \frac{f(x)+f(-x)}{2}$ and $odd[f(x)]=\frac{f(x)-f(-x)}{2}$ for an arbitrary $f$. I tried using               even[ff, x_] := (ff[x] + ff[-x])/2      But that doesn't seem to work. What would the correct approach to this be?


title: How do I get a MeshRegion from an obj file, or from Geometry3D

text: How do I read in an obj file as a `MeshRegion` so I can e.g. compute its area? If I just import the object and try `Area[O]` it tells me it is not a correctly specified region, even for e.g. the StanfordBunny. Also, how do I turn `Geometry3D` into a `MeshRegion`? For example `Area[ExampleData[{"Geometry3D", "SpaceShuttle"}]]` does not work either. It seems that geometry has more than one representation in different parts of _Mathematica_ \- bad.


title: When I use Rule, why doesn't this work?

text: k.k.k //. {k.k -> k}      works perfectly, so the output is just `k`. But, when I use `Esc`.`Esc` (center dot, CenterDot[k,k]) instead of . (comma),               k Esc.Esc k Esc.Esc k //. {k Esc.Esc k -> k}      does not work while               k Esc.Esc k //. {k Esc.Esc k -> k}      works. How can I fix this problem?


title: How to make a CDF document with dynamic content?

text: I would like to create a CDF document that uses dynamic content. The example code is:               fun=x^2-1;     InputField[Dynamic[fun]]      And what I get is $Aborted instead of interactive document. How to make a useful document? EDIT: What I am really trying to do is to make a CDF document in which the given function is plotted. Initially the function is x^2-1, but the user should be able do input any function.


title: Export a simple DataSet with key-value associations to CSV in Mathematica 10

text: I'm trying to Export a simple dataset with key-value pairs to a CSV               Export["n.csv", MyDataset, "CSV"]      This results in a single-line serialization:               Dataset[<|"A" -> 3757, "B" -> 426, "C" -> 193, ...."D" -> 1|>, TypeSystem`Assoc[TypeSystem`Atom[String], TypeSystem`Atom[Integer], 15], <|"Origin" -> HoldComplete[Sort[Dataset`DatasetHandle[265575026537634], Greater]], "ID" -> 109770792907938|>]      The desired result is:               A,3757     B,426     C,193     ...     D,1


title: Why are the attributes of Plot changing?

text: In version 9, with a newly started _Mathematica_ session, try the following code:               plotAttributes = Attributes[Plot]          Plot[Sin[x], {x, 0, 1}];          Attributes[Plot]          % == plotAttributes      > `{Protected, ReadProtected}` > > `{HoldAll, Protected, ReadProtected}` > > `False` Is there any explanation why `Plot` doesn't have `HoldAll` as one of its attributes when a fresh _Mathematica_ session is started, and acquires this attribute only after I call `Plot` once?


title: How can I get every distinct size-n combination of a list?

text: Let's say I have a list:               {a, b, c}      I would like to, for say $n=2$ get every distinct pair from that list. That is, the expected result should be, for some function `choose`:               choose[{a, b, c}, 2]     (* {{a, b}, {a, c}, {b, c}} *)      My attempt at this was like so:               choose[list_, n_] :=         DeleteDuplicates[Permutations[list, {n}], Union[#1, #2] == #1 &]      And it does give the expected result for this example. There are, however, some problems in which I would like some help addressing:   1. `Permutations` creates more combinations that I need, which forces me to use `DeleteDuplicates`. Is there away to directly arrive at all combinations?   2. The `DeleteDuplicates` operation is very costly. Is there a way I could use the structure of the `Permutations` result to my advantage to get rid of the unwanted repeats?   3. My function DOES make an error when there are supposed to be _intended_ repeats. For instance, `choose[{b, b, c}, 2]` should give `{{b,b}, {b, c}, {c, b}}` \- as every element in the list is considered "distinct" even though the values could be equal - but instead, the duplicate deletion removes the `{c, b}`. **EDIT** I have figured out a way to address #3. If I create a symbolic list `tempList` in which every element is unique, then replace that with the list, I am able to preserve "distinct" combinations even though they have the same value:               choose[list_, n_] :=         With[{tempList = Array[Unique[] &, Length@list]},              DeleteDuplicates[             Permutations[tempList, {n}],              Union[#1, #2] == #1 &] /. Thread[tempList -> list]]      However, there's still room for improvement as having to use the replacement is not great for larger `list` lengths and values of $n$.


title: Triangle that collapse cells

text: I'm not very good in English , so is hard to explain but how put the triangle in the left that deploy or collapse a group of cells ?


title: Series expansion with irrational power

text: I need the series expansion of a fairly nasty function and its derivative:               f = (x - a) (1 + b (1/(x - a))^((5 + Sqrt[73])/12) *        Hypergeometric2F1[(-7 + Sqrt[73])/12, (1 + Sqrt[73])/12, (        6 + Sqrt[73])/6, -(a/4)/(x - a)]) + a/2      $f\left(x\right) = (x-a) \left(1+b \left(\frac{1}{x-a}\right)^{\frac{1}{12} \left(5+\sqrt{73}\right)} \, _2F_1\left(\frac{-7+\sqrt{73}}{12} ,\frac{1+\sqrt{73}}{12} ;\frac{6+\sqrt{73}}{6} ;-\frac{a}{4 (x-a)}\right)\right)+\frac{a}{2}$ where $x$, $a$ and $b$ are positive real numbers and I know $x \gg a$. I'm interested in the series expansion of $f$ and $f'$ in inverse powers of $x$:               Series[f, {x, \[Infinity], 1}] // Normal      $\dfrac{b \left(\dfrac{1}{x-a}\right)^{\dfrac{\sqrt{73}}{12}}}{\left(\dfrac{1}{x}\right)^{7/12}}-\dfrac{a}{2}+x$               Series[D[f, x], {x, \[Infinity], 1}] // Normal      $b \left(\dfrac{1}{x}\right)^{5/12} \left(\dfrac{1}{x-a}\right)^{\dfrac{\sqrt{73}}{12}}+1$ The problem is I can't figure out how to get this to simplify any further. I need to get these in the form $ c_1 x + c_0 + \dfrac{c_{-1}}{x^{p}} $ for some constants $c_i$ and $p$, but `Series` doesn't expand the term with $x-a$ in the denominator. I guess because the power is irrational? How can I get the answer in the desired form? I could do it by pen and paper of course, but I would love to have it in code. Using `Assumptions -> {x > a > 0, b > 0}` doesn't seem to make any difference. Any help is appreciated.


title: Evaluation of second argument to NIntegrate

text: Apologies if this is a duplicate, but I couldn't find it. The expression               Integrate[x^2, Flatten[{{x},{1,2}}]]      evaluates properly, to $\frac{7}{3}$. However,               NIntegrate[x^2, Flatten[{{x},{1,2}}]]      returns               NIntegrate::vars: Integration range specification Flatten[{{x},{1,2}}] is not of the form {x, xmin, ..., xmax}. >>      An explicit `Evaluate` is required on the second parameter to make this work. So I assume that NIntegrate has a `HoldAll` on its second parameter. Did I have any way of knowing this before hand? That is, is this behavior documented? And, if it is (or even if it is not), why do the two functions behave differently?