title: Simplifying numerical expressions involving special functions

text: I've encountered the following problem. There is the identity that the special functions `EllipticK[x]` and `EllipticE[x]` satisfy: $$K(x)E(1-x)+E(x)K(1-x)-K(x)K(1-x)=\frac{\pi}{2}$$ _Mathematica_ does not seem to know it so I included it into assumptions:               $Assumptions = EllipticK[x] EllipticE[1 - x] + EllipticE[x] EllipticK[1 - x] -                    EllipticK[x] EllipticK[1 - x] == Pi/2      If I now evaluate               Simplify[EllipticK[x] EllipticE[1 - x] + EllipticE[x] EllipticK[1 - x] -             EllipticK[x] EllipticK[1 - x]]      I will get `Pi/2`, fine. The problem is that I want this identity to be used not only symbolically but also numerically, i.e. for example I would like _Mathematica_ to simplify               Simplify[EllipticE[2/3] EllipticK[1/        3] + (EllipticE[1/3] - EllipticK[1/3]) EllipticK[2/3]]      down to `Pi/2`. Not only It does not happen when I just stated this identity symbolically but even direct evaluation with this assumption does not yield desirable answer. Namely,               FullSimplify[      EllipticE[2/3] EllipticK[1/         3] + (EllipticE[1/3] - EllipticK[1/3]) EllipticK[2/3],       Assumptions ->        EllipticE[2/3] EllipticK[1/           3] + (EllipticE[1/3] - EllipticK[1/3]) EllipticK[2/3] == Pi/2]      returns               EllipticE[2/3] EllipticK[1/        3] + (EllipticE[1/3] - EllipticK[1/3]) EllipticK[2/3]      How can I get `Pi/2` there instead?


title: How do I show cross sections of a basic shape using calculus?

text: Assume I have an object whose radius is modeled by the function $x^2$. Using calculus and circular cross-sections, the object's volume is given by $\pi\int_a^b(x^2)^2dx$. But given an arbitrary function $f(x)$, how do I illustrate circular cross sections on an interval?


title: Rotation of Graphics3D like rotating Plot3D

text: I like the way 3D plots are rotated with the z-axis always pointing up-down. Is there an elegant way of forcing that type of rotation on Graphics3D? I have tried the following:   1. Using an invisible locator and mapping the position to a specific viewpoint. That works, but behaves strangely (from the users perspective) because the graphics rotates as soon as the mouse is clicked and not the 'click-drag'-way, that you would expect, due to the locator jumping.   2. Using 'Show' to combine the Graphics3D with a Plot3D. Then the rotation is exactly as I would like, but it slows the animation due to the (undesired) surface.


title: Converting StringJoin to StringForm inside Hold

text: Let's say I have a piece of code:               Hold[{code1,           "asdad " <> ToString[testa] <> " adsd " <> ToString[testb],           code2}] (*MWE ofc*)      which I want to convert. Each `StringJoin[...]` should be replaced so I will get: > >     Hold[{code1, StringForm["asdad `` adsd ``", testa, testb], code2}] >   I have an answer but maybe one may show shorter approach:               Hold[{code1, "asdad " <> ToString[testa] <> " adsd " <> ToString[testb], code2}         ] /. HoldPattern[StringJoin[x__]                         ] :> RuleCondition@(               StringForm[StringJoin @@ (Hold[x] /. _ToString :> "``"),                           ##] & @@ Cases[Hold[x], HoldPattern[ToString[z_]] :> z]               ) // InputForm      > >      Hold[{code1, StringForm["asdad `` adsd ``", testa, testb], code2}] >   **Edit:** This solution is not perfect. It evauates `testa` and `testb`, does not matter in my case but for generality let's assume they may **not be evaluated.** Also, referring to first of Mr.Wizard's suggestions: **`StringJoin` expressions may appear or different levels** too.


title: "No file exists for resource PasteTemplateString"

text: I am running Mathematica on a Raspberry Pi and the above error message comes up virtually every time I press `ctrl + shift + K` to view the suggested functions and their templates. I cannot find anything about this specific error online and it is becoming very irritating. Does anybody know what may be causing this and how I can fix it?


title: Triangular lattice with periodic boundary conditions

