title: How can parts of a list of lists be printed to the nb, at regular interval positions?

text: I have a large list of lists with the dimensions {441,21,21,3} of which I need to print the x,y,z data from every 21st part up to 441. How can I print the 21x21x3 piece of every 21st part of this list? Here's what I've tried below that did not do the job. Also is there an more memory efficient way to perform this task?:               Table[Print["mylist parts", mylist[[i++21]]], {i, 1, 441}];


title: Why do I get the error: "The specified setting for the option FEFloatIterator cannot be used."?

text: "The specified setting for the option FEFloatIterator cannot be used." This an error I am getting in a sizeable interface, containing 138 declarations in an outer `DynamicModule` with one inner `Manipulate`. * * * This undocumented error appeared as a pop-up on a red-boxed control (in this case, an iterator [but not a float iterator!]) where the setting for the control depended on an initialization section which timed out because of a non-terminating computation.


title: Compute integral symbolically

text: I want to compute the following integral:                   Ro = 8         bo = -2.68*Pi/180         lo = 1.50*Pi/180         r = Sqrt[Ro^2 + (Dl*Cos[bo])^2 - 2 Ro*Dl^Cos[bo]*Cos[lo]]         z = Dl*Sin[bo]         sa = Sqrt[(0.6^2*r^2 + z^2)/0.4^2]         sb = ((r/0.9)^4 + (z/0.4^2)^4)^(1/4)         rhoBulge = rhoBB*(sa^(-1.85)*Exp[-sa] + Exp[-sb^2/2])         Integrate[rhoBulge*Dl*(1 - Dl/Ds), {Dl, 0, Ds}]      But I just obtain the integral rewritten and no solution. I'm new in mathematica, so any tip or help would be awesome. Thanks!


title: How can I overload autocompletion to work with full contexts?

text: I would like for the autocomplete feature to search through contexts, for example if I have a symbol named A`B`C`MyFunction, when I type A` and press "cmd + shift + k" it will complete it. _Edit_ To be clear, I don't want to have to type the path because it's usually very long, and I don't want to have to type the function name again, even if the path itself gets auto completed. I want the following: If I have these functions:               Very`Long`Context`For`My`Function1     Very`Long`Context`For`My`Function2     ...      I want to be able to type Very` and then press CMD+Shift+k, to get a dropdown menu saying exactly               Very`Long`Context`For`My`Function1     Very`Long`Context`For`My`Function2     ...


title: Moving two Spheres in the Opposite Direction

