title: Persistence length of a polymer chain

text: I'm trying to calculate the persistence length (Lp) of a polymer chain using Mathematica. The first and simplest method is to compare the `EuclideanDistance` between two points on the polymer and arc length separating the points. This works for me. I'll describe how I implemented this now and then give the other method based on tangent-tangent angle correlations which should also work but I'm having trouble with. Hopefully someone might know about this stuff and be able to help. This article describes what I'm trying to do. I've put some more references and a helpful figure at the end. Two of the linked articles at the end are free/open access and I can provide copies of the other linked articles if people are interested and cannot retrieve them. You can get a sample dataset here, units are in microns but it doesn't really matter:               data = Uncompress@Import["http://pastebin.com/raw.php?i=60aazeuc"]      In the literature traced curves from pixel-based images are often smoothed using a weighted moving average               smoothdata = MovingAverage[data, {1, 2, 4, 2, 1}];      To calculate the arc length lets interpolate along the curve with a cubic spline to a parametrized curve (starting at 0).               f = Interpolation[Transpose[{Range[0, Length[smoothdata] - 1], smoothdata}],                        Method -> "Spline", InterpolationOrder -> 3];      To find the length along the curve I based it on @Szabolcs answer.               v = FunctionInterpolation[Norm[f'[t]], {t, 0, Length[smoothdata] - 1}]     dist = Derivative[-1][v]     totallength = dist[Length[smoothdata] - 1];     invdist = FunctionInterpolation[InverseFunction[dist][d],                                     {d, 0, totallength}]      The `invdist` function returns the parameter along the curve for a given length. Now I made a function that takes a window of arc length x (in microns) and translates it along the curve (in 5 nm steps) and then returns the mean of the square of the `EuclideanDistance` between the end points of all the subsets of the curve. This is repeated for a range of arc lengths and then the result               distance[x_] :=        Mean[         Table[             EuclideanDistance[f[invdist[t]], f[invdist[t + x]]]^2,              {t, 0, totallength - x, 0.005}         ]       ];      Now we can run the function:               tofit = ParallelTable[{x, distance[x]}, {x, 0, totallength, 0.1}]      and fit the result (dropping the first (0,0) point) to the model from the literature:               fit = NonlinearModelFit[             Rest@tofit, {4 Lp s (1 - (2 Lp /s) (1 - Exp[-s/(2 Lp)]))}, {Lp}, s,             MaxIterations -> 1000, Method -> "NMinimize"           ];      Ta da! It works. Lets plot the data and the fit.               Show[       ListPlot[tofit, Joined -> True, PlotRange -> All],        Plot[fit[x], {x, 0, totallength}, PlotStyle -> {Red, Dashed}]     ]      ![Mathematica graphic](http://i.imgur.com/A5JnZ.png) In this case Lp is 0.79 microns, sounds reasonable. The other method to measure the persistence length is based on the angle between tangents on the curve separated by a certain arc length. See: this graphic stolen from the linked paper. Using the cubic spline fit its easy to calculate the tangent vectors at a point. This next function similarly translates a window of arc length x along the curve except this time it finds the dot product (cosine of the angle) of the unit tangent vectors at the endpoints of the window and returns the mean of all the dot products (cosines of the angles).               cosinecorrelation[x_] :=        Mean[         Table[               Dot[Normalize[f'[invdist[t]]], Normalize[f'[invdist[t + x]]]],               {t, 0, totallength - x, 0.005}         ]       ];      This should result in an exponential decay `<cos(theta)> = Exp[-x/Lp]`, However, I get basically a linear function, also the values drop below zero. As far as I can tell that shouldn't happen... Does something look wrong with what I did?               ListPlot[        ParallelTable[{x, cosinecorrelation[x]},                       {x, 0, totallength, 0.1}        ],         Joined -> True, PlotRange -> All     ]      ![Mathematica graphic](http://i.imgur.com/Zb6S2.png) The next method is to look at the mean square angle (instead of the cosine of the angle), `<theta^2> = -x/Lp` which should be a linear function of arc length, x. However, (warning, potentially stupid question follows), when I use `ArcCos` I always get a positive angle (same with `VectorAngle`), even when the dot product is negative. This must have to do with how Mathematica defines `ArcCos`, how, can I make it so negative dot products give the equivalent negative angle. Here is my broken function, based on the MMA `ArcCos`               anglesquaredcorrelation[x_] :=        Mean[         Table[           (ArcCos[Dot[Normalize[f'[invdist[t]]], Normalize[f'[invdist[t + x]]]]])^2,            {t, 0, totallength - x, 0.005}         ]       ];      An alternative implementation, based on `VectorAngle`, which confusingly doesn't seem to give the same values for larger x.               vectorangle[x_] :=       Mean[        Table[           VectorAngle[f'[invdist[t]], f'[invdist[t + x]]]^2,            {t, 0, totallength - x, 0.005}      ];      Any help would be greatly appreciated! For interested parties much of the theory was presented in this 1979 paper based on earlier work by Landau and Lifshitz (Landau, L. D. & Lifshitz, E. M. (1958) _Statistical Physics, Course of Theoretical Physics_ , Vol. 5, Pergamon, London.) Here is a helpful set of plots and equations from another paper: ![Dropbox graphic](https://dl.dropbox.com/u/3730003/Clipboard.png) Open access article this time: PDF, and another open access paper PDF.


title: CountryData and the areas of the world

text: If I add the WaterArea and the LandArea of the world, I get the same number as if I asked for the total area of the world in the first place:               In[1]:= {CountryData["World", "WaterArea"] + CountryData["World", "LandArea"],              CountryData["World", "Area"]}          Out[1]= {5.10066*10^8, 5.10066*10^8}      Now, if I add the area of all the countries, it does not add up to the total LandArea of the world:               In[2]:= {Total[CountryData[#, "Area"] & /@ CountryData[]],               CountryData["World", "LandArea"]}          Out[2]= {1.35936*10^8, 1.4912*10^8}      So my question is: Are some countries missing? Are the ice caps to blame?


title: How can I crop manipulator from a plot

text: I wanted to know how can I crop a `Manipulator` from a plot. the code for plot is                  a=  With[{z1 = .25, z2 = 1, x = 1},         Manipulate[       PopupWindow[     Graphics[      DiscretePlot[Sin[a t], {t, 0, 2 Pi, Pi/6}, ExtentSize -> Full,        ImageSize -> Scaled[x], AspectRatio -> z1/z2]], {a}],      OpenerView[{"Vertical", Control[{{a, 1, "Manipulator"}, 1, 30}]}],      ControlPlacement -> Bottom]]          I have tried using `Export` and `Import` functions and it is working fine                ImageCrop[Import[Export["test.gif", a, "Graphics"]], 90]      But, I wanted to know some other way to do this as I think `Export` and `Import` takes a lot of time in execution.


title: how to plot $x=0$ and $y=0$

text: I tried to plot plane $x = 0$ and $y=0$ with `Plot3D[x = 0, {x, -4, 4}, {y, -4, 4}]` but it seems that it didn't work out. How can I plot the above planes? Also is there a way to plot with z parameter being in the function? Note: I was trying to illustrate a closed surface by planes x=0,y=0,z=0 and 2x+2y+z=4


title: Calculate Integral with cos

text: Integrate[ (Pi/4 - x/2)  cos (n *x), {x, 0, Pi}]      This doesnt give me desired results .n is natural 1,2,3,4,5...   I want to get something like $$\frac{1-(-1)^n}{2n^2}$$


title: Obtaining joint distributions and conditional distributions using Mathematica

text: I have two multivariate Gaussian distributions $p(x)$ and $p(z)$ with mean vectors $m_x$ and $m_z$, and covariance matrices $\Sigma_x$ and $\Sigma_z$. my model is a simple linear model $x = W z+n$ where $n$ is a noise vector with mean $0$ and diagonal covariance matrix of the form $\sigma^2 I$, where $I$ is the identity matrix. I observe the variable $x$. now how can I calculate the joint distribution $p(x,z)$ and the conditional distributions $p(x|z)$ and $p(z|x)$?


title: Using units and piecewise functions in Integrate

text: For simple cases, Quantities appear to be handled well by `Integrate`:               m = Quantity["Meters"];     s = Quantity["Seconds"];          Integrate[1 m/s, {t, 1 s, 2 s}]      returns `1 m`. But `Integrate` has problems when `Piecewise` is introduced:               Integrate[Piecewise[{{1 m/s, 1 s <= t < 1.5 s}, {2 m/s, 1.5 s <= t <= 2 s}}], {t, 1 s, 2 s}]      returns:               Integrate::units: Integrate was unable to determine the units of quantities that appear in the input.      I've tried rearranging the units in a few different ways. For example:               Integrate[Piecewise[{{1 m/s, 1 <= t/s < 1.5}, {2 m/s, 1.5 <= t/s <= 2}}], {t, 1 s, 2 s}]          Integrate[Piecewise[{{1, 1 <= t/s < 1.5}, {2, 1.5 <= t/s <= 2}}] m/s, {t, 1 s, 2 s}]      But everything I've tried so far gives the same error. I am aware I could completely remove the units from the integration and tack them back on afterwords, like this:               Integrate[Piecewise[{{1, 1 <= t < 1.5}, {2, 1.5 <= t <= 2}}], {t, 1, 2}] m      However, that's not what I'm looking for. Is there a way to make this work? **Update** Thanks to @zentient, whose answer led me to the solution I finally used, which is this: I globally define my unit symbols like this:               m = Quantity["Meters"];     s = Quantity["Seconds"];      … so I couldn't use @zentient's solution directly. However, by wrapping `Integrate` in a `Block`, I can achieve the same effect. I also found that it worked better to assume that my unit symbols were greater than zero. This eliminates the piecewise result given by @zentient's approach.               Block[{m, s}, Integrate[Piecewise[{{1 m/s, 1 s <= t < 1.5 s}, {2 m/s, 1.5 s <= t <= 2 s}}], {t, 1 s, 2 s}, Assumptions -> {m > 0, s > 0}]]      This returns `1.5 m`. The `Block` temporarily undefines the unit symbols, so that they are treated as generic symbols within the `Block`. Upon exiting the `Block`, the unit symbols are automatically replaced with their global definitions. (I'm sure there's a more technically precise way to explain that using DownValues and whatnot, but I don't quite grok all of that yet!)


title: Using Mathematica to find a Derivative

text: I am given a system first order differential equations: $x'=y$ and $y'=6x^2-a/2$, where $a$ is a constant and $'$ denotes $t$-derivatives. I then make the substitution $(x,y)=(x_1y_1,y_1)$. This implies that $x_1=\frac{x}{y}$ and $y_1=y$. The $t$-derivatives are $$x_{1}'=\left(\frac{x}{y}\right)'=\frac{yx'-xy'}{y^2}=1-x_{1}y_{1}^{-1}(6x_{1}^2y_{1}^2-a/2)$$ and $$y_{1}'=6x_{1}^2y_{1}^2-a/2.$$ I need to continue in this fashion, that is, in the next step, for example, we let $(x_{1},y_{1})=(x_{2}y_{2},y_{2})$ and then find $x_{2}'$, $y_{2}'$, etc. Is there a way I can compute the derivatives in Mathematica? For instance, how would I find $x_{1}'$ in Mathematica. Thanks, Radz.


title: Improving the source-code indentation in Wolfram Workbench

text: One thing that I like about the more recent versions of the Mathematica front- end is that I think it does a good job indenting code. The language's functional nature, in my experience, leads to a lot of nesting, and the small indentation works well for this pupose. However, for some reason, the rules used for Wolfram Workbench (at least as of version 2.0) are evidently completely different, and the results look much worse. This can be helped somewhat by adjusting editor settings for Eclipse, but it still needs a lot of work. For example, here's a really silly approach for determining whether an integer is even or not, which I picked because it has a lot of indentation, as it's formatted in a Mathematica notebook:               Module[{even, odd, withoutLimit},       even[0] = True;       odd[0] = False;            even[n_Integer] := odd[n - 1];       odd[n_Integer] := even[n - 1];            Attributes[withoutLimit] = {HoldFirst};       withoutLimit[expr_] :=        Block[{$IterationLimit = Infinity},         expr];            With[{test =          Function[n,           n >= 0]},        Pillsy`EvenQ[n_Integer] := withoutLimit@even[n] /; test[n];        Pillsy`EvenQ[n_Integer] := even[-n];             Pillsy`OddQ[n_Integer] := withoutLimit@odd[n] /; test[n];        Pillsy`OddQ[n_Integer] := odd[-n]]];      I find this quite readable. Here's the same code, copied into Workbench and formatted using its automatic source formatting (I added some whitespace between logically related definitions, which I'm used to doing manually):               Module[ {even, odd, withoutLimit},       even[0] = True;       odd[0] = False;            even[n_Integer] :=         odd[n - 1];       odd[n_Integer] :=         even[n - 1];            Attributes[withoutLimit] = {HoldFirst};       withoutLimit[expr_] :=         Block[ {$IterationLimit = Infinity},           expr         ];            With[ {test =          Function[n,           n >= 0]},              Pillsy`EvenQ[n_Integer] :=           withoutLimit@even[n] /; test[n];         Pillsy`EvenQ[n_Integer] :=           even[-n];              Pillsy`OddQ[n_Integer] :=           withoutLimit@odd[n] /; test[n];         Pillsy`OddQ[n_Integer] :=           odd[-n]       ]     ];      I'd like to make the second example look a lot more like the first example. In particular, the insistance that trailing square brackets from `With`, `Module` and `Block` should get lines all to themselves, like they're curly braces from C, makes me crazy.


title: Synchronizing manual rotations for multiple Graphics3D outputs?

text: Say I make a set of three Graphics3D images, here of three different cones, by evaluating:               {Graphics3D[{Cone[{{0, 0, 0}, {2, 3, 4}}, 3]}],       Graphics3D[{Cone[{{1, 0, 1}, {1, 1, 1}}, 4]}],       Graphics3D[{Cone[{{1, 1, 1}, {9, 9, 9}}, 4]}]}      I would like to manually rotate one of the images showing a single cone, and have the other objects follow that rotation, or at least rotate to the final state once I let go of my mouse. Is this possible?


title: NDSolve Plotting issue

text: I am trying to solve a system of ODEs with one extra boundary condition.               eq1 = f'''[y] + f[y] f''[y] - m f'[y] - f'[y]^2 - s (f'[y] + y/2 f''[y]) == 0;     eq2 = g''[y] - (s/2(3 g[y] + y g'[y]) + 2 g[y] f'[y] - g'[y] f[y]) + f''[y]^2 == 0;      With boundary conditions               bc = {f[0] == 0, f'[0] == 1, g[0] == 1, f''[b] == 0, g'[b] == 0};      With the arbitrary trial values, the integrated solutions will generally not satisfy the outer boundary conditions.               f''[b] == 0 and f[b] == s b/2      I need to find a way to adjust the two trial values such that the numerical solution eventually matches the required boundary conditions and satisfy the relation `f[b] = s b/2`. Here are my questions   * If I fix `m` (say = 1), then how I can plot `b` vs `s`?   * If I fix `s` (say = 1.2 and 0.8), then how I can plot `f'[b]` vs `m`?   * If I fix `s` (say = 1.2 and 0.8), then how I can plot `f''[0]` vs `m`?  What value `b` will take? Here is my try, but it's not working               g[b_?NumericQ, m_?NumericQ, s_?NumericQ] :=        f[b] /.          NDSolve[{eq1, eq2, f[0] == 0, f'[0] == 1, g[0] == 1, f''[b] == 0, g'[b] == 0},            {f, g}, {y, 0, b}]          s2[b_, s_] := FindRoot[g[b, s, m], {b, 0}]      **Paper and Pen implementation of Shooting method** As it is mentioned by @Peltio, here is the possible Shooting method. **Note** $theta$ is `g` and $\eta$ is `y`. ![enter image description here](http://i.stack.imgur.com/mRqJg.png) **The output should look like this**   1. `b` vs `s` ![enter image description here](http://i.stack.imgur.com/c5iYm.png)   1. `f'[b]` vs `m` ![enter image description here](http://i.stack.imgur.com/tv43X.png)   1. `f''[0]` vs `m` ![enter image description here](http://i.stack.imgur.com/k0ikg.png)


title: The proper way to write the input for a certain series

text: Mathematica tells the series below doesn't converge. I think it converges. What would the proper way to write things be as an input?               Sum[((-1)^(n) Log[1 + 2 n])/(1 + 2 n), {n, 0, Infinity}]


title: import a list of replacement rules

text: I have a text file with a set of replacement rules, of the form > >     x^3y^2 -> 4, >     xy^2 -> 2, >     ... >   for example. I'm having some issues trying to figure out how to tell _Mathematica_ to read those rules and apply them. So far I've tried               F[x,y] /. "!cat rules.txt"       but that gave an invalid syntax error. Any suggestions? **EDIT** After some initial suggestions, here is some extra information: After using the Import command as suggested by rm -rf, and removing the last comma from the text file, mathematica does not interpret the result as a list of replacement rules. If I now do               replaceList = {Import["rules.txt"]};     F[x3,x4,x5] /. replaceList      Mathematica now says:               ReplaceAll::reps: {x5^3->5,     x4*x5^2->5,     x3*x5^2->5,     x2*x5^2->5} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>      **EDIT2** Ok all, here is a very concrete example of what I'm facing. Thank you for helping me thus far, I'm sorry to be vague. In a text file called rules.txt I have the following content:               $ cat rules.text      x1*x2^2->1,     x1^2*x3->3,     x1^3->4       In mathematica I have the following code followed with an error:               F[x1_, x2_, x3_] := x1 *x2^2 + x1^2*x3 + x1^3     rules = Import["rules.text"]     {{"x1*x2^2->1,"}, {"x1^2*x3->3,"}, {"x1^3->4"}}      Obviously the formatting of the rules are incorrect, but if we try to brute force it, we get the error:               F[x1, x2, x3] /. rules     ReplaceAll::reps: {x1*x2^2->1,} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>     ...     (*followed by similar errors for the other replacement rules read in*)      One quick attempt at fixing is to flatten the import table, or do what Michael E2 suggested:               rules = Flatten[Import["rules.text"]]     out = {"x1*x2^2->1,", "x1^2*x3,", "x1^3->4"}          F[x1, x2, x3] /. rules     ReplaceAll::reps:      "\!\({\"x1*x2^2->1,\", \"x1^2*x3->3,\", \"x1^3->4\"}\) is neither a list \     of replacement rules nor a valid dispatch.."      Or,               rules = ToExpression@Import["rules.text"]     ToExpression::sntx: Invalid syntax in or before "x1*x2^2->1, ".     ToExpression::sntx: Invalid syntax in or before "x1^2*x3->3, ".      Which fails also. Please let me know if I can add any more information to make the issue clearer, and thanks again. **EDIT3** I found a workaround solution. If one removes the comma from the text file, so that it reads:               $ cat rules.dat      x1*x2^2->1     x1^2*x3->3     x1^3->4      the following commands resolve the issue:               F[x1_, x2_, x3_] := x1 *x2^2 + x1^2*x3 + x1^3     F[x1, x2, x3] /. ToExpression@Flatten[Import["rules.dat"]]     out = 8      _note_ the importance of the .dat extension. .txt does not work.


title: How do I save my animation/manipulation in pdf?

text: Is it possible to presserve my animation and manipulation plots in the pdf?


title: Select elements of list within a date range

text: I have a list which consists of elements each of which has a date in `DateList` format, a number and a flag (Y/N). e.g.               {{{2010, 11, 29, 16, 6,  0.}, 17.7, "N"},       {{2010, 12, 2,  14, 38, 0.}, 11.9, "N"},       {{2010, 12, 2,  20, 1,  0.},  8.2, "N"}}      I want to extract those elements which are dated within the last 90 days and also the same date range but one year previous (into two separate lists). I presume the way to do this would be to define an `Interval` between the `AbsoluteTimes` of the ends of the ranges. But how do I filter the list on this basis: i.e. apply a filter (`IntervalMemberQ`) on the basis of the `AbsoluteTime` of the first element in each element in the list? I presume that it's something to do with pure functions but I can't get the syntax right.


title: Issue with DateListPlot and Dynamic List

text: Imagine that we are getting readings from an external device (ie Arduino) at a given interval of time. We'll simulate the reading as follows.               getDataPoint[] := {DateList[], First@RandomVariate[NormalDistribution[0, 1], 1]}     dataList[myList_List, maxPoints_Integer] :=               Module[{x}, x = Append[myList, getDataPoint[]];               If[Length@x > maxPoints, Take[x, -maxPoints], x]]     data = {}     DateListPlot[ Dynamic[Refresh[data = dataList[data, 15], UpdateInterval -> 1,     TrackedSymbols -> {}]]]      Gives me the following error message _DateListPlot::ntdt: The first argument to DateListPlot should be a list of pairs of dates and real values, a list of real values, or a list of several such lists_ If I add the command separately, it does render the chart. Of course, I don't want to display the list data being updated in the screen, just the chart.               Dynamic@DateListPlot[data, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/H5oYW.gif)


title: systemmodeler does not work with OSX 10.9

text: Systemmodeler v. 3.0.2. does not work anymore with Mac OX 10.9. Model centre works fine but simulation centre produce an error message. "error: No executable generated./var/folders/2g/dfgpd6_n45x3bfg12phwn7v00000gn/T/sme_1388340148_1316277068.exe" Also, in preferences: system modeller cannot find the compiler G++ in use/bin although it is there. Same problem if I try to run the model in mathematica. Everything was working fine with the previous version of Mac OSX Seems there is a compatibility issue between systemmodeler and OSX 10.9? Any fix coming?


title: Plotting a vector field

text: Can I somehow plot a vector field and the scattered data point associated with each and every vector? Also, is there any way to prevent _Mathematica_ from interpolting the vector field? I am trying to plot this data as a vector field. The data is from a .dat file that includes the following four columns: x-coord, y-coord, vecx, vecy. http://wikisend.com/download/386548/testBC.dat I managed to plot the following with Tecplot ![enter image description here](http://i.stack.imgur.com/87dev.png) I am trying to remake this plot in Mathematica               testBC = Import["C:\\...testBC.dat", "Table", "IgnoreEmptyLines" -> True];     testBCx = testBC[[All, 1]];     testBCy = testBC[[All, 2]];     ux = testBC[[All, 3]];     uy = testBC[[All, 4]];     u = Transpose[{ux, uy}];     testbdry = Transpose[{testBCx, testBCy}];     ListVectorPlot[Transpose[{testbdry, u}], PlotRange -> Full,      VectorPoints -> 10, VectorScale -> {0.1, 0.2}]      Results in the following ![enter image description here](http://i.stack.imgur.com/n9b0f.png) _Mathematica_ interpolates the inside of the airfoil. How can I remake the plot from Tecplot, i.e., how can I show the scatter plot of x, y, and the vectors pointing away from every point. Also, I want _Mathematica_ to plot all the vectors as in Tecplot, not to only sample and interpolate.


title: How to change the Integer to a special form in an expression?

text: * * * I have an expression. I want to change all the Integers to a new form. The rule is, x_Integer->x._f. But we should consider some special cases. For example,                 input = 22 +  4/5 x1 x1 x1 + (2 x2^4 + 343 Pi^4)/       Sqrt[67 - x1 x1 x3 x3 + x2^(5/4)] + (4 x1 - x2)^(-3/2 q) +         Exp[-x1 x1 + 4 x2 x2 - 3 x1];      The output expression should be,                output = 22. _f + E^(-3. _f x1 - x1^(2. _f) + 4. _f x2^(2. _f)) + (          4. _f x1^(3. _f))/(5. _f) + (4. _f x1 - x2)^(-3. _f x3/2. _f) + (       343. _f \[Pi]^(4. _f) + 2. _f x2^(4. _f))/Sqrt[         67. _f + x2^(5. _f/4. _f) - x1^(2. _f) x3^(2. _f)];      So, how to construct the rule function? Thanks!


title: Help to plot Poincare section for a system of delay differential equations

text: I'am trying to plot Poincare section for a 4-dimentional system of Delay differential equations. I don't know how to specify initial conditions. Can I use each of the code in the following ? Also how can I plot map in 3D? First code:                   system={v'[t]== -v[t]^3+0.55* v[t]- w[t]+ 1.3* Tanh[y[t-4]],v[t /; t <= 0]==0.3,w'[t] == v[t] - 1.128*w[t],w[t /; t <= 0]==0.6,     y' [t]== -y[t]^3+0.55* y[t]- z[t]+ 1.3 *Tanh[v[t-4]],y[t /; t <= 0]==0.5,z'[t] == y[t] - 0.58* z[t],z[t /; t <= 0]==0.7};vars={v[t],w[t],y[t],z[t]};     data =      Reap[     sol = First[NDSolve[system,vars,{t,0,400},     Method->{"EventLocator",     "Event":> v[t],     "EventAction":>Sow[{y[t],z[t]}]},  MaxSteps -> \[Infinity]]][[-1, 1]]]          systemdata = Map[psect, {{0.3, 0.6, 0.5, 0.1},{0,0.1,0.2,0.3}                           }];          ListPlot[abcdata, ImageSize -> Medium]      The second code:               abc = {v'[t]== -v[t]^3+0.55* v[t]- w[t]+ 1.3* Tanh[y[t-4]],w'[t] == v[t] - 1.128*w[t],y' [t]== -y[t]^3+0.55* y[t]- z[t]+ 1.3 *Tanh[v[t-4]],z'[t] == y[t] - 0.58* z[t]};     psect[{v0_, w0_, y0_,z0_}] :=       Reap[NDSolve[{abc, v[t /; t <= 0]==0,w[t /; t <= 0]==0.6, y[t /; t <= 0]==0.5,z[t /; t <= 0]==0.7,           WhenEvent[v[t] == 0, Sow[{ y[t],z[t]}]]}, {}, {t, 0, 500},          MaxSteps -> \[Infinity]]][[-1, 1]]     abcdata = Map[psect, {{0.3, 0.6, 0.5, 0.1},{0,0.1,0.2,0.3}                           }];          ListPlot[abcdata, ImageSize -> Medium]


title: Efficient ways to rotate a ListPlot?

text: I have a numerical solution from a differential equation that is in the form of a list, in $(x,z)$-plane. I would like to rotate the 2D `ListPlot` around the $z$-axis to generate a 3D plot. The length of the list is $25\,000$; the step size between each point is $0.0003$. I have tried rotate each point $36$ degrees for $9$ times to obtain a list of triples and then use `ListPlot3D`. This method, however, takes about $5$ minutes to generate a plot. Is there a more efficient way of rotating a 2D `ListPlot`? I was thinking about cutting off the number of points being rotated. How many points can I omit to retain most of the features of the original plot?


title: p-iteration algorithm to solve Lambert's problem for interplanetary trajectories

text: I've been reading up on using the `p`-iteration method to solve Lambert's problem for choosing the correct interplanetary trajectory between two planets given the initial position of the source planet, final position of the target planet as well as a time of flight of the spacecraft. I can solve the equations manually, but what I wanted was to make a while loop in _Mathematica_ that would automatically find the required time of flight. As an example, here is what I have so far (which I got from http://www.braeunig.us/space/interpl.htm):               G = 6.672*10^-11;     M = AstronomicalData["Sun", "Mass"];     m = AstronomicalData["Earth", "Mass"];     deltat = 207*86400; (*seconds*)     r[1] = {0.473265, -0.899215, 0};     r[2] = {0.066842, 1.561256, 0.030948 };          Subscript[μ, s] = G M/(149.597870*10^9)^3 (*In AU^3/s^2*)          (*p-iteration constants*)     r1 = Sqrt[r[1].r[1]]     r2 = Sqrt[r[2].r[2]]     deltaA = ArcCos[r[1].r[2]/(r1 r2)]/Degree     k = r1 r2 (1 - Cos[deltaA Degree])     l = r1 + r2     m = r1 r2 (1 + Cos[deltaA Degree])          (*p-iteration calculations*)     a = (m k p)/((2 m - l^2) p^2 + 2 k l p - k^2)     f = 1 - r2/p (1 - Cos[deltaA Degree])     g = (r1 r2 Sin[deltaA Degree])/Sqrt[Subscript[μ, s] p]     fdot = Sqrt[Subscript[μ, s]/p]     Tan[(deltaA Degree)/2] ((1 - Cos[deltaA Degree])/p - 1/r1 - 1/r2)     gdot = 1 - r1/p (1 - Cos[deltaA Degree])     deltaE = ArcCos[1 - r1/a(1 - f)] (*In radians*) (*used if a is positive*)     deltaF = ArcCosh[1 - r1/a(1 - f)] (*In radians*) (*used if a is negative*)     t = g + Sqrt[a^3/Subscript[μ, s]] (deltaE - Sin[deltaE ]) (*used if a is positive*)     t = g + Sqrt[(−a)3/Subscript[μ,s]](Sinh[deltaF]−deltaF) (*used if a is negative*)      I've been trying to make a while loop to perform iterations on the above calculations that will choose a value for `p` in order to match t as close as possible to `deltat` but have so far been unable to get a working solution. The way to choose a new value for p for each new iteration is done using the following equation:               p[n+1]=p[n]+(deltat-t[n])(p[n]-p[n-1])/(t[n]-t[n-1])      where `t[n-1]` and `t[n]` are the first and second iterations of the above algorithm respectively. Does anyone know how I could do something like this in a while loop? Any help would be great appreciated. EDIT: With regards to using the FindRoot function, this is what I tried (I essentially replaced g, a and deltaE in                t = g + Sqrt[a^3/Subscript[μ, s]] (deltaE - Sin[deltaE ])       with the basic equations I started with) which unfortunately brought up a few errors: ![enter image description here](http://i.stack.imgur.com/P3JmX.png)


title: Quickly pruning elements in one structured array that exist in a separate unordered array

text: I have two lists, which we'll call `testList` and `modifiedTestList`. The first list looks something like this:               testList = Table[RandomReal[{0, 1000}, {RandomInteger[{0, 32}], 2}], {i, 1, 10}];      To generate `modifiedTestList`, I can flatten `testList` by strictly one level (never breaking up the pairs of real numbers specifying 2D coordinates), scramble the elements, and select and prune elements. For example:               modifiedTestList = Flatten[testList, 1];     modifiedTestList = RandomSample[modifiedTestList, Length[modifiedTestList]];     modifiedTestList = Select[modifiedTestList, #[[1]] > 700 &];      Once I've had my fun, I'd like to take `testList` and prune away all of the 2D coordinates that no longer exist in `modifiedTestList` while respecting the original array structure of `testList` (i.e. `testList` should not be flattened and elements should not be moved between subarrays). Let's say `testList` and `modifiedTestList` are both quite large ($>10^6$ elements each). Is there a fast way to do the above pruning provided these large data structures?


title: Small problem at equation solving

text: I have $2$ equations in $2$ parameters which involve integrations. The limits of the integrals can not be defined analytically. They also require equation solving and eventually I couldnt incorporate everything in a nice way to solve. Here is my code **density functions**               f0[y_] :=1/(E^((1 + y)^2/2)*Sqrt[2*Pi])     f1[y_] :=1/(E^((-1 + y)^2/2)*Sqrt[2*Pi])        **likelihood function**               l[y]=E^(-(-1 + y)^2/2 + (1 + y)^2/2)      **inverse of the likelihood function**               ll[y_] :=Log[y]/2      The integral limits $yu$ and $yl$ which I have problems with, where $λ0$ and $μ0$ are some parameters.               FindRoot[l[yu] == Sqrt[(λ0*(λ0 + μ0*f1[yu]))/(λ0*(λ0 + (μ0 - 1)*f0[yu]))], {yu, 3}]     FindRoot[l[yl] == Sqrt[(λ0*(λ0 + (μ0 - 1)*f1[yl]))/(λ0*(λ0 + μ0*f0[yl]))], {yl, 3}]      Whenever $λ0$ and $μ0$ are known it is easy to find a solution for $yu$ and $yl$ %% my $2$ equations are as follows               h1[y_] :=Integrate[-2 + Sqrt[λ0/(λ0 + (-1 + μ0)*f0[y])] + Sqrt[(λ0 +(-1 + μ0)*f0[y])/λ0], {y, yu, Infinity}] +Integrate[-2 + Sqrt[λ0/(λ0 + μ0*f0[y])] + Sqrt[(λ0 + μ0*f0[y])/λ0], {y, -Infinity, yl}] + Integrate[-2 + Sqrt[(f1[y]*(λ0*f0[y] + λ0*f1[y]))/(f0[y]*(λ0*f1[y] + f0[y]*(λ0 + (-1 + μ0 + μ0)*f1[y])))] + Sqrt[(f0[y]*(λ0*f1[y] + f0[y]*(λ0 + (-1 + μ0 + μ0)*f1[y])))/(f1[y]*(λ0*f0[y] + λ0*f1[y]))], {y, yl, yu}]          h3[y_]:=Integrate[Sqrt[(λ0*f0[y]^2)/(λ0 + (-1 + μ0)*f0[y])], {y, yu, Infinity}] + Integrate[Sqrt[(λ0*f0[y]^2)/(λ0 + μ0*f0[y])], {y, -Infinity, yl}] + Integrate[Sqrt[(f0[y]*f1[y]*(λ0*f0[y] + λ0*f1[y]))/(λ0*f1[y] + f0[y]*(λ0 + (-1 + μ0 + μ0)*f1[y]))], {y, yl, yu}]      I am using `Findroot` to solve them as follows:               FindRoot[{h1[y] == 0.08, h3[y] == 1}, {{μ0, 0.4}, {λ0, 0.8}},               StepMonitor :> Print["Step to μ0 = ", μ0]]      as one can see $h1$ and $h3$ involve $yl$ and $yu$ which are the solution of another equations. These equations can only be numerically evaluated. At this point my eventual aim is to solve the last `FindRoot` of my code. In simple words if I would be _Mathematica_ I would guess some $λ0$ and $μ0$ then I would go to the first $2$ `FindRoots` of my code solve them and get $yl$ and $yu$ numerically. Then using these values I would obtain $h1$ and $h3$ and eventually I would go to last `FindRoot` of my code to see if $h1=0.08$ and $h3=1$ are satisfied or not. If not I would change $λ0$ and $μ0$ until the equations are satisfied. This is of course the worst way of solving the equations but _Mathematica_ would have a better way I suppose. How should I modify my code such that _Mathematica_ could start solving them? The equations are horrible and will take at any case alot of time. Thanks for reading my problems and for any help.


title: Simplify ignores DiracDelta contribution from Coulomb sources

text: Executing the following line,               Simplify[Div[Grad[-1/Sqrt[{x, y, z}.{x, y, z}], {x, y, z}], {x, y, z}]]      yields 0. However, this is incorrect, since $\nabla\cdot\nabla\left(|\mathbf{r}|^{-1}\right)=-4\pi\delta(\mathbf{r})$ in 3-space. I understand that this problem is coming from the fact that `Simplify` assumes $\mathbf{r}\neq\mathbf{0}$. However, I don't know how to coax Mathematica into giving the correct result without essentially having to resort to doing mathematics by hand, which kind of defeats the purpose of using a computer algebra system. In this case the result is obviously wrong so no harm is done, but for more complicated vector expressions I have no idea whether `Simplify` is going to give wrong answers without warning when applied to functions with spatial singularities. Is there any automated way to handle such singularities to give correct answers in Mathematica?


title: Different ordering for KroneckerDelta?

text: I have an expression like this: ![enter image description here](http://i.stack.imgur.com/eFiad.jpg)               Assuming[m [\Element] Integers && n [\Element] Integers, 1/2 I J n (4-m n+n^2) KroneckerDelta[m,-n]]//FullSimplify      Now, since `KroneckerDelta` has attribute `Orderless`, that means it will sort things into canonical order, and since my expression has $n^2$ in it, I assume that's why it's evaluating the Kronecker for m->-n (I tried putting KroneckerDelta[n,-m] but got the same result). Now, technically this is correct. But I'd like that my expression was given in terms of `m`, not `n`. If I manually replace `n` by `-m` I get the desired output $$-iJm(2+m^2)$$ but I'd like to get that automatically within Mathematica. Is that possible without explicitly doing the replacement `/.n->-m`?


title: Shorter syntax for Fold and FoldList?

text: I find it tedious to write out the following:               a = {1, 2, 3, 4};          Fold[f, First @ a, Rest @ a]      > >     f[f[f[1, 2], 3], 4] >   It becomes additionally cumbersome when working with held expressions, e.g.:               b = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4];          SetAttributes[g, HoldAll];          b /. _[x_, __] :> Fold[g, Unevaluated[x], Rest@b]      > >     g[g[g[1 + 1, 2 + 2], 3 + 3], 4 + 4] >   Likewise for `FoldList`. Is there a shorter syntax to achieve this?


title: Accessing temporary value of a Nest evaluation

text: The function `Nest[]` must store the temporary values in the memory somewhere (those values that would form the entries of the list which is returned by the equivalent `NestList` function). Does anyone know if there is a way to access said values in an interrupted evaluation (using a kernel subsession)? Alternatively, is there a way to know all temporary variables currently in use and to print out their values?


title: Eliminating functions from system of PDE in Mathematica

text: _Mathematica_ users, Let's see an example of three PDEs: How can I eliminate variables `q1[x,y,z]` and `q2[x,y,z]` from a system of three PDEs in _Mathematica_. In final form, I need just one equation in function of `p1[x,y,z]`. Why this code is working well when I want to eliminate `q1` and `q2` from `a1`, `a2` and `a3`, but doesn't work when I want to eliminate `q1` and `q2` from `a1`, `a2`, `a3` and `a4`?                a1=A1*D[p1[x,y,z],{z,2}]-A2*(D[p1[x,y,z],{x,2}]+         D[p1[x,y,z],{y,2}]+D[q1[x,y,z], {x,1}]+D[q2[x,y,z],{y,1}])==0;                a2=A9*(A2*D[(D[q1[x,y,z],{x,1}]+D[q2[x,y,z],{y,1}]),{x,1}]+A2*(D[q1[x,y,z],{x,2}]+         D[q1[x,y,z],{y,2}]))-A4*(D[p1[x,y,z],{x,1}]+q1[x,y,z])-A8*D[q1[x,y,z],{z,2}]==0;                a3=A9*(A6*D[(D[q1[x,y,z],{x,1}]+D[q1[x,y,z],{y,1}]),{y,1}]+A7*(D[q2[x,y,z],{x,2}]+         D[q1[x,y,z],{y,2}]))-A1*(D[p1[x,y,z],{y,1}]+q2[x,y,z])-A4*D[q2[x,y,z],{z,2}]==0;           a4=A09*A006*D[(D[q2[x,y,z],{x,1}]+D[q2[x,y,z],{y,1}]),{y,1}]+A004*D[q1[x,y,z],{z,2}]==0;           rule=Flatten[{#[x,y,z]->#,Derivative[n_,m_,o_][#][x_,y_,z_]-># x^n y^m z^o}&/@{p1,q1,q2}];           invRule=(x_->z_):>z Derivative[Sequence@@x][p1];           ww1=Eliminate[{a1,a2,a4}/.rule,{q1,q2}]/.(x_==y_)->(x-y);           ww2=CoefficientRules[ww1,{x,y,z}];           t=Total[ww2/.p1->1/.invRule]==0;           t


title: How can I manipulate TemporalData?

text: Version 9 introduced `TemporalData` but, truth be told, the documentation doesn't suggest that one can do much with it. Many of us have probably assumed we'd be better off sticking with the date-value pairs familiar from use in `DateListPlot` and elsewhere. Are there some (perhaps undocumented) functions I can use to manipulate temporal data after putting it in `TemporalData` form?


title: Mark an 2d-area on a 3dPlot (ListPlot3d)

text: I have a list `{(IC,s,FK)}`, which I use to generate a 3d-plot with the help of the command `ListPlot3D`. `IC` and `s` go from `0` to `1`. ![enter image description here](http://i.stack.imgur.com/jorUf.jpg) There is an area (lets say `0.11 < IC < 0.3, 0.1 < s < 0.4`) which is specially important, because this is the physical range. For some reason I want to plot the whole parameter space, but highlight (for example with a red rectangle) this physical range. It would be great to frame the physical range with a red rectangle on the surface of the 3d-Plot. (In the end, this 2d-rectangle should look similar to these mesh lines, but it should frame the range, defined above). Do you have any idea?


title: Solving Within InverseCDF

text: I have the following input data:               Remove["Global`*"]     x = 5/30 // N;      y = 0.8;     μ = 0.2;     T = 5;     ρ = 0.8;      σ (*to be determined*)      And this is the given equation:               Solve[CDF[        NormalDistribution[], ((1/            Sqrt[ρ])*(((Sqrt[1 - ρ])*(InverseCDF[                NormalDistribution[], (x)]) + (InverseCDF[               NormalDistribution[], (CDF[                 NormalDistribution[], -(Log[y] + (μ - 0.5*σ^2)*                      T)/(σ*Sqrt[T])])]))))] == 0.0158854, σ,       InverseFunctions -> True]      If I want to Solve for "ρ" it works, but whenever I try to Solve for σ i get the following error message: > "Solve was unable to solve the system with inexact coefficients or the > system obtained by direct rationalization of inexact numbers present in the > system. Since many of the methods used by Solve require exact input, > providing Solve with an exact version of the system may help. >>" Is here the problem that sigma is simultanously in both an inverseCDF and a CDF? is there a formula which can be applied in order to get rid of the CDF and inverseCDF? Or should it be done by splitting up the given equation? Can anybody help me? thanks in advance


title: Is it possible to get a VertexColors effect in cylinder?

text: I'm trying to create a figure illustrating a cylinder filled with gas. And I saw a very good looking similar one at here. The shape is polygon and by using the VertexColors option, it creates a impression of gas inside the building, with high density near the floor and low density near the roof. However, I would like to plot a cylinder, and for a cylinder, there seems no option of VertexColors. So how can I create the same shading effect for a cylinder? Code copied from here               w = 100;     l = 200;     h = 30;     m = 70;     backwall = {{0, l, 0}, {w, l, 0}, {w, l, h}, {0, l, h}};     side1 = {{0, 0, 0}, {0, 0, h}, {0, l, h}, {0, l, 0}};     side2 = {{w, 0, 0}, {w, 0, h}, {w, l, h}, {w, l, 0}};     floor = {{0, 0, 0}, {w, 0, 0}, {w, l, 0}, {0, l, 0}};     top = {{0, 0, h}, {w, 0, h}, {w, l, h}, {0, l, h}};     front = {{0, 0, 0}, {w, 0, 0}, {w, 0, h}, {0, 0, h}};     leftRoof = {{0, 0, h}, {w/2, 0, m}, {w/2, l, m}, {0, l, h}};     rightRoof = {{w, 0, h}, {w/2, 0, m}, {w/2, l, m}, {w, l, h}};     roofBack = {{w, l, h}, {w/2, l, m}, {0, l, h}};     roofFront = {{w, 0, h}, {w/2, 0, m}, {0, 0, h}};     building = {backwall, side1, side2, floor, front, leftRoof, rightRoof,         roofBack, roofFront};     figure = Graphics3D[{Opacity[0.5],         Style[Polygon[building,           VertexColors -> Map[0.5 + #[[3]]/80 &, building, {2}]],          Lighting -> {{"Ambient", White}}]}, Boxed -> False,        RotationAction -> "Clip"]      ![enter image description here](http://i.stack.imgur.com/9zsS6.png)


title: Creating overlapped block matrices

text: I'm doing an FEM assignment using _Mathematica_.               (EK1 = {{a11, a12}, {a21, a22}}) // MatrixForm     (EK2 = {{b22, b23}, {b32, b33}}) // MatrixForm      I don't know how the best way to create new matrix like this:               (K = {{a11, a12, 0}, {a21, a22 + b22, b23}, {0, b32, b33}}) // MatrixForm      MATLAB does it quite easily but how about _Mathematica_?


title: Can I select or implement a Manipulate bookmark from an arbitrary control?

text: I understand how I can select a bookmark from the "+" menu of a `Manipulate`. Is there a way to select a bookmark from an arbitrary control, or define a control that implements bookmark functionality? For example, if I have something like               Manipulate[{x, y, z},      {x, 0, 10}, {y, 0, 10}, {z, 0, 10},      Bookmarks -> {"Center" :> {x = 5, y = 5, z = 5},"Zero" :> {x = 0, y = 0, z = 0}}]      Can I add a control that does the same thing as selecting the bookmark from the menu? For example, can I add something similar to `{preset, {"Center", "Zero"}}`, to create something that looks like ![enter image description here](http://i.stack.imgur.com/ApAvc.png) where choosing one of the setters performs assignments to collections of `Manipulate` variables? Specifically: is there   1. a way to implement bookmark-like functionality by specifying a control that sets several `Manipulate` variables at once; is there    2. a way to explicitly select a bookmark from an arbitrary control (e.g. is there something like an"SelectBookmark[ _bookmark_ ]")? I'd have thought that               Manipulate[{x, y, z}, {x, 0, 10}, {y, 0, 10}, {z, 0, 10},      {{preset,         Which[# === "Center", (x = 5; y = 5; z = 5),              # === "Zero",   (x = 0; y = 0; z = 0)] &}, {"Center", "Zero"}}]      would at least achieve (1), but it has no apparent effect; I see no way to do (2).


title: Function that assigns properties

text: I want to create a function that creates and assigns properties to a symbol. In theory this would behave similarly to the `NonzeroValues` property of `SparseArray`s. Here's what I currently have, and where I'd like to go.               func[x_] := Module[{data},       (*data=Import data from source based on x*)       HoldPattern[func[x, "Length"]] = Length@data;       HoldPattern[func[x, "Dimensions"]] = Dimensions@data;      ]               func[15,"Length"]      > `225` However, I'd like this to work more like this:               var=func[15];          var["Length"]      > `225` It would be ideal not to have to calculate this every time a property is retrieved. For efficiency sake, importing the data every time a property is retrieved isn't feasible. How so I define these subvalues at the first function call and store them for fast retrieval later?


title: Mathematica Sec and Csc

text: How can I prevent Mathematica from using the "old fashioned" functions "Sec" and "Csc"? In Germany these functions are "old fashioned" as they are not taught anymore at school.


title: Plot integration curve of a system of ODEs

text: I'm really n00b in _Mathematica_ , so please bear with me, as this seems to be my only option to learn how to do what I wany to do. I have a system of two differential equations:               y' = v[t]     v'[t] = -a^2y      Now, assuming I know the solution of this system is: $y = cos(a\,t),\ v = -a\,sin(a\,t)$, I want to plot the integral curve of the two, on the v-y surface, with `a t` getting values from 0 to `2 π`. I've tried various combinations of `StreamPlot`, `VectorPlot` and many other functions, without any success, although I think it's suppose to be really simple. I've tried also to make a plot in 3D with `VectorPlot3D`, but to no avail. I'll appreciate any help.


title: Creating a function that can be called like the definite integral template (dintt)

text: The definite integral template takes 4 arguments as can be seen here: ![enter image description here](http://i.stack.imgur.com/pKK5Z.png) Is it possible to make a function that can be called in the same kind of way? For example is it possible to make this call a function foo, like so: ![enter image description here](http://i.stack.imgur.com/Bifxi.png)


title: Filling using colors rendered corresponding to the difference between two curves

text: Suppose there are two curves f1[x] and f2[x], and we want to fill the area between them using colors corresponding to the vaule of f2[x]-f1[x], so that any filling line segemts with the same length will be rendered with same color. My question is, how can we do this using built-in commands like `Filling`, `FillingStyle` and `ColorFunction`, etc? A direct call of `ColorFunction` will not help because in specification               ColorFunction -> Function[{x, y}, g[x,y]]      the x and y are refered always as the absoulate coordinates, however we need to refer to y2-y1 in our case. I have not figured out how to get this done using pure function. I can write a code doing this from sketch similiar to the idea suggested in this question, but such treatment is not universal... Besides, there is already such an example documented in Mathematica,               ListLinePlot[Accumulate[RandomReal[{-1, 1}, 250]], ColorFunction -> "Rainbow", Filling -> Axis]      which is actually a similar case to my question but with f1[x] always equal to zero. So I think there should be a solution using only built-in commands... Furthermore, if there is indeed such a solution, then we can simply generalize the relation from merely f2[x]-f1[x] to more interesting forms.


title: Wikipedia People only search

text: I am trying to search people from Wikipedia(For example `.*John.*` in REGEX). The following query is close, but it isn't generalized like `.*John.*` ~~and only gives back historic figures that have passed~~ (They only aren't Alphabetized).               Import["http://en.wikipedia.org/w/api.php?action=query&list=search&\srsearch=wikipedia&srprop=timestamp&eititle=Template:Persondata", "XML"]      link The following query works although I can't seem to limit the results to people only.               Import["http://en.wikipedia.org/w/api.php?action=query&list=embeddedin&eititle=Template:Persondata&eilimit=100&format=xml&redirects", "XML"]      link2 | API sandbox Although currently I'm running into Wikipedia API issues, I am looking for a way to get the results in Mathematica (and therefore I believe this question makes most sense on M.stackexchange).


title: How to change color dynamically?

text: I am new to `Mathematica` and want to change the `FillingStyle` Dynamically in this `Plot`. I want that when I pick a color from the "Color" then, it should dynamically change in the Sin plot.                a = RGBColor[1, 2, 0]      Row[{Button["<<Color>>", a = SystemDialogInput["Color"]],      Evaluate[Plot[Sin[m], {m, -Pi, Pi}, Filling -> Bottom,      FillingStyle -> Dynamic[a]]]}]      I am able to pick a color but the plot is not changing dynamically. But, it changes when I am executing it again.


title: How can I make sure that 3D plots have the exact same orientation and viewpoint?

text: First off, I apologize that I can't come up with a simpler working example, but I only seem to have this problem with the larger examples. I am trying to make animations, using functions like the ones listed here. In order to make an animation, I need for the resulting 3D image to have a stationary camera. Here are two examples that I can't get this to work on. My apologies on the filesize, both of the images are 14MB when put into a text file.               img1 = Import["https://dl.dropboxusercontent.com/s/8878c5m3cjv2zmv/img1.m"];     img2 = Import["https://dl.dropboxusercontent.com/s/qbyx4t7yexoerqc/img2.m"];         GraphicsRow[{img1, img2}]      ![enter image description here](http://i.stack.imgur.com/XtewQ.png) If it isn't obvious that the two images have a different orientation, then try this:                   Manipulate[Show[{img1, img2}[[n]], ImageSize -> 500], {n, {1, 2}}]      I have even tried to make sure that they have the same options for `ViewPoint`, `ViewVertical`, and `ViewCenter`. This can be verified by a function I made,               Quiet[viewpoint[graphics_] :=          Evaluate[          FilterRules[{AbsoluteOptions[graphics]}, {ViewPoint,             ViewVertical, ViewCenter}]];];     viewpoint /@ {img1, img2}      which returns               (*{{ViewCenter -> {0.5, 0.5, 0.5}, ViewPoint -> {0.141, 0.19199, -3.37},        ViewVertical -> {0.0417, 0.0978, -2.0278}}, {ViewCenter -> {0.5,          0.5, 0.5}, ViewPoint -> {0.141, 0.19199, -3.37},        ViewVertical -> {0.0417, 0.0978, -2.0278}}}*)      So what am I missing? How can I make sure that every single time I create a 3D image that the view is identical? Is there another important viewing option besides those 3? Thanks in advance.


title: How to put a dodecahedron inside another dodecahedron?

text: I know how to put a sphere inside a dodecahedron but instead of a sphere I would like it to be another dodecahedron. How can I do it?               Graphics3D[{{Opacity[.3], FaceForm[Yellow],         PolyhedronData["Dodecahedron", "Faces"]}, Brown, Sphere[{0, 0, 0}],        Boxed -> False}]      ![enter image description here](http://i.stack.imgur.com/i7LOt.png)


What is the command to find function invariant? http://demonstrations.wolfram.com/AFunctionInvariantUnderAGroupOfTransformations/ what is algorithm it use to calculate this? **Edit** there is a book do it in this way Hope this book give you an idea on how to do multivariate case


title: Accidentally corrupted graphics (?) data of notebook --- now it won't open

text: In the process of editing my scripts' variable names with a haphazard "replace in all open files" in my text editor, I accidentally replaced portions of graphics data in a notebook (and I believe this is the only issue with the notebook). Here's a sample of my notebook in my text editor:               Cell[BoxData[       Graphics3DBox[GraphicsComplex3DBox[$Failed, {{        {Opacity[0.4], EdgeForm[None],           GraphicsGroup3DBox[{Polygon3DBox[CompressedData["     1:eJxNnXeYFcXz9e/esIiiIFGUKNw7d0Ewo0y4CIKKAdDdvYqKAQOKOWfFnHPO     OWdRMSsgmHPOIKhgzgnR93z29Pf5vX/M0zU93T09Mz3d1VWnqvpP3m+rffO5     ...     SIz7Av/VL5TBhqJPyesWaxZ5/ULdD6rGk39asT0GPMtTShc12+f3763GSrJP     eEPn42ueVxM9322Z2wHfOz3zHo292vZgj0rBN2yz/cX+qXbWVt46Op7\[CapitalOmega]2S8X     PkPQO5K3ZsifUHP+JrF9m+Lj9FXWmcR2+a8n3i/jAwIM6OiS8aPgNuKQzz76     4cx7TXSVD2Teu+MDFhwgfljAOT2aud6Wsf2U0A54IVLaBUP0ZtX22vhBf67Z      The `\[CapitalOmega]` doesn't belong. Unfortunately, "undo" is no longer available, and there's no obvious way for me to sift through and re-replace some of the symbols that I changed (for instance, they aren't all obvious like `\[CapitalOmega]`). Mathematica can no longer open the notebook (I wait while it grinds and heats-up, then have to force-quit). Is there some way to delete the graphics (or even all output cells) from the text file? I was considering just trying this (deleting the cells that seem like graphics), but it seems like there might be a lot of ways this could go wrong. Help!


title: How can I get DSolve to solve my ODE?

text: I evaluated               DSolve[{x[t] x''[t] + x'[t]^2 - g x[t] == 0, x[0] == 0, x'[0] == 0}, x, t]      and the output was `{}`. But this ODE actually has solutions `x[t] = 0` or `x[t] = 1/6*g*t^2` I was able to solve this ODE with Maple 14 ![enter image description here](http://i.stack.imgur.com/kQR6A.png) How can I get the same solutions from _Mathematica_?


title: How can I solve this system of functional equations?

text: I would like to use _Mathematica_ to find maps `a, b, c, d, e, f` such that               eq1 = a[t] a[s] + b[t] d[s] == a[t + s]     eq2 = a[t] b[s] + b[t] e[s] == b[t + s]     eq3 = d[t] a[s] + e[t] d[s] == d[t + s]     eq6 = d[t] b[s] + e[t] e[s] == e[t + s]     eq4 = a[t] c[s] + b[t] f[s] + c[t] == c[t + s]     eq5 = d[t] c[s] + e[t] f[s] + f[t] == f[t + s]      Can anybody can help me with this?


title: What is a good alternative to this numerical example taken from FindFit?

text: I am using MMA V9.0 What do you suggest for this numerical example? I am not getting good results trying to use my own procedure to find a "best" fit using the 1-norm. The 1-norm example for `FindFit` that uses a fitting function to fit the first 20 primes returns `{1.1478,1.00474,1.05178}` for the three parameters `{a,b,c}`. My procedure below, formally equivalent to the fitting function in the example, returns `{1.06472, -0.0518796, 1.4054}`, although the fitting curves do not differ significantly. The `FindFit` example finds a minimum of `16.2208` while my procedure finds `17.1524`, probably not significant.               dat = Table[Prime[u], {u, 20}]          Res[pars_] := Module[{sol, y, z, mdl, res},       sol = Simplify[          DSolve[{y''[x] == a*c*(2*b + c*x)/(b + c*x)^2, y[0] == 0,             y'[0] == a*Log[b]}, y[x], x]][[1]];       y = y[x] /. sol;       z = y /. {a -> pars[[1]], b -> pars[[2]], c -> pars[[3]]};       mdl = Table[z /. x -> i, {i, 1, 20}];       res = dat - mdl;       Norm[res, 1]       ]          sol = NMinimize[Res[{a, b, c}], {a, b, c}]      However, I am doing this so that I can use a nonlinear ODE and do everything numerically. The function below `ResI`, the numerical equivalent of `Res`, does what it is supposed to do.               ResI[pars_] := Module[{sol, YFcn, mdl, res},       sol = NDSolve[{y''[x] ==             pars[[1]]*             pars[[3]]*(2*pars[[2]] +                 pars[[3]]*x)/(pars[[2]] + pars[[3]]*x)^2, y[0] == 0,            y'[0] == pars[[1]]*Log[pars[[2]]]}, y, {x, .5, 20.5}][[1]];       YFcn[x_] := y[x] /. sol;       mdl = Table[YFcn[i], {i, 1, 20}];       res = dat - mdl;       Norm[res, 1]       ]      The problem I am having is that `NMinimize` is not picking up numerical values for the integration. The following does not work.               solI = NMinimize[ResI[{a, b, c}], {a, b, c}]


title: How can I get a certain kind of iteration?

text: Can I get this type of do-loop in _Mathematica_?               Do[Print[j," ",k," ",l], {j,k,l, {a, b,z}, { c, d,y} }]      I want this to work so that, in the first iteration, `j`, `k` and `l` take on the values `{a, b, z}` and then, in the second iteration, the values `{c, d, y}`. So the result should be > >     a b z >     c d y >   I'm interested in any kind of a looping structure which can do this job for me. I don't necessarily need a do-loop.


title: Pruning coordinates in subarrays of a list conditional on them having non-real components

text: If I have a list of 2D coordinates placed in subarrays of a data structure like the following:               testList = Table[RandomReal[{0, 1000}, {RandomInteger[{0, 32}], 2}], {i, 1, 10}];      And if I sneak in a few entries where 2D coordinates have non-real or non- integer component values (positive or negative Infinity values, etc.) is there a way to quickly prune these coordinates away? In other words, I'd like to go through a data structure like `testList` and quickly delete any coordinate that has a positive to minus `Infinity` in it. Is there a way to make something like the following work?:               Select[testList, {_Real, _Real} &];      What if `testList` is already flattened by one level? Does the larger context of the data structure matter for `Select`? The following works for `testList`, but is not exactly ideal:               For[i = 1, i <= Length[testList], i++,            testList[[i]] =          Select[testList[[i]], NumberQ[#[[1]]] == True && NumberQ[#[[2]]] == True &];          ];


title: Reuse ParametricPlot3D plotting options

text: I create several ParametricPlot3D's that all should look the same: `BoundaryStyle -> Thick`, `AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}}`, `Boxed -> False`, etc. To ensure consistency and make changing the options easier, I would like to specify them only once. From what I've understood, it's possible to change the default options of ParametricPlot3D permanently by using `SetOptions`. I don't particularly like this solution, because it would affect the appearance of all ParametricPlot3Ds. Alternatively, I tried using               para := {BoundaryStyle -> Thick, AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}},              Boxed -> False}     Show[ParametricPlot3D[{u, v, 0}, {u, 0, 1}, {v, 0, 1}], para]      but here MMA complains > An unrecognized option name ("BoundaryStyle") was encountered while reading > a Graphics. This is the original code for one ParametricPlot3D:               ParametricPlot3D[{u, v, 0}, {u, 0, 1}, {v, 0, 1},        BoundaryStyle -> Thick, AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}},       Boxed -> False]      Any suggestion is much appreciated.


title: Progress Indicator & sums

text: Having looked here, what should I do differently to get the progress indicator working properly?               Monitor[Plot[{Pause[0.1];      LogIntegral[x] - Sum[2 N[Re[ExpIntegralEi[ZetaZero[n] Log[x]]]], {n, 1, 500}] - Log[2],      Sum[PrimePi[x^(1/n)]/n, {n, 1, Floor[Log[x]]}]},      {x, 2, 1000}], Row[{ProgressIndicator[x, {2, 1000}], x}, " "]]


title: How can Private functions be made completely opaque?

text: I want to make Private functions. From my point of view, being a Private function means that the function is not accessible from other packages. For that purpose I wrote the following code. But my private function can be called in another package. I don't want that.               (*Package 1*)     BeginPackage["Test1`"];     Begin["`Private`"];     Test1`Private`function1[x_] := x     End[];     EndPackage[];     (*Package 2*)     BeginPackage["Test2`"]     function2[x_] := Test1`Private`function1[x]     EndPackage[]      As you can see from the above code, `function1` is a private function in `Test1`. That same function when called in `Test2` is still accessible, but I don't want that. How can I resolve this. Can anyone help me?


title: Statistical analysis of data-list with recurring x-values

text: I have a list of data as follows with repeated x-values:               data={{42, 2.73}, {41, 3.5}, {41, 3.16}, {41, 2.73}, {39, 2.83}, {39,        2.66}, {47, 3.22}, {41, 2.86}, {41, 3.38}, {42, 2.62}, {39,2.32}, {46, 2.99}, {49, 2.3}, {39, 3.22}, {42, 1.53}, {49,1.46}, {49, 1.88}, {49, 1.08}, {47, 1.01}, {41, 1.17}, {40,1.3}, {46, 2.32}, {43, 1.85}, {39, 2.63}, {40, 2.72}, {49,1.9}, {48, 1.76},      {40, 1.67}, {42, 2.73}, {48, 2.97}, {43,1.81}, {41, 0.88}, {41, 2.56}, {40, 2.4},      {39, 2.08}, {49, 1.84}, {48, 2.07}, {46, 1.84}, {45, 2.24}, {44, 1.29},      {44, 2.05}, {42, 1.78}, {41, 1.59}, {40, 1.27}, {49, 3.21}, {47, 2.81}, {44, 3.1},      {43, 3.29}, {39, 3.3}, {44, 1.71}, {46, 3.08}, {47, 3.7}, {46, 3.04}, {44, 3.04},      {45, 2.88}, {49, 2.69}, {47, 1.74}, {47, 2.36}, {45, 2.94}, {44, 1.97}, {44, 2.55},      {43, 1.53}, {43, 3.91}, {42, 3.22}, {39, 1.84}, {44, 1.13}, {46, 1.48}, {42, 2.85},      {41, 4.21}, {41, 2.4}}      a) How do I find the mean + standard error for each distinct x-value, and present the result as a graphical plot for all elements of the above list? b) How do I determine the linear fit based on these mean values?


title: Wrong plotmarkers in the legend generated by ListLinePlot

text: `ListLinePlot` generates the same legend for different lists of data when `PlotMarkers` and `PlotStyle` options are used:               list = {{{1, 2}, {2, 3}, {3, 4}}, {{2, 4}, {4, 6}, {6, 8}}};     ListLinePlot[list, PlotStyle -> Black, PlotMarkers -> {Automatic, 16},      PlotLegends -> {"A", "B"}]      ![enter image description here](http://i.stack.imgur.com/phdN0.png) Is this a bug? I have _Mathematica v10.0.0_ installed on _Windows 8 x64_.


title: Does pass-by-value affect the performance of function calls?

text: I only have a little coding experience in C, and I remember I was told that pass by reference is more efficient than pass by value since the parameters don't need to be copied. Since there is no pass by reference in _Mathematica_ , I'm wondering if that affects the performance of function calls, especially when dealing with large data?


title: MouseAppearance and cursor problems

text: I have to create a `Graph` object, which can be manipulated by the user, though I do not want to have the `Graph`-specific cursor (an arrow with an `UndirectedEdge` symbol next to it) not to confuse the user with any extra information. I assumed this would work:               MouseAppearance[      Graph[{1 <-> 2, 2 <-> 3,3 <-> 1},       ImageSize -> 200,       EdgeShapeFunction -> ({Black, AbsoluteThickness@2, Arrowheads@.1,            MouseAppearance[Arrow[#1, .1], "Arrow"]} &),       VertexShapeFunction :> ({Hue[.6, .2, .8],            MouseAppearance[Disk[#1, .1], "Arrow"]} &)       ],      "Arrow"]      ![Mathematica graphics](http://i.stack.imgur.com/OX3tH.png) But it doesn't work. While all graphics objects and the whole graph itself are wrapped into `MouseAppearance` still the `Graph`-specific cursor appears when I move the mouse away of edges or nodes. Over nodes and edges, the standard arrow cursor is displayed correctly, as expected. Unfortunately, when I capture the screen with the cursor included, it **always** saves the normal arrow cursor irregardless how it looks on screen. Strange. That's why I did not include a picture with a cursor over it. Can anyone answer the following questions?   1. Why `MouseAppearance[..., "Arrow"]` does not work here (only partially)?   2. How can the `Graph`-specific cursor appearance be invoked? The documentation for `MouseAppearance` (under More nformation) does not list it among the built-in ones.   3. Why `PrintScreen` or any other screenshot application is unable to capture the `Graph`-specific cursor? Platform is: Win7 64bit


title: How to make a point's position time-dependent given a formula for the next step?

text: I've made a program that is just some points on a plane. Red points are cops and green points are robbers. Each point has a vector indicating where it is going to be in the next step of $t$. Right now $t = 0$ but I want to see what happens when $t=1,2,3,\ldots$ Here is a picture: ![enter image description here](http://i.stack.imgur.com/KxnSk.png) The points are in this list. `rob[i]` and `cop[i]` make random pairs of x-y cordinates:               r = Table[rob[i], {i, 1, n}],     c = Table[cop[i], {i, 1, m}]      The next position are given by the formulae:               Table[r[[i]] + Normalize@Sum[(r[[i]] - c[[j]])/Norm[r[[i]] - c[[j]]]^2, {j, 1,Length[c]}],{i,1,Length[r]}]      and               Table[c[[i]] + Normalize@ Sum[(r[[i]] - c[[j]])/Norm[r[[i]] - c[[j]]]^2,{j, 1,Length[r]}],{i,1,Length[c]}]      for robbers and cops, respectively. I want to do something like add a parameter $t$ and when that parameter changes the next position of the points should be updated by the above formulae. Thanks for helping. **EDIT:** Using the answer of asterix314 I came accross this: ![enter image description here](http://i.stack.imgur.com/uu4LY.gif)


title: Fitting one function to another

text: I'd like to see how close I can fit an exponential function to a cosine function in the domain of $\;-\frac{\pi}{2}$ to $\frac{\pi}{2}$ in the least squares sense.               FindFit[Cos[x], {A*Exp[l*(Cos[x] - 1)], -π/2 <= x <= π/2}, {A, l},  x]      > >     FindFit::fitd: First argument Cos[x] in FindFit is not a list or a > rectangular array. >   I could create a table for `Cos[x]` to pass as the first parameter but I feel like I'm approaching this wrong and should be able to give _Mathematica_ my problem in symbolic form. Perhaps, I should try Minimize but I didn't get any results out of it.               Minimize[{(Cos[x] - A*Exp[l*(Cos[x] - 1)])^2, -π/2 <= x <= π/2}, {A, l, x}]      > >     Minimize[{(-A E^(l (-1 + Cos[x])) + Cos[x])^2, -π/2 <= x <= π/2}, {A, l, > x}] >


title: How do you get high resolution plots in applications using the Mathematica MathService?

text: This is for Mac users only using MathService (MathService it seems, given that it was created back in 2004, is a power pc code and requires Rosetta to run on Intel). If I type a plot command in another application (in this case TextEdit): ![enter image description here](http://i.stack.imgur.com/w8REL.png) ...and then use Mathematica to evaluate that code within that application using MathService: ![enter image description here](http://i.stack.imgur.com/mWdMG.png) ...all works fine. ![enter image description here](http://i.stack.imgur.com/8CWOA.png) But the problem then arises when you want to print the document because the graphic is at screen resolution. Does anyone know how to use MathService to generate print quality plots within other applications? Also in MS Word it seem that only the "Evaluate to Text" service is available which (obviously) returns `FullForm` of the plot rather than the graphic. Why isn't "Evaluate to Graphic" available? Incidentally using Mathematica this way seems to allow multiple undos of kernel evaluations.


title: How to Text justify string that includes SubScriptBox in it?

text: I am using Grid to document a demo I have. i.e. I am writing the documentation of the demo as a help option, which will display information when clicked on. Everything is working well. I am using the following pattern to do that:               help=Block[{a,b,c,.....}, (*Block is needed to prevent $nnn in symbols showing*)            Style[TraditionalForm[Grid[{              {"some text here, all in string"},         {equation here using symbols a,b,c, as in  a=b+c},          ...       ]], FontFamily -> "Times"]           ]      Then later on, when I want to display information, I simply display the help symbol. The nice thing also about this, is that I typeset these all once, in the initialization section. So that it is fast to display before as the help is typeset once and stored in the symbol. The final result is really nice. The same as Latex. I see no difference at all. The only glitch, is when I have long text, I'd like it to be full justified. Using normal Grid Alignments does not help here, and so I have to use `TextCell`, with the `TextJustification->1` for it to work. But the only problem is that some of the text I have might include subscript, like this one example: ![enter image description here](http://i.stack.imgur.com/VgCin.png) And you can see that the `TextCell` does not like that one part (I understand also why it is not happy). I am trying to see if I can use `TextCell` (as it seems the only way to have text justified in a grid) and at the same time use little bit of subscript and such in the string. If there is such a trick. For the actual math part of the documentation, I can split the math from the text like I show above in the rest of the grid. But there are some parts, where I need to write all the text in one place, and use little bit of subscript and such in there. But also be able to text justify everything so it looks nice. In a way, this is like I do in Latex, where the main equations go as centered form, and the description around them has very little math. I am trying to emulate this with the help of Grid. If I do not use textCell, this is the result: ![enter image description here](http://i.stack.imgur.com/Oqamk.png) So it works now, but text is not justified inside the grid. It does not look as nice. Here is the code, if someone wants to try something. I tried many things, but so far, no luck. below is small example, left many things out. I have to keep the `ContentSize` fixed there since the overall size is fixed for display.               Manipulate[      Style[TraditionalForm[Grid[{          {"let \!\(\*SubscriptBox[\(u\), \(n\)]\) be the outward normal \     derivative on the boundary"}          }, Frame -> All]        ], FontFamily -> "Times"],      ContentSize -> {300, 475}      ]      I do not want to use `GraphisGrid` and `rasterize` things and such. And this will be used for a demo that runs in CDF plugin, so the following symbols can't be used : `SetOptions`, `ToExpression`, `Symbol` , `$Context`, `SetAttribute`s, `Clear`, `Unprotect`, `DownValues`, `UpValues`, `OwnValues` and packages not allowed to be used or created also. Also, `Manipulate[]` has to be the most outside construct. Thank you, Note: `TextJustification -> 1` does alignment on BOTH ends. Using LineIndent->0 only does it on one side. Below is an example of the difference. ![enter image description here](http://i.stack.imgur.com/dX1qS.png)


title: Fitting a beta distribution to a probability density curve

text: If I have a spectral data set showing measured energy on the y-axis and frequency on the x-axis, how would I go about fitting this to a beta distribution? For example, lets say I had the data for the following curves showing spectrum for this ship: ![enter image description here](http://i.stack.imgur.com/scd8Z.gif) How do I determine the beta curve fit parameters to say the blue line? Taking it one step further. If I have a wav sound file of the sound of an engine, how would I do the same thing? _**UPDATE_** I attempted to use the supplied answer and got an error as follows: ![enter image description here](http://i.stack.imgur.com/1eHIU.png) **The data file can be downloaded from the following URL:acoustic power spectrum data to 3k hz** The overall goal here is to generate a curve approximating the shape like this: ![enter image description here](http://i.stack.imgur.com/Wrt9a.png)


title: How do I get a two-term polynomial with a leading negative sign to display in the correct (i.e. textbook) order?

text: The first three expressions evaluate as expected and the polynomial is displayed in what I would call "textbook" form. The last expression, however, switches the order of terms. Mathematica employs this change for two-term polynomials if it results in getting rid of the leading negative sign (at least that is the best I can deduce).               x^2 + x + 5 // TraditionalForm     (* x^2 + x + 5 *)          -x^2 + x + 5 // TraditionalForm     (* -x^2 + x + 5 *)          x^2 + x // TraditionalForm     (* x^2 + x *)          -x^2 + x // TraditionalForm     (* x - x^2 *)      These polynomials are the result of prior symbolic manipulation, so I cannot simply use `HoldForm` or the equivalent to maintain the desired order. Is there a way to change this behavior in general so that the last expression displays as `-x^2 + x`? I can think of substitution rules to fix this particular example, but would like to find a robust solution that applies as transparently as possible across the board. **Edit** Additionally, `PolynomialForm` produces the same results:               PolynomialForm[-x^2 + x , TraditionalOrder -> True]     (* x - x^2 *)          PolynomialForm[-x^2 - x , TraditionalOrder -> True]     (* -x^2 - x *)      It seems that Mathematica will produce the traditional order for polynomial terms except when there are only two terms and reversing the order eliminates the leading negative sign.


title: How to specify a specific range for a loop?

text: I'm having trouble with setting up a particular range in a loop for my programming. Now I have a defined range of data (not continuous numbers) that needs to be applied in a loop. Since the aim for my code is to generate functions/expressions with the range automatically, I need to figure out a way to applied those data. The code is               MapThread[(Subscript[C, #1][x, y] :=           Subscript[q, 2 #1 - 1] +            x*Subscript[q, 2 #1] - (Subscript[q, #2] +              y*Subscript[q, #2 + 1])) &, {Range[], Range[]}];      data for #1 is: 3, 4, 5, 4, 6, 6, 6, 6. data for #2 is: 1, 2, 4, 3, 1, 2, 3, 5. As u can see from the code, I cannot simply define the range in the loop. My idea is to create a list for the data and maybe apply it in the loop? thx for ur help!


title: LinearModelFit of WeatherData

text: I am trying to perform a linear regression on some weather data, but I can't seem to figure out how to perform the operation. What I have right now is this:               temperature = WeatherData["Chicago", "Temperature", {{1990},{2010},"Month"}]     model = LinearModelFit[temperature,x,x]      Any ideas on what I am doing wrong?


title: How to make a filled Ellipsoid?

text: I want to make a filled `Ellipsoid`, but it seems `Filling` options doesn't work in `Graphics` options. I have a matrix               matrix1={{1,4},{6,8}}      thus I plot en ellipse from his `Eigenvalues` and `Eigenvectors`               valmat = Eigenvalues@matrix1;     vecmat = Eigenvectors@matrix1;     pair = {0.5, 0.5}     ellips1 =      Ellipsoid[pair, {Abs[valmat[[1]]], Abs[valmat[[2]]]}, {vecmat[[1]], vecmat[[2]]}];     plot1 = Graphics[{Red, ellips1}, GridLines -> Automatic,      GridLinesStyle -> Directive[Gray, Dotted]];     partot1 =      Show[plot1, Frame -> True,      FrameLabel -> {Style["x", 18], Style["y", 18]}, AspectRatio -> 1,      FrameTicks -> {Automatic, Automatic, None, None},      LabelStyle -> Directive[13], ImageSize -> 500]      ![enter image description here](http://i.stack.imgur.com/FrLIh.jpg) The question is how to filled this ellipse with an specific color??..and also (if it's possible) the transparency on that. Thanks


title: Contour Plot in Cylindrical Coordinates

text: I'm trying to render an equation in the cylindrical coordinates, and I used the following codes:               With[{λ = 1, f = 50, R = 25},      ContourPlot[        -Mod[(Pi/λ)*(Sqrt[ρ^2 + f^2] - f), Pi] /. {ρ -> Norm[{x, y}], ϕ -> ArcTan[x, y]},        {x, -R, R}, {y, -R, R},        Contours -> 20, ContourLines -> False,        RegionFunction -> (Sqrt[#1^2 + #2^2] < R &),        ColorFunction -> "Rainbow", Frame -> False]]      However, I got a pattern which seems **not smooth** because points were sampled equally in the Cartesian coordinates. How can I get a smooth contour plot? Furthermore, can I plot such a pattern in the 3D coordinates? Thanks a lot. Here is an example of the output that I would like: ![enter image description here](http://i.stack.imgur.com/uHm7r.png)


title: List-operations only when restrictions are fulfilled (Part 2)

text: Consider the following:               data={{{3544128000, 80}, {3544732800, 80}, {3545337600, 80},     {3545942400, 80}, {3545942400, 160}, {3546547200, 160}, {3547152000, 0}}};      After the satisfying answers to my former question (Part 1), another issue occurred, but with the same background (List-operations only when restrictions are fulfilled): After applying               Transpose[{#[[All, 1, 1]],            Total[#[[All, All, 2]], {2}]}] &[#] & /@ (GatherBy[#, First] & /@         data)      on `data` (thanks to Andy Ross for the approach), I receive               {{{3544128000, 80}, {3544732800, 80}, {3545337600, 80}, {3545942400, 240},     {3546547200, 160}, {3547152000, 0}}}      which resembles to               {{x_-n*604800_, y_},...,{x_-604800_, y_}, {x_, u_},     {x+604800_, z_},{x_+2*604800_, z_},...,{x_+m*604800_, z_}}      I would like to do the following:   1. `u_->y_` (*Transform u_ to y_*)   2. `residual=(y_-u_)/(n+1)` (*Calculate residual of y_ and u_ and divide it be `n+1`*)   3. `{{x-n*604800_, y_+residual},...,{x-604800_, y_+residual}, {x_, y_+residual},{x+604800_, z_},{x_+2*604800_, z_},...,{x_+m*604800_, z_}}` ( _Distribute`residual` to all periods from `x_-n*604800` to `x_`_) The result in case of `data` will then be:               {{{3544128000, 120}, {3544732800, 120}, {3545337600, 120}, {3545942400, 120},         {3546547200, 160}, {3547152000, 0}}}      For better understanding, please consider the following examples:               Example1 = {5, 5, 5, 2, 2, 2, 6, 4, 4, 4};     MyFunction@Example1     {5, 5, 5, 3, 3, 3, 3, 4, 4, 4}          Example2 = {2, 2, 2, 6, 4, 4, 4};     MyFunction@Example2     {3, 3, 3, 3, 4, 4, 4}          Example3 = {2, 2, 2, 4, 4, 4};     MyFunction@Example3     {2, 2, 2, 4, 4, 4}      `MyFunction` detects a peak within the dataset and "kills" it by replacing the peak and the preceding sequence (with constant values) with `y+residual` (see `2.`, `Example1` and `Example2`). It is important that `MyFunction` returns the original list when no peak occurs in the list (see Example 3.).


title: What exactly does AddTeX2Eps do and how does one use it?

text: What exactly is Janko Slavic's addon package AddTeX2Eps supposed to do, and exactly how does one get it to work? I do understand it's supposed to allow one to use TeX `psfrag` processing upon a Mathematica-generated graphic, but I cannot discern from the meager docs what's going on. And I can't get the supplied sample notebook `AddTeX2Eps- Example` to process correctly. When I evaluate the notebook, from the `EpsExport` command there I get a long list of errors starting with `OpenRead::noopen : canot open EpsExport.ps` (So I never get to the point of being able to use the exported file from within LaTeX where, I presume, psfrag is going to process it.)


title: Make AdjacencyGraph hide single unconnected elements

text: Is there a way to force AdjacencyGraph to hide single unconnected or self connected elements?               AdjacencyGraph[{{0, 1, 0, 0, 0}, {0, 0, 1, 1, 0}, {0, 1, 0, 0, 0}, {1,         1, 1, 0, 0}, {0, 0, 0, 0, 1}}]      ![enter image description here](http://i.stack.imgur.com/1RggU.png)


title: In version 9 PlotLegends, how can I remove the strange edges that appear around LegendMarkers?

text: I'm running Mathematica version 9. I am using `ListPlot` to plot two sets of data. For each data set, I am using different `PlotMarkers`: for the first data set, I use red disks, while for the second data set, I use red rectangles. To do this, I define `Graphics` objects `redDisk` and `redRectangle` as shown below. (I have found that it is necessary to define nonzero `ImagePadding` to prevent the edges of the `Graphics` from being cut off.) Next, I want to display a plot legend describing the two different `PlotMarkers`. To do this, I want to use the `PlotLegends` option that is newly implemented in Mathematica version 9. I define a `PointLegend` called `legend`. Within `PointLegend`, I use pass in the objects `redDisk` and `redRectangle` to the `LegendMarkers` option. Then I give `legend` to the `PlotLegends` option of `ListPlot` and use the `Placed` function to position the legend in the plot. The code to do all of this is the following:               (* Define PlotMarkers *)     pm = 8; (* size of PlotMarkers *)     redDisk =        Graphics[{Red, Disk[]}, ImageSize -> (pm + 2),         ImagePadding -> {{1, 1}, {1, 1}}];     redRectangle =        Graphics[{Red, Rectangle[]}, ImageSize -> (pm + 1),         ImagePadding -> {{1, 1}, {1, 1}}];          (* Define a PointLegend using the PlotMarkers defined above *)     legend = PointLegend[{Red, Red}, {"red disk", "red rectangle"},         LabelStyle -> {18, FontFamily -> "Arial"},         LegendFunction -> "Frame",         LegendMarkers -> {redDisk, redRectangle}];          (* Create some data to plot *)     myRange = Range[0, 2 Pi, 0.175];     diskData = Transpose[{myRange, Sin[myRange]}];     rectangleData = Transpose[{myRange, Cos[myRange]}];          (* Plot the data *)     myPlot = ListPlot[       {diskData, rectangleData}, PlotRange -> All, Frame -> True,        FrameLabel -> {"x", "y"}, BaseStyle -> {18, FontFamily -> "Arial"},        PlotStyle -> Red, PlotMarkers -> {redDisk, redRectangle},        ImageSize -> 500,       PlotLegends -> Placed[legend, Scaled[{0.65, 0.85}]]       ]      which gives this output: ![SmallGraphic](http://i.stack.imgur.com/TKwhO.png) _**However,_** when I zoom in on this graphical output, I see that the markers inside the `PointLegend` do not appear exactly the same as the `PlotMarkers` of `ListPlot`. **_Specifically,_** the markers inside the `PointLegend` appear to have a strange gray edge or border: ![ZoomGraphic](http://i.stack.imgur.com/MTw69.png) where I used the Mathematica front end's magnification feature to zoom in on the `myPlot` graphical output. The strange gray edges/borders persist even when I export `myPlot` to, for example, a pdf file:               (* Export the data as a pdf file *)     Export["example.pdf", myPlot]      When I open `example.pdf` in a pdf viewer and zoom in, I see the following. The strange gray edges/borders are still apparent in the `LegendMarkers` within the legend: ![PDFGraphic](http://i.stack.imgur.com/9r0Fm.png) **So, my question is, how can I remove the gray edges/borders of the`LegendMarkers` so that the `LegendMarkers` and `PlotMarkers` look the same?** Thanks for your time.


title: Scale Insetted Characters to Plot

text: I am trying to place a curly brace within a plot such that the top/bottom of the curly brace line up with two horizontal lines in the plot: ![enter image description here](http://i.stack.imgur.com/yLqCe.png) I have not been able to find a way to make the curly brace have the right size without setting the size explicitly by hand. Insetting a Text object doesn't work as the font size is used to scale text, and guessing the right font size is a complete guessing game. I settled upon using "Pane" with the "ResizeToFit" ImageSizeAction set, however I am not sure how to then specify the Inset size or the ImageSize for pane to get the desired results. Here is the code I am using to generate this plot. ImageSize being set to "5" is just a guess to get approximately the right size, but ideally I want the top/bottom of the curly brace to exactly line up with the two horizontal dashed lines:               f = 1/x;     \[Epsilon]pl =        Plot[{f}, {x, 0, 1}, PlotStyle -> Black,         PlotStyle -> AbsoluteThickness[1]];          \[Epsilon]1pl =        Plot[{f}, {x, 0.2, 0.4},         PlotStyle -> Directive[Red, AbsoluteThickness[1.5]]];     \[Epsilon]1dashed =        ListPlot[{{{0.1, f /. x -> 0.27}, {0.27, f /. x -> 0.27}}, {{0.1,            f /. x -> 0.3}, {0.3, f /. x -> 0.3}}},         PlotStyle -> Directive[Red, Dashed, AbsoluteThickness[1]],         Joined -> True];          Show[\[Epsilon]pl, \[Epsilon]1pl, \[Epsilon]1dashed,       PlotRange -> {{0, 1}, {0, 6}}, Axes -> False, Frame -> True,       ImageSize -> 600,       FrameStyle -> Directive[AbsoluteThickness[1], FontSize -> 24],       FrameTicks -> False, FrameLabel -> {"\!\(\*     StyleBox[\"r\",\nFontSlant->\"Italic\"]\)", "\!\(\*     StyleBox[\"\[Epsilon]\",\nFontSlant->\"Italic\"]\)"},       Epilog ->        Inset[Pane["{", ImageSize -> 5,          ImageSizeAction ->           "ResizeToFit"], {0.095, ((f /. x -> 0.27) + (f /. x -> 0.3))/         2}, {0, 0}, {Automatic, (f /. x -> 0.27) - (f /. x -> 0.3)}]]      Additionally, I would like to be able to scale the curly brace such that the original aspect ratio isn't maintained (i.e. the width of the curly brace will be a fixed value, but the height can vary). What is the best way to go about doing this?


title: Why is ListDensityPlot unable to plot datasets with extreme ranges

text: Consider the following dataset:               data = Flatten[      Table[{x 10^-9, y 10^-9, x^2 + y^2},{x, -100, 100, 10}, {y, -100,100, 10}]      , 1];      If I try to `ListDensityPlot` this set:               ListDensityPlot[data]      ![Mathematica graphics](http://i.stack.imgur.com/DKNjB.png) it does not plot the function. However, if I do the obvious re-scale of the coordinates:               data2 = Flatten[Table[{x , y , x^2 + y^2}, {x, -100, 100, 10}, {y, -100, 100, 10}], 1];      it has no problem plotting it:               ListDensityPlot[data2]      ![Mathematica graphics](http://i.stack.imgur.com/IsOJV.png) The same problem exists for other plotting methods (`ListPlot3D`, `ListContourPlot`, etc.). While rescaling the coordinates is a simple fix, is it possible to plot datasets of this sort without first rescaling the coordinates?


title: How to take matrix elements as input to another matrix or loop?

text: Say I have matrix tmp1 of size 1000 x 5 (shown is just a small section for illustration purpose), consisting of real numbers![enter image description here](http://i.stack.imgur.com/f8JFZ.png) and 0: How can I iteratively take every non-zero real number elements and use it as input for another 'For' loop argument limit to calculate another set of matrix values? For example, taking second row, first column value of 4.956 I would like to use it to calculate a 'For' loop like r=0.4; For[i = 0, i < **4.956** , i = i + 0.2, calculate P = Exp[-r i]*i P += P And place this cumulated P result into tmp2 output matrix at same corresponding location as where 4.956 was taken from. Then repeat for the next non-zero element of tmp1, so for row 2, column 2 value of 1.234: For[i = 0, i < **1.234** , i = i + 0.2, calculate P = Exp[-r i]*i P += P and result into tmp2 location row 2, column 2. Any zero elements found in tmp1 will simply be mapped to tmp2 of same location. Thanks.


title: Can't load LevelScheme package

text: My problem is that I can not load the `LevelScheme` Package. I am using _Mathematica_ 8\. I downloaded and unzipped the folder from this website. I saved it in the Download folder Now I append to _Mathematica_ 's search path using:               AppendTo[$Path, "/Users/alessandromanzotti/Downloads/LevelScheme"]      > {"/Applications/Mathematica.app/SystemFiles/Links",   >  "/Users/alessandromanzotti/Library/Mathematica/Kernel",   >  "/Users/alessandromanzotti/Library/Mathematica/Autoload", > "/Users/alessandromanzotti/Library/Mathematica/Applications", > "/Library/Mathematica/Kernel", "/Library/Mathematica/Autoload", > "/Library/Mathematica/Applications", ".", "/Users/alessandromanzotti", > "/Applications/Mathematica.app/AddOns/Packages",   >  ...   >  "/Users/alessandromanzotti/Work/Software/Mathematica/LevelScheme", \ > "/Users/alessandromanzotti/Downloads/LevelScheme"} Everything seems OK               SetDirectory["/Users/alessandromanzotti/Downloads/LevelScheme"];      FileNames[]       > {"BlockOptions", "ClipToRectangle", "CustomTicks", "doc", ".DS_Store",   >  "ForEach", "InheritOptions", "Kernel" , "LevelScheme" , > "NamedColors"} But I get an error using `Get["LevelScheme`"]`. What can I do?


title: Why do some CountryData flags render at low resolution?

text: This question is related to data analysis introduced here Why do some flag images from the `CountryData` dataset render at very low resolution both in Front End and when exported in PDF? (Here Philippines and UnitedKingdom as examples: flag images were not searched exhaustively). ![enter image description here](http://i.stack.imgur.com/x3eia.png) ![enter image description here](http://i.stack.imgur.com/C2gxv.png) To reproduce the flag images, use the following code:               # -> Image[CountryData[#, "Flag"], ImageSize -> 20] & /@ CountryData[]      I observe this in MMA 8.0.4 on OSX 10.7.3


title: Make all the lines equally sharp

text: Graphics[{       Line[{{# - 1, -0.5}, {# - 1, 5.5}} & /@ Range[6]],       Line[{{-0.5, # - 1}, {5.5, # - 1}} & /@ Range[6]]       }]      There are two kinds of lines in this simple picture, some lines look sharp and others look blurry. How can I avoid this effect? If I zoom in the graphics by dragging the controlled-corner, the blurry effect still exists with different lines. ![enter image description here](http://i.stack.imgur.com/Uan8e.png)


title: hexList[[1]] returns a list of decimal numbers

text: Sorry for not being clear about this question earlier. I appreciate the answers I got, but the edits I made should make the question more understandable. I have been working with hex in _Mathematica_ , and for some reason I can't get a list of hex _strings_ to work properly. I have a list of hex strings - for example:               toCharachterHex[inChar_] := Return[IntegerString[ToCharacterCode[inChar], 16]];      When I call the function like this:               hexList = toCharachterHex["ajdv*3"]      _Mathematica_ returns               {"61", "6a", "64", "76", "2a", "33"}      Now, when I type `hexList[[1]]`, _Mathematica_ gives me               {"97", "106", "100", "118", "42", "51"}      Why would _Mathematica_ do this? Shouldn't `hexList[[1]]` give me `61`?


title: "And" to continue evaluation after "False"

text: Below, is it possible to print `No` and have x be 2. That is, I'm looking for an `And`-like function that looks at all arguments before returning.               x := 1     If[And[True, False, True, False, (x := 2; True)], Print["Yes"], Print["No"]]; x


title: Problem achiving effect I want with ColorFunction

text: I want to create a plot showing historical annual maximum and minimum temperatures. I've figured out how to get 10 years of historical temperature data from Wolfram|Alpha. The plot below shows the highest, average high, average low, and lowest temperature during the past ten years for Austin, Tx. The problem occurs when I try to use ColorFunction to control the filling color. ![image](http://i.imgur.com/vZ6rA.jpg) The code below returns a relatively small amount of data that can be used to replicate the problem.               max = Map[#*9/5+32.&, WeatherData["KATT","MaxTemperature",{{2011,1,1},{2011,12,31},"Week"}][[All,2]]];       min = Map[#*9/5+32.&, WeatherData["KATT","MinTemperature",{{2011,1,1},{2011,12,31},"Week"}][[All,2]]];              DateListPlot[{max, min},{{2011,1,1},Automatic,"Week"},Joined->True, Filling->{1->{2}}, ColorFunction ->"Rainbow"]         I would like to have simple a vertical color gradient. Instead, the fill color is a more complicated function of the top curve and the y-axis. I can't describe it properly, but hopefully, the problem is apparent. I've tried several approached to controlling the fill color, but none of them do what I want, and most of them don't work at all. ![image](http://i.imgur.com/vXorV.jpg) I would ultimately like to use slightly different filling styles between the highest ever and average highest temperature, and between the average lowest and lowest ever - perhaps less opaque, and for the four plot lines to still be visible.


title: Automatically load packages at startup

text: I'm a physics student and I try to simplify my day with _Mathematica_. Every time I use _Mathematica_ I need `Div[]`, `Grad[]`, `Curl[]`, etc., so I use `Needs["VectorAnalysis`"]`. My question is: Is there any way to tell _Mathematica_ that the package `VectorAnalysis`` should always be loaded? It would simplify my day enormously. By the way, I tried               DeclarePackage["VectorAnalysis`", {"Div", "Grad", "Curl"}]      from the _Mathematica_ tutorial on Automatic Loading of Packages, which says: > When you first use Grad, Mathematica automatically loads the package that > defines it. Unfortunately, nothing happens. The functions are still unknown, until I use `Needs["VectorAnalysis`"]` What am I doing wrong, and how do I fix my problem?


title: Have the kernel load a user-defined function by default

text: I wrote a very simple function that I would like to act as if it were one of the default functions that came with _Mathematica_ , so that you don't have to load or import any package before you make use of it. The reason is, the function is so simple, that its almost just as easy to just re-write the function as it is to import a file every time. It would be nice though if I just didn't have to do anything. Is there any way to achieve this behavior?


title: Developing Mathematica applications with IntelliJ IDEA

text: I create Mathematica application. For example testPrj. Now I want load this application for test. Here is a problem: how can I setup environment for loading my application with simple `<<testPrj`? First what I try is to add to a `$Path` path of my application. But it should be done every time after loading Mathematica (any notebook). PS: My application has a custom way and it is better not to change


title: Accessing the Data of an RLink RDataFrame

text: I am trying to extract the data table itself from an RLink-generated RDataFrame:               Needs["RLink`"];     InstallR[];     REvaluate["require(datasets);"];     REvaluate["data(airquality);"]     airquality = REvaluate["as.data.frame(airquality)"]      ![RDataFrame Output](http://i.stack.imgur.com/GHGHD.png) but now I would like to extract out the goodies like RNames and RData so that I may work with them independently. (BTW, TableForm on an RDataFrame is _awesome_!) I tried messing around with its InputForm, but I got stuck. How do I extract RNames, RData, etc. into standard _Mathematica_ lists?


title: Wolfram Workbench - how to rename local variables

text: I'm refactoring some old code. I used really short names for local variables, which I'm coming to regret. **Is there an easy way to rename local variables in scope using Wolfram workbench?** Here is an example How could I change `d` inside `Test`, but not in the `Print` statement?               Test[d_]:=d+1;     (*Some other code*)     Print[d];      Or the same for `l` inside `Module`?               Test1[x_]:=Module[{l},l=x+1];     (*Some other code*)     Print[l];      There is a Ctrl+1 QuickFix rename variable, which I discovered while researching this question, but it seems to work only on the whole file... Using WB 2.0 (anybody even still uses WB 1.1?)


title: Sharp ListDensityPlot

text: I have some quantity varying with time (horizontal axis of the plot): it first oscillates then it has a jump (larger than the amplitude of the oscillations), then it continues oscillating. I have that quantity for a discrete set of cases (vertical axis of the plot). I would like to find an option for `ListDensityPlot` that would allow me to really emphasize that jump: I don't want a nice smooth color scheme but rather one that would make the small oscillations invisible and would focus on the larger jump. I can I control `ListDensityPlot` to do that ?


title: Getting increased accuracy for roots of determinant

text: I have a matrix $a(\kappa)$ from which I am trying to determine $\kappa$ by using the equation $det(a(\kappa)) = 0$. The matrices I deal with are on the order of 100 X 100 to 500 X 500. Originally I was trying to do this symbolically which of course went no where fast, and so I posted the problem here: Find Determinant/or Row Reduce parameter dependent matrix. As a result I am now essentially using a singular value decomposition to find $\kappa$. The code is               f[x_?NumericQ] := Last[SingularValueList[a /. \[Kappa] -> x, Tolerance -> 0]]      Then I create a plot for a range of $\kappa$ values which should contain the physically correct $\kappa$. I am getting values of $\kappa$ which fit my expectations, and seem to be correct. The correctness comes form the fact that 1) I am reproducing someone else's work, and 2) $\kappa$ is essentially an eigenvalue and I can check the eigenfunctions. Right now I can get $\kappa$ to about 4 digits of accuracy that is, if I increase the size of my matrix, my $\kappa$ will converge to about 4 digits buy beyond that the value of the 5th digit is anyone's guess. Are there any tricks to increase the accuracy of the results?


title: Structure of curated data?

text: Is there a way to programmatically access the structure of curated data present in Mathematica (for each type of information, for example for CountryData or ChemicalData) that would allow access to any kind of available information ? This would also allow the possibility to build generic graphical interfaces for accessing the data.


title: Why does Mathematica choose branches as it does in this situation?

text: Consider these integrals:               $Assumptions = {e>0,e<1/2};     term1 = Integrate[x/(1-x) (1/(1-4x+4x^2))^e - 1/(1-x), {x, 0, 1}]     term2 = Integrate[1/2 x(1-x) (1/(1-4x+4x^2))^e, {x, 0, 1}]     term3 = Integrate[x/(1-x) (1/(1-4x+4x^2))^e - 1/(1-x)                       + 1/2 x(1-x) (1/(1-4x+4x^2))^e, {x, 0, 1}]      The third integrand is the sum of the first and second integrands. So it follows that `term3 == term1 + term2` should be true. I won't write down the full results because they're long and mostly irrelevant, but `term3` has a nonzero imaginary part, whereas neither `term1` nor `term2` does:               term3 - term1 - term2 == 2 Pi I      Mathematically, I get why this is a reasonable result (I think): Mathematica has to choose a branch for the exponential function, and in the first integral it chooses the branch that gives a purely real result, whereas in the last case it chooses a different branch. Why would it do that, though? Is there something about these expressions that prompts Mathematica to choose the branch that it does in each specific case? For future integrals, if I run into something like this again, can I tell which branch the integrator is going to pick? Or is it something highly dependent on the details of the algorithm and thus random as far as I'm concerned? I'm also curious to know if I could input these expressions differently so that Mathematica will choose the real branch of the exponential in every case, but that's not a priority since I know what the answer is, and it may be a matter for a separate question in any case.