text: I am trying to generate an equilateral triangular lattice with **fixed** vertices and periodic boundary conditions. I am supposed to assign an index (starting from 0) to each vertex in my lattice and then find all the 6 nearest neighbors of each point. In the following you can see what I have tried so far. Here "a" shows the length of the sides of my unit triangle and Lx and Ly indicate the size of my box. I have tried to find the neighbors of each point by measuring its distance from all other points. Now if you run the program and check the "connectionx" file, you can see that some of the points (points near the boundaries) have less than 6 neighbors and it is because I do not know how to impose periodic boundary conditions on my lattice. Do you have any suggestions that can help me find all the 6 neighbors of each point using periodic boundary conditions?! Thank you in advance!               SetDirectory["my favorite directory"];          x0 = 0;     y0 = 0;     a = 1;     R1x = a;     R2x = a*1/2;     R2y = a*Sqrt[3]/2;     Lx = 10.5;     Ly = 9.5;          Q1 = -16;     Q2 = 32;     r = -1;          points = OpenWrite["points.dat", FormatType -> OutputForm]     Do[     Do[     x = x0 + m*R1x + n*R2x // N;     y = y0 + n*R2y  // N;     If[0 < x < Lx && 0 < y < Ly, r += 1;     Write[points, r, "\t", x, "\t", y]]     , {m, Q1, Q2}]     , {n, Q1, Q2}]     Close[points]; (*This part gives me the right positions of particles with their x and y coordinates*)          data = ReadList["points.dat", Number, RecordLists -> True];     con = OpenWrite["connectionx.dat", FormatType -> OutputForm]     distance[i_, j_] :=      Sqrt[(data[[i]][[2]] - data[[j]][[2]])^2 + (data[[i]][[3]] -         data[[j]][[3]])^2];     Do[     WriteString[con, i - 1, " "];     Do[     If[     i != j && distance[i, j] <  1.01*a,     WriteString[con, j - 1, " "]     ]     , {j, 1, Length[data]}]     WriteString[con, "\n"]     , {i, 1, Length[data]}];     Close[con];


title: How do I interrupt (abort) a computation in Mathematica?

text: Sometimes I (inadvertently or naively) write a code that would take Mathematica a long time to compute on my laptop or any computer for that matter. For example: Table[Length[Select[Permutations[n], #[[1]] == 1 &]], {n, 1, 10}]. This returns {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880} in about ten seconds. But if I want more terms (even one more) it takes Mathematica much too long to compute. I usually have to close the program and restart a new session or sometimes I have to unplug my laptop and remove the batteries and restart the computer. Is there an easier way to stop the computation? Is it harmful to my laptop when Mathematica runs a "slow code" for a long period of time (say 10 -15 hours)?


title: ListLinePlot with colors from data

text: I am trying to color a simple 2D plot (using `ListLinePlot`) based on data in the form of 3-vectors.               ListLinePlot[data[[All, {1, 2}]]]      I would like to use one of the `ColorData` color schemes (like "Temperature") for the line color, depending on this third value in my table 3-vectors. That is,`Data[[All, 3]]` will be the source of the color-coding values.


title: Text with subscript is automatically Italic

text: I am creating a figure for a document using `Graphics` in which there is `Text` with some variables and again those same variables with some subscripts. The `Text` with subscript is automatically _Italic_. I do not want this, especially because it contrasts with the variables without subscript which are not _Italic_. How can I change this behaviour?


title: How to evaluate an input cell automatically after evaluating the previous one

text: Is there any way to automatically evaluate an input cell after evaluating the previous one without the need to press `ENTER`?


title: Mouse cursor disappears

text: After working on a notebook for a while sometimes my mouse cursor disappears. I can click on different cells and the text cursor will move accordingly but I just can't see the mouse cursor. Just now after having the window out of focus for a while it came back. I don't have a system setting that makes the cursor disappear while typing, but in mathematica the cursor seems to disappear briefly whenever I press a key (so when typing continuously it blinks like crazy); could this be related? It doesn't happen in any other program so I'm assuming it's a Mathematica glitch/feature. I am using Mathematica 9 on Linux. I have definitely come across this problem before but I can't remember what mathematica version or OS I was using, so I'll leave it at that.


title: Define a color function based on color samples obtained from ColorBrewer

text: I am quite new to mathematica and I am searching for a way to create a smooth colormap based on the samples given by http://colorbrewer2.org/ . Is it possible to create a interpolated function from those sample points?!


title: How determine The most possibility probable with programming

text: i have a scatter chart of probable of happen some thing like below chart ![enter image description here](http://i.stack.imgur.com/j6iCu.png) link of google chart i what determine the probable The most point in below chart , can use a mathematic method to determine for programming


title: How to draw grid lines on top of a plot?

text: I want to use `ArrayPlot` instead of a `DensityPlot` because it seems to be faster (more here) I still want axes ticks to have real values and not array index. I came up with following code which basically centers and scales `ArrayPlot` according to `PlotRange` given to `Graphics`:               arrayPlot[data_, opts___] :=        Module[{dim = Dimensions[data] // N, rls, range, imgSz, aRatio,          cf},        rls = {opts}~          Join~{PlotRange -> Transpose@{{1, 1}, dim},            ImageSize -> {500, 300}, ColorFunction -> "Rainbow"};        {range, cf} = {PlotRange, ColorFunction} /. rls;        aRatio = 1/Divide @@ (ImageSize /. rls);        Graphics[{Scale[#, (range.{-1, 1})*dim^-1] &@               Translate[#, (range.{1, 1} - dim)*0.5] &@             First@ArrayPlot[data, ColorFunction -> cf,                DataReversed -> True]}, Frame -> True,            AspectRatio -> aRatio, #] & @@ rls        ];      It works OK and with:               dataP[m_, n_] := Table[i*Boole[j < i], {i, 1, m}, {j, 1, n}];     arrayPlot[dataP[100, 100], ImageSize -> {500, 500},       ColorFunction -> "Rainbow", PlotRange -> {{-21, 23}, {-1, 1}}]      I get ![image](http://i.stack.imgur.com/YQyts.png) If I modify a arrayPlot with `GridLines -> Automatic , GridLinesStyle -> Directive[Orange, Thickness[0.05]]` added to `Graphics`, I get gridlines behind the plot. ![enter image description here](http://i.stack.imgur.com/Llc6i.png) How can I make the grid lines appear in front of the plot? It is possible to add `Mesh` to `ArrayPlot`, but I want to avoid it since it will require synchronization of mesh with axes ticks. # Edit Considering answer by 'rm -rf' the updated function is:               arrayPlot[data_, opts___] :=        Module[{dim = Dimensions[data] // N, rls, range, imgSz, aRatio,          cf},        rls = {opts}~          Join~{PlotRange -> Transpose@{{1, 1}, dim},            ImageSize -> {500, 300}, ColorFunction -> "Rainbow",            Method -> {"GridLinesInFront" -> True}};        {range, cf} = {PlotRange, ColorFunction} /. rls;        aRatio = 1/Divide @@ (ImageSize /. rls);        rls = Select[rls,         MatchQ[#, Alternatives @@ (#[[1]] & /@ Options[Graphics]) -> _] &];        Graphics[{Scale[#, (range.{-1, 1})*dim^-1] &@               Translate[#, (range.{1, 1} - dim)*0.5] &@             First@ArrayPlot[data, ColorFunction -> cf,                DataReversed -> True]}, Frame -> True,            AspectRatio -> aRatio, ##] & @@ rls        ];          arrayPlot[dataP[100, 100], GridLines -> Automatic ,       ColorFunction -> "BlueGreenYellow",       GridLinesStyle -> Directive[Orange, Thickness[0.01]],       ImageSize -> {500, 500}, PlotRange -> {{-28, 23}, {-1, 1}}]


title: Best way to Export a large list of figures?

text: I have over _2000 graphs_. I would like to `Export` them, ideally, in one `PDF` document with all the graphs on it.


title: Group dataset on two keys (GroupBy)

text: I would like to group the elements of row c of the following dataset according to the values in the columns a and b. That is **Go from here** ![dataset2](http://i.stack.imgur.com/JUQXC.jpg) **To here** ![grp](http://i.stack.imgur.com/TGpw5.jpg) And then I would like to print this on a grid, without visible lists (like {2,7})                   1      2      x  1      4      y  2          7        z  7      8      **Code** This is the dataset I used               dataset2 = Dataset[{     <|"a" -> 1, "b" -> "x", "c" -> 1|>,     <|"a" -> 1, "b" -> "y", "c" -> 2|>,     <|"a" -> 1, "b" -> "z", "c" -> 7|>,     <|"a" -> 2, "b" -> "x", "c" -> 4|>,     <|"a" -> 1, "b" -> "y", "c" -> 7|>,     <|"a" -> 2, "b" -> "z", "c" -> 8|>}]      and this is the dataset2 after grouping on columns a an b               grp = Dataset[{<|"b" -> "x", "a=1" -> {1},      "a=2" -> {4}|>, <|"b" -> "x", "a=1" -> {2, 7},      "a=2" -> {}|>, <|"b" -> "x", "a=1" -> {7}, "a=2" -> {8}|>} ]      **Example from the help** that comes close to what I want to do               dataset = Dataset[{     <|"a" -> 1, "b" -> "x", "c" -> {1}|>,     <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,     <|"a" -> 3, "b" -> "z", "c" -> {3}|>,     <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,     <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,     <|"a" -> 6, "b" -> "z", "c" -> {}|>}]      ![dataset](http://i.stack.imgur.com/dJvrq.jpg)               dataset[GroupBy[Key["b"]], Catenate, "c"]


title: Mathematica not able to confirm its own solution to differential equation

text: I type the following into _Mathematica_ :               DSolve[q''[x] + 2 x/(x^2 - 1) q'[x] - 4*q[x]/(x^2 - 1) == 0, q[x], x]      It gives me the result               q[x] -> C[1] LegendreP[1/2 (-1 + Sqrt[17]), x] +        C[2] LegendreQ[1/2 (-1 + Sqrt[17]), x]      Suppose I take `C[2]=0` and `C[1] =1`, and then I try the following command:               FullSimplify[      D[D[LegendreP[1/2 (-1 + Sqrt[17]), x], x], x] +        2*x/(x^2 - 1)*D[LegendreP[1/2 (-1 + Sqrt[17]), x], x] -        4*LegendreP[1/2 (-1 + Sqrt[17]), x]/(x^2 - 1)]      This is evaluating the LHS of the diff eq at the solution, as provided by _Mathematica_ , and yet the result I get is NOT zero: I get               (1/(2 (-1 +         x^2)^2))((9 + Sqrt[17]) LegendreP[1/2 (-1 + Sqrt[17]),          x] - (19 + 3 Sqrt[17]) x LegendreP[1/2 (1 + Sqrt[17]), x] +        2 (5 + Sqrt[17]) LegendreP[1/2 (3 + Sqrt[17]), x])      I was wondering if someone knew how I could make it fully simplify the result to give me zero, as numerically evaluating it gives extremely small numbers.


title: Detecting the existence of an element in a subarray with specific properties

text: If I have an array that looks like this:               testArray =        {{"StringOne", 3.444}, {"StringOne", 433}, {"StringOne", 1}, {"StringOne", 8},         {"StringOne", 1}, {"StringOne", 5}, {"StringOne", 2}, {"StringOne", 1},         {"StringOne", 9}, {"StringOne", 1}, {"StringTwo", 7.64}, {"StringTwo", 34},         {"StringTwo", 6}, {"StringTwo", 99}, {"StringTwo", 54}, {"StringTwo", 12.33},         {"StringTwo", 6}, {"StringTwo", 7}, {"StringTwo", 76}, {"StringTwo", 1}};      I want to quickly detect the existence of a subarray of the form: `{"StringTwo", n}` for all $n > k$ (for some real-valued $n$ and $k$). How can I best do this?


title: Statistics confusion

text: I have two data sets. When I do a `QuantilePlot[data1, data2]`, I get the graph below. However, `KolmogorovSmirnovTest[data1, data2]` returns 0. While clearly the distributions of the two data sets are somewhat different, it is equally clear that they are not that far apart. Now, to add to the confusion, while the examples for `KolmogorovSmirnovTest[]` do give an example of two data sets being compared, the actual documentation seems to tell us how to see if data matches a symbolic distribution. So, it all seems rather goofy. Anybody have thoughts? **EDIT** I withdraw the "bug" theory, since I have now compared the same data in Matlab (thanks to @Szabolcs's excellent MATLink (matlink.org)) and MATLAB is in agreement with Mathematica (except that Mathematica's 0 is MATLAB's 1) ![enter image description here](http://i.stack.imgur.com/7DU3p.jpg)


title: How are MemberQ and FreeQ so fast?

text: I would like to understand the implementation that allows `MemberQ` and `FreeQ` to be as fast as they are. I noticed this thanks to this fine answer. I start with a list of True|False values:               lst = Insert[Table[True, {500000}], False, 499000];      It is not packed:               Developer`PackedArrayQ[lst]      > False I compare timings:               Scan[Identity, lst] ~Do~ {100} // Timing     MemberQ[lst, False] ~Do~ {100} // Timing     FreeQ[lst, False]   ~Do~ {100} // Timing      > {4.93, Null} > > {0.405, Null} > > {0.25, Null} What allows these functions to be more than an order of magnitude faster than simply Scanning the list?


title: Show path with arrows in a matrix

text: I have a matrix, for example, 5x5 matrix `Partition[Range[25], 5]`. And I am given a list, for example:                {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {5, 2}, {4, 2},       {3, 2}, {2, 2}, {1, 2}, {1, 3}, {2, 3}, {3, 3}, {4, 3},       {5, 3}, {5, 4}, {4, 4}, {4, 5}, {5, 5}       and I need to trace the path from the element in `(1,1)` to `(2, 1)`, and then from `(2, 1)` to `(3, 1)`, etc., from `(4, 5)` to `(5, 5)` and end there. How can I draw this graphically with an arrow indicating each of the transition?


title: Is Compress[] compatible between different Mathematica versions?

text: `Compress[]` was introduced in version 6 of Mathematica. It gives a compressed version of expressions represented as a string of ASCII characters. It preserves more information than the `InputForm` of expressions (for example it keeps packed arrays packed). Are the strings returned by `Compress` compatible between versions? Can a compressed expression created using version 6 be uncompressed in version 8? What about the reverse (reading a version-8-compressed expression in 6 or 7)? What happens if a version 8 specific object such as `Graph` is uncompressed in version 6 or 7?


title: How can all those tiny polygons generated by RegionPlot be joined into a single FilledCurve?

text: `RegionPlot` will usually generate a large number of tiny polygons for filling the region:               RegionPlot[-1 < x < 1 && -1 < y < 1 && x^2 + y^2 > 4/5, {x, -1.2,        1.2}, {y, -1.2, 1.2}, Mesh -> All]      ![Mathematica graphics](http://i.stack.imgur.com/Q0gty.png) When exported to PDF, these are often not very fast to render. It is clear that theoretically these polygons could be joined into a single `FilledCurve`, defined by the outlines only. This should be much faster to render. How can we do this in a robust way? * * * Note: the reason we need a `FilledCurve` and that a plain `Polygon` will not work is that a `FilledCurve` can have a hole in it (it may be multiply connected), like in the image above. Alternatively I will accept a solution which uses more than one `Polygon`, but still reduces the number of `Polygons`s as much as possible (in the example above two polygons will suffice). * * * Here's a complex `RegionPlot` to test on:               a = 36;     g = RegionPlot[       Mod[Sqrt[x^2 + y^2] - 7/2 ArcTan[x, y] + Sin[x] +           Cos[y], \[Pi]] < \[Pi]/2, {x, -a, a}, {y, -a, a},        PlotPoints -> 100]      The equation is from here.


title: How to select a set of cells to cut and paste into another notebook

text: I'd like to cut and paste from one Demonstration notebook to another. These notebooks have a few sections where the content is separated into disjoint cells (examples: Details, Related Links, Search Terms), like so: ![search terms](http://i.stack.imgur.com/SKDB1.png) How can I select a set of these sort of separate cells, so that I can cut and paste them en-mass to another notebook (I really want this for text from the Details section, not the search terms, as in the image above).


title: How to calculate the $H_2$ and $H_\infty$ norms of TransferFunctionModels or StateSpaceModels?

text: Lets assume we have a system model:               tf = TransferFunctionModel[{{          (s^3 - 2.841 s^2 + 2.875 s - 1.004)/           (s^3 - 2.417 s^2 + 2.003 s - 0.5488)}}, s];     ss = StateSpaceModel[tf]      ![enter image description here](http://i.stack.imgur.com/kVJCE.png) **My question is:** How to calculate $H_2$ and $H_\infty$ norms of this system or transfer function? Is there a built-in function for it? **Some notes:**   * In MATLAB `norm(ss,2)` or `norm(ss,inf)` does that.   * Mathematical calculations can be done as in this link. From the `LyapunovSolve` examples one can compute the $H_2$ norm of an asymptotically stable continuous-time system as below:               {a, b, c} = {{{-1, 2, 3}, {0, -2, 2}, {0, 0, -3}},                  {{1, 1}, {1, 1}, {1, 1}},                  {{1, 1, 1}, {1, 1, 1}}};          x = LyapunovSolve[a, -b.Transpose[b]];     h2norm = Sqrt[Tr[c.x.Transpose[c]]] // N      > 6.12917


title: Detecting grid lines in a raster image

text: **Motivation** : Last October 7 there was a presidential election in Venezuela. Although the opposition saw an unprecedented increase in its votes, the government votes increased even more resulting in the current president being re-elected. The votes were counted by computers that are not trustworthy because of what they have done in the past. Each voting machine printed a voting certificate with the results. About 90% of such certificates where collected by the opposition and are available to anyone at http://hayuncamino.com/actas/ In each voting table there was a paper notebook were each voter put its signature and fingerprint. According to the law, the total number of votes from this notebook was supposed to be compared to the votes reported by the machine. The results certificate provided a space where this number must be hand written. Unfortunately it seems that in a very large number of voting tables the law was broken because the space for this verification is empty. By using Mathematica image processing capabilities I intend to find out in which voting tables the verification was done and compare the results of this subset with its complement. **The original question:** I need to process a large number of images for a non-profit organization report. The images contain a grid with borders and cells. The cells B2 and C2 (spreadsheet coordinates) can be hand written or can be empty, and that is what needs to be detected. Here is an example of a filled form: ![filled form](http://i.stack.imgur.com/CmKLx.png) And this is an example of an empty form: ![enter image description here](http://i.stack.imgur.com/1OM9l.png) My plan is to detect the coordinates of the following points: ![enter image description here](http://i.stack.imgur.com/mC9Cm.png) and then compute to total amount o black pixels in the area defined by them. **So my question is: What strategy would you recommend to reliably detect the location of those points indicated in red?** I have already tried using `ImageLines`, `Radon`, and `FindGeometricTransform` without much success. I think that the best approach is not to look for independent lines but instead look for the grid as a whole. This is what I am trying to do:               figWithoutSideBorders =        ColorNegate @         ImageAdd[fig,                   ColorNegate @ Erosion[#, 3] & @ MeanFilter[#, 1] & @ MaxDetect[fig, 0.95]         ]      ![enter image description here](http://i.stack.imgur.com/D1PoK.png) I careful crafted this matrix so that it has the same proportions as the target grid:               formMatrix = SparseArray[{Band[{ 1, 1 }, Automatic, {0,1}] -> 1,                               Band[{15, 1 }, Automatic, {0,1}] -> 1,                               Band[{29, 1 }, Automatic, {0,1}] -> 1,                               Band[{52, 1 }, Automatic, {0,1}] -> 1,                               Band[{66, 1 }, Automatic, {0,1}] -> 1,                               Band[{ 1, 1 }, Automatic, {1,0}] -> 1,                               Band[{ 1,105}, Automatic, {1,0}] -> 1,                               Band[{ 1,146}, Automatic, {1,0}] -> 1,                               Band[{ 1,265}, Automatic, {1,0}] -> 1},                               {66,265}];     formFigure = ColorNegate @ ArrayPlot[formMatrix, AspectRatio -> Automatic, Frame -> False]      ![enter image description here](http://i.stack.imgur.com/Yu3rn.png) But when I try to use `FindGeometricTransform`, it fails. Maybe it does not work with hollow objects? ![enter image description here](http://i.stack.imgur.com/S02hf.png) As I last resort, I am thinking about doing horizontal and vertical histograms and look for proportionally spaced peaks, but I want to ask the community before I over engineer a solution. Thanks in advance. **UPDATE 1:** @nikie answer is certainly very useful and I am thankful for that. My only concern is that this method looks for any table instead of looking for a 4x3 table with row heights 21%, 21%, 36%, 21% and column widths 40%, 15% and 45%. The fragility of the method is exposed by using the other provided sample image where a vertical line, that is not part of the table is confused for an additional column: ![misrecognized table](http://i.stack.imgur.com/K0Wot.png) **UPDATE 2:** As suggested by @belisarius I have added some context / motivation for this question. **UPDATE 3:** I have now finished the processing. Only 5.7% on the voting certificates where not blank in the target total votes verification area. About 99% of the voting certificates were processed automatically. I have developed a set of functions that could be useful for other people doing similar tasks (and even in different areas), so I plan to write an answer to share that. Look also for a torrent file in the comments area.


title: How does Interpolation really work?

text: I'm looking for some explanation or advice, not help in solving something. Recently I finished my program and my supervisor said "Ok, now it's time for your first paper: write a scientific text about how your program works". If I understand him correctly it means I have to describe the algorithm I used instead of writing in a manner like "for this purpose I use the built-in `Interpolation` function, and for this purpose I use `NDSolve`" etc. I know how `FindRoot` and `NDSolve` work because there is an explanation in the doc pages about the methods they use, but I did not find detailed information about `Interpolation`. The only thing I know it fits with polynomial curves. So my question is: What exactly does the `Interpolation` function do? How does it work? How does it determinate (partial) derivatives? And why do 3D data points have to be situated in rectangle order to interpolate a surface? If there is some literature I may read and then reference it would be great too.


title: How to implement dual numbers in Mathematica?

text: I wonder how can I implement dual numbers in _Mathematica_ , so that all functions work well with them (as with complex numbers). Particularly, for each function $f$, $f(\varepsilon)=f^\prime(0)\varepsilon$


title: Why does this sum not simplify properly?

text: I was trying to get Mathematica to simplify some moderately ugly sums and I ran into some pretty weird behaviour, which I tracked down to the following example. I'm working with Christoffel-Darboux-type sums of Hermite polynomials, which are known to simplify nicely, a fact of which Mathematica is aware:               Sum[(HermiteH[k, x] HermiteH[k, y])/(2^k k!), {k, 0, n}]          Out[1]= (2^(-1 - n) (HermiteH[n, y] HermiteH[1 + n, x] -      HermiteH[n, x] HermiteH[1 + n, y]))/((x - y) n!)      So far so good. However, even simple changes to the above expression make Mathematica output a far more complex answer which is not what I'm looking for in general and which in this case is evidently rather wrong:               Sum[(HermiteH[k, -x] HermiteH[k, y])/(2^k k!), {k, 0, n}]      > ![enter image description here](http://i.stack.imgur.com/Z06EQ.png) The problem is somewhat related to this question on `Simplify`, but I can't see why Mathematica would think the code above is in any way simpler than just               -(2^(-1 - n) (HermiteH[n, y] HermiteH[1 + n, -x] -      HermiteH[n, -x] HermiteH[1 + n, y]))/((x + y) n!)      Can anyone share some insight? or is this some kind of bug?


title: Prevent package from being opened in a notebook interface

text: I have a package which I need to deploy in a client's environment. It has proprietary code and solutions that I need to protect from prying eyes and inquisitive minds. The forum has discussed much of this sort of thing in the past. See: How safe is Encode? How to distribute proprietary Mathematica code Seeking strategies to deploy a function securely without a front end I will utilize `Encode`, `DumpSave`, and attributes: `Locked` and `ReadProtected`. They help but I wonder if I can impose other barriers to access. The package in question will only need to get called from `NET/Link`. This leaves me with three related questions:   * Does any means exist to prevent the package from ever opening in a front end notebook?   * Does any means exist to prevent the package from ever being called from a front end notebook?   * Does any means exist to delete or erase the package's code if someone did open it in a notebook?


title: How to add several Locators to a Graphic with a mouse click?

text: **Background:** Suppose I have something like this:                DynamicModule[{pt1 = {0, 0}, pt2 = {0, 1}, pt3 = {1, 0}},       Graphics[Polygon[{pt1, pt2, pt3}], PlotRange -> 1]]      which I would like to change into this via a mouse click on the `Polygon` into this:                DynamicModule[       {pt1 = {0, 0}, pt2 = {0, 1}, pt3 = {1, 0}},       Manipulate[        Graphics[Polygon[{pt1, pt2, pt3}], PlotRange -> 1],        {{pt1, {0, 0}}, Locator}, {{pt2, {0, 1}}, Locator}, {{pt3, {1, 0}},          Locator}]]      **Question:** What code should I add to one of the snippets above to achieve this?


title: Labeling plots without evaluation

text: This is my first question here so please excuse my mistakes. Let us consider a rather contrived example:               f[x_, y_, z_] := x y z     {y, z} = {1, 1};     Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> f[x, y, z]]     Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> Subscript[f, x, y, z]]     Manipulate[Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> f[x, y, z]], {y, 0, 1}, {z, 0, 1}]      Only `PlotLabel` is used here, but I am making the same argument for `AxesLabel`, `Epilog -> Inset[]`, and other ways of labeling plots. The problem here is that the evaluator in Mathematica eagerly replaces all occurrences of `f`, `y` and `z` by their values, so instead of $f(x,y,z)$ in the plot one sees $x$. There are several solutions:   1. Different variables, say `ff`, `yy` and `zz`, can be used in the code, leaving the symbols `f`, `y` and `z` free for labeling. However, this makes the code much more incomprehensible.   2. Labels can be enclosed in quotes, for example, `"f[x, y, z]"`. This works with `Subscript[f, x, y, z]` but the formatting is wrong for `f[x, y, z]` (variables are not italicized and brackets appear in lieu of parentheses).   3. Labels can be enclosed in `HoldForm` or `Block`, for example, `HoldForm[f[x, y, z]]` or `Block[{f, x, y, z}, f[x, y, z]]`. This does not work for `Manipulate`, presumably because it defines its own local variables.   4. Type such monstrosity as `\\!\\(\\*FormBox[SubscriptBox[\\(f\\), \\(x, y, z\\)], TraditionalForm]\\)` directly in the code. I wonder if there is a simple way to tell Mathematica to use the expression `f[x,y,z]` as-is, with formatting but without evaluation. It would even be better if I can tell it to, say, replace only `y` with its current value in `Manipulate` but leave `z` untouched. As an additional question, it is sometimes nice to label a condition on the plot, such as $y=1$. I can get away with               Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> HoldForm[y] == y]     Clear[y]     Manipulate[      Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> Symbol["y"] == y], {y, 0,        1}, {z, 0, 1}]      but this seems awfully complicated and inconsistent. Perhaps I can again tell Mathematica to skip evaluating `Equal`, and treat it as a given expression? ## Edit Based on the discussion below I have summarized several ad-hoc strategies to deal with labels:   * Define a label via              l = {HoldForm[x], HoldForm@f[x, y, z]}     l = StringForm["Plot of ``", HoldForm[Subscript[f, x, y, z]]]     l = HoldForm[y == #1 \[And] z == #2] &      in global scope, before local variables creep in. These should be shielded against all global and local definitions of the variables. (The last label should be used as `PlotLabel -> l[y, z]`.)   * Wrap `Plot` or `Manipulate` with a `Module` and define local labels in the same way. For example,              Module[{l = HoldForm@f[x, y, z]},       Manipulate[       Plot[f[x, y, z], {x, -1, 1}, PlotLabel -> l], {y, 0, 1}, {z, 0, 1},        Initialization :> (f[x_, y_, z_] := x y z)]]      This is okay as long as the label is defined outside of the scope in which `f`, `y` and `z` are actually used. But if the plotting code is to be encapsulated in a function `plot[f_] := ...`, then this approach fails if the label involves `f` and `f` is declared globally as a pure function, such as `f = #1 #2 #3 &`. In that case, one may consider `plot[fn_] := ...`.   * If `f` is to be displayed unevaluated, such as $f(x,y,0.12)$, use              Manipulate[      Plot[f[x, y, z], {x, -1, 1},        PlotLabel ->         With[{y = Symbol["y"], z = z}, HoldForm@f[x, y, z]]], {y, 0,        1}, {z, 0, 1}, Initialization :> (f[x_, y_, z_] := x y z)]      `y` is displayed as-is, and it is wrapped in `Symbol` so that it is properly formatted; but `y` must not already be defined globally, otherwise that global value will show. `z` shows its current value, set probably through a `Manipulate`.   * If `f` is to be displayed in evaluated form, such as $x\times y\times0.12$, use              Manipulate[      Plot[ReleaseHold@f[x, y, z], {x, -1, 1},        PlotLabel -> With[{y = Symbol["y"], z = z}, f[x, y, z]]], {y, 0,        1}, {z, 0, 1}, Initialization :> (f[x_, y_, z_] := HoldForm[x y z])]      However, it is hard to guarantee all plotting functions are wrapped in `HoldForm`.   * If any of the preserved variables (`x` and `y`) are already defined globally, it is possible to guard against them with `With[{x = "x", y = "y"}, ...]` at the cost of `x` and `y` not being properly formatted and the risk of wrong variable ordering.   * Nothing could be done if the variable is declared in the same scope as the label is used. `HoldForm[x]` will display its decorated name. In short, there is no one single solution that works in every case except global-variable injection.


title: Time-efficient manipulation (zeroing) of expression

text: I have huge matrices in the form of               mtx1 = {{24+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8]},{24+24 FF[5,10] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[7,8] GG[7,8]},{24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]+24 FF[7,8] GG[7,8],24+24 FF[5,10] GG[5,10]+24 FF[6,9] GG[5,10]+24 FF[7,8] GG[5,10]+24 FF[5,10] GG[6,9]+24 FF[6,9] GG[6,9]+24 FF[7,8] GG[6,9]+24 FF[5,10] GG[7,8]+24 FF[6,9] GG[7,8]}};      but the matrices I use are much bigger. Now I want to get rid of each term that contains `FF[___]` or `GG[___]`. Both always come together, therefore I used               mtx2 = mtx1 /. FF[___] -> 0;      (* mtx2={{24, 24, 24}, {24, 24, 24}, {24, 24, 24}} *)      and got the desired result in mtx2. Unfortunatly it turns out that this zeroing is extremly time-consuming. For my huge matrices, it takes on the order of 100 seconds. **Question:** Is there a more time-efficient way to zero all `FF[___]`-terms in `mtx1`? **Comparison:** I compare several approaches, for a big 3 big test-matrix. The approaches also include the construction of the matrix. _my original approach_   * {174.8417751, 65.4913582, 25.3878123} seconds _Coefficient-Creation of Matrix_   * {134.4920621, 51.4260521sec, 19.6079772} seconds _belisarius' Block-evaluation methode_   * {82.3675688, 31.5639078, 12.3822025} seconds _eldo's Join/Partition_   * {77.8615328, 29.0973367, 11.2742769} seconds _kguler's Block-evaluation_   * {75.8906436, 29.1315892, 11.6544345} seconds _Mr.Wizard's mtx1[[All, All, 1]]_   * {75.5589726, 29.0378220, 11.9491954} seconds **Edit** The full problem, including the matrix-creation is posted here:  Time- efficient creation of matrix


title: Vertex Names of Subgraph in Order of Connectivity

text: I extract path subgraphs $P_4$ of an undirected graph $G$. And want to list the VertexNames of the subgraphs in the same order as they are connected. Here is an example:               g = Graph[{6 <-> 7, 1 <-> 6, 3 <-> 1, 3 <-> 2, 5 <-> 4, 3 <-> 4},      VertexLabels -> "Name", ImagePadding -> 10];     h = Subgraph[g, {1, 3, 6, 7}, VertexLabels -> "Name", ImagePadding -> 10]     HighlightGraph[g, h]     VertexList[h]      ![GraphImage](http://i.imgur.com/nG0E6NO.png) `VertexList[h]` always gives the vertex names in the order specified in line 5. Is it possible to extract the vertex names in the order of connectivity? The given example should give `{3,1,6,7}` or the reverse instead of `{1,3,6,7}`.


title: Cropping a plot via a command

text: I have a plot with some whitespace I'd like to get rid of. Ideally, I'd like to use a command like "ImageCrop", but for non-raster graphics (ImageCrop rasterizes the graphic). The Mathematica documentation tells you how to do this by hand (under the "cropping" section): http://reference.wolfram.com/mathematica/tutorial/InteractiveGraphicsLayout.html ...but there doesn't seem to be a way to do this via a command. I've tried all sorts of combinations of FrameMargins, ImageMargins, ImagePadding, etc, but to no avail. Even if I could just manually specify the number of pixels to crop by, that would be an improvement over the current situation, but ideally the best solution would be to replicate ImageCrop for non-raster graphics.


title: Some questions about random numbers

text: How can I get non-repeating random numbers from Mathematica 8? How can I know which distribution the numbers I get are? Can I choose the distribution I want together with the non-repeating random numbers? How to write the expressions or formulas of permutation and combination? Are these numbers real random numbers, not pseudo-random numbers?


title: Are greek symbols causing different evaluation?

text: I've updated today to Mathematica 9.0.1.0 from version 8 and found something that absolutely confuses me.   Let us define a piecewise function:               gr[x_, v1_, v2_, v3_, v4_, v5_] =      Piecewise[{{g, v1 < x < v1+v2}, {g, v1+v3 < x < v1+v2+v3},      {gs, v1+v2+v3+v4 < x < v1+v3+v2+v4+v5}}, 0]      and try integrating it with obvious assumptions:               Integrate[gr[x, a, b, c, d, e], {x, 0, END},      Assumptions -> {0 < a < a+b < a+c < a+b+c < a+b+c+d < a+b+c+d+e < END}]      This takes around 60 seconds and obviously results in `2 b g + e gs` (although it seems it was a lot faster in Mathematica 8, though it's not the point here). Now, if we do the very same integration, but with different symbols:               Integrate[gr[x, τ, δ, Δ, τs, δs], {x, 0, TR},      Assumptions -> {0 < τ < τ+δ < τ+Δ < τ+δ+Δ < τ+δ+Δ+τs < τ+δ+Δ+τs+δs < TR}]      All of a sudden this doesn't evaluate in 60 seconds, running till it pages all the memory available and crashing afterwads. Can anyone explain this?


title: Showing Two Manipulated Plots Together

text: I want to show a scatter plot and bar chart next to each other in order to show the change in both factors for each county. The scatter plot shows life expectancy per county on the basis of income, while the stacked bar graph shows the change in life expectancy for females and males from 1958 to 2010. Help! Initialization Code:               fx = {30461, 15514, 24021, 21285, 20777, 23711, 20100, 23386, 22318, 23659, 26025, 21601, 20022, 27480, 26101, 24756, 25292,  24333, 23264, 25305, 26523, 23116, 20828, 30744, 20811, 20815, 24144, 26338, 24501, 36184, 43509, 23903, 25870, 27304, 24217, 30268, 22295, 21285, 18746, 35864, 30618, 29810, 35589, 33592, 18004, 29660, 21900, 22515, 23971, 25115, 23750, 32373, 25582, 24519, 19404, 25720, 24826, 22204, 24401, 36412, 23398, 19748};     fy = {81.5, 80.1, 81.2, 81, 79.1, 81.7, 80.7, 80.1, 80, 81.3, 80.9, 79.7, 80.6, 81.8, 80.3, 81.1, 79.8, 80.6, 81, 80.5, 81.1, 81.2, 80.1, 82.4, 81.7, 81.5, 81.3, 81.6, 79.8, 80.3, 84.1, 79.6, 80.9, 81.8, 81.9, 81, 80.4, 80, 81.3, 82.4, 83.8, 79.9, 81.6, 83.4, 79.6, 82.4, 81.6, 81.8, 79.1, 80.7, 80.5, 82.3, 79.1, 82.2, 82.2, 81.2, 82, 80.4, 80.6, 84.1, 80.2, 80.5};      femaledata = Transpose@{fx, fy};      femaleplot = ListPlot[femaledata, PlotStyle -> Purple];     mx = {39042, 27328, 27180, 30975, 30575, 34676, 29953, 34696, 31914, 31538, 36356, 29548, 28262, 43545, 36360, 31519, 29278, 32237, 35597, 32959, 31694, 32693, 33374, 33829, 35787, 32441, 33919, 36295, 31531, 54018, 54895, 35160, 32899, 37783, 36910, 42130, 33210, 32378, 25208, 54179, 34948, 37152, 51023, 46681, 26683, 46960, 21971, 32196, 34242, 32220, 35500, 50695, 32212, 35172, 28101, 38048, 37360, 33014, 36181, 51852, 35061, 31333};     my = {77.4, 77.3, 75, 76.1, 74.9, 77, 75.5, 75.6, 76.3, 76.5, 76.3, 76.9, 76.4, 77.9, 75.7, 77.3, 77, 76.1, 75.7, 75.2, 77.3, 77.2, 75.5, 77.3, 76, 77.6, 77.8, 77.6, 76.1, 79.6, 79.3, 75.5, 76.1, 76.9, 76.8, 77.6, 76.1, 75.9, 76.8, 78.7, 79, 76.5, 77.3, 76.9, 75.5, 78.7, 76.9, 77.4, 76.4, 76.8, 75.9, 78, 75, 77.6, 78.8, 77.1, 77.6, 77.2, 76.8, 79.8, 76.8, 77.1};          maledata = Transpose@{mx, my};      maleplot = ListPlot[maledata, PlotStyle -> MediumBlue];      ScatterPlot:               Manipulate[Show[maleplot, femaleplot, Graphics[{PointSize[.02], Point[county]}], Graphics[{PointSize[.02], Point[county1]}], PlotRange -> {{10000, 60000}, {70, 85}}, AxesOrigin -> {10000, 70}, ImageSize -> 500, AxesLabel -> {"Median Income", "Life Expectancy"}], {{county,{30461, 81.5},"Female County"}, {{30461, 81.5}->"Albany", {15514, 80.1}->"Allegany", {24021, 81.2} -> "Bronx", {21285, 81} -> "Broome", {20777, 79.1} -> "Cattaraugus", {23711, 81.7} -> "Cayuga", {20100, 80.7} -> "Chautauqua", {23386, 80.1} -> "Chemung", {22318, 80} -> "Chenango", {23659, 81.3} -> "Clinton", {26025, 80.9} -> "Columbia", {21601, 79.7} -> "Cortland", {20022, 80.6} -> "Delaware", {27480, 81.8} -> "Dutchess", {26101, 80.3} -> "Erie", {24756, 81.1} -> "Essex", {25292, 79.8} -> "Franklin", {24333, 80.6} -> "Fulton", {23264, 81} -> "Genesee", {25305, 80.5} -> "Greene", {26523, 81.1} -> "Hamilton", {23116, 81.2} -> "Herkimer", {20828, 80.1} -> "Jefferson", {30744, 82.4} -> "Kings", {20811, 81.7} -> "Lewis", {20815, 81.5} -> "Livingston", {24144, 81.3} -> "Madison", {26338, 81.6} -> "Monroe", {24501, 79.8} -> "Montgomery", {36184, 80.3} -> "Nassau", {43509, 84.1} -> "NewYork", {23903, 79.6} -> "Niagara", {25870, 80.9} -> "Oneida", {27304, 81.8} -> "Onondaga", {24217, 81.9} -> "Ontario", {30268, 81} -> "OrangeCounty", {22295, 80.4} -> "Orleans", {21285, 80} -> "Oswego", {18746, 81.3} -> "Otsego", {35864, 82.4} -> "Putnam", {30618, 83.8} -> "Queens", {29810, 79.9} -> "Rensselaer", {35589, 81.6} -> "Richmond", {33592, 83.4} -> "Rockland", {18004, 79.6} -> "StLawrence", {29660, 82.4} -> "Saratoga", {21900, 81.6} -> "Schenectady", {22515, 81.8} -> "Schoharie", {23971, 79.1} -> "Schuyler", {25115, 80.7} -> "Seneca", {23750, 80.5} -> "Steuben", {32373, 82.3} -> "Suffolk", {25582, 79.1} -> "Sullivan", {24519, 82.2} -> "Tioga", {19404, 82.2} -> "Tompkins", {25720, 81.2} -> "Ulster", {24826, 82} -> "Warren", {22204, 80.4} -> "Washington", {24401, 80.6} -> Wayne, {36412, 84.1} -> "Westchester", {23398, 80.2} -> "Wyoming", {19748, 80.5} -> "Yates"}, ControlType -> PopupMenu}, {{county1, {39042, 77.4}, "Male County"}, {{39042, 77.4}->"Albany", {27328, 77.3}->"Allegany", {27180, 75} -> "Bronx", {30975, 76.1} -> "Broome", {30575, 74.9} -> "Cattaraugus", {34676, 77} -> "Cayuga", {29953, 75.5} -> "Chautauqua", {34696, 75.6} -> "Chemung", {31914, 76.3} -> "Chenango", {31538, 76.5} -> "Clinton", {36356, 76.3} -> "Columbia", {29548, 76.9} -> "Cortland", {28262, 76.4} -> "Delaware", {43545, 77.9} -> "Dutchess", {36360, 75.7} -> "Erie", {31519, 77.3} -> "Essex", {29278, 77} -> "Franklin", {32237, 76.1} -> "Fulton", {35597, 75.7} -> "Genesee", {32959, 75.2} -> "Greene", {31694, 77.3} -> "Hamilton", {32693, 77.2} -> "Herkimer", {33374, 75.5} -> "Jefferson", {33829, 77.3} -> "Kings", {35787, 76} -> "Lewis", {32441, 77.6} -> "Livingston", {33919, 77.8} -> "Madison", {36295, 77.6} -> "Monroe", {31531, 76.1} -> "Montgomery", {54018, 79.6} -> "Nassau", {54895, 79.3} -> "NewYork", {35160, 75.5} -> "Niagara", {32899, 76.1} -> "Oneida", {37783, 76.9} -> "Onondaga", {36910, 76.8} -> "Ontario", {42130, 77.6} -> "OrangeCounty", {33210, 76.1} -> "Orleans", {32378, 75.9} -> "Oswego", {25208, 76.8} -> "Otsego", {54179, 78.7} -> "Putnam", {34948, 79} -> "Queens", {37152, 76.5} -> "Rensselaer", {51023, 77.3} -> "Richmond", {46681, 76.9} -> "Rockland", {26683, 75.5} -> "StLawrence", {46960, 78.7} -> "Saratoga", {21971, 76.9} -> "Schenectady", {32196, 77.4} -> "Schoharie", {34242, 76.4} -> "Schuyler", {32220, 76.8} -> "Seneca", {35500, 75.9} -> "Steuben", {50695, 78} -> "Suffolk", {32212, 75} -> "Sullivan", {35172, 77.6} -> "Tioga", {28101, 78.8} -> "Tompkins", {38048, 77.1} -> "Ulster", {37360, 77.6} -> "Warren", {33014, 77.2} -> "Washington", {36181, 76.8} -> Wayne, {51852, 79.8} -> "Westchester", {35061, 76.8} -> "Wyoming", {31333, 77.1} -> "Yates"}, ControlType -> PopupMenu}]      Bar Chart:               Manipulate[BarChart[county, ChartLayout ->"Stacked", ChartLegends -> {"female", "male"}, ChartStyle -> "Pastel", ImageSize -> 500, AxesLabel -> {"County","Increase In Life Expectancy (Years)"}], {county, {{3.8,5.8} -> "Albany", {1.7,4.9} -> "Allegany",{6.4, 9.6} -> "Bronx",{2.5,4.2} -> "Broome",{1.7, 3.6} -> "Cattaraugus",{3.8, 5.5} -> "Cayuga",{2.9, 3.6} ->"Chautauqua",{2.2, 4.2} -> "Chemung",{1.6, 5.2} -> "Chenango",{3.3, 4.8} -> "Clinton",{2.6, 4.8} -> "Columbia", {2.1, 5.8} -> "Cortland",{2.5, 5.6} -> "Delaware",{3.6, 6.1} -> "Dutchess", {3.5, 5.3} -> "Erie",{4.4, 7} -> "Essex",{3.3, 7.2} -> "Franklin", {2.4, 4.9} -> "Fulton", {2.5, 3.9} -> "Genesee", {3.3, 4.4} -> "Greene", {4.4, 7} -> "Hamilton", {2.9, 5.1} -> "Herkimer", {3.8, 5.4} -> "Jefferson", {6.7, 9.8} -> "Kings",{3.6, 4.3} -> "Lewis",{3.1, 5} ->  "Livingston",{2.2, 6.5} -> "Madison",{3, 5.1} -> "Monroe",{1.6, 4.3} -> "Montgomery", {5.5, 6.7} -> "Nassau",{8.4, 13} -> "NewYork",{2.1, 4.2} -> "Niagara",{2.8, 4.5} -> "Oneida",{3.5, 5} -> "Onondoga",{3.1, 3.7} -> "Ontario",{3.7, 7.1} -> "OrangeCounty",{3.2, 5.1} -> "Orleans",{2.8, 5.3} -> "Oswego",{2.9, 4.3} -> "Otsego",{4.6, 6.7} -> "Putnam",{6, 8.5} -> "Queens",{2.3, 5.3} -> "Rensselaer",{4.7, 7.4} -> "Richmond",{5.7, 7} -> "Rockland",{2, 4.7} -> "StLawrence",{4.6, 6.2} -> "Saratoga",{3.4, 5.4} -> "Schenectady", {3.8, 5.3} -> "Schoharie",{0.4, 5.1} -> "Schuyler",{2.1, 4.4} -> "Seneca",{3.2, 4.9} -> "Steuben",{4.9, 6.1} -> "Suffolk",{2.5, 5.7} -> "Sullivan",{3.6, 5.1} -> "Tioga",{3.4, 5.5} -> "Tompkins",{3.2, 5.9} -> "Ulster",{4.7, 6.3} -> "Warren",{3, 6.7} -> "Washington",{3.1, 5} -> "Wayne",{5.5, 7.1} -> "Westchester",{2.1, 5.4} -> "Wyoming",{1.8, 4.8} -> "Yates"}, ControlType -> PopupMenu}]      Thanks a lot!


title: TextAlignment->Center in a notebook with WindowSize->All

text: I'm creating a dialog with `CreateDialog`. I want one of its cells to have its text centered. By default (and I like that default), the notebook created has `WindowSize` set to `All`, which I'm guessing adjusts the window width according to the widest cell. _The problem_ The centered cell doesn't show. What's a neat way to make this work? I could live with programatically querying the "real" size of the dialog, so that I can then set it explicitly in `WindowSize`, in which case `TextAlignment->Center` seems to work, but I don't know how. _Sample code_               CreateDialog[{"¿Hasta dónde se lava la cara un pelado?",         Style["bo", TextAlignment -> Center]}];      Same happens with               CreateDialog[{"¿Hasta dónde se lava la cara un pelado?",         Cell["bo", TextAlignment -> Center]}];      However               CreateDialog[{"¿Hasta dónde se lava la cara un pelado?",         Style["bo", TextAlignment -> Center]}, WindowSize -> {300, 100}];


title: Write 199319989756262759279209 = 5x + y, where x and y are integers

text: $\frac{199319989756262759279209}{5} $ = $ 3.9864\times 10^{22}$ according to _Mathematica_ , but I would like to see this number exactly in decimal form (not in scientific notation). I'm attempting to use the Euclidean Algorithm and Extended Euclidean algorithm to get a final result, and precision and accuracy both are very much needed. This number truncated would give me x and then y is simply the difference of that large number and `5 x`. Unless there's an easier way to do the Euclidean algorithm in _Mathematica_ as well that'd be nice.


title: intersection of two lines with a slope slider

text: I am trying to build an IS/LM model with sliders for a few things including the slope of the IS curve. I am stuck getting the equilibrium ticks and dashed lines to properly follow the intersection of the two lines when the slope is changed. I have tried incorporating my variable `i` in as many ways as I can think of into the ticks and dashed lines, but continually come up short. I am a newbie at _Mathematica_ and the code is confusing the hell out of me and making the basic math more confusing for me. Help!               Manipulate[       Show[         Plot[Tooltip[s + .8 *q, "LM"], {q, 0, 150},            AxesOrigin -> {0, 0}, PlotStyle -> {Thick, Blue},            AxesLabel -> {"GDP", "Interest Rate"},            PlotRange -> {{0, 100}, {0, 100}}, PlotLabel -> IS LM,            Ticks -> {{{0.77*d - (0.77*s), "GDP"}}, {{d - i*(0.77*d - (0.77*s)), "r"}}},            BaseStyle -> {FontWeight -> "Bold", FontSize -> 12}],          Plot[Tooltip[d - i*q, "IS"], {q, 0, 200},            AxesOrigin -> {0, 0}, PlotStyle -> {Thick, Green}],          Graphics[{Dashed,            Line[{{0.77*d - (0.77*s), 0},                  {0.77*d - (0.77*s), d - i (0.77*d - 0.5 (0.77*s))}}]}],          Graphics[{Dashed,            Line[{{0, d - i (0.77*d - (0.77*s))},                  {0.77*d - (0.77*s), d - i (0.77*d - (0.77*s))}}]}]],        {{d, 75, "Fiscal Policy"}, 50, 100, 2},       {{s, 0, "Monetary Policy"}, 0, 100, 2},        {{i, .5, "Interest Sensitivity"}, 0, 5, .1}]


title: Hatched bars and bar-specific background in BarChart

text: I would like to diagonally hatch the bars in `BarChart` and to have three different background colors for the different bars, like this: ![enter image description here](http://i.stack.imgur.com/iXa9S.png) Any ideas how to reproduce this image? The closest post I found is here.


title: Import xls data with dates

text: I have an excel table that have 2 columns, the first one are dates, and the second one are values. I want to plot the value vs the date. I need to: first clean all the non numbers strings like {"Junio",""}, then make the date to something that Mathematica would understand. > {{"Unidad Indexada", ""}, {"Período Junio 2002 -", ""}, {"", ""}, {"", > "Valor"}, {"Fecha", "Pesos ($)"}, {"", ""}, {"", ""}, {"2 0 0 2", ""}, {"", > ""}, {"Junio", ""}, {"", ""}, {{2002, 6, 1, 0, 0, 0.}, 1.}, {{2002, 6, 2, 0, > 0, 0.}, 1.0004}, {{2002, 6, 3, 0, 0, 0.}, 1.0008}, {{2002, 6, 4, 0, 0, 0.}, > 1.0012}, {{2002, 6, 5, 0, 0, 0.}, 1.0016}, {{2002, 6, 6, 0, 0, 0.}, 1.002}, > {{2002, 6, 7, 0, 0, 0.}, 1.0024}, {{2002, 6, 8, 0, 0, 0.}, 1.0029}, {{2002, > 6, 9, 0, 0, 0.}, 1.0033}, {{2002, 6, 10, 0, 0, 0.}, 1.0037}, {{2002, 6, 11, > 0, 0, 0.}, 1.0041}, {{2002, 6, 12, 0, 0, 0.}, 1.0045}, {{2002, 6, 13, 0, 0, > 0.}, 1.0049}, {{2002, 6, 14, 0, 0, 0.}, 1.0053}, {{2002, 6, 15, 0, 0, 0.}, > 1.0057}, {{2002, 6, 16, 0, 0, 0.}, 1.0061}, {{2002, 6, 17, 0, 0, 0.}, > 1.0065}, {{2002, 6, 18, 0, 0, 0.}, 1.0069}, {{2002, 6, 19, 0, 0, 0.}, > 1.0074}, {{2002, 6, 20, 0, 0, 0.}, 1.0078}, {{2002, 6, 21, 0, 0, 0.}, > 1.0082}, {{2002, 6, 22, 0, 0, 0.}, 1.0086}, {{2002, 6, 23, 0, 0, 0.}, > 1.009}, {{2002, 6, 24, 0, 0, 0.}, 1.0094}, {{2002, 6, 25, 0, 0, 0.}, > 1.0098}, {{2002, 6, 26, 0, 0, 0.}, 1.0102}, {{2002, 6, 27, 0, 0, 0.}, > 1.0106}, {{2002, 6, 28, 0, 0, 0.}, 1.0111}, {{2002, 6, 29, 0, 0, 0.}, > 1.0115}, {{2002, 6, 30, 0, 0, 0.}, 1.0119}, {"", ""}, {"Julio", ""}, {"", > ""}, {{2002, 7, 1, 0, 0, 0.}, 1.0125},...


title: ReadList can't read correctly

text: I'm trying to load some data into Mathematica from some files generated by fortran. But ReadList seems can't get the number correct. Here is a simplified version of the problem:               ReadList[StringToStream@" 0.000000000000000000E+00        0.490953850725349982E-10        0.135898165173686872E-09        0.264968686580858939E-09", Number]     (*{0.,4.9095385072534998*10^12709,1.3589816517368687*10^12708,2.6496868658085894*10^12708}*)      In the documentation, it promised that: > ReadList can handle numbers that are given in Fortran-like "E" notation. > Thus, for example, ReadList will read 2.5E+5 as 2.5*10^5. Note that ReadList > can handle numbers with any number of digits of precision. Why ReadList can't read this correctly? Is this a bug? `Import` can get the numbers correct               Import[Export["/work/mwu3/temp/1234.dat", " 0.000000000000000000E+00        0.490953850725349982E-10        0.135898165173686872E-09        0.264968686580858939E-09"], "List"]     (*{0.,4.9095385072534998*10^-11,1.3589816517368687*10^-10,2.6496868658085894*10^-10}*)      but I have very large data files, `Import` would take forever. Is there a way to solve it? Here is my system information: Mathematica: 9.0 for Linux x86 (64-bit) (November 20, 2012), ReleaseID -> 9.0.0.0 os : Linux version 2.6.32-358.6.2.el6.x86_64 (mockbuild@x86-022.build.eng.bos.redhat.com) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC) ) #1 SMP Tue May 14 15:48:21 EDT 2013


title: Using high RasterSize or ImageResolution changes contour pattern

text: I found that the detailed contour pattern will be altered if we `Rasterize` the original graphics using high `RasterSize` or `ImageResolution`. Here is an example:               g = ContourPlot[Sin[x] Sin[y], {x, -3, 3}, {y, -3, 3},            Contours -> Function[{min, max}, Range[min, max, 0.01]],            ContourStyle -> Directive[Black, Opacity[.3], Thickness[.002]],            ImageSize -> 500]      which looks like ![enter image description here](http://i.stack.imgur.com/Ud9tC.png) Now we `Rasterize` g using four times its original pixel size               dim = ImageDimensions@Rasterize[g];     Rasterize[g, RasterSize -> 4*dim]      and we obtain ![enter image description here](http://i.stack.imgur.com/Rmq3j.png) So the patterns of the contour lines are different. I firstly think that this problem can be solved by increasing the `Thinckness` value in `ContourStyle`, but this will not make the result better. I wonder if we can improve it? * * * **Update** As a workaround, can we try to preserve the pattern by keeping the contour in vectot format (together with axis and ticks), and only `Rasterize` the background? In this case I think there might be problems with the thickness of contour lines.


title: Need help with exception handling

text: I have read the docs for `Catch`, `Throw`, and friends multiple times, and I confess that I find them utterly incomprehensible... Can someone tell me how one would port the following Python snippet to Mathematica?               def safeeval(fn, x, epsilon=sys.float_info.epsilon):         try:             # first attempt             return fn(x)         except Exception, first_exception:             try:                 try:                     # second attempt                     return fn(x + epsilon)                 except:                     # third (and last) attempt                     return fn(x - epsilon)             except:                 # give up!                 raise first_exception      In words: return `fn(x)`, trapping any exceptions during the evaluation of `fn(x)`. If there is an exception, cache it in `first_exception`, and return `fn(x + epsilon)`, again trapping any exceptions. If there is again an exception (a second one), return `fn(x - epsilon)`. Lastly, if there is again an exception (a third one), give up and re-raise `first_exception`. A higher-level, less literal translation of the above would be this: return the first one of `fn(x)`, `fn(x + epsilon)`, and `fn(x - epsilon)` that evaluates without errors ( _silencing any errors that do occur along the way_ ). If none of these expressions evaluates without errors, then proceed exactly as with the usual evaluation of `fn(x)` (emitting the appropriate error messages, etc.). * * * EDIT: OK, I finally came up with a solution that approximates what I described above, though I'm not sure it's anywhere close to optimal:               safeEval[fn_, x_, epsilon_:$MachineEpsilon]:= Module[{v, sentinel},         v = Quiet[Check[fn[x],                         Check[fn[x+epsilon],                               Check[fn[x-epsilon],                                     sentinel]]]];         If[v =!= sentinel, v, fn[x]]     ]      I was (*ahem*) thrown off by the whole `Catch`, `Throw` nomenclature. (These functions now seem to me like something unnaturally tacked onto Mathematica to make it look more like other more widely known languages.)


title: How to find the positive region of this function?

text: I'm new-ish to Mathematica and I'm using it to learn the basics of derivative trading (for fun not for trading!). I've defined a simple function to calculate the pay off of a trading on a call. I have no problem drawing the P/(L) diagram but I cannot find which Mathematica function to use to get the region of x for which my P/(L) is positive. Can you help? * * * My function is basic and calculates the difference between the cost of the call (callPremium) and value of the Call at expiration:                PayOffCall[currentPrice_?NumberQ, strikePrice_?NumberQ,         callPremium_?NumberQ] :=        FinancialDerivative[{"European",           "Call"}, {"StrikePrice" -> strikePrice,           "Expiration" -> 0}, {"InterestRate" -> 0.1, "Volatility" -> 0.2,           "CurrentPrice" -> currentPrice, "Dividend" -> 0.05}] -         callPremium;      I can then easily plot the P/(L) diagram               ListLinePlot[{#, PayOffCall[#, 50, 2]} & /@ Range[47, 57, 1],       AxesLabel -> {"Strike Price at Expiration", "P/(L)"}]      ![enter image description here](http://i.stack.imgur.com/oLk0S.jpg) I can find the break-even point:               In:= FindRoot[PayOffCall[x, 50, 2] == 0, {x, 47, 57}] // Quiet     Out:= {x -> 52.}      And now I'd like Mathematica to tell me that _PayOffCall[x,50,2] is positive for x>=52_. I've tried different function without any success: Solve,NSolve, FindMaximum, etc... but I think my Mathematica skills are letting me down. For instance:               In:= NSolve[PayOffCall[x, 50, 2] > 0, x]     NSolve::nsmet: This system cannot be solved with the methods available to NSolve. >>     Out:= NSolve[PayOffCall[x, 50, 2] > 0, x]      I'd like to know the right function to return:               Out:= {x>52.}      Any help to this newbie question is much appreciated! * * * Thanks to b.gatessucks for his answer. Now if I define an additional function for Put               PayOffPut[currentPrice_?NumberQ, strikePrice_?NumberQ,         putPremium_?NumberQ] :=        FinancialDerivative[{"European",           "Put"}, {"StrikePrice" -> strikePrice,           "Expiration" -> 0}, {"InterestRate" -> 0.1, "Volatility" -> 0.2,           "CurrentPrice" -> currentPrice, "Dividend" -> 0.05}] -         putPremium;      I can draw the P/L diagram for a "Long Straddle" where I buy a 50 Call at 3 USD and I buy 50 Put at 2 USD               ListLinePlot[{#, PayOffCall[#, 50, 3] + PayOffPut[#, 50, 2]} & /@        Range[41, 59, 1],       AxesLabel -> {"Strike Price at Expiration", "P/(L)"}]      ![enter image description here](http://i.stack.imgur.com/pAN6n.jpg) But then neither FindRoot or NMinimize return the correct region               In:= FindRoot[PayOffCall[x, 50, 3] + PayOffPut[x, 50, 2] == 0, {x, 47, 57}]     Out:= {x -> 55.}     In:= NMinimize[{x, 41 < x < 60,        PayOffCall[x, 50, 3] + PayOffPut[x, 50, 2] > 0}, x]     Out:= {41., {x -> 41.}}      What's the solution then!? * * * **Update** Thanks to eldo and b.gatessucks answers, I created the following simple algorithm:               << RootSearch`     f[x_] := PayOffCall[x, 50, 3] + PayOffPut[x, 50, 2];     r = RootSearch[f[x] == 0, {x, 1, 100}]; // Quiet     r2 = x /. r; AppendTo[r2, r2[[-1]]*1.5]; PrependTo[r2, 0.0001];     r2 = Partition[r2, 2, 1]     Do[       v = f[#] & /@ Range[##, 1.] & @@ r2[[n]];       AppendTo[r2[[n]], "Profit" -> AllTrue[v, # >= 0 &]],       {n, Length[r2]}];     r2      Which returns what I needed:               {{0.0001, 45., "Profit" -> True}, {45., 55., "Profit" -> False}, {55.,        82.5, "Profit" -> True}}


title: Set defaults for ViewPoint and AxesLabel

text: Instead of adding `AxesLabel -> {x, y, z}` every time to code in order that the axes appear, how can I make _Mathematica_ display the axes by default? Also, how can I get _Mathematica_ to display the axes, by default, as they are shown in the following image? I want to obviate having to by rotate my images manually every time _Mathematica_ makes its initial display. ![enter image description here](http://i.stack.imgur.com/WhEXS.jpg)


title: Plot points, line and plane in one 3D plot

text: What's the easier way to plot these coincidently in 3D: ● The plane $5x - 4y - 9z = 0$   ● Parametric line $x = t, y = t/2, z = t/3$   ● Two points: $(0, 0, 0), (1, -1, 1)$ ? Moreover, how can I pick a distinct colour for each and to choose the size of the points? I tried the following, but to no avail:               aa = ContourPlot3D[       5 x - 4 y - 9 z == 0, {x, -10, 10}, {y, -10, 10}, {z, -10, 10},        AxesLabel -> {x, y, z}]          bb = ParametricPlot3D[       {t, t/2 t, t/3}, {t, -10, 10},        PlotStyle -> RGBColor[1, 0, 1], AxesLabel -> {x, y, z}]        cc = ListPlot3D[{0, 0, 0}, {1, -1, 1}, AxesLabel -> {x, y, z}]         Show[aa, bb, cc]      I referenced Normal lines to surfaces or planes in a 3D plot, http://stackoverflow.com/questions/7435954/plot-plane-point-line-sphere-in- same-3d-plot-multiple-figures-in-same-plot, and http://www.math.uconn.edu/~hurley/math220/Mathematica_docs/Lines.pdf.


title: How can I draw a curve through as set of xyz points?

text: I have a list of data and want to make a curve like the one below which I made in solidworks. The problem of this curve is, that I don't know how to put it in a box with coordinates. ![](http://i.stack.imgur.com/djJVR.png) The best I could get in _Mathematica_ are points connected with lines, which is not good enough. My code is:               Graphics3D[       {Red, Line[pot], Black, AbsolutePointSize[6], Point[pot]},        BoxRatios -> {3, 2, 1.5}, Axes -> True, ImageSize -> 450]      And this the image it produces: ![enter image description here](http://i.stack.imgur.com/5KLfT.png) Is there a solution?


title: How can I adjust the span between under bar and formula

text: ### _Mathematica_ : ![Mathematica graphics](http://i.stack.imgur.com/478z2m.png) ### LaTeX: $\alpha =\underset{\square }{\overset{\square }{\lim \sup \sqrt[n]{\left|a_n\right|}}}$


title: How to get control over DepthFirstScan?

text: Is there a way to **conditionally** take control the flow during a depth-first scan against a **TreeGraph**? I have a tree graph whose nodes are constructed as object, and there's a method `isTrue[para_]` for each node.               isValid[desc] = "Check whether input is valid";     isValid[isTrue, para_] := Module[{result},         result = SyntaxQ[para];         Return[result];     ];          isNumber[desc] = "Check whether input is a number";     isNumber[isTrue, para_] := Module[{result},         result = NumberQ[ToExpression[para]];         Return[result];     ];          isInteger[desc] = "Check whether input is an integer";     isInteger[isTrue, para_] := Module[{result},         result = IntegerQ[ToExpression[para]];         Return[result];     ];          isFraction[desc] = "Check whether input is a fraction";     isFraction[isTrue, para_] := Module[{result},         result = !IntegerQ[ToExpression[para]];         Return[result];     ];           tree =        TreeGraph[{isValid, isNumber, isInteger, isFraction},          {isValid -> isNumber, isNumber -> isInteger, isNumber -> isFraction},         VertexLabels->"Name"];      Here is the tree image of the code, The root is `isValid`. ![The structure of tree](http://i.stack.imgur.com/O208W.png) If my input is "3.5", I expect the depth-scan flow should be `isValid -> isNumber -> isFraction` because the `isInteger` gives `False`. I tried `Abort[]` like (as well as `Return[]`):               DepthFirstScan[tree, isValid,       "DiscoverVertex" -> (If[#[isTrue, "3.5"], Print[#], Abort[]]&)];      But this broke the whole scan flow. What I want is: when the node gives `False`, it and its child-nodes should be skipped, but the scan should continue scanning the remaining nodes.


title: Expression evaluation inside of FindRoot inside a Compiled Function

text: I'm trying to get some performance increase out of my own implicit differential equation solver using `Compile[]`. The uncompiled function is of the following form:               fun = Module[       {sol = ConstantArray[0, 10], init = 0.001},       f[xN_] = xN + xNP1^2 == 4;       Do[         sol[[i]] = xNP1 /. FindRoot[f[init], {xNP1, init}];         init = sol[[i]]         , {i, 10}       ];       sol     ]      which works correctly. Of course, for the real function I need many more than 10 iteration in the loop and was hoping to gain some performance increase with `Compile[]`. Here is the compile code:               cFun = Compile[{},              Module[                {sol = ConstantArray[0, 10], init = 0.001},                f[xN_] = xN + xNP1^2 == 4;                Do[                  sol[[i]] = xNP1 /. FindRoot[f[init], {xNP1, init}];                  init = sol[[i]]                  , {i, 10}                ];                sol              ]           ]      However, the compiled function fails with because `f[init]` is held unevaluated as passed into `FindRoot`, I believe. Is there a way around this or another solution I am not thinking of?


title: Problem with exporting nested Rows/Columns to HTML

text: I will show the problem on the following MWE:               Export["test.html",            Column[{ Row[{"test", "1"}]  }],            "HTML",            "CSS" -> None]      > >     $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> >     General::stop: Further output of $RecursionLimit::reclim will be > suppressed during this >     calculation. >> >   Single `Row[{"test", "1"}]` without `Column` produces no error. Also let's assume I can't use `Grid`.


title: How can I increase the number of polygons / resolution for this plot?

text: I have generated the following plot: ![enter image description here](http://i.stack.imgur.com/vrDYA.png) Code:               RegionPlot3D[  x^2 + z^2 < 1 &&   x^2 + y^2 < 1, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, Axes -> False]      However, the resolution is a bit poor in the plot above. How can I increase the polygon count or increase the resolution some other way?


title: Saving Animate[...] as GIF using Save Graphic As

text: Is saving an animation as simple as clicking "Save Graphic As..." in the right-click context menu of the animation? It doesn't seem to work for me--the file naming dialog comes up and I click "Save" but no file seems to be created. I read about using `Manipulate` and `Export`, but keep running into errors going this route (like the kernel hanging and Dynamic Update disabling). I'll keep playing with the code, but was hoping there'd be an easier way to save the animation, "WYSIWYG"-style. ![Can't save graphic as...](http://i.stack.imgur.com/xcsAr.png) The full code is below:               prices = FinancialData["QCOM", All][[All, 2]]     S[x_] := MovingAverage[prices, x];     F[x_] := MovingAverage[prices, x];     Animate[si = Interpolation[S[s]]; fi = Interpolation[F[f]];       Show[ListPlot[{prices, S[s], F[f]},         PlotStyle -> {RGBColor[0.7, 0.7, 0.7], Blue, Red},         Joined -> {True, True, True}, PlotStyle -> {Thin, Thin, Thin}],        Plot[{si[x], fi[x]}, {x, 1, Length[S[s]]},         MeshFunctions -> {(si[#] - fi[#]) &}, Mesh -> {{0}},         MeshStyle -> Directive[Red, PointSize[Large]]],        ImageSize -> {480, 300}], {{s, 150}, 150, 1000, 1}, {{f, 79}, 79,        460, 1}, AutorunSequencing -> All, AnimationDirection -> Backward]      I'm new to Mathematica; I apologize if I'm missing something obvious... * * * I tried @Nasser's code, but keep getting this every 10 or so seconds: ![Continue waiting](http://i.stack.imgur.com/5YVOk.png)


title: SetAttributes[f,Flat]: Why the order dependence?

text: I'm experiencing a strange phenomenon. Here's a (quite artificial) test case: The following definition work just fine:               f[x___Real]:={x}     g[a_,f[n_Integer]]:={a,n}     SetAttributes[f,Flat]          f[a,f[b,c]]     (*      --> f[a,b,c]     *)          g[f[1.0],3]     (*      --> g[{1.},3]     *)      As do the following (in a fresh kernel):               f[x___Real]:={x}     SetAttributes[f,Flat]     g[a_,f[n_Integer]]:={a,n}          f[a,f[b,c]]     (*      --> f[a,b,c]     *)          g[f[1.0],3]     (*      --> g[{1.},3]     *)      However, the following (evaluated in a fresh kernel again) hangs on the definition of `g`:               SetAttributes[f,Flat]     f[x___Real]:={x}     g[a_,f[n_Integer]]:={a,n}      Now I don't see any reason why the definition of `g` should depend on whether I've first defined `f` or first set the `Flat` attribute on it. Can anyone explain the mystery? PS: If anyone can think of a better title, feel free to change it accordingly.


title: Convergence in NIntegrate vs Integrate

text: I am faced with this situation that for a certain integration, $\int _0 ^\infty \frac { \tanh (\pi \sqrt{x} )} {\sqrt{x+10} } dx$ - the command `Integrate` returns that this doesn't converge but `NIntegrate` gives back a number - but after some messages about slow convergence and precision etc. What exactly is going on? What is the "right" answer?


title: Control variable and body variable decoupling in Manipulate

text: This issue was raised as an offside problem in this thread. Consider the following example, that does not work as expected:               Manipulate[{x, r}, {{x, r}}, {r, 0, 1}]      Note that as `r` is manipulated the `InputField` of `x` is updated (as the initial value of `x` is set to be `r`) **but not the** `x` displayed as the body of the `Manipulate`. Interestingly, if `x` depends on `r` in a different way (endpoints of range instead of initial value) the example works as expected: whenever `r` is changed it changes both the displayed values of `x`:               Manipulate[{x, r}, {x, r, 1}, {r, 0, 1}]      It seems like that in `Manipulate` changing a variable (`r`) does not trigger a re-evaluation of the initial-value-dependent variable (`x`) displayed in the body though its value displayed in the control is updated correctly. **I have no idea why the first example does not work the same way as the second does.** While it might be said that this is a feature, I would argue that the unexplained decoupling of the two representations of `x` (as body and control) is quite disturbing. **Workarounds**   1. The re-evaluation can be triggered by making `x` dynamic:              Manipulate[{Dynamic[x], r}, {{x, r}}, {r, 0, 1}]        2. Moving the definition of `x` out of the control-arguments to the body of the `Manipulate`:              Manipulate[{x = r, r}, {r, 0, 1}]        3. Rewriting it in `DynamicModule`: it has an explicit function inside the `Dynamic` of `r` that sets `x` whenever `r` is modified:              Panel@DynamicModule[{x, r = .5},         x = r;         Grid[{               {"x", InputField[Dynamic[x]]},               {"r", Slider[Dynamic[r, (r = #; x = #) &], {0, 1}]},               {Panel[Dynamic@{x, r}], SpanFromLeft}              }, Alignment -> Left]         ]


title: How to solve simultaneous equations faster with Compile?

text: I have large 6x6 matrix `U`which is a multiplication of 15 rotational matrix. All of the elements are `Sin\\[theta]` and `Cos\\[Theta]`. I have to solve simultaneous equations using the matrix elements. Yesterday i ran the code for 14 hours with core i3 machine at windows 7. Still no output. I know that `Complie` can run code quicker but i am not an expert on this. So i need help. here is the code.I tried but failed to use complie here. how to use complie or how can i run the code faster?               Solve[U[[2,4]]==0.12 && U[[1,4]]==0.11 && U[[2,5]]==0.17 && U[[1,5]]==0.11 &&           U[[2,6]]==0.14 && U[[1,6]]==0.11 &&           U[[3,1]]==0    && U[[3,2]]==0    && U[[3,3]]==0    && U[[3,4]]==0    &&            U[[3,5]]==0    && U[[3,6]]==0,       {\[Theta]12, \[Theta]13, \[Theta]14, \[Theta]15, \[Theta]16, \[Theta]23, \[Theta]24,         \[Theta]25, \[Theta]26, \[Theta]34, \[Theta]35, \[Theta]36, \[Theta]45, \[Theta]46,         \[Theta]56}     ]


title: Elementwise, compilable min function

text: I am trying to implement efficiently a transfer-matrix like algorithm. On each iteration, I have two vectors $x=\{x_1,\dots,x_n\}$, $y=\{y_1,\dots,y_n\}$ with real numbers and I need to compute the vector $\{\min(x_1,y_1),\dots,\min(x_n,y_n)\}$. I tried four approaches for computing it:   1. Uncompiled `MapThread[Min,{listX,listY}]` call   2. Compiled `MapThread[Min,{listX,listY}]` call   3. Uncompiled `Random`Private`MapThreadMin[{listX,ListY}]` call   4. Compiled `Random`Private`MapThreadMin[{listX,ListY}]` call (Code see below). The resulting timings were: 4.5s (for 1), 3.5s (for 2), 1.5s (for 3) and 4 reverted to uncompiled evaluation, giving 6.3s. So my questions are:   1. Is the uncompiled `Random`Private`MapThreadMin[{listX, ListY}]` call the fastest way to evaluate the element-wise minimum of two lists, or does anybody have a better idea?   2. Why does the example using `Random`Private`MapThreadMin[{listX, ListY}]` fail to compile? My code examples are:               it1[wd_, len_] :=          Module[{pot1, fval},          pot1 = RandomVariate[NormalDistribution[], {len, wd}];         fval = ConstantArray[0., wd];         Do[fval = MapThread[Min, {RotateLeft[fval], fval}] + pot1[[k]];, {k, 1, len}];         Return[fval]];          it2 := Compile[{{wd, _Integer}, {len, _Integer}},         Module[{pot1, fval},          pot1 = RandomVariate[NormalDistribution[], {len, wd}];         fval = ConstantArray[0., wd];         Do[fval = MapThread[Min, {RotateLeft[fval], fval}] + pot1[[k]];, {k, 1, len}];         Return[fval]]];          it3[wd_, len_] :=          Module[{pot1, fval},          pot1 = RandomVariate[NormalDistribution[], {len, wd}];         fval = ConstantArray[0., wd];         Do[fval = Random`Private`MapThreadMin[ {RotateLeft[fval], fval}] + pot1[[k]];, {k, 1, len}];         Return[fval]];          it4 := Compile[{{wd, _Integer}, {len, _Integer}},         Module[{pot1, fval},          pot1 = RandomVariate[NormalDistribution[], {len, wd}];         fval = ConstantArray[0., wd];         Do[fval = Random`Private`MapThreadMin[ {RotateLeft[fval], fval}] + pot1[[k]];, {k, 1, len}];         Return[fval]]];      And to obtain the timing values, I used               Table[it1[20, 10] // First, {10000}]; // AbsoluteTiming     Table[it2[20, 10] // First, {10000}]; // AbsoluteTiming     Table[it3[20, 10] // First, {10000}]; // AbsoluteTiming     Table[it4[20, 10] // First, {10000}]; // AbsoluteTiming      Thank you in advance!


title: Speed up adding Poisson noise to an image

text: I'm simulating some images corrupted with Poisson noise, but I'm encountering a few problems with performance. According to the documentation on `ImageEffect`, one can add Poisson noise according to the following rule: ![enter image description here](http://i.stack.imgur.com/jfWZz.png) Loading up an example image, and running the code:               man256 = ImageAdjust[ImageResize[ExampleData[{"TestImage", "Man"}], {256, 256}]];     ImageAdjust[ImageEffect[man256, {"PoissonNoise", 0.8}]] // AbsoluteTiming          (* 10.839 seconds *)      Subsequently running it again in the same kernel, it only takes 0.196 seconds. Meanwhile, the Gaussian noise effect:               ImageAdjust[ImageEffect[man256, {"GaussianNoise", 4.}]] // AbsoluteTiming          (* 0.014 seconds *)      And then running it again once more, it only takes 0.006 seconds. I tried defining my own functions for adding Poisson and Gaussian noise for comparison. Note that I define the amount of Poisson noise slightly differently to the Mathematica method (in a way that actually makes more sense to me).               addPoissonNoise[x_, peak_] :=       Block[{imagedata},        imagedata = peak*ImageData[x];        Map[If[# == 0., 0., RandomVariate[PoissonDistribution[#]]] &, imagedata, {2}]        ];          addGaussianNoise[x_, sig_] :=       Block[{imagedata},        imagedata = ImageData[x];        Map[# + RandomVariate[NormalDistribution[0., sig]] &, imagedata, {2}]        ];          ImageAdjust[Image[addPoissonNoise[man256, 40.]]] // AbsoluteTiming     (* 6.495 seconds *)          ImageAdjust[Image[addGaussianNoise[man256, 4.]]] // AbsoluteTiming     (* 0.007 seconds *)      So on an initial run, my code is faster than the built-in code in both cases. But on subsequent runs, it's slower than the built-in code. Considerably slower in the case of Poisson noise. The Gaussian example is only for comparison - it's the Poisson noise I'm more interested in, and speeding up the **initial** run of the code, as ~10 seconds is considerably slower than I'd like, and in reality my images are bigger than 256x256 pixels. Is there any way to speed-up the corruption of an image with Poisson noise? **Update #1** Replacing `Map` with `ParallelMap` speeds up my Poisson noise function, but it's still quite slow (taking about 1.89 seconds on my machine). Avoiding multiple calls to `RandomVariate` is hard to avoid, I think. It's a shame `PoissonDistribution` can't be compiled (Which Distributions can be Compiled using RandomVariate). **Update #2** There's this question: Why is Poisson Random Deviate Generation so slow? (For info, this is with v10 on Win8.1)


title: How to pick out the element in a list of lists which satisfies a particular condition?

text: I have got a list:               lis:={     {{1, 2, 3, 4}},     {{1, 2, 3}, {4}},     {{1, 2, 4}, {3}},     {{1, 2}, {3, 4}},     {{1, 2}, {3}, {4}},     {{1, 3, 4}, {2}},     {{1, 3}, {2}, {4}},     {{1, 4}, {2, 3}},     {{1}, {2, 3, 4}},     {{1}, {2, 3}, {4}},     {{1, 4}, {2}, {3}},     {{1}, {2, 4}, {3}},     {{1}, {2}, {3, 4}},     {{1}, {2}, {3}, {4}}     };      and I would like to pick out those lists which satisfy the following condition:               list == Mod[list+2,4,1]      but, they should be "equal" as a set of lists, not in a "element to element" way. For example, `{{1,2},{3,4}}` is a list satisfied the condition, since `Mod[{{1,2},{3,4}}+2,4,1]` is `{{3, 4}, {1, 2}}`, which is not equal to `{{1,2},{3,4}}` since the "position" is not right, but we should regard it as equal in the sense of set, since they are both the set of `{1,2}` and `{3,4}`. An example which not satisfied our condition is that `{{1,2,3},4}`, since `Mod[{{1, 2, 3}, 4} + 2, 4, 1]` is `{{3, 4, 1}, 2}`, as a set they are not equal, one is the union of `{1,2,3}` and `{4}`, but the results is the union of `{1,3,4}` and `{2}`. Can I use a pattern to sort out the one satisfied my condition in the list? I would like to make it work with any list.


title: How to write beveled fractions?

text: How to write beveled fractions like ${}^a/_b$? In contrast to $\frac{a}{b}$ and $a/b$ (see this question).


title: Is It Possible To Replicate Tab Stop Behaviour (or Even PageFooter Behaviour but in Regular Cell)

text: I am trying to insert a (text) cell into a notebook that replicates the behaviour of tab stops in MS Word, for example. Put differently, I have two strings and I want the one string to align on the left side of a page and the other string to align on the right side of the page _but on the same line_. I thought it may perhaps be possible using some version of:               Cell[         TextData[{                 Cell["First String",TextAlignment->Left], " \t ",                 Cell["Second String",TextAlignment->Right]         }], "Text"]      Of course, this doesn't work. In fact, I have realised that I can't use regular menu formatting commands to create the effect I want in a cell (so that I could look at the raw expression and see how it is done). Perhaps it can't be done? **However** I do know, for example, that one can set the `PageFooters`/`PageHeaders` option in the stylesheet for a notebook and that this option is preset to accept a list like `{{ll,lc,lr},{rl,rc,rr}}` where the first list is for left-facing pages and the second for right-facing pages and the three elements in each list correspond to left alignment, center alignment and right alignment of text in the footer (essentially what I want to do in a regular cell). Any suggestions?


title: Help in NIntegration Methods - Takes too long, why?

text: I have this code. It is a triple integral, and using the automatic method gives me a wrong answer for $T=0.1$ (the correct answer is $5.44$, while I got $3.73$ ). I've tried to change the integral method to `GaussKronrodRule`, but it takes too long (until now, hours) and also I received a message > Return::nofunc: Function Module not found enclosing > Return[False,Module].Parallel`Developer`QueueRun::hmm: Received unexpected > result . And for $T > 1$ gives the correct results, in the automatic method mode. I think it is a problem in the method of `NIntegrate`, right ? 1) How can I solve that ? 2) In Fortran, I have a gausslegendre method. Is this option available in _Mathematica_?               σ = 0.6;          minroot[g_?NumericQ,b_?NumericQ]:=     Module[{rts,r},        rts=r/.Solve[1-(b/r)^2-g^-2*(2/15*σ^9 (1/(r-1)^9-1/(r+1)^9-9/(8r)                     (1/(r-1)^8-1/(r+1)^8))-σ^3 (1/(r-1)^3-1/(r+1)^3-3/(2r)                     (1/(r-1)^2-1/(r+1)^2)))==0,r];       rts=Select[rts,With[{nval=N[#,100]},Im[nval]==0&&nval>0]&];       Max[rts]];          aA[g_?NumberQ,b_?NumberQ,i_]:=Pi-2 b         NIntegrate[         1/(r^2*Sqrt[1-(b/r)^2-g^-2*(2/15* σ^9 (1/(r-1)^9-1/(r+1)^9-9/(8r) (1/(r-1)^8-1/(r+1)^8)) -         σ^3 (1/(r-1)^3 - 1/(r+1)^3-3/(2r) (1/(r-1)^2-1/(r+1)^2)))]),            {r,minroot[g,b],Infinity},         Exclusions->             {r^2*Sqrt[1-(b/r)^2-g^-2*(2/15*σ^9 (1/(r-1)^9-1/(r+1)^9-9/(8r) (1/(r-1)^8- 1/(r+1)^8))-             σ^3 (1/(r-1)^3-1/(r+1)^3-3/(2r) (1/(r-1)^2-  1/(r+1)^2)))]==0},         MaxRecursion->i,Method->{Automatic,"SymbolicProcessing"->0}];          qQ[g_?NumberQ,i_]:=       NIntegrate[2*(1-Cos[aA[g,b,i]]) b,                 {b,0,10},                  MaxRecursion->i, Method-> {Automatic,"SymbolicProcessing"->0}];          o[T_,i_,j_]:=       (1/T^3) NIntegrate[(g^5*qQ[g,i])/E^(g^2/T),                 {g,0,Infinity},                 MaxRecursion->j,                 Method->{Automatic,"SymbolicProcessing"->0}];


title: Orthogonalizing without normalizing

text: Is there a way to make `Orthogonalize` do the normal Gram-Schmidt procedure without normalizing the result? As far as I've understood this was possible with Mathematica 5.2. One way would be to just multiply with the norms but being complicated expressions the whole thing would be easier without normalizing in the first place.


title: How to export 3D graphics to Collada (.dae) format?

text: I'm looking for a way to export 3D graphics objects to the Collada (`.dae`) format. I need an automated way, i.e. using Blender to manually convert from another format is not a good solution. I'm sure all of the following is not possible at the same time, but ideally:   * Aspect ratio (`BoxRatios`) should be preserved   * Colours should be preserved (if possible)   * Visible bounding box should be preserved (if possible)   * Initial view point should be preserved when opening the file in a viewer (if possible)   * Supporting `Polygon` and `Cuboid` is sufficient. * * * Information that would help me implement this myself:   * Which formats that Mathematica supports can theoretically handle most of the requirements above? Out of these, which one does Mathematica have the best support for?   * Are there command line programs or other Mathematica-controllable tools that can convert a Mathematica-exportable format to Collada?


title: How can I solve an equation with symbolic coefficients?

text: I want to try to solve the following                a x^(17/6) - b x^2 - 1 == 0      where `a` and `b` are variable coefficients (which are very small and positive). I cannot get an analytic solution (not surprised), but `NSolve` is not doing the job for me. I am a novice to Mathematica; is anyone able to do `NSolve` for `x` on Mathematica and get a numerical result?


title: Collect terms in a sum

text: Suppose I have this expression                   Sum[F[i, j] KroneckerDelta[j, k], {j, 1, 3}]               (* F[i, 1] KroneckerDelta[1, k] + F[i, 2] KroneckerDelta[2, k] +                 F[i, 3] KroneckerDelta[3, k] *)      Is it possible for _Mathematica_ to present the contracted result               F[i,k]      ?


title: Subtracting results of NDSolve

text: I have 2 variables as a results from the `NDSolve[]` which are `ua` and `uw`. This is how I do it, and I got the result for `ua` and `uw` just fine and I can plot them.               eq1 = Derivative[2, 0][uw][z, t]*cwv -      Derivative[0, 1][ua][z, t]*cw == Derivative[0, 1][uw][z, t];          eq2 = Derivative[2, 0][ua][z, t]*cav -      Derivative[0, 1][uw][z, t]*ca == Derivative[0, 1][ua][z, t];          ic1 = {uw[zmax, t] == ui + p0, uw[z, tmin] == ui};          ic2 = {ua[z, tmin] == uatm};          sol2 = NDSolve[Flatten[{eq1, eq2, ic1, ic2}], {uw, ua}, {z, zmin, zmax}, {t, tmin,      tmax}, MaxSteps -> Infinity, MaxStepSize -> dt/step, InterpolationOrder -> All];`      However, I want to subtract the two variables such that: `result = (ua-101)-uw` and I failed. I use this as a code to subtract `result = ua[z, t] /. sol2 - 101 - uw[z, t] /. sol2;` Can someone please tell me the reason why it is failed and what should I do to fix this? The complete code is given as follows:               kw = 1*10^(-10);(*m/s*)          ka = 8*10^(-13);(*m/s*)          gw = 10;(*kN/m^3*)          m2w = 2.41*10^(-4);(*coefficient of compressibility of water phase with respect to matric suction*)          m1w = 0.8*10^(-4);(*coefficient of compressibility of water phase with respect to axial stress*)          m2a = 1.11*10^(-4);(*coefficient of compressibility with air phase with respect to matric suction*)          m1a = 0.37*10^(-4);(*coefficient of compressibility of air phase with respect to axial stress*)          p0 = 200;(*applied pressure -kPa*)          tmin = 0;(*minimum or time when the pressure is applied*)          tmax = 5000;(*latest inspected time*)          zmin = 0;(*top elevation*)          zmax = 0.02;(*bottom elevation*)          uatm = 101;(*kPa-atmospheric air pressure*)          step = 1000;(*The higher the step, the higher the accuracy*)          ui = -300;(*Initial matric suction*)          temp = 300;(*temperature in kelvin*)          wa = 28.97;(*kg/kmol*)          s = 0.7887;          n = 1.0696/(1 + 1.0696);          (*CALCULATION*)          r = 8.31432;(*Universal gas constant in j/(mol K*)          g = 9.8;(*gravity acceleration-m2/s*)          da = ka/g;          cwv = kw/(gw*m2w);          cw = ((1 - m2w/m1w)/(m2w/m1w));          ca = (m2a/m1a)/(1 - (m2a/m1a) - (1 - s)*n/(uatm*m1a));          cav = (da/(wa/(r*temp)*uatm))/(m1a*(1 - m2a/m1a) - (1 - s)*n);          dt = tmax - tmin;          (*Assuming that dua/dt is insignificant, Consolidation equation for unsaturated soil is duw/dt=cwv(d^2uw/dy^2)*)          eq = Derivative[2, 0][uw][z, t]*cwv == Derivative[0, 1][uw][z, t];          ic = {uw[zmax, t] == ui + p0, uw[z, tmin] == ui};          sol = NDSolve[Flatten[{eq, ic}], uw, {z, zmin, zmax}, {t, tmin, tmax},MaxSteps -> Infinity, MaxStepSize -> dt/step,InterpolationOrder -> All]          is = 300;(*ImageSize*)          Plot3D[uw[z, t] /. sol, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t, uw[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500]          Column[Manipulate[Plot[uw[z, t] /. sol, {z, zmin, zmax}, PlotRange -> All, AxesLabel -> {z, uw[z, t]}, ImageSize -> is], {t, tmin, tmax}], Manipulate[Plot[uw[z, t] /. sol, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {t, uw[z, t]}, ImageSize -> is], {z, zmin, zmax}],  Manipulate[Plot[{uw[z, tmin] /. sol, uw[z, t1] /. sol, uw[z, t2] /. sol, uw[z, t3] /. sol, uw[z, t4] /. sol, uw[z, tmax] /. sol}, {z, zmin,zmax}, AxesLabel -> {z, uw[z, t]}, ImageSize -> is], {t1, tmin + dt/300, tmin + dt/51}, {t2, tmin + dt/50, tmin + dt/16}, {t3, tmin + dt/15, tmin + dt/3}, {t4, tmin + dt/3, tmin + dt/1}]]               (*Assuming that dua/dt is significant*)     eq1 = Derivative[2, 0][uw][z, t]*cwv -      Derivative[0, 1][ua][z, t]*cw == Derivative[0, 1][uw][z, t];          eq2 = Derivative[2, 0][ua][z, t]*cav -      Derivative[0, 1][uw][z, t]*ca == Derivative[0, 1][ua][z, t];          ic1 = {uw[zmax, t] == ui + p0, uw[z, tmin] == ui};          ic2 = {ua[z, tmin] == uatm};          sol2 = NDSolve[Flatten[{eq1, eq2, ic1, ic2}], {uw, ua}, {z, zmin, zmax}, {t,tmin,tmax}, MaxSteps -> Infinity, MaxStepSize -> dt/step, InterpolationOrder -> All];               (*Coupled equation version*)     Column[Plot3D[uw[z, t] /. sol2, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All,AxesLabel -> {z, t, uw[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500],      Plot3D[ua[z, t] /. sol2, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t, ua[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500]]          Column[Manipulate[Plot[uw[z, t] /. sol2, {z, zmin, zmax}, PlotRange -> Full, AxesLabel -> {z, uw[z, t]}], {t, tmin, tmax}],Manipulate[Plot[uw[z, t] /. sol2, {t, tmin, tmax},PlotRange -> Full, AxesLabel -> {t, uw[z, t]}], {z, zmin,zmax}]]Column[Manipulate[Plot[ua[z, t] /. sol2, {z, zmin, zmax}, PlotRange ->Full,AxesLabel -> {z, ua[z, t]}], {t, tmin, tmax}],Manipulate[Plot[ua[z, t] /. sol2, {t, tmin, tmax}, PlotRange -> Full, AxesLabel -> {t, ua[z, t]}], {z, zmin, zmax}]]          Column[Manipulate[Plot[{uw[z, tmin] /. sol2, uw[z, t1] /. sol2, uw[z, t2] /. sol2,uw[z, t3] /. sol2, uw[z, t4] /. sol2, uw[z, tmax] /. sol2}, {z, zmin, zmax}, AxesLabel -> {z, uw[z, t]}, PlotRange -> Full, AxesLabel -> {z, uw[z, t]}], {t1, tmin + dt/1000, tmin + dt/51}, {t2, tmin + dt/50, tmin + dt/16}, {t3, tmin + dt/15,tmin + dt/3}, {t4, tmin + dt/3, tmin + dt/1}], Manipulate[Plot[{ua[z, tmin] /. sol2, ua[z, t1] /. sol2, ua[z, t2] /. sol2, ua[z, t3] /. sol2, ua[z, t4] /. sol2, ua[z, tmax] /. sol2}, {z, zmin, zmax}, AxesLabel -> {z, ua[z, t]}, PlotRange -> Full], {t1, tmin + dt/500, tmin+ dt/51}, {t2, tmin + dt/50, tmin + dt/16}, {t3, tmin + dt/15, tmin + dt/3}, {t4, tmin + dt/3, tmin + dt/1}]]          (*Comparison*)          Manipulate[Plot[{uw[z, t] /. sol, uw[z, t] /. sol2}, {t, tmin, tmax},PlotRange -> All, AxesLabel -> {t, uw[z, t]}], {z, zmin, zmax}];          (*Matric Suction*)          result = ua[z, t] /. sol2 - 101 - uw[z, t] /. sol2;     Plot3D[result, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t, \[Psi][z, t]}, BoundaryStyle -> Thick, ImageSize -> 500]    `      Regards,


title: Why can't FindInstance find a solution to this equation?

text: FindInstance[680 == 1/3 2^m (-1 + 4^v), {m, v}, Integers]      `FindInstance` seems to be unable to find the integer solution $ {m = 3,v = 4} $ in the equation above (failing with the message:               FindInstance::nsmet : The methods available to FindInstance are insufficient to find     the requested instances or prove they do not exist.      Is there are technique that can be used to find integer solutions to equations like the above?


title: Addition of Matrices

text: How can I add the Matrices created by this:               SeedRandom@0;     Table[RandomInteger[{0, 34}, {2, 2}], {2}, {5}] // MatrixForm      > $\left( \begin{array}{ccccc} \left( \begin{array}{cc} 32 & 33 \\ 22 & 15 \\ > \end{array} \right) & \left( \begin{array}{cc} 3 & 30 \\ 34 & 4 \\ > \end{array} \right) & \left( \begin{array}{cc} 14 & 24 \\ 28 & 10 \\ > \end{array} \right) & \left( \begin{array}{cc} 10 & 12 \\ 21 & 31 \\ > \end{array} \right) & \left( \begin{array}{cc} 33 & 5 \\ 15 & 0 \\ > \end{array} \right) \\ \left( \begin{array}{cc} 9 & 13 \\ 22 & 31 \\ > \end{array} \right) & \left( \begin{array}{cc} 26 & 22 \\ 1 & 9 \\ > \end{array} \right) & \left( \begin{array}{cc} 31 & 15 \\ 28 & 13 \\ > \end{array} \right) & \left( \begin{array}{cc} 27 & 15 \\ 16 & 8 \\ > \end{array} \right) & \left( \begin{array}{cc} 23 & 13 \\ 33 & 25 \\ > \end{array} \right) \\ \end{array} \right)$


title: How to splice together several instances of InterpolatingFunction?

text: I have a set of `InterpolatingFunction` returned by `NDSolve` which are valid over different (but overall continuous) domains. How do I splice them together into one single InterpolatingFunction over all the domains? `Piecewise` seems to promising, but I can't manage to return the piecewise function from another function then use it later the same way as `InterpolatingFunction`. I guess there is also the brute force way of generating a grid of points using the original set of `InterpolatingFunction` then interpolating points again, but that's very elaborate and CPU-consuming, not to mention potentially inaccurate if the interpolation grid is not chosen properly. Thoughts? * * * Thanks to the answer from Mr. Wizard, this is the solution I ended up using:               JoinInterpolatingFunction[intervals_List, flist_List] :=       Module[{getGrid},       getGrid[f_InterpolatingFunction, min_?NumericQ,          max_?NumericQ] := {{min, f[min]}}~          Join~(Transpose@{f["Grid"] // Flatten, f["ValuesOnGrid"]} //             Select[#, (min < #[[1]] < max) &] & )~Join~{{max, f[max]}} // N;       Interpolation[        Table[getGrid[flist[[i]], intervals[[i]], intervals[[i + 1]]], {i,             Length@flist}] // Flatten[#, 1] & //          DeleteDuplicates[#, (#1[[1]] == #2[[1]]) &] &,         InterpolationOrder -> 2]]      `JoinInterpolatingFunction[{I1,I2,..,In},{func1,func2,...func(n-1)}]` gives an `InterpolatingFunction` that takes values of `func1` between [I1,I2], `func2` between (I2,I3], ... `func(n-1)` between (I(n-1),In].


title: How can I calculate a limit with a free variable?

text: For example, when I evaluate               Limit[(1 + x^n + (x^2/2)^n)^(1/n), n -> Infinity]      _Mathematica_ does not output any result. When I evaluate               Plot[Limit[(1 + x^n + (x^2/2)^n)^(1/n), n -> Infinity], {x, -10, 10}]      a piecewise graph is output. But I want to get the function, not only the graph. How can I do it?


title: Using FortranForm

text: I need to use in Fortran, matrices that I create in Mathematica, therefore, I need to format them, so that Fortan can understand them. I focus on the simplest example: Let's say I have tha matrix A created in Mathematica               A = {{1, 1}, {1, 1}};      Then, I am supposed to use FortranForm               FortranForm[A]      which gives as an output               List(List(1,1),List(1,1))      My question is, what do I do with this now? This cannot be the input file to Fortran, since this should be only numbers as far as I am aware. It could be that, the input file to Fortran is the out put of               List(List(1,1),List(1,1))      but this is nothing in Mathematica, so it does not give any output. Any help please?