text: We know that we can achieve to a box contained two spheres by the code:               Graphics3D[Table[Sphere[{i, Mod[i^2, 10], Mod[i^3, 12]}], {i, 2}]]      ![enter image description here](http://i.stack.imgur.com/kVJzR.png) How can the left sphere move in a vector path to the right of the box and the right one move to the left of the box simultaneously?


title: Ndsolve, transmission line transients

text: I am trying to use `NDSolve` to analyze transients in transmission lines. I started with this simple one:               s = NDSolve[{∂_(t,t) u[t,x] == 2*∂_(x,x) u[t,x], u[0,x] == 1,                    u^((1,0))[0,x] == 0, u[t,0] == Sin[t]},                  u, { t, 0, 40}, { x, -10, 10}];      So: voltage is initially constant (at `t = 0`). One end of the line is shorted. But, this is not approved. _Mathematica_ says: > >     NDSolve::ndnco: The number of constraints (1) (initial conditions) is > not equal to >     the total differential order of the system plus the number of discrete > variables (2). >> >   How could `NDSolve` be used for transmission line transient analysis?


title: How can I export specific data into different pages in .PDF format?

text: I have made various `Grid`-s and arranged them column-wise in another `Grid`. All `Grids` are working fine and I exported that final `Grid` into PDF format. The entire `Grid` appeared in a single page after exporting, but I want to `Export` some `Grid`-s to one page and remaining ``Grid`-s to another page. I tried the following code but it doesn't work:               grid1 = Grid[{{Style["Life Alerts", Bold, 20], SpanFromLeft,       SpanFromLeft}, {Style["Alert", Bold, 15], Style["<>", Bold, 15],       Style["%Life", Bold, 15],       Style["OnDay", Bold, 15]}, {Style["L1", Bold, 15],       Style["<", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}, {Style["L2", Bold, 15],       Style[">", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}, {Style["L3", Bold, 15],       Style[">", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}}, Alignment -> {{Left}, Center},        Background -> {None, {Yellow}}, Frame -> True,        FrameStyle -> Directive[Thickness[4], Black], Spacings -> {1, 1},          Dividers -> {{}, {True, True, True}}];      ![Mathematica graphics](http://i.stack.imgur.com/co1BZ.png)                 (*Exporting code*)       Export[SystemDialogInput["FileSave",".Pdf"], (Grid[{{grid1}, {grid1}}])]      Can anybody help me?


title: Change syntax from other programs to mathematica syntax

text: Is there a good way to transform syntax from other computer algebra systems or from latex to mathematica syntax?


title: which is better, using Assert[] or manual checks on arguments and other computations?

text: I never used Asserts in Mathematica, but trying to see what advantage they have over just argument check and additional definitions of the function to capture unwanted input. For example, which one of these 2 would you think is better?               ClearAll[f]     f[x_] := (Assert[x > 0]; Sqrt[x])     On[Assert];     f[2.]     f[-2.]      The last call above generated in the console a beep and a message:               Assert::asrtf: Assertion -2.>0 failed. >>      But I could also just write               ClearAll[f];     f[x_] := Sqrt[x] /; x > 0          f[2.]     f[-2.]      and the second call will return unevaluated               f[-2.]      and If I want a beep, I could always do something like               ClearAll[f];     f[x_] := Sqrt[x] /; x > 0     f[x_] := Throw["f[x] not supported for negative values"]      or something along these lines. Since asserts seem to be used to assert that input to a function is within the ranges supported by the function, what benefit they have over the other method shown above? Or should one look into using Asserts inside the function itself, i.e. in the middle of a computation, to check that intermediate results are within expected ranges? But also then, I would use a simple `If` check instead, and return an error code to the caller (which I prefer) or use Throw. An example from help shows this:               myFun[x_] :=      Block[{y},       y = x^2;       Assert[y > 5];       Sin[y]       ]      So that the call `On[Assert]; myFun[1.0]` generated `Assert::asrtf: Assertion y>5 failed`. But I can write instead               myFun[x_] :=      Block[{y},       y = x^2;       If[y <= 5, Throw["y<=5"]];       Sin[y]       ]      and now the call `myFun[1.0]` will also generate a message and a beep as well from the same place. I guess I am looking for when in Mathematica the use of Assert would be better and recommended over these other ways of checking. My only guess now is that Assertion code can be disabled and enabled more easily, and this can have an effect on run time. i.e. after testing the code, I can disable Asserts from the final version, and it should run faster, since all these checks are not being done at run time any more. But with the manual checking as above, that code remains there all the time. thanks


title: Finding a best fit curve and plotting it

text: I have a list as shown below:               m01 = {{250, 0.083121}, {200, 0.0888446}, {150, 0.0992422}, {100, 0.121567}, {50, 0.186825}}      I'm new to Mathematica, and would like to know how can I do these jobs: 1- How can I can plot it with `ListPlot` and make minimal formations on it? 2- How do I fit a curve on it? Witch command I use? How to put the curve plot together with the points?


title: Exporting a Large Multidimensional Sparse Array

text: I'm trying to export a sparse array from Mathematica to share with collaborators who primarily use Matlab. The sparse array in question is 4 dimensional, (72 x 93 x 94 x 172) with ~4M non-zero elements. I've tried a number of possibilites but haven't found a working format. Is there a cross-program compatible format for large multidimensional (sparse)matrices? The data is easily exported in the native Mathematica `WDX` and `MX` formats, except, as far as I can tell these can't be read by any other programs. Based on this question/answer (support-for-compressed-sparse-column-sparse- matrix-representation), I've tried the `HarwellBoeing` `RSA` format.               test = SparseArray[RandomInteger[{1, 100}, {10^6, 4}] -> RandomInteger[10, 10^6]]     Export["text.rsa", test]      This returns: `Export::rank:` The sparse array `SparseArray[<<1>>]` to be exported in `HarwellBoeing` format is not a matrix of rank 2. I've also tried the `MatrixMarket` `MTX` format:               Export["text.mtx", test]      This gives a different error: `Export::type:` `SparseArray[<<1>>]` cannot be exported to the `MatrixMarket` format. The matlab format, the most obvious choice, also doesn't work:               Export["text.mat", test]      Another new error this time: `Export::type:` `{<<1>>}` cannot be exported to the `MAT` format. However, the Matlab `MAT` format appears to support 3 dimensional sparse arrays, in this case we can export each 3D array making up the 4D array and it works, although when imported into matlab each file is actually 100 2D arrays, so the 3D actually support isn't implemented correctly and does not give a matlab 3D matrix.               MapThread[Export, {# <> ".mat" & /@ ToString /@ Range[100], test}]


title: How to change alignment of Grid/Matrix created using menu (Insert->Matrix/Table->New)

text: When I create a `Grid` using the menu, as follows: ![Mathematica graphics](http://i.stack.imgur.com/q9XiX.png) and then start to add data, I'd like to make the alignment to be left and not center which is the default ![Mathematica graphics](http://i.stack.imgur.com/E4U0F.png) There is no option to change this when creating new Grid as one can see: ![Mathematica graphics](http://i.stack.imgur.com/1s20B.png) If I try to change the alignment in code by making new variable like this                  data2 = Grid[data, Frame -> All, Alignment -> Left]      and then use `data2` from now on, I find it is no longer possible to add rows/columns to data2. Question: How to control alignment of Grid/Matrix when it is created using the menu? Is there a way to do that afterwords while keeping the functionality of adding rows/column? I am using V9 on windows 7. **update** adding a row, after making new copy with correct alignment, does actually work. The cursor has to be on the row itself, and not outside, and not by selecting the whole grid. This screen shot shows the correct way. Again, make sure the cursor is inside the grid, at the row where the new row needs to be inserted. ![Mathematica graphics](http://i.stack.imgur.com/AKWWK.png) **Update 12/27/12** Just wanted to point out the difference between making a Grid using the menu, vs. the command Grid. When using the menu to create a Grid, the data added to the Grid can be access as a matrix, directly. But when creating the Grid in code using the command itself, the data is wrapped by the Grid, and one needs an extra dimension to access the data. This picture explains: ![Mathematica graphics](http://i.stack.imgur.com/k6aKm.png) So, this shows that it would have been better to be able to make the Grid using the menu. But becuase it is missing the alignment option, one has to use the command itself, but then one must remember to add the extra dimension now each time.


title: Computing 10-dimensional volume of a 9-sphere

text: I'm trying to compute 10-dimensional volume of a 9-sphere with radius r using Monte Carlo.               r = 1000     F = Piecewise[{{1, Sum[x[i]^2, {i, 10}] <= r}}, 0]     NIntegrate[F, {x[1], -1000, 1000}, {x[2], -1000, 1000}, {x[3], -1000, 1000}, {x[4], -1000, 1000}, {x[5], -1000, 1000}, {x[6], -1000, 1000}, {x[7], -1000, 1000}, {x[8], -1000, 1000}, {x[9], -1000, 1000}, {x[10], -1000, 1000}, Method -> {"MonteCarloRule", "Points" -> 1000000}]      But the results always off by the factor of 1e(P/2), where 1eP = The correct factoring. I'm wondering where did I do wrong? ![enter image description here](http://i.stack.imgur.com/Ijr0V.png) Also I want to clean up the code               NIntegrate[F, {x[1], -1000, 1000}, {x[2], -1000, 1000}, {x[3], -1000, 1000}, {x[4], -1000, 1000}, {x[5], -1000, 1000}, {x[6], -1000, 1000}, {x[7], -1000, 1000}, {x[8], -1000, 1000}, {x[9], -1000, 1000}, {x[10], -1000, 1000}, Method -> {"MonteCarloRule", "Points" -> 1000000}]      I try to do this               NIntegrate[F, Table[{x[i], -r, r}, {i, 10}], Method -> {"MonteCarloRule", "Points" -> 1000000}]      But it doesn't work as Table[] gives list. I need to make it into sequence somehow. But trying to apply Sequence[] to Table[] still give me a list. Is there anyway to get around this?


title: How to create an executable notebook in Mac OS X

text: All, I am looking for help to create a notebook to be executed via terminal in MAC OSX. The notebook uses the front end. This is what I have so far               #!/Applications/Mathematica.app/Contents/MacOS/Mathematica -script          UsingFrontEnd[NotebookEvaluate["/Users/MyFolder/MyFile.nb"]]      When I run the script in snow leopard Mathematica opens a new notebook containing the above code displayed in quotes, when run in lion I get a window saying the notebook cannot be opened. I will be very grateful to anyone who can point me in the right direction as to how to proceed. Many thanks


title: How to plot stability region of Fourier analysis

text: Stability limits for Runge–Kutta methods in the complex ΩΔt-plane are needed to be plotted like this: ![enter image description here](http://i.stack.imgur.com/EQ5hC.png) For example, let `P=1+z` where `z` is complex. Under the stability condition `|P|<=1`, the plot line should be that of RK-1 in the given plot. Similarly, if `P=1+z+1/2*z^2`, then when `|P|<=1` the plotting line is the corresponding of RK-2. I am trying to code `P=1+z` like this:               Clear[yRe, yIm, w, NP, k, ϕ]     a = 1;     zexp = a*(Cos[ϕ] + I*Sin[ϕ]) + 1     xp[ϕ_Real, a_Real] = Abs@zexp*Cos[ϕ];     yp[ϕ_Real, a_Real] = Abs@zexp*Sin[ϕ]     NP = 30;     For[k = 1, k <= NP, k++,      w = 2.*Pi*(k - 1)/NP;      yRe[k] = xp[ϕ, a] /. {ϕ -> w};      yIm[k] = yp[ϕ, a] /. {ϕ -> w};      ]     yRe = Table[yRe[k], {k, 1, NP}];     yIm = Table[yIm[k], {k, 1, NP}];     pointsz = Transpose[{yRe, yIm }];          pic1 = ListPlot[pointsz, AxesOrigin -> {0, 0},        PlotStyle -> Directive[Thick, Black, PointSize[Large]],        AxesStyle -> Directive[Black, 15],        AxesLabel -> {"Re(ωΔt)",          "Im(ωΔt)"}, AspectRatio -> Automatic]      The resulted plot as following is not correct. The truth is like RK-1 in the above figure. ![enter image description here](http://i.stack.imgur.com/Qyrfs.png) How can i get the correct plot lines of RK-1 and RK-2 using Mathematica? Thanks.


title: Degree Symbol missing in PolarPlot when exported to PDF

text: I am trying to produce a polar plot. The axis should be in degrees. While no error occurs, the `pdf` export isn't working properly. Instead of the degree symbol I get a square (while using `acrobat`) and a 'D' when I use `nitro`. The code I am using is               r = 2.81794*10^(-15);     m = 511;     a1 = 1/m;     a2 = 5.9/m;     ds1[theta_] :=       10*r^2*(1/(1 + a1*(1 - Cos[theta])))*((1 + Cos[theta]*Cos[theta])/       2)*(1 + (a1^2*(1 - Cos[theta])^2)/((1 +           Cos[theta]*Cos[theta])*(1 + a1*(1 - Cos[theta]))))     ds2[theta_] :=       10*r^2*(1/(1 + a2*(1 - Cos[theta])))*((1 + Cos[theta]*Cos[theta])/     2)*(1 + (a2^2*(1 - Cos[theta])^2)/((1 +           Cos[theta]*Cos[theta])*(1 + a2*(1 - Cos[theta]))))          Needs["PlotLegends`"]     PolarPlot[{ds1[theta], ds2[theta]}, {theta, -π, π}, PolarAxes -> True,        PolarGridLines -> True, PolarTicks -> {"Degrees", Automatic},        PlotRange -> Automatic,        PlotLabel ->        Style[Framed["Klein-Nishina Compton Cross Section"], 20, Red,         Background -> Lighter[Yellow]],         PlotLegend -> {"1keV", "5.9keV"}, LegendShadow -> {.01, -.01}, LegendTextSpace -> 5,        LegendBackground -> LightPurple, LegendSize -> {0.5, 0.5},         Background -> LightYellow]            Export["Klein.pdf", %]      ![Mathematica graphics](http://i.imgur.com/7K2I9.png) I also tried to export it in other formats, which is working fine, however I need `.pdf` format...


title: How to calculate the unknown quantity in an infinite series?

text: ![enter image description here](http://i.stack.imgur.com/Jhx7L.jpg) ![enter image description here](http://i.stack.imgur.com/KnCsn.jpg) I'd like to calculate x value in this equation. Basically, I tried to 2 types of method which are FindRoot and NSolve. But, I have failed the calculation caused by these errors up to now. If there is anyone who knows this problems, plz let me know what I should do first! Thank you for your cooperation.


title: Quickly display a color graphically

text: When manipulating colors, the output is shown as a textual expression like `Hue[1/5]`, `RGBColor[2/3, 1, 1/3]`, `GrayLevel[3/5]`. It can be hard to visualize what color these represent. How can you quickly display the color itself on screen?


title: How can I use nested conditionals inside my functions?

text: I'm a big fan of using conditionals inside my functions to deal with cases, that is, to pattern match in stages and possibly leave a function unevaluated.               In[1]:= f[x_] :=      (        (          (            True            ) /; EvenQ[x]          ) /; x > 2        ) /; x < 10          In[2]:= f[4]     Out[2]= True      However I don't fully understand the extent to which I can do this. For example, mixing If statements in doesn't work:               In[3]:=          h[x_] :=          (            If[x > 2,             (               True               ) /; EvenQ[x]             ,             False             ]            ) /; x < 10              In[4]:= h[4]         Out[4]= True /; EvenQ[4]      A clarification on both the limitation and merits of this style of coding would be helpful. I find this style of programming to be handy for a number of reasons, but a primary reason is the ease of defining a blanket default case and letting the pattern matching do its work, e.g. `f[_] := $Failed`.


title: Implicit Equality and RegionPlot

text: I have the following problem: I would like to do a RegionPlot like               RegionPlot[F[x,z,y]<1,{x,0,1},{y,0,1}]      The problem is that the variable z is an implicit (and not reducable via e.g. Solve, meaning too non-linear) but continuous function of x and y, for example               G[x,y,z]==0.      The functions F and G are well-defined. Would anyone know how to solve this issue in a general way?


title: How to compile the code for generate Pythagorean_triple?

text: I am finding Pythagorean_triple, it worked slowly. I tried to compile, but it gives some warnings. I also use "Case" or "Do" ,both of them failed.I'm sure my CCompiler has been set correctly. How can I compile the following code?               With[{m = 200},      Select[Flatten[Table[{x, y, z}, {x, m}, {y, x, m}, {z, y, m}],         2], (#1^2 + #2^2 == #3^2 &) @@ # &]      ]


title: One-column table not properly displayed by TableForm

text: I want a table with a single column of data, and with headings along both the rows and the column. One might expect it to work like this:               TableForm[{"one", "two", "three"},       TableHeadings -> {{"$10MM", "$20MM", "$30MM"}, {"col"}}]      But this does not work; it displays the data and the row labels correctly, but it does not label the column. What am I missing?


title: Is it possible to produce "tilt-shift" effect in Mathematica?

text: I attempted to produce a kind of miniature faking look from a street scene photo. I tried to shift the perspective lines close to parallel to each other to obtain such effect. However, the result looks ugly. Is there a better way to do it? This is the original photo. ![This is the original photo.](http://i.stack.imgur.com/AkqJW.jpg) This is the result from the code below. ![enter image description here](http://i.stack.imgur.com/R8ObL.jpg)               im = Import["http://i.stack.imgur.com/AkqJW.jpg"]          pts = {{0, 0}, {0, 1}, {0.25, 0},  {0.25, 1}, {0.5, 0}, {0.5,1}, {1, 0}, {1, 1} };     imgcol = BSplineFunction[ImageData[im ], SplineDegree -> 1];     Manipulate[       Module[{f},        f = BSplineFunction[Partition[pts, 2], SplineDegree -> 1,          Method -> {"Extrapolation" -> "Clamp"}];             ParametricPlot[        f[u, v], {u, 0, 1}, {v, 0, 1},        ColorFunction -> (imgcol[1 - #4, #3] &),        MaxRecursion -> 0,        PlotPoints -> ControlActive[20, 100],        Mesh -> None,         Epilog -> { Gray, Opacity[.7], Line[Partition[pts, 2]]},         ImageSize -> {300, 300},        PlotRange -> {{0, 1}, {0, 1}},        PlotRangePadding -> Scaled[0.01],        FrameTicks -> None        ]        ],      {{pts, {{0, 0}, {0, 1}, {0.25, 0},  {0.25, 1}, {0.5, 0},  {0.5, 1},         {1, 0}, {1, 1} }}, {0, 0}, {1, 1}, Locator },      TrackedSymbols :> {pts}      ]


title: How to simplify the integration result of the following program?

text: In the following program, the `fec[x]` is a function depending on $x$ while `q3[t]` and `q5[t]` are functions depending on $t$. Now, I want to use `Integrate` for the polynomial which is composed by `fec[x]`, `q3[t]`, `q5[t]`, et al. for the independent variable $x$. I believe the result `c` is zero, but I don' t know why the software could not convert it to zero automatically. Could you help me?               inta = Cos[q3[t]] fec[x] q5[t]^2 D[q3[t], t]^2;     a = Integrate[inta, {x, 0, L1}];          b1 = Cos[q3[t]] q5[t]^2 D[q3[t], t]^2;     b = Integrate[fec[x], {x, 0, L1}] b1;          c = a - b;


title: Rendering of a HighlightGraph in a Manipulate content pane distorted by changing the highlighted edge

text: A `HighlightGraph` inside a `Manipulate` initially displays correct however after approximately 2 seconds, the layout changes and the text, links and nodes get displaced. It appears to be caused by the Manipulate cell, after the initially correct display - is again being evaluated after two seconds (judging by the appearance of the darkening of the evaluation indicator right side of the cell). Please find a simplified example and see how components "jump" away from the initial, correct placement. The real problem I experience is on a larger graph and the effect is substantially more dramatic, as nodes are displaced in a manner that the graph becomes illegible. Despite the simplicity of this mock-up, It does show the reevaluation (if that is what it is) after two seconds and the displacement of nodes and text. What is causing this and how can I avoid it, preferable without changing what I am trying to display? To my knowledge, it is only happening when I combine a graph with self-loops and Vertex labelling inside a `Manipulate` wrapped around `HighlightGraph`.               f = {1 <-> 5, 5 <-> 6, 5 <-> 5, 6 <-> 4, 4 <-> 5, 5 <-> 3, 3 <-> 6,           6 <-> 2, 2 <-> 4, 4 <-> 1, 1 <-> 3, 3 <-> 2, 2 <-> 1};     h = Graph[f, VertexLabels -> description, ImagePadding -> 10];     Manipulate[HighlightGraph[h, f[[i]]], {i, 1, 12, 1}]       ![Mathematica graphics](http://i.stack.imgur.com/1XVV8.png)


title: Singularity / stiffness / precision errors with NDSolve

text: I have a relatively simple 2nd Order ODE problem I'm trying to solve numerically $p'' + \frac{1}{r}p' = A(\frac{p(r)}{p(r) + k_{m}})$ where $A = 7.5795*10^9$ and $k_{m} = 1$. So trying to get numerical solution in Mathematica between the boundaries $r_{o} = 5 \times 10^{-6}$ and $r_{c}$ ($r_{c}$ is at LEAST 0.000102329 and likely 10-30 microns bigger, but I'll use small estimate for this example . We also know $p(r_{o}) = p_{o} = 100$, and $p'(r_{c}) = p(r_{c}) = 0$; but this is seriously upsetting Mathematica; I'm getting the following warnings depending on what versions I run;               s = NDSolve[{D[r*O2'[r], r] - con*r*((O2[r])/(O2[r] + km)) == 0,  O2[rc] == 0, O2[ro] == po}, O2, {r, ro, rc},Method -> {"StiffnessSwitching"}, MaxSteps -> 100000]      Produces a host of errors of the form; > NDSolve::ndsz: At r == 0.00009971646984096604`, step size is effectively > zero; >singularity or stiff system suspected Trying the other condition               s = NDSolve[{D[r*O2'[r], r] - con*r*((O2[r])/(O2[r] + km)) == 0,  O2'[rc] == 0, O2[ro] == po}, O2, {r, ro, rc},Method -> {"StiffnessSwitching"}, MaxSteps -> 100000]      produces the errors > FindRoot::cvmit: Failed to converge to the requested accuracy or precision > within 100 >iterations. NDSolve::berr: "There are significant errors > {-0.125305,-99.99} in the boundary value >residuals. Returning the best > solution found." The attempted solutions look frankly obscenely wrong, so Im guessing there's a stiffness or singularity probem. I've tried a few tricks to try and circumvent this and I'm getting no joy; is there something I'm missing? So far I've tried increasing the value for rc, and re-writing the equation differently but I'm still having problems. Anyone any idea of why I'm getting these errors and how to resolve them?


title: Operator syntax for Merge-like Query

text: Is it possible to take advantage of Dataset's Query operator syntax to Merge parallel queries thereby avoiding Function's that are otherwise required? Using the planets data:                planets = ExampleData[{"Dataset", "Planets"}];          {moonMasses, nMoons } = {planets[All, "Moons", Median, "Mass"],        planets[All, "Moons", Length, "Mass"]}      ![enter image description here](http://i.stack.imgur.com/v1syL.jpg) These queries are nearly equivalent merges: (1) `Merge[{moonMasses // Normal, nMoons // Normal}, List]` ![enter image description here](http://i.stack.imgur.com/TWkoa.jpg) (2) `planets[All, "Moons", {Median[#], Length[#]} &, "Mass"] // Normal` ![enter image description here](http://i.stack.imgur.com/PKpcr.jpg) The values in (1) are unfortunately wrapped in an extra nested list (and further requres normalizing the data as Merge doesn't take `Dataset` arguments). (2) is preferred (normalizing here only because 10.0.0 `Dataset Format` is not usable). How to avoid using `Function` in (2), eg, to shorten the query to a syntax similar to:               planets[All, "Moons", {Median, Length}, "Mass"]


title: Finding the first five eigenvectors and values for a 500×500 matrix

text: I'm trying to find the first five eigenvalues and vectors of a matrix that has the following proporties:               L = 10;     NN = 500;     ℏ = 1;     a = 1;     V0 = 5;     dx = L/NN;     Clear[x]     x[n_] := -L/2 + (n - 1/2) dx     Vsw = -V0* i Piecewise[{{1, -1/2 < x < 1/2}, {0, x > 1/2}, {0, x < -1/2}}];     i = SparseArray[{{i_, i_} -> 1, {i_, j_} /; Abs[i - j] == 1 -> 0}, {500, 500}];     s = SparseArray[{{i_, i_} -> -2, {i_, j_} /; Abs[i - j] == 1 -> 1}, {500, 500}];     Hkin = 1/(dx)^2 s;     Hsw = Hkin + Vsw;      In simple English this means I have two matrices:   * one that is allmost diagonal with constant values   * another that is diagonal with a constant value, but only for a some region of definition of `x[n]` I think using piecewise is not good here, but I can't seem to find anything else that works. Also, I'm not sure if my use of `n` is OK here.


title: Usage of Block in Compile

text: When is there an advantage to using `Block` in `Compile`? For instance, if I have a multiple-step code, how do I decide which variable assignments I should put into the first argument of `Block[]`? Is it unwise to have functions being evaluated in there?


title: Permutation of arguments of product of functions

text: Given a function, g, which is symmetric in its argument, g(a,b)=g(b,a), consider the product g(a,b)*g(c,d)*g(e,f). I would like to get all the permutations of this product with respect to the arguments, that is, terms such as g(a,c)*g(b,d)*g(e,f), which respect the symmetry so that g(c,a)*g(b,d)*g(e,f) would not be among the generated terms. Is there a way to get Mathematica to do this? Many thanks for any help.


title: Discrete peaks to curve via Voigt summation

text: I have two data sets. One is an experimental recording of an absorption spectrum, composed of regularly spaced (wavenumber, intensity) coordinates with a fine wavenumber resolution, thus making superposed Voigt peaks. The second one is computation that gives coordinates (wavenumber, intensity) for the maximum of each peak. I want to obtain a function that would   * Take X,Y coordinates of my simulated dataset   * Generate a Voigt profile (mean X from dataset, integration Y from dataset, fixed Sigma, fixed Gamma)   * Repeat for the whole experimental dataset (~150 points displayed as green bars)   * Plot the sum of all these Voigt functions The Voigt profile is not a requirement, I can work with a Gaussian to begin with. So there would only be 3 parameters, 2 from the dataset and Sigma. ![enter image description here](http://i.stack.imgur.com/X1pBE.png) This graph was made in Origin, but I'm using _Mathematica_ 9.


title: Isolating characters in a string

text: I'm struggling to find the right function in mathematica to isolate specific characters in a string. I have got a formula as string (I imported it from an excelfile) like this: **y = 0.97*x1 + 0.521*x2 - 30.21 - 0.07431*x3 - 0.126*x4 - 0.1939*x5 - 0.361*x6** Now I want to isolate the coefficients, e.g. 0.97,0.521 from the x's and maybe store it seperately, so that I know which coefficients were for which x. I thought this would be easily done and I browsed through the help of mathematica, but I couln't find any example which helps me so far. Maybe some of you can help me out which functions is best for this task?


title: Reading between blank lines in external data files

text: I have an external data file with several columns and thousands lines of data. For the sake of this question, let's assume that we use               I1 = Import["data.out","Table"];      to import a sample data file which is the following               data = {{2,-1,0},{-4,0,2},{7,5,-1},{},{8,1,-3},{-5,2,-3},{},{-4,-1,3},{3,7,2},{0,0,2},{}}      We see, that there are empty sub-lists {} corresponding to blank lines to the external data file. Also, at the end there is always a blank line. Each blank line acts as a separator distinguishing between different piles in the data file. So, my question is the following: how can plot using `ListPlot` like               S1 = ListPlot[Flatten[List /@ data[[All, {2, 3}]], 1], Joined -> True,                   Frame -> True, Axes -> False, AspectRatio -> 1,                    PlotStyle -> {Black, PointSize[0.001]}]      all the different sets of data? In other words, how can I plot only the first sequence until the first blank line (`{2,-1,0},{-4,0,2},{7,5,-1}` according to the sample), or the data between let's say, 4rd and 5th blank lines, the last set, etc?


title: How to draw the image of a circle under the action of a transformation of the phase flow?

text: How to draw the image of a circle $x^2+(y-1)^2<1/4$ under the action of a transformation of the phase flow for the equation $\dot{x}=y,\ \dot{y}=-\sin x$? Here $\dot{x}$ means $dx/dt$. Any help or suggestions will be appreciated! The following code shows how to plot the trace of a point under that action which may be helpful.               splot =        StreamPlot[{y, -Sin[x]}, {x, -4, 4}, {y, -3, 3}, StreamColorFunction -> "Rainbow"];     Manipulate[       Show[splot,          ParametricPlot[           Evaluate[First[{x[t], y[t]} /.              NDSolve[{x'[t] == y[t], y'[t] == -Sin[x[t]], Thread[{x[0], y[0]} == point]},                {x, y}, {t, 0, T}]]],            {t, 0, T},            PlotStyle -> Red]],        {{T, 2}, 1, 20},        {{point, {3, 0}}, Locator},        SaveDefinitions -> True]


title: BarChart3D does not print zeros and odd tick positions

text: **Note: This is a version 9.0.0 problem that is fixed in 9.0.1.** * * * I want to generate a simple 3D view of some frequencies for two variables. I have the counts in a 4x3 matrix, say. This is my bar chart code:               BarChart3D[      Map[Labeled[#, Text[Style[#, Black, Opacity[1.], Bold, 20]],          Above] &, {{1, 0, 2}, {0, 0, 2}, {2, 1, 0}, {0, 2, 1}}, {2}],      ChartLayout -> "Grid",      BarSpacing -> Large,      ChartElements -> Graphics3D[Cylinder[]],      ChartStyle -> Directive[Opacity[0.3]],      AxesLabel -> {None, None, None},      Ticks -> {{{1/2, "Del"}, {2, "Nor"}, {2 + 3/2, "Amp"}},        {{1/2, "Osteo"}, {1.75, "Ewing"}, {3, "Rhabdo"}, {4.25,           "Neuro"}}, {0, 1, 2}},      ViewPoint -> {1.3`, -2.4`, 2.`}      ]      And this is what I got with _Mathematica_ 9.0 (more precisely, 9.0.0.0 Mac OS X.) ![Mathematica graphics](http://i.stack.imgur.com/JfX39.png)   * First, for readability, I want to place a label in each column. But as you can see, zeroes are not displayed. How can I get BarChart3D to plot my zeros? Or probably better, to draw a flat disk in corresponding place.   * (Not as important) Notice how I placed the ticks for the _x_ and _y_ axes. The matrix is 4x3, so I don't understand where those positions come from (the ones I had to use to put the labels - see `Ticks` above). My guess is that my positions are probably wrong, although visually seem ok for now. Help would be much appreciated. **Update** As workaround for zeros, I put a `If[#==0,0.01,Labeled[...]]` in `Map` and displays ok. Still, I am intrigued on how to position tick labels correctly, with `Ticks` or some other option.


title: How do I change the way Mathematica pronounces English words (e.g. "futile" is not pronounced correctly)?

text: I am absolutely desperate. I cannot get my Borg to pronounce "futile" correctly.               Speak["Resistance is futile."]      Leo pronounces "futile" as expected and there is no indication that this word is pronounced differently in the US and the UK. I have also tried various incorrect spellings but with no real success. Is it actually possible to install and use other speakers? Are there means to adapt the pronounciation of specific words or phrases? **EDIT:** Question 1: "few-tile" and "hoss-tile" as suggested below sound very good on my computer. Fact is, "futile" and "hostile" are not pronounced incorrectly but do follow the American pronounciation. We are probably spoiled by British actors (Patrick Steward) mingling in American series. Believe it or not, I watched the "Scorpion" episode (species 8472 appears for first time) of ST-TNG and yes, Data and Geordie use American pronounciation. **EDIT:** Question 2: Mathematica resorts to the default "voice" installed in the (in my case) Windows 7 set-up. Adaptions such as speaker's speed are also inherited by Mathematica.


title: How to prevent output truncation when importing large Graphics?

text: The `Evaluation` Preferences in _Mathematica_ specify a maximum output size of `1048576` Bytes before truncation occurs. That makes a lot of sense when thinking about large lists of data, but is causes trouble when displaying large `Graphics`. Here is an example. It is produced using version 9.0.1.0 on a MacBook Pro with Retina display running OS X 10.7.5. I'm importing a `PDF` file with a large polygon count.               Export["t1.pdf", Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}]];     First@Import["t1.pdf"]      ![large output](http://i.stack.imgur.com/ml6nU.png) This truncation warning does nothing to save space in the notebook, and the full output is in fact generated. So it would be nice if one could automatically suppress the truncation warning which serves no purpose here. I don't think it's a valid solution to just increase the truncation Byte limit above its default value, because that would affect regular data output as well, and I don't want to increase the limit for that case. Normally I would of course avoid exporting and importing `PDF` from 3D graphics, but it can't always be avoided if you have an external `PDF` file you'd like to display in the notebook.


title: Interpolation impossible for ListPlot with Missing?

text: I have a list of data to plot. I would like to plot them with lines but delete some data before plotting and leave the lines disconnected where data is deleted. For example,               ListPlot[Sin[0.5 Range@100] /. {a_?Negative -> Missing[]}, Joined -> True]      This works well. However, the data is not dense enough to make smooth plots. Thus I want to turn on interpolation:               ListPlot[Sin[0.5 Range@100] /. {a_?Negative -> Missing[]},       Joined -> True, InterpolationOrder -> 2]      However, This ends up with en error message and the same figure without interpolation. > ListPlot::ioproc: > "{{1.,0.479426},{2.,0.841471},{3.,0.997495},{4.,0.909297},{5.,0.598472},{6.,0.14112},<<39>>,{46.,Missing[]},{47.,Missing[]},{48.,Missing[]},{49.,Missing[]},{50.,Missing[]},<<50>>} > may contain non-machine-precision numbers, complex numbers, or invalid > entries." I think to set the data points to `Missing[]` should be the right way to remove data. Thus is it a bug that the data fail to interpolate? I would have first interpolated data by hand using               Interpolation[data] /@       Range[Min[data[[All, 1]]], Max[data[[All, 1]]],        (Max[data[[All, 1]]] - Min[data[[All, 1]]] + 1)/(10.*Length[data])]      and send the result to ListPlot. But let me still ask this question because I thought `InterpolationOrder -> 2` should work but it didn't.


title: Name scope confusion

text: Sorry for the too ambiguous title. First consider a following code snippet.               x = "x"; y = "y";          kk[] := Module[ {q, w, m},         q[a_] := a + 1;         w[a_] := a^2;         m[Global`x] = q;         m[Global`y] = w;         m     ]      With this function `kk` I can write code like this,               kk[][x][1]    (* output -> 2 *)     kk[][y][2]    (* output -> 4 *)      as expected. However, I want to change the name of the global variables `x` and `y` to those of the local variables `q` and `w`. Thus, consider a below snippet. q = "x"; w = "y";               kk2[] := Module[ {q, w, m},         q[a_] := a + 1;         w[a_] := a^2;         m[Global`q] = q;         m[Global`w] = w;         m     ]      Note that the only change to the above code is the global variable names `x` and `y`. However, this function `kk2` does not work as expected anymore. Can you explain? The output I got was,               kk2[][q][1] (* unevaluated *)     kk2[][w][2]      Thanks in advance. EDIT: add `[]` to each `kk2` calls as pointed by m_goldberg


title: Area enclosed by two functions

text: i want to calculate the area percentage of a function in a certain regime above a constant threshold. For example:               f[x] = sin[x] x²       from 0 to 2 with a threshold `g(x) = k` If I would do it by hand, I would identify the intersections points between the two functions and than calculate the integrals of the right ones and substract the value of G(x) from F(x) to just get the volume above the threshold. Depending on the number of intersections there quite a number of integrals to consider. So I thought, let _Mathematica_ do the the leg work! Well, but I am quite a novice in _Mathematica_ , and soon realised that I have only a vague idea how to do it in _Mathematica_. Probably there is even a better way to do it than described in the middle paragraph, because at the end it could also just approximate the enclosed areas numerically. Can anyone show me how to do it? Edit: Thank your very much for your answers/solutions. With a small correction (probably I explained poorly what I wanted) the solution from rasher worked just fine (and I understood the code used). In will also try to learn from Chenminqi solution which looks defintely more sophisticated and exceeds my current mathematica knowledge. So again, thanks to everyone!


title: Automatically add appropriate prefix to Quantity

text: Is there a function that automatically adds the appropriate prefix to a `Quantity` object? For example, I would like a function               quantityWithAppropriatePrefix[Quantity[0.000001,"Meter"]]      that would yield > >     Quantity[1,"Micrometers"] >   For some units this hack works:               UnitConvert[UnitConvert[0.00001,"Meter"],"Imperial"],"SI"]      > >     Quantity[10., "Micrometers"] >


title: Write memory usage to file in script

text: Is there a way to write the MemoryInUse into a file once a minute? In this Debugging memory leaks question there is a neat dynamic diagram showing the MemoryInUse over time. My problem is that I run my mathematica script without the front-end (math -script mystuff.m) and it seems that Dynamic does not work.


title: Graph adjacency matrix with unconnected nodes

text: I am trying to display a series of 9x9 adjacency matrices which represent directed graphs on a 3x3 grid. The issue I am running up against is this (compounded by that fact that I don't really know how to do anything in Mathematica): only the connected nodes appear, and they do so with a Mathematica-decided geometry. I'd like every point in the adjacency matrix to refer to the same fixed coordinate on the 3x3 grid every time. It seemed that `VertexCoordinates` might work, but it only refers to the vertices that have degree > 0, right? Insight on how to accomplish this? Any help would be much appreciated.


title: Table with dependent iterator

text: I'm trying to build a table where the iterator is based off of the ith-1 entry in the table. In other words, the value at _i_ is based on a function with _i-1_ as its input. EXAMPLE: Let's assume we're trying to get a pressure profile for a static column of gas. Since a gas's density changes greatly with pressure changes, we would want to break the static column into, say, 50 sections. So, we set the pressure at the bottom of the column and calculate the pressure at the top of the section ( _i+1_ ) using the formula $\ P_h = \rho g h/g_c$ (hydrostatic equation). The next section's known pressure is at _i+1_ and we'd solve for _i+2._ I've tried For and Table and can't get it to work. Thanks in advance. Update: I've figured out how to do it with the For[] construct, but not without the loop.               pc = List[4100];     For[i = 1, i < 50, i++,     pc = Append[pc, pc[[i]] - \[Rho]gh/gc]]


title: Output of the comand Put

text: I have a do loop in which I "Put" a ListPlot of a list in every iteration by doing               Put[ListPlot[list],"file"]      While the process is running and is still not finished, I get the desired plots in "file", but once the process is finished, I do not get the plot but the numerical values of the list with something like               {"      0.0134559544171447}", " {298.", " 0.013484438740159787}",        " {299.", " "}, {"      0.013512496857553435}", " {300.",      " 0.013540123145712023}}]}", " {}}}",      " "}, {"  {AspectRatio -> GoldenRatio^(-1)", " Axes -> True",      " AxesOrigin -> {0", " 0.0098}", " "}, {"   PlotRange -> {{0.",      " 300.}", " {0.00977737893161915", " 0.016994445972500355}}",      " "}, {"   PlotRangeClipping -> True",      " PlotRangePadding -> "}, {"    {Scaled[0.02]",      " Scaled[0.02]}}]}"}}      this is just a small piece of the output. I am working in the background by using "nohup" and running an .m file (in case it might have something to do with my issue). What do I have to do so that I always get the ListPlots as output? Thanks


title: Should I use \\\" or \" to match " in regex?

text: Both of the following return `True`:               StringMatchQ["foo\"bar", RegularExpression[".*\".*"]]               StringMatchQ["foo\"bar", RegularExpression[".*\\\".*"]]      Which is more correct? Also what about               StringMatchQ["foo\\bar", RegularExpression[".*\\\\.*"]]     StringMatchQ["foo\\bar", RegularExpression[".*\\.*"]]


title: Optimizing functions taking matrix arguments

text: I'm looking for general information on how to optimize matrix valued functions, I have the following function I'm looking to maximize (or figure out if this is possible at all).               MaximizeFunction[W_, DataCoupled_] :=        Module[{newDataCouple},         (* Elementwise Multiplication on a list of 2 element vectors *)         newDataCouple = Flatten[List[Dot[W, #] & /@ DataCoupled], 1];         (* Take the first and second elements of each of the vectors in the previous list and            perform an independence test on them to obtain the p-value *)         Return[           IndependenceTest[Extract[#, 1] & /@ newDataCouple,Extract[#, 2] & /@ newDataCouple]]];      Input values are of the type:               DataCouple = {{.5, .8}, {.7, .9}, {.6, .9}, ... }      W = {{1, 0}, {0, 1}}      Could I then use `NMaximize` or `Maximize` to optimize this function?


title: Solutions of cubic equation D>0 or D<0

text: I have problem to obtain three roots of cubic equation                N[Solve[a x^3 + b*x^2 + c*x + d == 0, x], 15]      using analytical procedure http://en.wikipedia.org/wiki/Casus_irreducibilis Discriminant of the system is positive and solutions which I obtained with the formula x1, x2 and x3 and Mathematica Solve are not the same?                a = 1;      b = 0.00100025;      c = 0.100000250125;      d = 0.0000500125;                p = (3 a c - b^2)/(3 a^2);      q = (2 b^3 - 9 a b c + 27 a^2 d)/(27 a^3);           N[q^2/4 + p^3/27]           t1 = \[Psi]1 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]1^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];     t2 = \[Psi]2 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]2^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];     t3 = \[Psi]3 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]3^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];          \[Psi]1 = 1;     \[Psi]2 = -(1/2) + Sqrt[3]/2 I;     \[Psi]3 = -(1/2) - Sqrt[3]/2 I;           x1 = t1 - b/(3 a);      x2 = t2 - b/(3 a);      x3 = t3 - b/(3 a);           N[x1]      N[x2]      N[x3]      N[Solve[a x^3 + b*x^2 + c*x + d == 0, x], 15]      And which formula to use in the case if the discriminant is negative? For example if the equations is in the following form                NSolve[0.5 + 25.1 x + 10. x^2 + x^3==0,x]


title: How to print coordinates above certain points

text: How do I place the x and y values of the points I have found (maxandmindistance) above the point in a plot? Here is my code so far:               Distance[t_] := t*(t - 1)*(t - 1.5)^2*(t - 3)     Velocity[t_] := Simplify[Distance'[t]]     maxandmindistance = Solve[Velocity[t] == 0, t]     Show[Plot[Distance[t], {t, 0, 3}],       Graphics[{Red, PointSize[Large],         Point[{t, Distance[t]} /. maxandmindistance]}]]      This results in a function with dots along it. They are the maximum and minimum values for the function. The problem is that the coordinates (x,y values) are not shown.


title: Get Coordinates 4 significant digits limitation

text: The tool "get coordinates" (clicking on a plot), seems to work with a fixed number of significant digits (4), in a way that we can quickly lose sensibility (the tool really becomes useless). The following example shows the problem:               Plot[a, {a, 1950, 1950.2}]      ![enter image description here](http://i.stack.imgur.com/BPI1k.png) I imagine that this is a feature tending to the bug classification. Is there a way of correcting this behavior? (on 9.0.1)


title: Expectation of a composite Markov-Gamma distribution

text: In a model I have a discrete two-state first order Markov process, defined by a (2x2) transition matrix with two free parameters. If the first state occurs then the process outputs zero for that period. If the second state occurs then the process outputs a Gamma-distributed random variable characterised by another two parameters. I can work out the theoretical mean and variance of the overall stationary process using pen and paper, but I am unsure how to check my results (and also I want to practice my Mathematica) using symbolic calculations. Put another way, I would like to know how to calculate the mean and variance to which the composite Markov-Gamma process will converge. My code is below - all I have currently is a way to calculate the mean of the Markov process, P, and its stationary mean (Mean[S]). However, I would like to be able to derive the mean and variance of R inserted into P for times when the process is in state 2, and zeros for when P is in state 1. Many thanks! Ben               M = {{1 - pdw, pdw}, {pwd, 1 - pwd}}     P  = DiscreteMarkovProcess[{1, 0}, M]     S = StationaryDistribution[P]     R = GammaDistribution[a,b]


title: Launching Remote Kernels takes a lot of time

text: I recently played around with establishing a remote kernel setup without using mathematica grid. To do this I use the `LaunchKernels[]` command and `ssh` to establish the connection. A call to my remote desktop (RemoteDesktop) then looks like:               Needs["SubKernels`LocalKernels`"]     LaunchKernels[RemoteMachine["RemoteDesktop",        "ssh -x -f -l username `1` math -mathlink -linkmode Connect `4` -linkname `2` -subkernel -noinit >& /dev/null &", 8]]      Which returns the following error: > SubKernels`Protected`kernelFlush::time: Operation LinkWrite timed out after > 15.` seconds It actually took me some time to figure out, that launching a kernel on RemoteDesktop actually takes longer than the predefined limit of 15 seconds. If I increase the limit to some way higher timespan like this:               Parallel`Settings`$MathLinkTimeout = 100.      `LaunchKernels[]` sure takes its time, but all the kernels are launched eventually. **So I cannot help but wonder: Is this an ordinary behavior or do you think something is going wrong regarding my setup, which results in launching kernels taking more time? If so, what could be the reason?** Further information: I am working on a MacBook Pro with OS X 10.9 and Mathematica 9.0.1. I testet remote connections to another Mac with OS X 10.8 and Mathematica 9.0.1 and a 64 Bit Linux Machine. Launching kernels took way longer than 15 seconds in each of these two scenarios.


title: Memory problem with producing complex graphics of general type

text: The problem I am about to ask has appeared once here: Memory Leak in Frontend - anyone know a workaround?. However, in this question I would like to put it in a bit different context. **Problem recipe:**   * Set $HistoryLength to 0 (this forces mathematica not to keep any history of evaluations)   * Create a graphic object, which contains many colors/opacities/primitives/pointsizes/...   * Open system monitor in your operational system   * Rasterize the object in mathematica   * Export it (optional), clear all the variables   * Check your system monitor: memory used by mathematica frontend has grown larger **Example of the problem:** This example is not minimal, but is aesthetically appealing. Following the recipe, first set the history length:               $HistoryLength = 0;       Then create a graphic object. In this case, it is a set of approx 0.5 10^4 points, having random positions inside a 0.5 radius sphere, random sizes and random colors, following some colorscheme. A cylinder is added afterwards to make the object look like a tree.               PointNumber = 10^4;     BushSize = 0.5;     PointLocations =        Select[(2 BushSize {Random[], Random[], Random[]} - {0.5, 0.5,              0.5}) & /@ Range[PointNumber], Norm[#] < BushSize &];     PointNumber2 = Length[PointLocations];     PointSizes = 0.01 Random[] & /@ Range[PointNumber2];     PointColors =        ColorData["PlumColors"][Random[]] & /@ Range[PointNumber2];     GraphicObject =        MapThread[{#1, PointSize[#2], Point[#3]} &, {PointColors,          PointSizes, PointLocations}];      Now, open the system monitor and rasterize everything:               TreeStuff =       Rasterize[       Graphics3D[{Opacity[0.8], Brown, EdgeForm[],          Cylinder[{{0, 0, -1}, {0, 0, 0.1}}, 0.01], GraphicObject},         PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, ImageSize -> 600,         Boxed -> False]]      As you can see, mathematica front-end has expanded in size by some 50 Mb! It is not all, at all. If you reevaluate the notebook, mathematica will pick another set of random points and will expand in the memory again. However, if you re-rasterize an object which has been rasterized before, memory will not be leaked. **Discussion:** The described behavior is clearly a bug. Say, one is producing an animation. If a given frame has been rasterized and saved, no information needs to be stored about it in the memory. Nevertheless, it gets stored incrementally. It seems hard to imagine, that nobody has ever created complex graphics with mathematica before. In particular, in processing datasets or in creating animations, one has to rasterize such graphics many times. In this case, if the parameters of graphics change, mathematica takes all the system memory. Therefore, at least somebody, making complex graphics with mathematica, must have faced a similar problem before. What do people commonly do to treat this issue? How can one clear the frontend memory, which expands so obviously in system monitor after each new evaluation of the above presented code? **P.S.** The code outputs this pretty tree: ![enter image description here](http://i.stack.imgur.com/EAoPy.jpg)


title: Specify the color of a horizontal grid line in a plot

text: I wish to plot a function and add a red, horizontal grid line at the height of the Euler-Masheroni constant. I am successful in ploting the line at Exp[EulerGamma], but I am having difficulties with getting it red Code:               ListLinePlot[robinplot, PlotRange -> All, GridLines -> {{}, {Exp[EulerGamma]}}]      I have used this code but it only makes my robinplot red:                ListLinePlot[robinplot, PlotRange -> All, GridLines -> {{}, {Exp[EulerGamma]}}, PlotStyle->{Red}].      How can I get a red line at height Exp[EulerGamma]?


title: Object separation from a 2.5D surface

text: I'm trying to identify the shape and the boundaries of objects. The data was generated with a laser scanner and represent the surface of an area in which many boulders lay on the ground and making up heaps. the data is available here ![enter image description here](http://i.stack.imgur.com/mdats.jpg) In the center of the plot you can see a bigger boulder an i want to seperate it from the other stuff around. For this goal I tried different methods which I want to present you and hope that you could enhance these idea(s) But at first i will reduce the number of samples in the data, because for the most ways the data is to big and need enormous computation time:               data3D = Import["data-a.dat"];     data3Ds = Round[data3D, 0.05] // DeleteDuplicates;      My first intention was to work with ImageProcessing like in this question: Image segmentation and object separation in 3D using Mathematica, because i worked a lot with 2D image processing. At first sight it was a nice idea to create an 3D image out of the data and worked more or less. But the result was not satisfying. The main problem is that all filters and transformations detect the edges between the data points and the NULL-values and doesn't (what i want to do) segment between the data. The presented DistanceTransfrom was created for volumetric data, in my example it is a surface in a three dimensional space. I would like to show some examples and the results, but the .nb-script crashed and I have no access to the results anymore... As second try I used the idea of the documentation of VertexNormals. The idea was to get the orientation of smaller parts of the surface. For this an interpolation of the data is needed. The documentation suggest to use _ListSurfacePlot3D_.               g = ListSurfacePlot3D[data3Ds, Mesh -> None, MaxPlotPoints -> 50]      ![enter image description here](http://i.stack.imgur.com/eUMPc.jpg)               {pl, vl} =        First@Cases[g,          GraphicsComplex[pl_, prims_, VertexNormals -> vl_,            opts___?OptionQ] :> {pl, vl}, Infinity];     vl1 = Table[Norm[vl[[i]] - {0, 0, 1}], {i, Length[vl]}];     nf = Nearest[pl -> vl1];     vl2 = ParallelMap[StandardDeviation[nf[pl[[#]], 50]] &,        Range[Length[pl]]]     ListPointPlot3D[List /@ pl,       PlotStyle -> ({PointSize[Medium],            Blend[{{.1, Darker[Green]}, {0.45, Yellow}, {0.7,               Red}}, #1]} & /@ vl2)]      _vl_ is a list of vectors representing the orientation of a point _pts_ and with the length of 1. _vl1_ is the difference of the orientation between all _vl_ and the vertical. At the end _vl2_ represent the deviation of the orientation of 50 surrounding data points at one point. ![enter image description here](http://i.stack.imgur.com/3VytF.jpg) The result is not that bad, but at the one hand I have no idea how to seperate the different parts. At the other hand this version is very slow and only for the reduced data points. Additionally the ListSurfacePlot3D creates some artefacts like in this question. At the end I tried another interpolation method and worked with tetrahedral meshs of the _TetGenLink_ Package. The simple interpolation function doesn't work good because the data is mainly unstructured (see this link and the related questions) and have more than on z-value for some x-y-pairs. Maybe you have better ideas for this segmentation problem or could give me some advice to think into other directions. I would apppreciate no solution for MMA version 10 because I'm just working with version 9. Thank you! **Edit 1 (Delaunay)** I've tried already the _TetGenLink_ -Package with the this help.               << TetGenLink`     {pts, tetrahedra} = TetGenDelaunay[data3Ds];     csr[{aa_, bb_, cc_, dd_}] :=       With[{a = aa - dd, b = bb - dd, c = cc - dd},        Norm[a.a Cross[b, c] + b.b Cross[c, a] +           c.c Cross[a, b]]/(2 Norm[a.Cross[b, c]])]     radii = csr[pts[[#]]] & /@ tetrahedra;     alphashape[rmax_] := Pick[tetrahedra, radii, r_ /; r < rmax]     faces[tetras_] :=       Flatten[tetras /. {a_, b_, c_,           d_} :> {{a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}}, 1]     externalfaces[faces_] :=       Cases[Tally[Sort /@ faces], {face_, 1} :> face]     polys = externalfaces@faces@alphashape[0.1];     Graphics3D[GraphicsComplex[pts, Polygon@polys], Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/kZkQR.jpg) The result is not that bad and works quite good with version 9. Just I don't have any idea to work further with this Graphic.


title: Is there any way to obtain an approximate inverse for very large sparse matrices?

text: I have a very large sparse matrix and I need to obtain its approximate inverse and save it as an sparse matrix too. Any of my efforts as could be seen in what follows fail for large n               ClearAll[n, s, f, aInv]     n = 100000;     s = SparseArray[{Band[{1, 120}] -> -2., Band[{950, 1}] -> -1.,          Band[{1, 1}] -> 20., Band[{1, 100}] -> 2.,          Band[{6, 800}] -> 1.1}, {n, n}, 0.];     f = LinearSolve[s];     aInv = f[SparseArray[{Band[{1, 1}] -> 1.}, {n, n},           0.]]; // AbsoluteTiming      The accuracy of the approximate inverse is not that important to me for the time being, if it could be obtained and saved in the sparse form then I can improve it by the existing iteration methods. Maybe the built-in pre- conditioners for large sparse matrices in _Mathematica_ 8 could be good. I would be grateful if someone give me some hints to obtain an approximate inverse for such large sparse matrices.


title: Adding Math to Plots

text: I have several formulas I would like to place at specific coordinates in a `Graphics` object I have already created. I need to be able to choose bold or not as well as how large to make it. I am unsure how to control the size of the text as well as why _Mathematica_ will not place it. Specifically, it continues to try to evaluate my text. One of the objects I wish to place on the plot is (since it won't let me post a picture) $$M^\mu = \oplus_{\lambda \ge \mu} \,m \, \lambda_\mu \, S^\mu$$ However, _Mathematica_ continues to try to evaluate the direct sum rather than just place it at say the point (0,0). Here is the code I am trying at the moment:               Graphics[{Style[HoldForm[M^μ == \!\(*UnderscriptBox[(StandardForm[⊕]), (λ ≥ μ)]\) m Subscript[λ, μ] S^μ], Medium], FormatType -> StandardForm}]      Any ideas?


title: How to normalise a line in mathematica

text: I'm working on creating a line plot from a histogram, as in the following:               {g, {binCounts}} =        Reap[Histogram[RandomVariate[NormalDistribution[0, 1], 100],               {-2,2,0.25},               Function[{bins, counts}, Sow[counts]]]];          {g, ListLinePlot[binCounts]}      What I'd like to know is, how can I normalised this line so the area under the curve is 1? (So I can compare the shapes of these histograms independent of the number of counts)


title: Fitting Function with 3 parameters

text: I am trying to fit a function with 3 parameters however the result strongly depend on the initial values of parameters:                data = ToExpression@Import["http://pastebin.com/raw.php?i=eSXQuV62"];           FindFit[data,           G/(2/3*x)*(1 - (4.13/G*(Log[k/(x*r)] + G/4.13))^(2/3)),           {{k, 0.0001}, {x, 0.2}, {G, 80}}, r]      the result are > >     {k -> -0.000803039, x -> 0.613938, G -> 47.9489} >   for different set of initial values of parameters                 FindFit[data,            G/(2/3*x)*(1 - (4.13/G*(Log[k/(x*r)] + G/4.13))^(2/3)),             {{k, 0.0001}, {x, 0.2}, {G, 100}}, r]      > >     {k -> -0.00247546, x -> 1.04233, G -> -341.32} >   I also get following message > FindFit::nrlnum: "The function value {31.8606 -11.8829\ I,32.8832 -11.8583\ > I,26.5785 -11.8548\ I,36.1803 -11.852\ I,27.6782 -11.8511\ I,<<42>>,20.6663 > -11.7998\ I,17.8617 -11.7998\ I,7.70671 -11.7992\ I,<<56>>} is not a list of > real numbers with dimensions {106} at {k,x,G} = > {-0.00247546,1.04233,-341.32}. Do you know how to solve this issue?


title: Export notebook to HTML produces low resolution GIF

text: I have equations written in my notebooks as text (the cells set as Format -> Style -> Text). When exporting the notebook to HTML (File -> Save As.. -> HTML) with the GIF option (the default) an HTML file is produced along with folders: HTMLFiles and HTMLLinks. The HTMLFiles folder contains GIF images of the equations in the text, but they are very low resolution / quality. Is there a way to make Export set them to a higher resolution? motivation: to write equations in Mathematica (it is nice to write in) and output the equations as images to use in a presentation. I have tried: SetOptions[Image, ImageSize -> 5000]; SetOptions[Image, ImageResolution -> 5000]; SetOptions[Graphics, ImageSize -> 5000]; SetOptions[Rasterize, RasterSize -> 1000]; With no luck. Thanks,


title: Using a different version of R with RLink on Windows 7

text: I'd like to run the R version installed in my Windows 7 system from within Mathematica 9 but when I execute the following command:               InstallR["RHomeLocation" -> "C:\\Program Files\\R\\R-2.14.2\\bin\\x64"]      I get the following error message: > InstallR::fail: Failed to install R. The following error was encountered: > Unable to load dynamic libraries Does anybody know how to fix this issue? Many thanks in advance


title: f[arg1, arg2,...,argN] vs. f[{arg1, arg2,...,argN}]

text: I am trying to reproduce the API of a function (written in R) that accepts an arbitrary number of arguments and handles it the same way as it would handle a single argument that is a list of different data sets. Is there a Mathematica idiom that allows a function to be defined so that:               f[ arg1, arg2, ..., argN ]      behaves the same as               f[ {arg1, arg2, ..., argN} ]      ?


title: How to load data into a Manipulate expression

text: I have data showing truncated octahedron geometry changing with time. How can I read those data into a `Manipulate` expression? To be specific, I want to manipulate time and have other parameters change correspondingly as in my data. Those parameter value should show simultaneously. Now I have geometry that I can change by varying the parameters. My `Manipulate` code is               Manipulate[      Grid[{{RegionPlot3D[          x + y + z < 0.866 A && x + y - z < 0.866 A &&            x - y + z < 0.866 A && -x + y + z < 0.866 A &&            x + y + z > -0.866 A && x + y - z > -0.866 A &&            x - y + z > -0.866 A && -x + y + z > -0.866 A, {x, -0.5*r*A,            0.5*r*A}, {y, -0.5*r*A, 0.5*r*A}, {z, -0.5*r*A, 0.5*r*A},           ImageSize -> 300, Mesh -> 1, PlotRange -> {-16, 16}],          SpanFromLeft, SpanFromLeft}, {"volume(nm^3)",          ScientificForm[          NIntegrate[           Boole[void =              x + y + z < 0.866 A && x + y - z < 0.866 A &&               x - y + z < 0.866 A && -x + y + z < 0.866 A &&               x + y + z > -0.866 A && x + y - z > -0.866 A &&               x - y + z > -0.866 A && -x + y + z > -0.866 A], {x, -0.5*r*A,             0.5*r*A}, {y, -0.5*r*A, 0.5*r*A}, {z, -0.5*r*A, 0.5*r*A}],           3] }, {"{002}Facets area(nm^2)",          ScientificForm[12*(0.866 A - 0.5*r*A)^2,           3]}, {"{111}Facets area(nm^2)",          ScientificForm[          4*(3)^(0.5)*((0.866 A)^2 - 3*(0.866 A - 0.5*r*A)^2), 3]}}],        {{A, 20, "Distance between {111} facets (nm)"}, 1, 20, Slider, Appearance -> "Labeled"},        {{r, 1.4, "Aspect ratio"}, 1.04, 1.4, Slider, Appearance -> "Labeled"},        ControlPlacement -> Top]      And a small subset of my data is               Time  A      r      200   16.09  1.084524549     210   15.74  1.062261753     220   15.02  1.053262317     225   14.59  1.067169294     235   14.21  1.073187896


title: Combining Newtonian 3D N-Body Simulation Output and Earth Sphere

text: I'm trying to figure out how to make a simulation whereby two satellites orbit Earth, but have run into a little bit of a snag. I have a solution to the system of ODEs for the n-body output, and I found a brilliant thread explaining how to create an Earth sphere here (How to make a 3D globe?) but I'm struggling to combine the output of the two. This is my attempt: (Note that "soln" is the output of the n-body NDSolve computations, which I didn't put in here as I thought combining the two entities would be a trivial syntactic edit. If the full code is needed I'll be happy to supply it as well)               Earth = Import["Desktop/earthtruecolor_nasa_big.jpg"];     EarthSphere =      ParametricPlot3D[{Cos[u] Sin[v], Sin[u] Sin[v], Cos[v]}, {u, 0,      2 Pi}, {v, 0, Pi}, Mesh -> None, PlotPoints -> 100,      TextureCoordinateFunction -> ({#4, 1 - #5} &), Boxed -> False,      PlotStyle -> Texture[Show[Earth, ImageSize -> 1000]],      Lighting -> "Neutral", Axes -> False, RotationAction -> "Clip",      ViewPoint -> {-2.026774, 2.07922, 1.73753418}, ImageSize -> 800];          Show[ParametricPlot3D[     Evaluate[{{x[1][t], y[1][t], z[1][t]}, {x[2][t], y[2][t],      z[2][t]}} /. soln], {t, 0, 20000}, AxesLabel -> {x, y, z},      AspectRatio -> 1, BoxRatios -> 1, PlotStyle -> Automatic,      ImageSize -> Large,      PlotRange -> {{-10000000, 10000000}, {-10000000,        10000000}, {-10000000, 10000000}}] {EarthSphere, {0, 0, 0}}]      This is my output so far: ![enter image description here](http://i.stack.imgur.com/eDRyi.png) EDIT: I added in the n-body code as I thought it would cause confusion if I did not:               G = 6.672*10^-11     m[0] = AstronomicalData["Earth", "Mass"];     tmax = 20000;     r[0] = AstronomicalData["Earth", "Radius"];     rx[1] = (r[0] + 300000 ) Cos[45 Degree];     ry[1] = (r[0] + 300000 ) Sin[45 Degree];     rz[1] = 0;     rx[2] = (r[0] + 600000 ) Cos[90 Degree];     ry[2] = (r[0] + 600000 ) Sin[90 Degree];     rz[2] = 0;     vx[1] = Sqrt[(G  m[0])/(r[0] + 300000)] Sin[45 \[Degree]]      vy[1] = Sqrt[(G  m[0])/(r[0] + 300000)] Cos[45 \[Degree]]     vz[1] = 0     vx[2] = Sqrt[(G  m[0])/(r[0] + 600000)] Sin[90 \[Degree]]     vy[2] = Sqrt[(G  m[0])/(r[0] + 600000)] Cos[90 \[Degree]]     vz[2] = 0     soln = NDSolve[{        x[1]''[t] == -((          G m[0] x[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        y[1]''[t] == -((          G m[0] y[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        z[1]''[t] == -((          G m[0] z[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        x[2]''[t] == -((          G m[0] x[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),        y[2]''[t] == -((          G m[0] y[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),        z[2]''[t] == -((          G m[0] z[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),             x[1][0] == rx[1], y[1][0] == ry[1], z[1][0] == rz[1],         x[2][0] == rx[2], y[2][0] == ry[2], z[2][0] == rz[2],         x[1]'[0] == -vx[1], y[1]'[0] == vy[1], z[1]'[0] == 0,         x[2]'[0] == -vx[2], y[2]'[0] == vy[2], z[2]'[0] == 0}, {x[1][t],         y[1][t], z[1][t], x[2][t], y[2][t], z[2][t]}, {t, 0, tmax} ,        MaxSteps -> 1000000, Method -> "StiffnessSwitching"]


title: Choosing among different function definitions without sacrificing speed

text: I'm working on some code that numerically integrates a function, let's call it `G`, which calls another function, `F`, that can be defined according to any of several models. In one model, there is an analytic expression for `F`. In the other models, `F` needs to be defined by loading data from a file and interpolating it. There is a different data file for each model (other than the analytic one). One way I tried to do this was to have a `Switch` statement in `F`, and get it to choose whether to use the analytic expression or to take data from a file each time it's called based on the options provided.               (* load data from a file and Interpolate it *)     FFromFile[filename_] := FFromFile[filename] = Module[{...}, ...]     FAnalytic[a_,b_,c_] := a^2+b^2+c^2     F[a_,b_,c_,OptionsPattern[]] :=  Switch[OptionValue[Model],        "File",FFromFile[OptionValue[Source]][a,b,c],        "Expr",FAnalytic[a,b,c]     ]     G[d_,e_,f_,phi_,opts:OptionsPattern[]] := Block[{g,h,i},        (* do a bunch of calculations to figure out g and h *)        i = F[g, h, 5, opts];        (* do more calculations involving i *)     ]     GenerateData[phi_,opts:OptionsPattern[]] := NIntegrate[G[x,y,z,phi,opts],        {x,2,10}, {y,0,x}, {z,0,3}, Method->"QuasiMonteCarlo", PrecisionGoal->3]      Unsurprisingly, that turned out to be too slow. So, another method I tried was to predefine `F`, since the same model is used throughout an integration.               (* load data from a file and Interpolate it *)     FFromFile[a_,b_,c_] = Module[{v,...}, v=ReadList[filename, ...]; ...];     FAnalytic[a_,b_,c_] = a^2+b^2+c^2;     Switch[TheModel,        "File",F=FFromFile,        "Expr",F=FAnalytic     ]     G[d_,e_,f_,phi_] := Block[{g,h,i},        (* do a bunch of calculations to figure out g and h *)        i = F[g, h, 5];        (* do more calculations involving i *)     ]     GenerateData[phi_] := NIntegrate[G[x,y,z,phi],        {x,2,10}, {y,0,x}, {z,0,3}, Method->"QuasiMonteCarlo", PrecisionGoal->3]      `filename` and `TheModel` would be defined prior to running this code snippet. This way is faster, though it turns out to be kind of inconvenient because sometimes I want to run calculations that compare two different models (for example, from two different files), which requires me to run one, save the data to a file, quit the kernel to ensure that all the definitions are cleared, start it up again and run the other. Plus, this method of passing information to the function by defining variables in advance (`filename` and `TheModel`) makes me kind of queasy ;-) Is there some way I can get the best of both worlds, namely be able to **specify the model by passing options to`GenerateData`, while still retaining the speed benefits of predefining `F`?**


title: dropping a row with at least one value larger than a particular value

text: So for instance I have M X N table. I want to drop any row which has an element larger than, say, one in the second or the third column. I guess I have to do some sort of pattern matching. But not exactly sure how to do it. I can use a table to search for a value and then find its Position and then drop the corresponding row. There must be a easier way to do this without traversing through each element using the Table function. help please :)


title: Export notebook to pdf in landscape orientation

text: Assuming the following is a notebook with a linebreak: ![enter image description here](http://i.stack.imgur.com/AunnN.png) How might I export a landscape pdf (preferred although other formats could work) such that **~~each cell content~~ each group of cells** above and below the page break are stretched to take up half of the landscape page. ![enter image description here](http://i.stack.imgur.com/JVLOZ.png) The colors are simply there to act as placeholders. I certainly could copy and paste such data into a word document, but ideally something like this could be automated.


title: Creating custom notation

text: How does one generate custom symbols? For example, the physicist notation for the rotation is "nabla cross function". In this case however, Mathematica complains that the `[esc]del[esc]` symbol evaluates to the unary operator `Del[]`, which of course cannot take a cross (`[esc]*[esc]`) after it, since a bracket is expected. Although a correctly looking output is generated by               Prefix[f[a], "\[Del]\[Times]"]      ![](http://i.stack.imgur.com/2vco3.png) the result cannot simply be assigned to an operation (`Prefix[...] := ...`) you can type in using the nicely readable [esc] commands I mentioned above. Is there some way of doing this, i.e. invoking completely custom functionality to (combinations of) existing symbols?


title: How can I break through Function's HoldAll attribute to force evaluation of a body element?

text: The question concerns creating a function. Let consider the following code               With[{f = Function[t, Cos[t]]},      {First[#], f'[#]} &     ]      which returns               (* ==> {First[#1], Function[t, Cos[t]]'[#1]} & *)      How to can I force it to return the derivative evaluated (only second part of the returned list); i.e., how to can I get               (* ==> {First[#1], -Sin[#1]} & *)


title: The clearest way to represent Mathematica's evaluation sequence

text: WReach has presented here a nice way to represent the _Mathematica_ 's evaluation sequence using `OpenerView`. It is **much more** clear way to go than using the standard `Trace` or `TracePrint` commands. But it could be improved further. I need straightforward way to represent the real sequence of (sub)evaluations inside _Mathematica_ 's main loop for beginners. In particular, it should be obvious when new evaluation subsequence begins and from which expression (it is better to have each subsequence exactly in one `Opener`). The evaluation (sub)sequence should be identified as easily as possible with the standard evaluation sequence. I mean that the reader should be able to map real evaluation step to one described in the Documentation for the standard evaluation sequence. Is it possible?


title: Data Table Manipulation in Mathematica: Step 2

text: In this previous post (Data Table Manipulation in Mathematica) we find the brilliant suggestion proposed by Leonid Shifrin that allows to select specific rows identified by the header name. I'm now looking for a way to then also select the data of a specific column (or more columns) of the subset of data generated by Leonid's select function. Suppose we have this data:               table = List[     {"ID", "Variable 1", "Variable 2"},      {"Alpha", 1, 0},      {"Beta", 1, 1},      {"Alpha", 0, 0}]      which when formatted as a grid looks like this:               ID     Variable 1 Variable 2     Alpha       1          0     Beta        1          1     Alpha       0          0      Using Leonid's function we can obtain this:               subset = select[table, where["Variable 1" == 1]]          (* {{"Alpha", 1, 0}, {"Beta", 1, 1}} *)      Suppose that we now want to sum all the values that are in the column named 'Variable 2'. We could just do this:               Total[subset[[All,3]]]      However, in this way we loose the advantage of using Leonid's function that can work directly with header names. Ideally, I would like to find a way to get those data by using the header name. Something like:               Total[subset[[All,"Variable 2"]]]      or, even better:               select[table, where["Variable 1" == 1], columns["Variable 2"]]      Any hints would be highly appreciated.


title: Overlaying location pointer on to a png file

text: So I have started off with importing a png image of size $512\times 1024$ px. I have then created two locators as demonstrated on the Wolfram tutorials:               length = DynamicModule[{p1 = {0, 0},         p2 = {1, 1}}, {Dynamic@         Graphics[{Arrow[{p1, p2}], Locator[Dynamic[p1]],            Locator[Dynamic[p2]]}, PlotRange -> 1024],         Dynamic[Grid[{{"Length:", EuclideanDistance[p1, p2]}, {"Slope:",             1/Divide @@ (p2 - p1)}}]]}]      I would like to be able to overlay these locators on to my png image and move them around, in order to measure the distance between two points on the image. I'm sure this should be possible but I really can't see how! Thanks for looking :)


title: Numbered equations/formulas

text: How do you number equations in _Mathematica_ notebooks so that they are exported correctly into latex? In case you don't know how to put numbered equations here is quick review.   1. Open a new notebook and create a new cell with an equation.    2. Select the cell, on the menu go to `Format -> Style -> DisplayFormulaNumbered` or change this by pressing the shorcut command+0 on mac or alt+0 on windows and enter `DisplayFormulaNumbered`. At this step you should have something like this: ![Output 2](http://reference.wolfram.com/mathematica/ref/format/TeX.html#1511511812)   3. Select the cell again in case you deselected like I did. Go to `Cell -> Cell Tags -> Add/Remove Cell Tags` or use the shorcut command+J on the mac (don't know about windows). A panel should appear, enter the name of how you would like to refer to the equation and click Add. I entered `simpleParabola`.   4. To see that you successfully added the tag go to `Cell -> Cell Tags -> Show Cell Tags`. You can use this options to show and hide the cell tags. I suggest to keep them on while you are editing and hiding them when you are done. This is what I see so far.  ![Output 4](http://i.stack.imgur.com/7aDbB.png) You can repeat these steps to enter your equations and labeling them. Now, to refer to them by the tag you have given them you have to write some text. Say you write something like:               This is my text and now I refer to XXX because it is important to refer to it.      What we want is to let `XXX` to refer to the label `simpleParabola`. What you do is select that part of the text. Then go to `Insert -> Automatic Numbering ...`. On `Counter` you need to select `DisplayFormulaNumbered` because that's the type of cell you want to refer to. Then select `simpleParabola`, click ok and you are done. The `XXX` should change to `1`. The good thing about this is that if in the future your numbers change then your number will automatically change. To test this, just go above the cell where you have numbered formula and create a new `DisplayFormulaNumbered` cell, Now this new one should have the label 1 and the cell with the tag `simpleParabola` should have label number 2. But guess what? You don't have to worry about changing the numbers in your text because you already linked it to the label. Here is a screenshot: ![Output](http://i.stack.imgur.com/kURZx.png) Ok, so we can create documents with numbered equations. Now lets assume that you are collaborating in some document and this document is required to be typed in latex. As the awesome _Mathematica_ user that you are you type the document faster in _Mathematica_ thanks to all the shortcuts that it offers. Finally, after you are done you save it in Latex format. Here is a what we obtain:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         g(x)=x^3         \end{equation}          \begin{equation}         f(x)=x^2         \end{equation}          This is my text and now I refer to 2 because it is important to refer to it.          \end{document}      Not bad. Unfortunately, our cell tags are gone. Now, laTeX users, please correct me if I'm wrong. Will the next modification work?                 %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         g(x)=x^3         \end{equation}          \begin{equation} \label{simpleParabola}         f(x)=x^2         \end{equation}          This is my text and now I refer to ~\ref{simpleParabola} because it is important to refer to it.          \end{document}      All I've done is add `\label{simpleParabola}` and `~\ref{simpleParabola}`. After running LaTeX on it twice I obtain this pdf ![pdf](http://i.stack.imgur.com/25x9Y.png) _Mathematica_ did a pretty good job at giving the latex version but it gave me the job to add the labels and references. Now here is something that is very interesting. If you have the modifed version of the latex document that I showed I want you to open a new notebook and enter:               NotebookPut[Import["Path_To_Latex_Document"]]      You will end up with a new document with the latex content in there. But what happened to the numbers? and why is the reference messed up? If you show the cell tags again it will reveal that the label that you put in latex was converted to a cell tag. And if you see the expression on the text you will see that it added the automatic numbering for you. The reason it isn't working is because it placed the wrong counter. ![Output](http://i.stack.imgur.com/Mzd0e.png) So now that you have an idea of what I am doing here are the questions:   * Is there any way to write in latex the style that the _Mathematica_ cells should use? Notice how _Mathematica_ uses `NumberedEquation` instead of the `DisplayFormulaNumbered` style.   * How do you specify the counter so that _Mathematica_ knows what counter to use. Notice that in this case it is using `Section` instead of `DisplayFormulaNumbered`.   * How do you make it so that when you export the notebook file to a latex file it places the `\labels` and `\~ref` in the latex file?  Any ideas? * * * I will post some new stuff I've found here. I still haven't found an answer. If you go to this link you will find an example. This is what I've been working with               ExportString[      Cell[       BoxData[{         "This is a reference to an equation: ",         CounterBox["NumberedEquation", "eq:myEq1"],         ". This is another one: ",         CounterBox["NumberedEquation", "eq:myEq2"],         ". And this is yet another one: (",         CounterBox["NumberedEquation", "eq:myEq3"],         ")."         }        ], "Text"       ]      , "TeX",      "ConversionRules" -> {        "Text" -> {          # &          }        } ]      The output I obtain is:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          This is a reference to an equation: CounterBox[NumberedEquation, eq:myEq1]. This is another one: CounterBox[NumberedEquation, eq:myEq2]. And this     is yet another one: (CounterBox[NumberedEquation, eq:myEq3]).          \end{document}      I can tell _Mathematica_ to let the the contents go as they are. One problem though, I want to replace say `CounterBox[NumberedEquation, eq:myEq1]` with `~\ref{eq:myEq1}`. How do you use the replacement rules here? ## EDIT: The `ConversionRule` for text should be               "Text" -> {         If[MatchQ[#, _CounterBox], "~\\ref{" <> #[[2]] <> "}", #] &      }      Here is the remaining problem I can't figure out:               ExportString[      Cell[       BoxData[        FormBox[RowBox[{RowBox[{"f", "(", "x", ")"}], " ", "=", " ", "x"}],          TraditionalForm]        ],       "NumberedEquation",       CellTags -> "eq:myEq"       ]      , "TeX",      "ConversionRules" -> {        "NumberedEquation" -> {          "\\begin{equation}\n", Convert`TeX`BoxesToTeX[#] &,           "\n\\end{equation}"          }        } ]      We get:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         f(x) = x         \end{equation}          \end{document}      We need to get               \begin{equation}\label{eq:myEq}         f(x) = x         \end{equation}      How do we obtain the `CellTag`?


title: Manipulating differential equations

text: I would be very grateful if anyone could help with manipulating the solution to the system of differential equations below. I've tried just about everything I can think of all to no avail. The code doesn't seem to be working (i.e. the parameters I'm trying to adjust have no effect on the dynamics of the graphs which can't be right-I computed other values myself and it gave a different plot). I have had a look at some similar topics like Manipulate a Differential Equation result but its quite specific for single differential equations rather than a system of equations. The variables I'd like to vary are mhigh, s0, p0 and z0. My code is given below:               Needs["PlotLegends`"];          De = 2.1;      B = 2.3;     B2 = 0.001;      mhigh = 0.001, mlow = 0.0004;     fr = 0.77, fs = 1, fp = 1.4;      s0 = 1000;      z0 = 1000;      p0 = 0;      r0 = 0;           solutionN2 =        NDSolve[{         Z'[t] == De*(S[t] + P[t] + R[t]) - B*Z[t]*((fs*S[t]) + (fp*P[t]) + (fr*R[t])),          S'[t] == fs*B* S[t]*Z[t] - (mlow + mhigh)*S[t] - De *S[t],          P'[t] == fp* B* P[t]*Z[t] + mlow *S[t] - B2* P[t] - De* P[t],          R'[t] == fr *B* R[t]*Z[t] + mhigh* S[t] + B2 *P[t] - De *R[t],          S[0] == s0, P[0] == p0,          R[0] == r0, Z[0] == z0},          {S, P, R, Z}, {t, 0, 200}];           Manipulate[        Plot[{Z[t] /. solutionN2, S[t] /. solutionN2, P[t] /. solutionN2, R[t] /. solutionN2},           {t, 0, 200},           ImageSize -> {700},           PlotStyle -> {Brown, Red, Blue, Darker[Green]},           PlotLegend -> {"Z", "S", "P", "R"}, LegendPosition -> {0.2, -0.2},           FrameLabel -> {Style["time (in days)", Medium]}],        {{s0, 1000, s0:initial sus pop"}, 0, 5000,          ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{z0, 0, z0:initial resources"}, 0, 5000,          ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{p0, 0, p0:initial p. sus. pop"}, 0, 1000,         ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{mhigh, (0.001), "mut. rate"}, 0, 0.01,          ImageSize -> {Tiny}, Appearance -> "Labeled"}]      Please bear with me as I'm a beginner with _Mathematica_. As stated, any useful help would be so much appreciated as Ive spent nearly the whole day trying to sort this out.


title: Efficient evaluation of functions defined by NIntegrate

text: I have a complicated function $f$ and I want to plot the function $F(x)$ defined by the definite integral of $f$ from $0$ to $x$: $$ F(x) = \int_0^x f(y)\mathrm dy. $$ Apparently $f$ cannot be integrated in closed-form, and I use `NIntegrate[]` instead               F[x_] := NIntegrate[f[y], {y, 0, x}];     Plot[F[x], {x, 0, 100}]      I would like to improve the efficiency of this computation by telling _Mathematica_ that `F[s + t]` is simply `F[s] + NIntegrate[f[y], {y, s, t}]` so that (for example) _Mathematica_ can save the value of `F[1]` and whenever `F[2]` or `F[3.2]` is needed, _Mathematica_ can substitute the value of `F[1]` and compute only the integral of the remaining interval. Essentially I am looking for the continuous version of the trick one uses to compute the Fibonacci sequence:               f[n_] := f[n] = f[n-1] + f[n-2]      Is there a simple way to implement this? Any help is much appreciated.


title: How do I find the degree of a multivariable polynomial automatically?

text: I have a very simple question which appears not to have already been answered on this forum. Is there built-in functionality that returns the degree of a multivariable polynomial? For example if the polynomial is               s1 + s2^2 s3 + s3^2 s4^7      I want _Mathematica_ to return 9. If there is no automatic solution, could somebody please suggest a simple (and fast) implementation? EDIT: I removed my "solution" because it actually only works for simple examples. I tested out the four solutions presented so far on a degree 20 polynomial in 6 variables (`ByteCount[poly] = 2006352`). I used `AbsoluteTiming` to determine that the answer I chose is the fastest, with a run-time of 53.06 s for 1000 evaluations. This is quite a bit faster than the closest competitor's run-time of 283.76 s for 1000 evaluations. UPDATE: I tested the improved version of the solution (the one with random reals) and found that the run-time is now slightly worse but still far better than the competition at 90.52 s for 1000 evaluations.


title: Parallel linear algebra with arbitrary precision

text: Is it possible to do parallel linear algebra with arbitrary precision within Mathematica (in a simple manner, as is done for the machine precision)?


title: Why does Assuming for Integrate not work as expected?

text: I'm trying to perform the following integral with Mathematica 7:               Assuming[{t>0},       Integrate[(-s^2 + 4*s*t + 2*alpha*s)^(-(1/2)*D),{s, 0, t}, {alpha, 0, Infinity}]]      If I perform the integration with just the t>0 assumption, Mathematica gives:               (1/(-2 + D))If[Re[D] < 2,       ( 2^-D t^(2 - D) (       -8 (-4 + D) Gamma[1 + D/2] Hypergeometric2F1[1 - D/2, D/2, 2 - D/2, 1/4]       + (-2 + D) D Gamma[D/2] Hypergeometric2F1[2 - D/2, D/2, 3 - D/2, 1/4]       ))/((-4 + D) (-2 + D) Gamma[1 + D/2]),       Integrate[(-s (s - 4 t))^(1 - D/2)/s, {s, 0, t}, Assumptions -> Re[D] >= 2 && t > 0]]      which indicates that D must be less than 2. If I now use the additional assumption `D<2` with `Assuming[{t>0,D<2},` Mathematica says that the integral no longer converges. (Also with exchanged places for the integration variables, the integral can no longer be calculated). Can anyone solve the mystery? Thanks, Tobias


title: Optimize inner loops

text: I'm Mathematica newbie so please be gentle :) I have this, heavily non- optimized part of code, which I would like to speed up. I have put all matrices to be RandomReal, but in my code they take specific values. Also, matrices mat3, mat4, mat6 and mat7 consist of random simple trigonometric functions. Any kind of help is much appreciated. I have read about Map, Table, Do, Functional Programming... but I don't know how to apply it. Code is part of Finite element-Finite strip calculation. I don't mind losing computing time during "real" calculation, but this part of code is just placing elements of matrices into other places with just few calculations. Matrices mat2, mat5, mat9, mat10 and mat11 need to be stored for later data processing. Bonus question: is it possible to Compile this part of code? Hope I gave optimal amount of data about my problem All the best, Aleksandar               limit1 = 10;     limit2 = 20;     limit3 = 10;     limit4 = 15;     mat1 = RandomReal[{-100, 100}, {limit3, 2}];     mat2 = RandomReal[{-100, 100}, {limit1, limit2, limit3, 2}];     mat3 = Table[Sin[m*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat4 = Table[Sin[m*s*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat5 = RandomReal[{-100, 100}, {limit1, limit2, limit3, 6}];     mat6 = Table[Sin[m*m*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat7 = Table[Sin[m*\[Pi]*y] + Cos[s*s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat8 = RandomReal[{-100, 100}, {limit2, limit3, limit4, 2}];     mat9 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];     mat10 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];     mat11 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];          For[n = 1, n < limit1 + 1, n++,     For[i = 1, i < limit2 + 1, i++,          For[j = 1, j < limit3 + 1, j++,          y = (mat1[[j, 1]] + mat1[[j, 2]])/2;          mat2[[n, i, j, 1]] = mat3[[i, j]];          mat2[[n, i, j, 2]] = mat4[[i, j]];          mat5[[n, i, j, All]] = 1/2 (mat6[[i, j]] + mat7[[i, j]]);          Clear[y];          For[k = 1, k < limit4 + 1, k++,          zz = 1/2 (mat8[[i, j, k, 1]] + mat8[[i, j, k, 2]]);          mat9[[n, i, j, k]] = {mat5[[n, i, j, 1]] + zz*mat5[[n, i, j, 4]],                            mat5[[n, i, j, 2]] + zz*mat5[[n, i, j, 5]],                            mat5[[n, i, j, 3]] + zz*mat5[[n, i, j, 6]]};     mat10[[n, i, j, k]] = mat11[[n, i, j, k]].mat9[[n, i, j, k]];          Clear[zz]     ]          ]]     ]


title: Plot 3D image of function

text: I'm (very!) new to _Mathematica_ , and trying to use it plot a set in $\mathbb{R}^3$. In particular, I want to plot the set $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{R}^3\setminus\\{0\\} \big\\}. $$ This is just the image of function from $\mathbb{R}^3\setminus\\{0\\} \to \mathbb{R}^3$. I haven't been able to make any of the plot functions display this. Any advice would be greatly appreciated. If it makes it easier, the set above is also $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{S}^2 \big\\}. $$ Alternatively, one could plot the three sets $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1+v^2+w^2}(vw,w,v) \text{ for some } (v,w) \in \mathbb{R}^2 \big\\}, $$ $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1 +u^2+w^2}(w,uw,u) \text{ for some } (u,w) \in \mathbb{R}^2 \big\\}, $$ $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1+u^2+v^2}(v,u,uv) \text{ for some } (u,v) \in \mathbb{R}^2 \big\\}. $$


title: What is PointForm?

text: I stumbled across a function called `PointForm` but the only documentation I can find is the pop-up line offered by autocomplete, which contains the same information as `Information[PointForm]`: ![enter image description here](http://i.stack.imgur.com/QFBDM.png) What does this mean and how does it work?


title: How to efficiently find multimap k-itemset frequency

text: I am doing this to learn association rules. The data `d` is in format `{id, value}`, for example:               {{0, 29}, {1, 30}, {1, 31}, {1, 32}, {2, 33}, {2, 34}, {2, 35}, {3, 36}, {3, 37}, {3, 38},      {3, 39}, {3, 40}, {3, 41}, {3, 42}, {3, 43}, {3, 44}, {3, 45}, {3, 46}, {4, 38}, {4, 39},      {4, 47}, {4, 48}, {5, 38}, {5, 39}, {5, 48}}      Bigger data example (task I am using it for has x100 amount data) I want to find number of id's that contain values `{x, y}` and `P(x|y)`. Something like:               Contains[d_, x_] := Take[Transpose[Select[d, #[[2]] == x &]], 1][[1]]     ContainsBoth[d_, x_, y_] := Length[Intersection[Contains[d, x], Contains[d, y]]]     ProbabilityOfXGivenY[d_, x_, y_] := ContainsBoth[d, x, y]/Length[Contains[d, y]]      I would like to print out a table or export into a file ![enter image description here](http://i.stack.imgur.com/lr3Ov.png) As my effort, I can write a brute force solution, that works well for input size of 100 instances.               GetRow[d_, {x_, y_}] := {x, y, ContainsBoth[d, x, y],        100 ProbabilityOfXGivenY[d, x, y] // N,        100 ProbabilityOfXGivenY[d, y, x] // N}     Select[GetRow[d, #] & /@        Select[Tuples[DeleteDuplicates[Transpose[d][[2]]], 2],          (#[[1]] < #[[2]]) &], #[[3]] > 1 &];     TableForm[%, TableHeadings -> {Automatic, {"x", "y", "\[Exists]{x,y}", "P(x|y)", "P(y|x)"}}]      **edit** : I slightly improved my bruteforce solution:               d = Import["https://raw.github.com/gist/4040530/       fb175e2134559351354572a4aa0554d462cae31b/gistfile1.txt", "Package"];     data = Take[d, 100000];          MultiSet[hm_, key_, value_] := hm[key] = value;     ContainsBoth[hm_, x_, y_] := Length[Intersection[MS[x], MS[y]]]     P[hm_, x_, y_] := 100 (ContainsBoth[hm, x, y]/Length[hm[y]])     GetRow[d_, {x_, y_}] := {x, y, ContainsBoth[d, x, y], P[d, x, y] // N, P[d, y, x] // N}          Timing[      Clear[MS];      MultiSet[MS, #[[1, 2]], #[[All, 1]]] & /@ SplitBy[SortBy[data, Last], Last];      parsedData = {#[[1, 1]], #[[All, 2]]} & /@ SplitBy[SortBy[data, First], First];      nrnodes = Length[pairs = DeleteDuplicates[Flatten[Subsets[#, {2}] & /@         parsedData[[All, 2]], 1]]];      result = GetRow[MS, #] & /@ pairs;      nrnodes]      This completes in 41.091 s on my computer.               Export[FileNameJoin[{NotebookDirectory[], "datax.csv"}], Reverse[SortBy[result, #[[3]] &]]]


title: Gaps at curve that represents the solution of system of equations as a function of parameter

text: Manipulate[{       Quiet[sol =           Solve[{K1*P*L == PL, K2*P*L == LP, K3*PL*L == LPL,             P0 == P + PL + LP + LPL, r*P0 == L + PL + LP + 2*LPL}, {P, L,             LP, PL, LPL}]][[2]];       complex[x_] := LPL /. sol[[2]] /. r -> x;       Plot[{complex[r]}, {r, 0.1, 6}]       },           {K1, 1001, 10000},      {K2, 1000, 10000},      {K3, 1000, 10000},      {P0, 0.1, 1}      ]      If `K1 == K2 == K3` we have nice curve otherwise there are gaps at curve. what's wrong?