How can I use FindRoot on an expression from NDSolve?

I have a second order ODE that I can only solve numerically using NDSolve, but I then need to use the solution in FindRoot and am running into errors. A simplified but analogous problem is the following: Find the solution to $\phi^{\prime\prime}(u) = -\omega^2 \phi(u)$ on the interval $0<u<1$ with the boundary conditions $\phi(0)=\phi(1)=0$, which will only be true for certain values of $\omega$ ($\omega=n\pi$ in this case). The code I am using is               eqnp = p''[ u] + ω^2 p[u];          psol[ω_?NumericQ] = NDSolve[{eqnp == 0, p[0] == 0, p[1] == 0}, p, u];          FindRoot[psol[ω], {ω, 3}]      but I am receiving errors. How can I feed a solution from NDSolve into FindRoot? I know that in the specific case above everything can be done analytically, but my actual ODE must be solved numerically, so I need to figure out how to solve this simplified problem completely numerically. EDIT: I have updated the post with the full problem. The ODE is both homogeneous and linear               λ = 0.00001; k = 1.0;     f[u_] := 1/(2λ u) (1-Sqrt[1-4λ+4λ u^2]);     A = Sqrt[1/2(1+Sqrt[1-4λ])];     K2[u_] := u^(-3/2)f[u](1 + 2λ u^2f'[u]);     K1[u_] := K2[u](4ω^2)/(A^2f[u]^2) - 4k^2u^(-1/2)(1 - λ(6u^2f'[u] + 4 u^3f''[u]));     eomu = 4u^3K2[u]ϕ''[u] + (6u^2K2[u] + 4u^3K2'[u])ϕ'[u] + K1[u]ϕ[u];      I define the boundary conditions at $u=1$ by finding the first few coefficients in the series solution (using normal Froebenius method). I then want to find the solution and use Dirichlet boundary conditions at $u=0$ to determine the eigenfrequencies. The first coefficient is $a1$ and the indicial exponent is $-\frac{I\omega}{2A}$ (the other solution to the indicial equation is unphysical and is discarded)               a1 = (k^2(1 + Sqrt[1 - 4λ])(1 + 8λ) + 2(-1 + 2λ)ω^2 + (I Sqrt[1 + Sqrt[1 - 4λ]] (12λ ω))/Sqrt[2])/(2Sqrt[2] Sqrt[1 + Sqrt[1 - 4λ]] (Sqrt[1 + Sqrt[1 - 4λ]]/Sqrt[2] - I ω))      (I have separate code to find an arbitrary number of coefficients, but to enter them here would be too much) Then define the solution to use as boundary conditions               ϕhnum[u_] := (1 - u)^(-I ω/(2A))(1 + a1(1 - u))     numh = 0.999999;     numb = 0.000001;      Then I use the code suggested by Jens               ϕsol[ω_?NumericQ] := ϕ /. First@NDSolve[{eomu == 0, ϕ[numh] == ϕhnum[numh], ϕ'[         numh] == ϕhnum'[numh]}, ϕ, {u, numb, numh}];          FindRoot[ϕsol[ω][numb], {ω, 1.0 - 1.0 I}]      When I do this I get the following error               FindRoot::lstol: The line search decreased the step size to within tolerance specified          by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the      merit function. You may need more than MachinePrecision digits of working precision to      meet these tolerances. >>      I know that for the first solution I expect something like $\omega = 1.95- 1.27 I$. Hopefully this clarifies the problem, and thanks again for any help.


Convert spectral distribution to RGB color

Presume I have a spectrum as a function of wavelength (an example being the blackbody spectrum): ![enter image description here](http://i.stack.imgur.com/wG9zg.jpg) I want to convert that to a single RGB color to display on-screen, i.e. the "color" of that object as it would appear to the eye. From Googling I can see that there are ways to do this with a matrix transformation for a single wavelength, but I was hoping someone already had a solution coded up in Mathematica for an arbitrary input spectrum.


Interpolation function rejected by ParametricPlot3D

I was playing around with the bouncing ball example, and decided to make a 3d version. I decided to use `ParametricPlot3D` for a simple independent 3D presentation. However, I found that having an interpolating function as the the first element in the list of three functions passed to `ParametricPlot3D` doesn't work.               ballz = NDSolve[{z''[t] == -9.81, z[0] == 5, z'[0] == 0,     WhenEvent[z[t] == 0.2, z'[t] -> -0.9 z'[t]]}, z, {t, 0, 10}];          bally = NDSolve[{y''[t] == 0, y[0] == -2, y'[0] == 4,      WhenEvent[y[t] == 4.8, y'[t] -> -0.9 y'[t]],      WhenEvent[y[t] == -4.8, y'[t] -> -0.9 y'[t]]}, y, {t, 0, 10}];          Manipulate[       ParametricPlot3D[{t - 2, y[t] /. bally, z[t] /. ballz}, {t, 0, a},          PlotStyle -> {Gray, Dashed, Thick},          PlotRange -> {{-5, 5}, {-5, 5}, {0, 10}}],        {a, 0.025, 10, 0.025}]      The above code works fine, but when I substitute by an interpolation function for the `t - 2` term, the function doesn't work. Can this be fixed?


How to generate a unique file name similar as that created by CreateTemporary

CreateTemporary can generate a unique file name like > >     file = CreateTemporary[] >     (* "C:\Documents and Settings\kkouptsov\Local > \Settings\Temp\m-263a0380-3a03-49ac-95cb-d21390b2d3fd" *) >   How do we generate a unique file name such as above example? The reason I don't use CreateTemporary because I don't need to actually create the file, but only need the file path. I plan to generate many of these names in parallel, and they should be unique to each other.


How to simplify power series in terms of functions

For example, after some computations mathematica outputs $$ \sum_{k=0}^{\infty} \frac{k g_k z^{k+4}}{(1-z)^3} $$ and we assume that $$G(z)= \sum_{k=0}^{\infty} g_k z^k $$ so the question is: how to force mathematica to simplify the first sum into the form $$ \frac{z^5}{(1-z)^3} G'(z) $$ **Edit** : In fact, the sequence `g[k]` and its generating function `G[z]` are unknown and I would keep them in a symbolic way. So the _Mathematica_ code could look like this:               G[z_] := Sum[g[k]*z^k, {k, 0, \[Infinity]}]     Some_function[Sum[k*g[k]*z^{k + 4}/(1 - z)^3, {k, 0, \[Infinity]}]]      > >     z^5/(1-z)^3 G'[z] >   I mean, after defining function `G[z]` (maybe it should be defined in some other way), one can use `Some_function` to transform some series into the formula that operates on the function `G[z]`. So the question is how to write such `Some_function`? I hope that clarify the problem.


Do any mainstream text editors support Wolfram Language syntax for highlighting?

Syntax Highlighting for Mathematica on a Blog There is the above, but I'm not terribly excited to install rogue packages. For example on github, I share lots of _Mathematica_ code. I see no way to highlight syntax. This may keep _Wolfram_ down in the way of becoming a more often used and more robust programming language. If the answer is, as I suspect, _"no"_ , perhaps a better question is _"why not?"_


Increase Size of InputForm in Manipulate

I would like to set a variable equal to a copy n' pasted list, all within the Manipulate[] environment:                Manipulate[list,{list,0}]      I would like to view and edit the elements of the list within the input field. The problem is the "white space" is not long enough to view the entire pasted list. How can I make the input field larger, as if I were entering in a paragraph of text?


FindRoot for numerical function and how to search more than one root

I have to find the first few zeros of function for which I have not the analitycal expression. The function is named `f` in the following code and it is the result of a combination of solution of differential equation. (I have attach its plot ). I tried with `FindRoots` and I tried to follow this post but I've not solved my problem...               ti = 0;     u = 8;     yi = 0;     zi = -.75;     zf = -.5;          sol = FullSimplify[DSolve[{y'[t] == 1/(2 zf) y[t] - u z[t],       z'[t] == -1 + 1/zf z[t] + u y[t], y[ti] == yi,       z[ti] == zi}, {y[t], z[t]}, t]];          {{ysol[t_], zsol[t_]}} = Simplify[{y[t], z[t]} /. sol,       Assumptions -> Element[u, Reals] && Element[zi, Reals] && t > 0];          {{Gy[t_], Gz[t_]}} = {-z[t], y[t]} /. sol;          soladj = DSolve[{vy'[t] == 1/(2 zf) vy[t] - u vz[t],       vz'[t] == -1 + 1/zf vz[t] + u vy[t], vy[T] == Gy[T],       vz[T] == Gz[T]}, {vy[t], vz[t]}, t];          {{VY[t_], VZ[t_]}} = {vy[t], vz[t]} /. soladj;          f[T0_?NumericQ] := ArcTan @@ First@RotationMatrix[{{VY[0], VZ[0]},      {Gy[0],Gz[0]}} /. T -> T0]          plotf = Plot[f[T0], {T0, 0, 4}, PlotRange -> Full, MaxRecursion ->15,      LabelStyle -> {FontSize -> 15}]      ![plotf](http://i.stack.imgur.com/dUcSI.jpg)


Why are some function names red?

I need to evaluate               Needs["GraphUtilities`"]      before I can use functions such as `GraphPath[]`. When I do so, some functions get colored red, but still work. Why does this happen and can I change this?


Is it possible to create iOS apps with Mathematica?

I am fairly new to Mathematica and don't have much experience with other programming languages, but I can already see that Mathematica and the Wolfram language are far easier to use than most others. With this in mind, I was wondering about the possibility of building apps for iPhone and iPod through Mathematica. Basically is it at all possible to use Mathematica to build apps? Even if it isn't possible to use Mathematica for iOS app development, what about using it to build programs for other platforms, like Windows, Macs, or browser programs? I've heard a bit about MathLink and Workbench but I don't really understand what they do or how to use them. Also i understand that the Wolfram Cloud will be launched soon but don't know what it will enable us to do. I would appreciate it if someone could give me a brief answer, or point me in the right direction.


How to find all possible correlations between n vectors

Given the Matrix               M = {{31.3, 31.2, 29.7, 29.7, 29.8, 29.2, 28.7, 28.3, 28.2, 28.2},        {31.7, 30.7, 30.7, 30.1, 30.2, 29.8, 29.2, 28.7, 28.5, 27.7},        {24.0, 24.2, 23.7, 23.7, 23.2, 23.1, 22.6, 22.2, 22.1, 21.7},        {23.2, 22.2, 22.2, 22.0, 22.2, 21.8, 19.5, 19.1, 19.1, 18.9}};      I want to get a list of all possible correlations between its vectors. With               x1 = Take[#, 2] & /@ Permutations[Range@Length@M];      And               x2 = Union@Cases[x1, {a_, b_} /; a < b];      I get the necessary permutation:               {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}      Finally, with               Correlation @@@ Partition[M[[Flatten@x2]], 2]      I get the desired result:               {0.923, 0.933, 0.893, 0.952, 0.946, 0.934}      I am, of course, not happy with this code and would wellcome any suggestion how one could write this succinctly.


Specify column width while exporting

I am trying to export a set of data into a file but I can not force mathematica to keep a certain width for each column. For example, when I export a table:               table={{10,2},{3,40}};     Export["file.dat",table, "Table", "FieldSeparators"->" ", Alignment->Right]      The result is:               10  2      2 40      Mathematica automatically determines column width such that the number with largest number of digits fits in. How can I export data with arbitrary space in each column to get:                10    2       2   40      such that `"FieldSeparators"->" "` is still the same but first column has space for three digits and the second one has space for 4 digits?


Programmatically copy code so that all output is commented out

**UPDATE: The final palette has a new homehere! Please test and provide feedback (usability, suggestions, bugs)** **A note to the readers and voters:** This is intended for community use, so please test the palettes in practice! I encourage all answerers to "steal" from each others, and come up with a solution that is the most pleasant / practical to use. * * * Sjoerd suggested that when we want to post input lines that alternate with output lines, instead of including the In/Out labels, we could simply comment out the output. Read his suggestion here:   * How should I include code samples in posts? I have seen several people use this style in the past few days. The only problem with it that it requires a lot of manual editing (too much work for my taste). How can we automate this process? **The challenge is:** Create a palette button that will copy the selection in the format suggested by Sjoerd. Two-dimensional expressions (i.e. things like $\int x^2 \; dx$) should be converted to plain text or input form. The notebook contents must not be modified/destroyed. An example (directly copied from Sjoerd's post):               In[108]:= D[Cos[x] Exp[x], x]     Out[108]= E^x Cos[x] - E^x Sin[x]      should be copied as               D[Cos[x] Exp[x], x]          (*       ===> E^x Cos[x] - E^x Sin[x]     *)      Let us ignore cells that are neither input nor output for now (text, headings, etc.) Can we create a tool that is good enough to be of practical use to the community?


Arnold's problem #8

The famous Arnold's problems (see http://www.math.upenn.edu/Arnold/Arnold- Trivium-1991.pdf ) are aimed at the strong graduate and postgraduate students of the top universities. I find it remarkable that a big part of the Arnold's problems can be solved with CASes. However, I have not seen any satisfactory solution of his problem #8: "How many maxima, minima, and saddle points does the function $ x^4+y^4+z^4+u^4+t^4 $ have on the surface $$ \{x+y+z+u+t=0,x^2+y^2+z^2+u^2+t^2=1,x^3+y^3+z^3+u^3+t^3=c\} ,$$ where $c$ is a real parameter?" Can it be solved with Mathematica?


How to use NDSolve to track equilibrium?

I am looking for an extension of `NDSolve` where integration runs until certain variables are settled at an equilibrium. Now I have a working solution in my sleeves but I would rather not show it yet, as I want answers to be unbiased and original, since I'm not convinced that my solution is optimal at all. Consider the following putative example (note that `EquilibriumNDSolve` is an undefined hypothetical function):               eqns = {        Derivative[1][a][t] == -a[t] - 0.2` a[t]^2 + 2.1` b[t],        Derivative[1][b][t] == a[t] + 0.1` a[t]^2 - 1.1` b[t],        a[0] == 0.5`,        b[0] == 0.5`        };          steps = {};          sol = EquilibriumNDSolve[eqns, {a, b}, {t, 0, 1000}, a + b,         EquilibriumThreshold -> 10^-5,         EquilibriumStepMonitor :> AppendTo[steps, t]        ];      This reads as: "numerically solve _eqns_ for _a_ and _b_ variables while _t_ goes from 0, until ( _a_ + _b_ ) is settled at an equilibrium. If no equilibrium is reached until _t_ = 1000", terminate. The solution should be a set of `{y.i -> InterpolatingFunction[...]}` (just like in case of `NDSolve`), and the result should be something like this:               Plot[Evaluate[{a[t], b[t]} /. sol], {t, 0, Last[steps]},       PlotStyle -> AbsoluteThickness[2], ImageSize -> 400,       GridLines -> {steps, {}}, GridLinesStyle -> {Dashed, GrayLevel[.7]}]      ![Mathematica graphics](http://i.stack.imgur.com/uyAsE.png) Vertical gridlines indicate positions where an equilibrium test was performed. The syntax and usage should vaguely work like this: > `EquilibriumNDSolve[eqns, {y1, y2, ...}, {t, t0, tmax}, z}]` numerically > solves the differential equation system _eqns_ for all variables $y_i$, with > independent variable _t_ running from $t_0$ to a maximum of $t_{max}$. > Iteration stops when variable _z_ settles at an equilibrium or no > equilibrium was found in the given range of _t_. Variable _z_ can be a > single variable, a list of variables, or any sensible combination of them, > e.g. $a+b$. `EquilibriumThreshold` should define a threshold value above which no equilibrium is registered. `EquilibriumStepMonitor` should work like `StepMonitor`: each time an equilibrium-test is performed, the _rhs_ of `EquilibriumStepMonitor :> func` is evaluated as well.


Template completion

In version 8, if one evaluates               test::usage="test[x,y]";      then types `test`, then `shift`-`cmd`-`k` (or `shift`-`ctrl`-`k`), a template appears with placeholders for `x` and `y`. In version 9, this does not work: if I evaluate the same thing, when I type `te`, I am offered the choice to select `test` from the dropdown menu, just like for the built-in functions. If I select `test` and then press `shift`-`cmd`, however, I do not get the template (whereas I do get a template for built-in functions if I do this). How do I get the frontend to show a template? # Note: This has been fixed as of 9.0.1


Color Change of Area under a curve

I am trying to set a graph to show the value of the equity of an investment based on whether the portfolio is invested or in cash. I tried using the `ColorFunction`, but was not successful. Here is the sample data.               colorCash = RGBColor[90/255, 180/255, 172/255];     colorInvested = RGBColor[216/255, 179/255, 101/255];     invested = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1,                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,                 0, 1, 0, 0, 0, 0};          period = {        {2005, 7, 1}, {2005, 8, 1}, {2005, 9, 1}, {2005, 10, 3}, {2005, 11, 1}, {2005, 12, 1},        {2006, 1, 3}, {2006, 2, 1}, {2006, 3, 1}, {2006, 4, 3}, {2006, 5, 1}, {2006, 6, 1},        {2006, 7, 3}, {2006, 8, 1}, {2006, 9, 1}, {2006, 10, 2}, {2006, 11, 1}, {2006, 12, 1},        {2007, 1, 3}, {2007, 2, 1}, {2007, 3, 1}, {2007, 4, 2}, {2007, 5, 1}, {2007, 6, 1},        {2007, 7, 2}, {2007, 8, 1}, {2007, 9, 4}, {2007, 10, 1}, {2007, 11, 1}, {2007, 12, 3},        {2008, 1, 2}, {2008, 2, 1}, {2008, 3, 3}, {2008, 4, 1}, {2008, 5, 1}, {2008, 6, 2},        {2008, 7, 1}, {2008, 8, 1}, {2008, 9, 2}, {2008, 10, 1}, {2008, 11, 3}, {2008, 12, 1},        {2009, 1, 2}, {2009, 2, 2}, {2009, 3, 2}, {2009, 4, 1}, {2009, 5, 1}, {2009, 6, 1},        {2009, 7, 1}, {2009, 8, 3}, {2009, 9, 1}, {2009, 10, 1}, {2009, 11, 2}, {2009, 12, 1},        {2010, 1, 4}, {2010, 2, 1}, {2010, 3, 1}, {2010, 4, 1}, {2010, 5, 3}, {2010, 6, 1},        {2010, 7, 1}, {2010, 8, 2}, {2010, 9, 1}, {2010, 10, 1}, {2010, 11, 1}, {2010, 12, 1},        {2011, 1, 3}, {2011, 2, 1}, {2011, 3, 1}, {2011, 4, 1}, {2011, 5, 2}, {2011, 6, 1},        {2011, 7, 1}, {2011, 8, 1}, {2011, 9, 1}, {2011, 10, 3}, {2011, 11, 1}, {2011, 12, 1},        {2012, 1, 3}, {2012, 2, 1}, {2012, 3, 1}, {2012, 4, 2}, {2012, 5, 1}, {2012, 6, 1}};          equity = {100, 100, 100, 107.60368663594471, 106.91244239631337, 113.13364055299542,               118.84792626728114, 130.6451612903226, 129.19354838709677, 133.8709677419355,               149.97695852534562, 147.99539170506912, 141.08294930875573, 145.52995391705065,        143.52534562211977, 137.02764976958522, 137.02764976958522, 137.02764976958522,        134.51650476681908, 137.964008923159, 141.4753557490608, 139.9005698998685,        142.77349003015175, 139.47495210278947, 136.77227909133777, 136.77227909133777,        138.2898921592307, 152.82155701480832, 163.44484849005894, 160.74224987600297,        171.42790901157795, 190.01347178823949, 199.95071899992203, 187.95533899753534,        180.13859223688132, 181.8017298455311, 190.01347178823949, 187.2692947339673,        187.2692947339673, 187.2692947339673, 187.2692947339673, 187.2692947339673,        187.2692947339673, 197.63707006655756, 200.49416055487052, 195.407673700677,        188.89264160232702, 208.22129164826242, 197.3556899427086, 202.0525735484958,        202.16079667305314, 213.9571172497998, 221.92233921721777, 250.29844247614417,        232.26846992489646, 229.34644556184912, 236.85713040612634, 235.8181884103762,        249.69239297862313, 257.3113009474577, 263.37179592266705, 249.97377310247217,        264.2375809191255, 276.85639724250774, 287.0510155758062, 293.1115105510154,        300.2542367717978, 281.0987437251542, 297.95990653118287, 302.7217240117045,        329.79914977594314, 323.8901671751141, 316.011523707342, 342.6127677235285,        384.66827392649884, 342.11494135056495, 362.2011532684015, 368.24000361869935,        328.9766540293077, 328.9766540293077, 319.22257687363395, 319.22257687363395,        319.22257687363395, 319.22257687363395};      The following charts show the value of the portfolio and whether I am an investor or not:               Column[{             DateListPlot[Transpose[{period, equity}], Filling -> Axis,                Joined -> True, ImageSize -> Large],              DateListPlot[Transpose[{period, invested}], Filling -> Axis,                ImageSize -> Large]     }]      This is what I tried to change the color, but it is not the correct thing to do as the period painted does not coincide with the investment period:               myColor = If[# == 1, colorInvested, colorCash] & /@ invested;          DateListPlot[Transpose[{period, equity}], Filling -> Axis,       Joined -> True, ColorFunction -> myColor, ImageSize -> Large]


Installing CRAN Packages

When I install `RLink`:               Needs["RLink`"]     InstallR[]      then evaluate the command               REvaluate["R.version.string"]      I see that it is running               {"R version 2.14.0 (2011-10-31)"}      a version which I did not intentionally install on my system. I believe that _Mathematica_ downloaded this itself. Now I wish to install packages. For example:               REvaluate["install.packages('LaplacesDemon')"]      yields               REvaluate::err:      General error in function RLink`Private`withRTemporaryVariables >>      Is it possible to install packages with _Mathematica_ 's version of R? Even a command line solution would be great. EDIT: It seems that the error above was an aberration. It stopped showing up after I restarted Mathematica. Following Sasha's advice, I tried to add a repository:               REvaluate["install.packages('LaplacesDemon', repos='http://cran.wustl.edu/')"]      and the error is equally as bad:               REvaluate::rerr: Failed to retrieve the value for variable or piece of code     install.packages('LaplacesDemon', repos='http://cran.wustl.edu/'.      The following R error was encountered: Error in typeof(myRandomVar123456759046) :     object 'myRandomVar123456759046' not found >>      Similar errors for ggplot2, Zelig, etc. There appears to be a whole R tree in               $HomeDirectory/Library/Mathematica/Paclets/Repository/RLinkRuntime-MacOSX-x86-64-9.0.0.0/SystemFiles/MacOSX-x86-64/R/library      but the R version there doesn't seem to be usable.


Using a different R version with RLink

I wish to use a different version of R than what is provided by _Mathematica_ 9. For example, I want to use the Macports version of R, where `R_HOME` is `/opt/local/lib/R`. When I type:               Needs["RLink`"]     InstallR["RHomeLocation" -> "/opt/local/lib/R"]      I get the error:               InstallR::fail: Failed to install R.      The following error was encountered: Unable to load dynamic libraries >>      (I tried to doctor up my `~/.MacOSX/environment.plist` with `DYLD_LIBRARY_PATH`, but no luck.)


How to choose variables from a list for a function and then use the solution in a subsequent function?

I am trying to calculate heating degree days and cooling degree days and output that information to a table. I am using mathematica's curated data to do this. In text this is what I would like to do. Use a city name to collect weather data (the mean temp for every day of a certain year), then calculate the HDD and CDD and to create a cumulative value of hdd and cdd for the entire year. I want to use the city name to collect a value for country name, country gdp, and city population. I have used a demonstration project to try and figure this out but I am stuck at this point. I have the following already worked out.               Module[      {dateRange, mean, cdd, hdd, station, country, location, population,        GDPPerCapita,       reference = (65 - 32)/1.8, cumList},      station = "Chicago";      country = CityData[station, "Country"];      population = CityData[station, "Population"];      location = CityData[station, "Coordinates"];      GDPPerCapita = CountryData[country, "GDPPerCapita"];      dateRange = {{2011, 1, 1}, {2011, 12, 31}, "Day"};      mean = WeatherData[station, "MeanTemperature", dateRange];      cdd = Join[Transpose[{mean[[All, 1]]}],         Transpose[{Max[# - reference, 0] & /@ mean[[All, 2]]}], 2];      hdd = Join[Transpose[{mean[[All, 1]]}],         Transpose[{Max[reference - #, 0] & /@ mean[[All, 2]]}], 2];      cumList = Transpose[{Join[          Transpose[{cdd[[All, 1]]}],          Transpose[{Drop[FoldList[Plus, 0, cdd[[All, 2]] + hdd[[All, 2]]],              1]}],          2]}];      Grid[station, country, location, population, GDPPerCapita,        Last[cumList]]]      In this particular example I used a set city name ie station = "Chicago". When I do this it returns the correct result for that specific city, in a grid in this case..               Grid["Chicago", "UnitedStates", {41.8376, -87.6818}, 2695598,        45230.2, {{{2011, 12, 31}, 3935.4}}]      I want the variables to be chosen from a list of cities....               cityLIST = CityData[#, "Name"] & /@ CityData[];      So basically I want to run this or something like it for every string in a list, and output the results to a table. I am new to mathematica, this is the first thing I have ever tried. If anyone has a minute to help me out with this I would really appreciate it. Thanks


Symbol not added to context

I have run into a problem that is currently stumping me. I'm running a WebMathematica server, and am trying to create a package to use on one of the pages. However, when I load the package, it appears to only load some of the public functions, and loads the rest of the public functions as belonging to the Private page, and the functions in the Private functions that are not revealed don't seem to be loaded at all. I'm including the entirety of the code here, because I honestly can't tell where my mistake could be... (I should note that this is running on Mathematica 5.2)               BeginPackage["UtilitiesTest`"]          revToIrrev::usage = "Takes a reaction string,          and if it is a reversible reaction returns a list         in the form {forward, backward}         Otherwise, it returns the reaction.";          getSpecies::usage = "Takes a reaction and         returns a list containing every species within that reaction.";          isValidRxnStr::usage = "Takes a reaction and         returns true if the reaction is correctly formatted.";          replaceWithVars::usage ="test";          getRxnSide::usage = "Test2";          generateVars::usage = "Generates a list of {species, variable}          pairs.";          Begin["`Private`"]               generateVars[specs_] := Module[{specList = specs},         specList = specList /. spec_ -> {spec, "Elem"};         Return[Table[{specList[[1]], Append[specList[[2]], i]}, {i, specList//Length}]];         ];          replaceWithVars[exprStr_, vars_] := Module[{repExpr = exprStr, varList = vars, repRules},         repRules = Table[{varList[[i,1]]->varList[[i,2]]}, {i, varList//Length}];         Return[StringReplace[repExpr, repRules]];          ];          replaceVars[expr_, vars_] := Module[{repExprStr = expr, varList = vars, repRules},         repRules = Table[{varList[[i,2]]->varList[[i,1]]}, {1, varList//Length}];         Return[StringReplace[repExprStr, repRules]];         ];          revToIrrev[rxn_] := Module[{rxnParser},         rxnParser[react__ ~~ "" ~~ prod__] := Module[{},                     Return[{react  ">"  prod, prod  ">"  react}];];         rxnParser[react__] := Module[{}, Return[react]];         Return[{rxnParser[rxn]}];         ];          getIrrevRxnList[rxns_, seperator_:"|"] := Module[{splitRxns},         splitRxns = StringSplit[rxns, seperator];         Return[Flatten[Map[revToIrrev, splitRxns]]];         ];          getSpecies[rxn_] := Return[Union[getReactants[rxn], getProducts[rxn]]];           getRxnSide[front__ ~~ "" ~~ back__, "front"] := Return[front];     getRxnSide[front__ ~~ "" ~~ back__, "back"] := Return[back];     getRxnSide[Except[__ ~~ "" ~~ __, front__ ~~ ">" ~~ back__], "front"] := Return[front];     getRxnSide[Except[__ ~~ "" ~~ __, front__ ~~ ">" ~~ back__], "back"] := Return[back];          getSumSpeciesWithCoeffs[sum_] := Return[StringSplit[sum, "+"]];          getSpeciesWithCoeffs[rxn_, type_] := Module[{rxnString = rxn, specString, specs},         specString = getRxnSide[rxnString, type];         specs = getSumSpeciesWithCoeffs[specString];              Return[specs];         ];          splitCoeff[coeff:(NumberString||"") ~~ spec:(LetterCharacter ~~ WordCharacter...)] :=         If[coeff === "", Return[{1, spec}], Return[{ToExpression[coeff], spec}]];          getReactantsWithCoeffs[rxn_] := Return[Map[splitCoeff, getSpeciesWithCoeffs[rxn, "front"]]];          getProductsWithCoeffs[rxn_] := Return[Map[splitCoeff, getSpeciesWithCoeffs[rxn, "back"]]];          getReactants[rxn_] := Return[Map[getSpec, getSpeciesWithCoeffs[rxn, "front"]]];           getProducts[rxn_] := Return[Map[getSpec, getSpeciesWithCoeffs[rxn, "back"]]];          getSpecPattern[] := Return[NumberString|"" ~~ LetterCharacter ~~  WordCharacter...];     getSpecPattern[spec_] := Return[NumberString ~~ spec];     getSpec[specStr_] := Module[{spec},         specStr /. ((NumberString|"") ~~ spec: (LetterCharacter ~~ WordCharacter...)) -> spec;              Return[spec];         ];           getSidePattern[spec_:getSpecPattern[]] := Module[{speciesPat, sidePat},         speciesPat = getSpecPattern[];         sidePat = (speciesPat ~~ "+")...~~ getSpecPattern[spec] ~~("+" ~~ speciesPat)...;                 Return[sidePat[]];         ];          isValidRxnStr[rxn_] := Module[{sidePat, posPat},         sidePat = getSidePattern[];         posPat = sidePat ~~ (""|">") ~~ sidePat;               Return[StringMatchQ[rxn, posPat]];         ];            removeInvalidRxns[rxns_] := Module[{rxnList = rxns, goodPos},         goodPos = Position[rxnList, {_?isValidRxnStr,_NumberString,(_NumberString)|NULL}];         rxnList = Extract[rxnList, goodPos];               Return[rxnList];         ];          isReactant[rxn_, spec_] := Module[{fullPat},         fullPat = getSidePattern[spec] ~~ (""|">") ~~ getSidePattern[];              Return[StringMatchQ[rxn, fullPat]];         ];          isProduct[rxn_, spec_] := Module[{fullPat},         fullPat = getSidePattern[] ~~ (""|">") ~~ getSidePattern[spec];              Return[StringMatchQ[rxn, fullPat]];         ];                decomposeRxnInfo[rxns_] := Module[{rxnList = rxns, parseRxn},          rxnList = removeInvalidRxns[rxnList];         rxnList = Flatten[Map[revToIrrev, rxnList]];              Return[NULL];            ];      End[]     EndPackage[]                In the webMathematica page I have the following (The msp:evaluate tags seem to get hidden, but each line is enclosed by them:                    Needs["UtilitiesTest`"]                    ?UtilitiesTest`*           The output from loading this page is               General KernelData0::      getSpecies     isValidRxnStr     revToIrrev      If I change ?UtilitiesTest to ?UtilitiesTest`Private The output is               General KernelData0::      UtilitiesTest`Private`generateVars


Changing BarLegend border style

I want all the lines in my plot to be a consistent style, let's say thick and black for the purpose of this question.               ContourPlot[y - x^2, {x, 0, 1}, {y, 0, 1},      ContourStyle -> Directive[Thick, Black, Opacity[1]],       FrameStyle -> Directive[Thick, Black],      PlotLegends -> BarLegend[Automatic]]      ![enter image description here](http://i.stack.imgur.com/h0YqV.png) However, the border of the legend bar is thin and grey. How do I change its style to match? I couldn't find any relevant options in the `BarLegend` documentation.


EstimatedProcess hangs with documentation example

Not sure if this is a bug or a typo but for the first example of the `ARMAProcess` in _Mathematica_ 9 we have:               data = Select[WeatherData["Champaign", "Temperature", {2012, 8}],                    FreeQ[#, Missing] &][[All, 2]];     temp = TemporalData[data]     eproc = EstimatedProcess[temp, ARMAProcess[3, 3]]      `EstimatedProcess` hangs, whereas if I just send the data (with `RLink`!) to R's `arima` solver (with `order=c(3,0,3)` so it is an ARMA model), it solves instantly, and all further analysis looks the same as the example, so it isn't given a bad solution or anything. Is there something wrong with the documentation (reminds me of the issues of trying to do optimization without using `?NumericQ` variables). Any thoughts? Really want to use this feature...


Why DateDifference returns machine number?

Is there any specific reason why `DateDifference` cannot give an exact number in this case?               DateDifference["Jan 2, 2013", "Jan 8, 2013", "Week"]      > 0.857143 Also, I'd like to know how the various `DayCountConvention` settings interact with the calculation, in particular for "Week", "Month", etc.


Drawing an implicit function using ListPlot with a constraint on the solution

I need to plot a complex implicit function, `ContourPlot` in this case is not very convenient for me. Therefore, I want to plot my function using discrete points. I think this simple approach is convenient, both for me to understand and for those who I want to help. So let's plot the unit circle using `ListPlot`. I can do it in this way (I'm sure there is much simpler way):               y[x_] := y /. FindRoot[x^2 + y^2 == 1, {y, 0.01}]     data = Table[{x, y[x]}, {x, -1, 1, 0.1}]     y2[x_] := y2 /. FindRoot[x^2 + y2^2 == 1, {y2, -0.01}]     data2 = Table[{x, y2[x]}, {x, -1, 1, 0.1}]     ListPlot[{data, data2}, PlotStyle -> {Black, Black}, AspectRatio -> 1]      Now I want to set constraint on the solution of y, say `y < 0.5`. How could I do this by using `Select`?


Display Log with desired notation in output

I wish to display logarithms with different bases in the single-term rather than numerator/denominator form during output:               Log[17]/Log[2]   ->  Log2[17]     Log[13]/Log[10]  ->  Log10[13]     Log[99]/Log[11]  ->  Log[11, 99]      What is the best way to apply formatting rules like this?


Check every list element for appearance

I'm used to _MATLAB_ so this might be a stupid question but _Mathematica_ is freaking me out. I have a big matrix with the following format:               M = {{A,B,C},{1,{1,3,6,7},0},{1,{3,7,9},1}}      As you can see, each element in the second column is a separate list again. These separate lists contain integers, so it's no problem to get back to them. For example if I use `MemberQ[M[[2,2]],1]` it returns `True`, as it's supposed to do. What I want to do now: my Matrix is a little longer, contains approx. 5'000 rows. I want to check every seperate list mentioned above for the appearance of a specific integer, as I did above with the `MemberQ`. As a result it should give me something like the following (taking `M` as example): `{True,False}`. I thought that's supposed to be easy with a for-loop as it is in _MATLAB_ , but _Mathematica_ always stops when condition is not met... Looking forward to your answers. Please state if I need to clarify my question!


Differences between 'Solve' and 'LinearSolve'

Using the function 'Solve' I can do the following: Solve[a x + y == 7 && b x - y == 1, {x, y}] I get the following output: ![enter image description here](http://i.stack.imgur.com/n5myu.jpg) I want to get the same output using 'LinearSolve' instead. How is this possible and also what's the difference between the two?


Cannot find the maximum value of a function

Consider the following function: $a Sin(x)+b Cos(x)$ I tried to obtain the maximum value of this function using `MaxValue[]`:               MaxValue[a Sin[x] + b Cos[x], x, Reals]      I expect _Mathematica_ to return the following answer: $\sqrt{a^2+b^2}$ But _Mathematica_ cannot find the answer. Why does this happen?


Strange behavior of DateList when converting string

DateList experiences some strange behavior which i cannot explain. This code works fine:               DateList[{"2012September1211:45:26", {"Year", "MonthName", "Day",         "Hour", ":", "Minute", ":", "Second"}}]      Returning               {2012, 9, 12, 11, 45, 26.}      But this code doesn't work:               DateList[{"2012October1211:45:26", {"Year", "MonthName", "Day",         "Hour", ":", "Minute", ":", "Second"}}]      Returning this error message: > DateString::str: String 2012October1211:45:26 cannot be interpreted as a > date in format {Year,MonthName,Day,Hour,:,Minute,:,Second}. >> The only thing i changed is the month from september to october. Really frustrating, i'm already staring at it for 2 hours... **Question: What am i doing wrong?**


Smooth Peter de Jong attractor

Today I was playing with Peter de Jong attractor. At the bottom of the page I've linked there are beautiful examples like: ![enter image description here](http://i.stack.imgur.com/R4Eg6.jpg) My attempts are not so great: ![enter image description here](http://i.stack.imgur.com/sX0Fa.png) **It is around 10^5 points. For more than 5*10^5 my 4GB RAM gives up. How can I achieve such smooth result on standard/oldish pc?** * * * Here is the piece of code to play with: Points generator:               fr2 = Compile[{{p, _Real, 1}, {n, _Integer}, {a, _Real, 1}, {b, _Real, 1},                    {c, _Real, 1}},        NestList[         { Sin[a[[1]] #[[2]]] - Cos[a[[2]] #[[1]]],           Sin[b[[1]] #[[1]]] - Cos[b[[2]] #[[2]]],           Sin[c[[1]] #[[1]]] - Cos[c[[2]] #[[1]]]           } &, p, n]];      Interactive toy: For printed color image I've used approach introduced by Szabolcs in antialiasing3D.               DynamicModule[{a, b, c, n, type, fig, controls, print},      Deploy@Dynamic[Refresh[         Panel@Grid[{{fig, controls}}, Spacings -> 2],         None]],           Initialization :> (        type = 1;        n = 100000;        {a, b, c} = {{1.4, -2.3}, {2.4, -2.1}, {2.41, 1.64}};             controls = Column[{           Slider2D[Dynamic@a, {-Pi, Pi, .01}], Dynamic@a,           Slider2D[Dynamic@b, {-Pi, Pi, .01}], Dynamic@b,           Slider2D[Dynamic@c, {-Pi, Pi, .01}], Dynamic@c,           Button["Print", print[], Method -> "Queued"] }];             fig = Graphics[{White, AbsolutePointSize@1,            Dynamic[            Point@fr2[{.0, .0, .0}, ControlActive[2 10^4, 10^5], a, b, c][[All , ;; 2]]]           }, ImageSize -> {1, 1} 500, Background -> Black, AspectRatio -> Automatic];             print[] := With[{t = 3, pointsize = 1, pts = 10^5, res = 72},          Composition[            CreateDocument,            ImageResize[Rasterize[#, "Image", ImageResolution -> t res], Scaled[1/t]] &,            Graphics[{AbsolutePointSize@pointsize,                Riffle[Hue@Rescale[#, {-2, 2}, {0, 1}] & /@ #[[;; , 3]],                   Point /@ #[[;; , ;; 2]]] &@#               }, ImageSize -> 800, Background -> Black] &            ][fr2[{.0, .0, .0}, pts, a, b, c]]];        )]      ![enter image description here](http://i.stack.imgur.com/RG401.png)


Writing intelligent replacement rules for symbols

I am learning about quaternions right now, and I wanted to play around with some concepts I am learning. e.g. take rotation of a point about an axis with specified angle.               th = 3.4;     v  = Sqrt[1/3.0]*(i + j + k)     q    = Cos[th] + Sin[th]*v;     qinv =  Cos[th] - Sin[th]*v;          p = 2*i + 3*j + 4*k;          r = q * p *qinv // Expand     r = r//.{ i*i->-1, j*j->-1,k*k->-1,                i*j->k , j*i->-k,                j*k->i,  k*j->-i,                k*i->j,  i*k->-j}      Here I want to rotate the point _p_ in three dimensions by the angle _th_ with the axis given by the unit vector _v_. So for that I basically just need to use replacement rules like did above. The result I get is               0.391808 + 2.26121 i - 0.0435342 i^3 + 3.1959 j - 0.0653013 j^3 +       4.1306 k - 0.0870683 k^3      How do I tell Mathematica to replace **'i^3'** etc. by **'-i'**? I would have thought Mathematica would be smart enough to use my 'i^2=-1' rule to figure this out. Generalizing this question, if I am manipulating symbols (not just quaternions) how do I specify replacements so that the final answer is as 'simple' as possible?


How to create a rectangle wave (duty cycle $\ne$ 50 %)?

I'm trying to use phase-shifted `SquareWave[]` functions to create a rectangle wave:               SquareWave[{0, 1}, x/100] * SquareWave[{0, 1}, x/100 - offsetx]      Two things:   1. This only allows for duty cycles less than 50 %.    2. While it's handy (it's always the phase shift $0\dots 1$, regardless of horizontal scale), I'm confused that `offsetx` isn't a function of the `x` scaling Is there a general function to create rectangle waves with duty cycles from 0 % to 100 %?


Accept Infinity as an Integer argument

I have the following function, albeit contrived:               Foo[x_Integer] :=       Module[{i},        i = 1;        While[i <= x && i <= 10, i++];        i - 1        ];      I am looking for the following               Foo[1] = 1     .     .     .     Foo[10] = 10     Foo[11] = 10     Foo[Infinity] = 10      However `Foo[Infinity]` returns `Foo[\\[Infinity]]` and not `10` . Is there an something that I can do, short of: `Foo[Infinity] = 10;` to get `Foo[Infinity]` to return `10` ? The problem is `i <= 10` is static in my contrived example, but will be dynamic in practice.


How do I solve N simultaneous equations for N variables?

I have a function:               f[x_] := x + 31 x^3 + 5 x^25      Which I want to find an expansion for:               ex[x_, a_, b_, c_, d_] := a + b x + c x^3 + d x^25      I do this by solving to find the coefficients a,b,c,d by setting the expansion equal to the function at the appropriate number of points:               sol = Solve[{ex[1, a, b, c, d] == f[1], ex[3, a, b, c, d] == f[3],      ex[2, a, b, c, d] == f[2], ex[4, a, b, c, d] == f[4]}]      This works fine, but its ugly. I've only used this to illustrate what I want to do... but actually I want to find an expansion involving 'N' expansion coefficients, and perform solve at N different points to find what they are. However, I don't understand how to do that without having functions with N+1 arguments and so on. If I haven't expressed myself clearly let me know and I'll add more. EDIT: Perhaps I'll add that really the expansion I'm looking for is something like (though how I put the coefficients into the function argument I don't know):               ex[x_,a[i]_,b[i]_,N_,M_]:= Sum[a[n] ChebyshevT[n,x],{n,0,N}] + Sum[b[n] * y[n,x],{n,1,M}]      Where the functions y[n,x] are some other functions which is not orthogonal to the Chebyshev polynomials.


My donut has holes in it!

More than one hole, I mean… I’m trying to export from Mathematica into the X3D format, with the longer term goal of generating 3D figures for PDF inclusion. But I'm stuck at the first step:               p = ParametricPlot3D[{(2 + Cos[v]) Sin[u], (2 + Cos[v]) Cos[u],          Sin[v]}, {u, 0, 2 Pi}, {v, 0, 2 Pi}, PlotStyle -> Red];     Export["test.x3d", p];      The donut thus generated has holes in it (as visualized here with FreeWRL): ![enter image description here](http://i.stack.imgur.com/ccppQ.png) ![enter image description here](http://i.stack.imgur.com/y5RE6.png) and the same is true for every 3D surface I've tried to export. MeshLab complains that the file contains “4 degenerated faces”, but I doubt it's the same issue, as there are a lot more than 4 holes! I am not a 3D format expert, so I don't really know where to go. Exporting to VRML gives the same issue, so I suspect something generic is going on, but I don't really know how to investigate. I tried importing back the files into Mathematica, but 3D graphics formats are apparently write-only. So, how do you advise me to tackle the issue? Do you have any experience in this kind of export?


Printing exported PDF graphics fails (version 8)

When I export even simple graphics, say, a `DateListPlot` to PDF under Windows, it refuses to print on any of the printers at work.   ![enter image description here](http://i.stack.imgur.com/f3RGx.png) Acrobat (Reader X) throws three modal dialogs in succession: "The document could not be printed", "There were no pages selected to print" and (sometimes) "There was a drawing error". Strangely, simple graphics (i.e. not a `GraphicsGrid`) will print correctly if you choose "Save Selection As..." or right-click and choose "Save Graphics As..." and save as a PDF. However PDFs produced using the `Export` command, or by saving some more complex `Grid`s of graphics, have this printing issue. I cannot see anything different in the properties of the PDFs produced with `Export` that might cause them not to print, when those produced using the various versions of "Save As..." do print. There is a work-around, which is to go into the Advanced tab of the print dialog and choose "Print as image". Since the intention is that colleagues will be running notebooks that automatically update and export PDF-format graphics, I am reluctant to use this work-around. People will forget what to do and blame me. I have already had problems sending graphics to colleagues that they then can't print. Other than manually exporting things all the time using "Save Selection As" and educating people on print settings, is there anything I can do to avoid printing errors? System: Windows XP, Mathematica 8.0.4. We're going to Windows 7 very soon, so maybe that will help. **EDIT**   I have now uploaded:   1. The file that does not print (produced using `Export`)   2. The file that does print As you can see, they look identical but there are about 100 extra bytes in the `Export`ed version. **EDIT 2** This bug seems to have been fixed in version 9.


Generate list of strings from a list of assigned variables

How do I generate a list of strings from a list of assigned variables? Eg. Convert               var1 = 10;     var2 = 11;     var3 = 17;     var4 = 5;          compvar = {var1, var2, var3, var4}; (*all variables assigned*)      into,               compvarstr = {"var1", "var2", "var3", "var4"};      Using `ToString` obviously converts the variables assignments into strings e.g.               compvarstr = ToString[#] & /@ compvar      gives, > {"10", "11", "17", "5"} i'm after the unassigned variable names as strings e.g. > {"var1", "var2", "var3", "var4"}; Apologies if this is a duplicate - I had a bit of a look and nothing seemed to answer it.


Devising a sparse array rule

Suppose I have a matrix               A={{1, 2}, {3, 4}}      that defines the positions of non-zero values in a sparse array:               S=SparseArray[Table[p1 = A[[i, 1]]; p2 = A[[i, 2]]; {p1, p2} -> 77, {i, Dimensions[A][[1]]}]];     ArrayRules@S     {{1, 2} -> 77, {3, 4} -> 77, {_, _} -> 0}      Is it possible to construct such a sparse array without explicitly building the table of correspondence, by using a single rule that extracts the positions of non-zero elements from matrix A? Mathematica documentation shows examples of such rules, e.g.               SparseArray[{{i_, j_} /; Abs[i - j] <= 1 -> -2 + 3 Abs[i - j]}, {5,5}]      How should a similar rule be devised for my case? Thank you!


Stationarity tests

I have the Time Series package and Mathematica 8. In the package, there is the function 'StationaryQ' to test the stationarity of a known model. Is there any function in Mathematica to test the stationarity of a given list of data?


Plotting Time Series with call to Wolfram Alpha

I am trying to plot stocks showing some of the local maxima. As an exercise I first tried to load Apple's stock data from Wolfram Alpha with the following code:               appledata =TimeSeries[WolframAlpha["AAPL", {{"History", 1}, "ComputableData"}][[1]]];       Show[DateListPlot[appledata],DateListPlot[FindPeaks[TimeSeriesResample[appledata], 12],        Joined -> False,PlotStyle -> Directive[PointSize[0.03], Red]]]       However, I am returning the following errors:               DateListPlot::ldata: TimeSeries[NotAvailable] is not a valid dataset or list of datasets. >>     FindPeaks::arg: The argument TimeSeriesResample[TimeSeries[NotAvailable]] at position 1 is not a consistent list of real values. >>     DateListPlot::ldata: FindPeaks[TimeSeriesResample[TimeSeries[NotAvailable]],12] is not a valid dataset or list of datasets. >>     Show::gcomb: Could not combine the graphics objects in Show[DateListPlot[TimeSeries[NotAvailable]],DateListPlot[FindPeaks[TimeSeriesResample[TimeSeries[NotAvailable]],12],Joined->False,PlotStyle->Directive[PointSize[0.03],\!\(\*GraphicsBox[{{GrayLevel[0], RectangleBox[{0, 0}]},{GrayLevel[0], RectangleBox[{1, -1}]},{RGBColor[1, 0, 0], RectangleBox[{0, -1}, {2, 1}]}},AspectRatio->1,Frame->True,FrameStyle-RGBColor[0.6666666666666666, 0., 0.],FrameTicks->None,ImageSize->{Automatic, 10.8},PlotRangePadding->None]\)]]]. >>      I'd like to move beyond just searching stocks such as Apple and be able to search tickers, maybe something like https://www.google.com/webhp?sourceid=chrome- instant&rlz=1C1LENP_enUS562US562&ion=1&espv=2&ie=UTF-8#q=ugaz&safe=off


Generating $n$ random samples every time

Is it possible to generate $n$ random samples, and always ensure that $n$ samples are generated? eg For $n=5$:               n=5; {n1, n2, n3, n4, n5} = (While[Total[set = Reverse@Sort@Round     [(tmp = RandomInteger[100, n])/Total@tmp 100]] != 100]; set);     s = Reverse[Sort[{n1, n2, n3, n4, n5}]];     a = rs[[1]]; b = s[[2]]; c = s[[3]]; d = s[[4]]; e = s[[5]];     PieChart[{a, b, c, d, e}, ImageSize -> 200,      ChartLabels -> {Style[StringForm["A:``%", a], 10],      Style[StringForm["B:``%", b], 10],      Style[StringForm["C:``%", c], 10],      Style[StringForm["D:``%", d], 10],      Style[StringForm["E:``%", e], 10]}]      is ok, but for large enough $n$ the numbers are often "used up" before the last few get a chance to sample (so, in the example of the above pie chart, "E" often doesn't feature). Is it possible to avoid the samples reaching $0$ before last $n$ is reached? (Obviously, by the time $n=100$, each sample should have value of $1$.)


Calculating average distance

I have a program that gives the average distance as the output. When I tried to repeat finding the average distance 100 times using Table, It failed to generate the output. This is the program.               Xarray = A @@@ Tuples[Range[0, 4], 3];     Table[M = RandomSample[Xarray, 7];     energies = RandomVariate[ExponentialDistribution[1.5], {7}];     f = {#, First@Pick[energies, M, #]} &;     list = Map[f, M]     c = Subsets[Range[Length@list], {2}];     d = Length@%          distanceBetween[{n_, m_}] :=        Norm[List @@ list[[n, 1]] - List @@ list[[m, 1]]]          Map[distanceBetween, c]     ans = % // N;          Total[%/d], {i, 100}]      The program is like this. I created an array of let say 500 elements and assigned energy to it. Next I choose a coordinate from the list and find the distance from other coordinates using the norm equation. Next I sum up that distances in the list and take the average of the distance. The Problem comes when I am trying to do this process 100 times using Table or Do command.


Memory Leak in RowReduce?

Recently I tried to do what I thought was a fairly small (relative to the 6 GB of RAM that I have on my machine) row reduction calculation on a matrix representing an undetermined linear system and was very surprised by how much trouble I had with it. The 2590 X 12155 matrix, `A` (available for download via Mediafire), takes a little over 17 MB to store, has rational entries, and is very sparse (~3% of the entries non-zero). The data structure I used to store `A` is _Mathematica_ 's rule-based representation for sparse arrays on a row-by-row basis (if this is unclear please see the example matrix from my last post). Curiously, I find that using `RowReduce` to find a row echelon form for `A` leaves a huge memory footprint well beyond what _Mathematica_ reports with `MemoryInUse`. I was able to observe this effect without leaving _Mathematica_ in an (to me miraculous) allegedly platform-independent way by using the answer that @WReach gave here in response to a question about memory monitoring. I began with               In[1] := $HistoryLength = 0;      to turn off caching and then set up a pair of commands which give respectively my machine's and _Mathematica_ 's estimates of how much memory is currently in use using the ideas of @WReach:               In[2] := Needs["JLink`"]              InstallJava[];              LoadJavaClass["java.lang.management.ManagementFactory"];          In[5] := temp = JavaBlock[{#,java`lang`management`ManagementFactory              `getOperatingSystemMXBean[]              @#[]} & /@ {getFreePhysicalMemorySize,               getTotalPhysicalMemorySize}]; memstart1 =               temp[[2, 2]] - temp[[1, 2]]          Out[5] := 3096420352          In[6] := memstart2 = MemoryInUse[]          Out[6] := 18286664          In[7] := temp = JavaBlock[{#,               java`lang`management`ManagementFactory`getOperatingSystemMXBean[]              @#[]} & /@ {getFreePhysicalMemorySize,               getTotalPhysicalMemorySize}]; memnow1 =               temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[7] := 94208          In[8] := memnow2 = MemoryInUse[] - memstart2          Out[8] := 1808      I've found that copying and running the preceding two lines of code wherever I want a memory sanity-check seems to give a fairly consistent way to compare how much memory _Mathematica_ has actually used since the start of the session and how much memory _Mathematica thinks_ it has used since the start of the session (the numbers 94208 and 1808 from the initialization above should be thought of as being effectively zero). Although it is probably obvious, I have of course assumed that the amount of RAM used by all other programs is constant throughout the session (which should be approximately correct if they are just running idly in the background). Now I read in the file containing the matrix and assign it to `A`:               In[9] :=  f = OpenRead["rrdemo"];               A = Read[f];               Close[f];      I also go ahead and define an array that will be used momentarily (recall that 12155 is the number of columns in `A`)               In[12] := W = Array[w, 12155];      Actually, although it's a bit off-topic, it's worth pointing out that there already seems to be some missing memory associated with the process of reading in the file `"rrdemo"` (in a separate session I checked that there is no missing memory associated with the definition of `W`):               In[13] := temp = JavaBlock[{#,                java`lang`management`ManagementFactory`getOperatingSystemMXBean[]               @#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[13] := 425725952          In[14] := memnow2 = MemoryInUse[] - memstart2          Out[14] := 268374384      This is actually nothing at all compared to what happens with `RowReduce`. To obtain a row echelon form for my matrix I use `RowReduce` in a straightforward way on a sparse array. To show that the problem is not with my generation of the sparse array, I first check the memory footprint of that step of the calculation:               In[15] := AbsoluteTiming[C1 = CoefficientArrays[Plus @@@ (#[[2]] w @@                #[[1]] & /@ # & /@ A), W][[2]];]          Out[15] := {5.447995, Null}          In[16] := temp = JavaBlock[{#,java`lang`management`ManagementFactory               `getOperatingSystemMXBean[]@#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[16] := 539504640          In[17] := memnow2 = MemoryInUse[] - memstart2          Out[17] := 385560664          In[18] := ByteCount[C1]          Out[18] := 100604400      The performance of _Mathematica_ here seems reasonable. The actual and reported memory usage go up from what they were before in proportion to the `ByteCount` of `C1`. Now look what happens if we `RowReduce` `C1`:               In[19] := AbsoluteTiming[C2 = Drop[ArrayRules[#], -1] & /@                RowReduce[C1, Method -> "OneStepRowReduction"];]          Out[19] := {402.172945, Null}          In[20] := temp = JavaBlock[{#,                java`lang`management`ManagementFactory`getOperatingSystemMXBean[]               @#[]} & /@ {getFreePhysicalMemorySize,                getTotalPhysicalMemorySize}]; memnow1 =                temp[[2, 2]] - temp[[1, 2]] - memstart1          Out[20] := 2461675520          In[21] := memnow2 = MemoryInUse[] - memstart2          Out[21] := 731499200          In[22] := ByteCount[C2]          Out[22] := 280479264      Something seems to be seriously wrong here. The `ByteCount` of `C2` is only ~ 280 Mb and this is close to the increase in the total memory usage reported by _Mathematica_. But the actual memory usage is ~3.3 times what _Mathematica_ thinks it is! I'm forced to conclude that _Mathematica_ fails to garbage collect more than 1.5 Gb of memory at the end of the calculation. In summary, I have a couple of related questions. Does anybody have any insights into the anomalous behavior of `RowReduce` that I just illustrated? Am I doing something wrong? More generally, does anybody have any idea as to whether or not _Mathematica_ has special algorithms for symbolic sparse linear algebra? Memory issues aside, it makes me suspicious that `RowReduce` takes so long to process `C1` (I have a 2.5 GHz processor) and that it returns a result that is no longer a sparse array. At this point I'm wondering whether _Mathematica_ is even the right tool for the job (symbolic linear algebra on large, very sparse undetermined linear systems). Any advice from more experienced users would be greatly appreciated. If it makes any difference, I'm using 64 bit Linux and am running _Mathematica_ v.8.0.4.


ListInterpolation causing .cdf security problems?

I've made a simple `.cdf` that makes a function from a list of data I've provided in table form (using `ListInterpolation`) and plots it on a graph (no importing, exporting or conversion of data from string) and I still get a grey block when I try to post it online, indicating that I'm violating some security rule. It works with the `{fullscreen: 'true'}` workaround, but I don't know what I'm doing that necessitates this. Advice? Thanks


Configuring Mathematica to send email from a notebook

I can't get my email settings set properly such that I can use `SendMail[]` to email directly from Mathematica. I have opened "Preferences", clicked on the tab "Internet Connectivity" and filled in all the settings to match those in my Apple Mail accounts settings. These include:   * Server   * Port Number   * Encryption Protocol   * Username   * From Address   * Full Name   * Reply To Odd that no setting exists for "Password"? The "Preference" window's "Test Internet Connectivity" tells me "Test succeeded..." Apple Mail has a setting to "Use default ports (25, 465, 587)" so I thought this might confuse the Mathematica settings, so I've tried setting the Apple Mail settings to "Use Custom Port" and specified each of the the default ports specifically. None of those settings worked either. I have also attempted to specify **all** available options for `SendMail[]` specifically also trying each of the 3 possible "default" ports described above.                SendMail[      "From" -> "myemail@myisp.com",      "To" -> "recipientemail@isp.com",      "Subject" -> "Example Message",      "Body" -> "Test",      "Server" -> "smtpout.secureserver.net",      "EncryptionProtocol" -> "SSL",      "FullName" -> "MyUserName",      "Password" -> "myPassword",      "PortNumber" -> 25 (* I also tried 465, 587 *),      "ReplyTo" -> None,      "ServerAuthentication" -> Automatic,      "UserName" -> "myUserName"      ]      Again `SendMail[]` gives me the same message: `$Failed`. Also, in the "Preferences" window under the "Proxy Settings" tab I have tried selecting both "User proxy settings from my system or browser" and "Direct connection to the Internet". The "Troubleshooting Internet Connectivity Problems - Wolfram Mathematica" in the "Document Center" suggests checking proxy settings. Given what mine look like in Snow Leopard's "Preferences" >> "Network" >> "Proxies" ![Proxies](http://i.stack.imgur.com/Nu6q4.png) I don't think I have much to help. I have no Firewall Setting on the computer. This has me stumped. Does anyone have an idea of what else I can try.


Splitting a list

Please consider the following list:               data={1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3};      Now I would like to split the list into 0-sequences and Not-0-sequences as following:               {{1}, {0, 0, 0}, {2, 5, 2, 3}, {0, 0}, {3}}      All numbers are non-negative `Integer`s, if that helps.


Defining symbol shortcuts in the Front End

I was wondering (because I could not find any documentation on this) if it is possible to do shorthand abbreviations for domains or could one define them? E.g. > In[1]:= Element[p,Complexes]   >  Out[1]= p $\in$ Complexes to instead do something of the following: > In[1]:= p `esc` elem `esc` `esc`CC `esc`   >  Out[1]= p$\in\mathbb{C}$ And similarly for others: $ \begin{align} \text{Algebraics}: &\text{esc AA esc} \,\mapsto\mathbb{A} \\ \text{Rationals}: &\text{esc QQ esc} \,\mapsto\mathbb{Q} \\ \text{Booleans}: &\text{esc BB esc} \,\mapsto\mathbb{B} \\ %%\text{Naturals}: &\text{esc NN esc} \,\mapsto\mathbb{N} \\ \text{Integers}: &\text{esc ZZ esc} \,\mapsto\mathbb{Z} \\ \text{Primes}: &\text{esc PP esc} \,\mapsto\mathbb{P} \\ \text{Reals}: &\text{esc RR esc} \,\mapsto\mathbb{R} \\ \end{align} $


TimeConstrained[] not taking full amount of time

I am using Mathematica to evaluate an integral within a given time constraint. Note that I have read in values of 'BigList' or `BL` from a file. If the file has a value for `(l,m)` of zero, then I evaluate the integral, otherwise, I read in the value of the integral from the file. The idea is to continually allow more and more time and 'knock out' the easiest integrals each time, instead of having the script run for hours before stopping when it would get to 'easier' integrals later. My problem is that, for the integrals which evaluate to zero, the output happens far too quickly. The integrals will ONLY evaluate to zero if the time constraint is met, these integrals will _never_ be zero on their own, so I know that if I get an output of zero, that it did not evaluate the integral in the time constraint allowed. The output, however, prints `(l) (m) 0` (where `(l)` and `(m)` are actual numerical values of l and m) almost within less than a second of each other. This tells me that it is not spending the full time (15 seconds in the example below) on the integral. Does Mathematica somehow know that it will take longer and give up or is something else going on? Shouldn't it work for 15 seconds before stopping and resulting in zero?               29 (* total time for each integral allowed *)     30 tt = 15;     31 (* loop through NeedList and assign values *)     32 (* Print["BLsize = ", BLsize]; *)     33 For[i=1, i<=BLsize, i++,     34   If[BL[[i]][[3]]==0,     35     l=BL[[i]][[1]];     36     m=BL[[i]][[2]];     37     (* Assign Jm to be Integrate[Abs[Sin[m*theta],{theta,0,2*pi}]] *)     38     If[m==0,Jm=2*Pi,Jm=4];     39     Ilm=TimeConstrained[Integrate[Abs[LegendreP[l,Abs[m],z]],{z,-1,1}],tt,0];     40     If[Ilm==0, BL[[i]]={l,m,0},     41       If[l==0, BL[[i]]={l,m,1/(Ilm*Jm)}, BL[[i]]={l,m,2/(Ilm*Jm)}];     42     ];     43     (*Print[FortranForm[N[BL[[i]][[3]]]]];*)     44     Print[BL[[i]][[1]], " ", BL[[i]][[2]], " ", FortranForm[N[BL[[i]][[3]]]]];     45   ]     46 ];      EDIT: here is a full working example ...               finp = OpenRead["dens_coefs"];     (* BigList *)     BL = ReadList[finp,{Number,Number,Number}]     Close[finp];     BLsize = Length[BL];          (* total time for each integral allowed *)     tt = 20;     (* loop through NeedList and assign values *)     For[i=1, i<=BLsize, i++,       If[BL[[i]][[3]]==0,         l=BL[[i]][[1]];         m=BL[[i]][[2]];         (* Assign Jm to be Integrate[Abs[Sin[m*theta],{theta,0,2*pi}]] *)         If[m==0,Jm=2*Pi,Jm=4];         Ilm=TimeConstrained[Integrate[Abs[LegendreP[l,Abs[m],z]],{z,-1,1}],tt,0];         If[Ilm==0, BL[[i]]={l,m,0},           If[l==0, BL[[i]]={l,m,1/(Ilm*Jm)}, BL[[i]]={l,m,2/(Ilm*Jm)}];         ];         Print[BL[[i]][[1]], " ", BL[[i]][[2]], " ", FortranForm[N[BL[[i]][[3]]]]];       ]     ];      an example of an input file might be:               3 -3 0.02829421210522584     3 -2 0.06666666666666667     3 -1 0.5706901657772195     3 0 0.     3 1 0.5706901657772195     3 2 0.06666666666666667     3 3 0.02829421210522584     4 -4 0.004464285714285714     4 -3 0.011904761904761904     4 -2 0.1361783763047951     4 -1 0.     4 0 0.     4 1 0.     4 2 0.1361783763047951     4 3 0.011904761904761904     4 4 0.004464285714285714      the program _should_ read these numbers in, figure out which ones are zero (in this case, {3,0}, {4,-1}, {4,0}, {4,1}) and attempt to produce the corresponding integrals. it should take no more than 20 seconds, but if it returns 'zero' then it should take AT LEAST 20 seconds (very close to 20 seconds, maybe a few clock cycles over). for what it is worth, i am running this from a command line script on a linux machine. i have tried `TimeConstrained` arguments in a Mathematica notebook (though not the _exact_ same thing) and it waits, as it should, in the notebook, but it is not waiting the full 20 seconds in the script. EDIT(2): for what it's worth, this seems to work as intended when running it from a notebook interface. it is only when running the script from command line that it gives me problems. any idea why that would happen?


Can't get DynamicModule[{..},..EventHandler[] ] working

This makes a slider to control the number of points. Click in the `Graphics` and the points slide over to where you click.               Manipulate[     DynamicModule[{points,oldPoints,centerG,oldCenterG,finalPnts,mousePosn},     points=Map[{10,12}+#&,Table[{Cos[2.0 Pi k/n],Sin[2.0 Pi k/n]},{k,1,n}]];     oldPoints=finalPnts=points;     oldCenterG=centerG=Mean/@Transpose[points];          Dynamic[EventHandler[Framed[Graphics[{PointSize[0.02],Point[     If[TrueQ[points==finalPnts],     oldCenterG=centerG;     oldPoints=points,     (* else *)     points=MapThread[     With[{mag=Norm[#2-#1]},If[TrueQ[mag<=0.02],#2,#1+0.04(#2-#1)/mag]]&,     {points,finalPnts}]     ]     ]},PlotRange->{{-15,15},{-15,15}},ImageSize->{600,600}]],     {"MouseDown":>(     mousePosn=MousePosition["Graphics"];     centerG=Mean/@Transpose[points];     finalPnts=Map[(#+mousePosn-oldCenterG)&,oldPoints]) ,     "MouseUp":>(centerG=mousePosn)     }]]      ],{{n,3},3,8,1}]      The problem is that my real application doesn't allow use of `Manipulate`. I thought the code below would work, but it breaks when you click in the `Graphics`. How to get the second version working?               DynamicModule[{points, oldPoints, centerG, oldCenterG, finalPnts,        mousePosn, n},           points =        Dynamic[Map[{10, 12} + # &,          Table[{Cos[2.0 Pi k/n], Sin[2.0 Pi k/n]}, {k, 1, n}]]];      oldPoints = finalPnts = points;      oldCenterG = centerG = Mean /@ Transpose[points];           Column[{        Slider[Dynamic[n], {3, 8, 1}],        Dynamic[EventHandler[Framed[Graphics[{PointSize[0.02], Point[              If[TrueQ[points == finalPnts],               oldCenterG = centerG;               oldPoints = points,               (* else *)               points = MapThread[                      With[{mag = Norm[#2 - #1]},                    If[TrueQ[mag <= 0.02], #2, #1 + 0.04 (#2 - #1)/mag]] &,                 {points, finalPnts}]               ]              ]}, PlotRange -> {{-15, 15}, {-15, 15}},             ImageSize -> {400, 400}]],          {"MouseDown" :> (             mousePosn = MousePosition["Graphics"];             centerG = Mean /@ Transpose[points];             finalPnts = Map[(# + mousePosn - oldCenterG) &, oldPoints]) ,           "MouseUp" :> (centerG = mousePosn)           }]]}]]


Turning evaluation off

I am making a directed graph, but Mathematica keeps trying to evaluate my labels. I know that I can just use " ", but I have a lot of input. Is there a way to turn evaluation off?               LayeredGraphPlot[{"C1.4.4" -> "T1.5.7", "1.23" -> "L1.5.4",        "P1.4.3" -> "C1.4.4", "P1.4.3" -> "C1.1.4", "P1.1.9" -> "P1.5.2",        "P1.1.9" -> "L1.5.3", "P1.5.2" -> "T1.5.7", "L1.5.3" -> "T1.5.7",        "L1.5.4" -> "T1.5.7", "P1.5.5" -> "T1.5.7", "L1.4.6" -> "L1.4.7"},       VertexLabeling -> True]


Precision problem while evaluating RegionMember or Element in V10

I'll try to give you a background on where the problem occured. The problem itself is defined near the end of the post. I'm running a sort of a simulation of a particle in a box. I finally got my hands on Mathematica10 so I decided to use new built-in mechanisms such as regions. Long story short: I need to determine the point at which the particle hits the bounding region. I defined my box by:               {X, Y, Z} = {.05, .05, .3};     ip1 = InfinitePlane[{{0, 0, 0}, {0, Y, 0}, {0, Y, Z}}];     ip2 = InfinitePlane[{{X, 0, 0}, {X, Y, 0}, {X, Y, Z}}];     ip3 = InfinitePlane[{{0, 0, 0}, {X, 0, 0}, {X, 0, Z}}];     ip4 = InfinitePlane[{{0, Y, 0}, {X, Y, 0}, {X, Y, Z}}];     ip5 = InfinitePlane[{{0, 0, 0}, {0, Y, 0}, {X, Y, 0}}];     ip6 = InfinitePlane[{{0, 0, Z}, {0, Y, Z}, {X, Y, Z}}];     reg = RegionIntersection[Cuboid[{0, 0, 0}, {X, Y, Z}], RegionUnion[ip1, ip2, ip3, ip4, ip5, ip6]];      I generate the initial position and velocity of the particle as random numbers, then draw a `HalfLine` from the position of particle along the velocity vector. Finally, I check the intersection of the `HalfLine` and the bounding region `reg` with `RegionIntersection`. Then I can extract the coordinates of the bouncing point and calculate the new velocity vector, define a new `HalfLine`, find the intersection, and so on... **The Problem** At some point, however, I get an error caused by the point not being a member (or element, both functions do the same in this case) of my bounding region (sounds ridiculously, because it's supposed to be the intersection of the region and the halfline). When I print the coordinates of that point, I get:               In: p1     Out: {0.0000316867, 0.00969779, 0.3}      So everything looks fine, but doesn't work. I checked it with `Manipulate` - I entered these coordinates manually and `RegionMember[reg,{0.0000316867, 0.00969779, 0.3}]` evaluated to `True`. Then I copied the coordinates of p1 from the output above and found out that they were in fact:               {0.00003168673646693154`, 0.009697790214128308`, 0.29999999999999993`}      The last coordinate was at fault. Is this a bug in the new functions? Any ideas how to get around it? **EDIT: Computing p1:** @user21               line = HalfLine[r + v/10^8, v];     p1 = RegionBounds[RegionIntersection[line, reg]][[All, 1]];      If `line` would start on the wall, `RegionIntersection` would consist of two points. To avoid that, I translate the origin of the `HalfLine` along v a bit. **EDIT 2: I've found a way around, but it doesn't answer the question about precision** Okay, instead of defining `p1` as an element of `RegionBounds` I used `RegionCentroid`:               old: p1 = RegionBounds[RegionIntersection[line, reg]][[All, 1]];     new: p1 = RegionCentroid[RegionIntersection[line, reg]]      And it seems to have solved the problem. But I have no idea why, because for a single point both `RegionCentroid` and `RegionBounds` should give the same result. I tried both functions on a "buggy" (i.e. found by `RegionBounds`) point and here's what I got:               In: RegionBounds[RegionIntersection[line, reg]]     Out: {{0.0494424, 0.0494424}, {0.0341449, 0.0341449}, {0.3, 0.3}}      And after copy-pasting the output:               {{0.04944240524519992`, 0.04944240524519992`}, {0.03414494309476567`, 0.03414494309476567`}, {0.30000000000000004`, 0.30000000000000004`}}      And for RegionCentroid:               In: RegionCentroid[RegionIntersection[line, reg]]     Out: {0.0494424, 0.0341449, 0.3}      Copy & paste:               {0.04944240524519991`, 0.03414494309476552`, 0.3`}      Well, I can imagine that it's due to internal functions used, but I'm still somehow confused that the results do not "converge" for this case.


Deploy a custom function to the cloud

Following my previous topic on how to optimize a complex function, I decided to write a custom algorithm because I need this task to be run locally and on machines with no access to _Mathematica_. Unfortunately the performance differences between my _java_ code and the _Mathematica_ 's one are really huge and I need another solution. I've just discovered _Wolfram Cloud_ and this seems the best way to make everything work because I can just execute my _Mathematica_ 's notebook, so I subscribed to the free tier to give it a try. Here's what I'm trying:               optimize[d_, p_] := Module[{n, m, q, k, A, b, result},         n=Length[d];          m=Dimensions[p][[2]];          vec[m_]:=Flatten[m\[Transpose]];          mat[v_]:=Partition[v,n]\[Transpose];          j[k_]:=ConstantArray[1,k];          q=j[m];          k=vec[p (d\[TensorProduct]q)];          A=ArrayFlatten[{IdentityMatrix[m]\[TensorProduct]j[n]}];          b=j[m]\[TensorProduct]{1,0};          result = mat[LinearProgramming[k,A,b]];          result      ];      CloudDeploy[APIFunction[{"d" -> "List", "p" -> "List"}, optimize[#d, #p] &, "String"]]      I'm using `List` as a parameter because `d` and `p` are like               d={7,5,11,3};     p=({{5,2,5,3,7,1,1,5,2,5,3,7,1,1},{2,8,3,2,7,2,3,2,8,3,2,7,2,3},{3,6,4,5,9,1,1,3,6,4,5,9,1,1},{4,6,2,8,14,8,4,4,6,2,8,14,8,4}});      Now, the function works fine in my local notebook and hitting evaluate actually makes the deploy. The problem is that the API doesn't return what I expect. While I expect a `string` that contains the result matrix, it outputs: > > Transpose[LinearProgramming[LinearProgramming[Transpose[{{{5,2,5,3,7,1,1,5,2,5,3,7,1,1},{2,8,3,2,7,2,3,2,8,3,2,7,2,3},{3,6,4,5,9,1,1,3,6,4,5,9,1,1},{4,6,2,8,14,8,4,4,6,2,8,14,8,4}} > {{7,5,11,3}} ? ConstantArray[1, {1}[[2]]]}]], > LinearProgramming[ArrayFlatten[{IdentityMatrix[{1}[[2]]] ? {1}}]], > LinearProgramming[ConstantArray[1, {1}[[2]]] ? {1, 0}]]] and I don't understand why. Do you know what the problem is? Their documentation is not that helpful and I'm quite clueless.


Multiplication sign in TeXForm?

How do I get Mathematica to produce TeX output that does not omit the multiplication signs ? For example, this expression:               (z03*z14*z32 + z01*z12*z43 + z14*(z01 + z03 + z12 + z32)*z43)      displays in Mathematica as:               (z14 z43 (z01+z03+z12+z32)+z01 z12 z43+z03 z14 z32)      And the output of TeXForm look like this: $$ \text{z14} \text{z43} (\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01} \text{z12} \text{z43}+\text{z03} \text{z14} \text{z32} $$ which is really hard to read because the spaces get ignored. How do I get TeXForm to produce this instead ?: $$ \text{z14}\times\text{z43}\times(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}\times\text{z12}\times\text{z43}+\text{z03}\times\text{z14}\times\text{z32} $$ Even better would be: $$ \text{z14}.\text{z43}.(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}.\text{z12}.\text{z43}+\text{z03}.\text{z14}.\text{z32} $$ Worse come to worse, I could even settle for something like this: $$ \text{z14}\;\text{z43}\;(\text{z01}+\text{z03}+\text{z12}+\text{z32})+\text{z01}\;\text{z12}\;\text{z43}+\text{z03}\;\text{z14}\;\text{z32} $$


Graphic using manipulate runs too slow

Here is a naive coding of a projection of a point on a sphere. It runs very slow. Can it be changed to run faster without losing its essential analytic character?               Magnify[Manipulate[       Show[ParametricPlot3D[{{x, 0, 1}, {0, y, 1}, {x, y, 1}, {x, x^2,            1}, {x*w, x*w^2, x}, {x, y, Sqrt[1 - x^2 - y^2]}, {x,            y, -Sqrt[1 - x^2 - y^2]}, {x/Sqrt[x^2 + (x^2)^2 + 1], (x^2)/            Sqrt[x^2 + (x^2)^2 + 1],            1/Sqrt[x^2 + (x^2)^2 + 1]}, {-x/Sqrt[x^2 + (x^2)^2 + 1], -(x^2)/            Sqrt[x^2 + (x^2)^2 + 1], -1/Sqrt[x^2 + (x^2)^2 + 1]}}, {x, -5,           5}, {y, -5, 5}, Axes -> False, Boxed -> False,          Mesh -> {{-5, 5}, {-5, 5}},          RegionFunction -> Function[{x, y, z}, 0 < x^2 + y^2 < 16],          SphericalRegion -> True, (*RotationAction->"Clip",*)         PlotStyle -> {Black, Black,            Directive[Opacity[0.5], Blue, Specularity[White, 50]],            Directive[ Red], Directive[ Red],            Directive[Opacity[0.5], Orange, Specularity[White, 50],             Mesh -> None],            Directive[Opacity[0.5], Orange, Specularity[White, 50],             Mesh -> None], Directive[Black], Directive[ Black]}],         Graphics3D[{Red, PointSize[.01],           Point[{{w/Sqrt[w^2 + (w^2)^2 + 1], (w^2)/Sqrt[w^2 + (w^2)^2 + 1],              1/Sqrt[w^2 + (w^2)^2 + 1]}, {-w/Sqrt[              w^2 + (w^2)^2 + 1], -(w^2)/Sqrt[w^2 + (w^2)^2 + 1], -1/Sqrt[              w^2 + (w^2)^2 + 1]}, {w, w^2, 1}}]}]], {{w, 1.086}, 0.01,         3}], 1.7]


Do a gauge transformation for a Chern-Simons theory?

Suppose we have the following Lagrangian density: $$ L=\epsilon^{\mu\nu\rho}\big(\sum_a A^a_{\mu}(x) \partial_\nu A^a_{\rho}(x)-\sum_{a,b,c}\frac{1}{3} f^{bca} A^a_{\mu}(x) A^b_{\nu}(x) A^c_{\rho}(x)\big) $$ under this infinitesimal transformation + $\dots$ $$ A^a_\mu(x) \to {A^a_\mu}'(x)\equiv (A^a_\mu(x) + f^{abc} \alpha^b(x) A^c_\mu(x) + \partial_\mu \alpha^a(x) +\dots) $$ where $x\equiv(t,x_1,x_2)$, $\epsilon^{\mu\nu\rho}$ is anti-symmetric and cyclic, $f^{abc}$ is anti- symmetric, but may not be cyclic in general. We end up with $L \to L'$ under $A^a_\mu \to {A^a_\mu}'$. And my question is: How to obtain a **well-simplified** $L'$ using _Mathematica_ ? The key point is: **without knowing the detailed structure $f^{abc}$, but only implement $f^{abc}$'s property to simplify the answer $L'$.** ps. I just took a glimpse at this post -how-to-manipulate-gauge-theory-in- mathematica, but I wonder whether there is a simpler way, since I am only doing **pure algebra?**


Mesh inside Plot legend

I have a plot for which I would like to create an legend that is black and white printer friendly. I have seen Jen's legendmaker but I don't know how to adapt it. I need help in making the legend for the exit region to appear meshed. The graph is incomplete right now and I will add more stuff to it.. like J and V etc etc but for now I want the exit regions and their legends to be black and white printer friendly. What can I do to get a mesh to appear in the legend for the exit region. Thanks **EDIT: Gaps in code fixed.** ![enter image description here](http://i.stack.imgur.com/5Ix9Z.jpg)               I1 = 15;     I2 = 8;     f1[x_] := I1;     f2[x_] := I2;     hddd = 20;     h00d = 60;     h00s = 150;     hsss = 180;         pl1 = Plot[{f1[x]}, {x, 0, 200}, AxesOrigin -> {0, 0},             PlotRange -> {-1, 20}, Epilog -> {              Inset[               Grid[{{Text[Style["J", "Garamond", 16]],                   Text[Style["First Function", "Garamond", 16]]}, {Text[                   Style["V", "Garamond", 16]],                   Text[Style["Second Function", "Garamond", 16]]}}], {h00s,                 I1 + 3}],              Inset[               Grid[{{Item["",                    Background -> RGBColor[0.35082, 0.595178, .853742],                    Frame -> True, FrameStyle -> AbsoluteThickness[1]],                   Style["Continuation Region", "Garamond", 16]}, {Item["",                    Background -> RGBColor[1, 1, .4], Frame -> True,                    FrameStyle -> AbsoluteThickness[1]],                   Style["Exit Region", "Garamond", 16]}}]], Dashed,               Arrowheads[Small], Arrow[{{h00s, I1}, {h00s, 0}}],               Arrowheads[Small], Arrow[{{h00d, I1}, {h00d, 0}}],               Arrowheads[Small], Arrow[{{hddd, I1}, {hddd, 0}}],               Arrowheads[Small], Arrow[{{hsss, I2}, {hsss, 0}}],               Inset[Style["Down Boundaries", "Garamond",                 16], {(hddd + h00d)/2, (I1 + I2)/2}],              Inset[               Style["Top Boundaries", "Garamond",                 16], {(hsss + h00s)/2, (I1 + I2)/2}],              }, Ticks -> {{{hddd, Text[Style["HDD", "Garamond", 20]]}, {h00d,                 Text[Style["H0D", "Garamond", 20]]}, {h00s,                 Text[Style["H0S", "Garamond", 20]]}, {hsss,                 Text[Style["HSS", "Garamond", 20]]}}, {{I1,                 Text[Style["High", "Garamond", 20]]}, {I2,                 Text[Style["Low", "Garamond", 20]]}}},             AxesLabel -> {Text[Style["Variable X", "Garamond", 20]],               Text[Style["Variable Y", "Garamond", 20]]}];         pl2 = Plot[{f2[x]}, {x, 0, 200}, AxesOrigin -> {0, 0},             PlotRange -> {-1, 20}];         ptd = ListPlot[{{h00d, I2}, {hddd, I1}},             PlotStyle -> {Directive[Red, PointSize[Large]]},             AxesOrigin -> {0, 0}, PlotRange -> {-1, 20}];         pts = ListPlot[{{h00s, I1}, {hsss, I2}},             PlotStyle -> {Directive[Green, PointSize[Large]]},             AxesOrigin -> {0, 0}, PlotRange -> {-1, 20}];         r1 = RegionPlot[            f1[x] > 0, {x, 0, hddd - 1}, {y, I1 - 0.15, I1 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r2 = RegionPlot[            f1[x] > 0, {x, h00s + 1, 200}, {y, I1 - 0.15, I1 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r3 = RegionPlot[            f1[x] > 0, {x, 0, h00d - 1}, {y, I2 - 0.15, I2 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r4 = RegionPlot[            f1[x] > 0, {x, hsss + 1, 200}, {y, I2 - 0.15, I2 + 0.15},             PlotStyle -> RGBColor[1, 1, .4], Mesh -> 2];         r5 = RegionPlot[            f1[x] > 0, {x, h00d + 1, hsss - 1}, {y, I2 - 0.1, I2 + 0.1},             PlotStyle -> RGBColor[0.35082, 0.595178, .853742]];         r6 = RegionPlot[            f1[x] > 0, {x, hddd + 1, h00s - 1}, {y, I1 - 0.1, I1 + 0.1},             PlotStyle -> RGBColor[0.35082, 0.595178, .853742]];         Show[pl1, pl2, ptd, pts, r1, r2, r3, r4, r5, r6]


Is it possible to manipulate FindFit

I was wondering if it is possible to manipulate a `FindFit[]` function. As a basic example, if I had an equation $ax^2+bx+c$ and a set of data, would it be possible to manipulate the `c` value, while _Mathematica_ outputs the best fit values for `a` and `b` for that `c` value?


Precision of number not maintained when saved via Export

Assume that the output of my calculation is `a` and is a number such as: > `a = 100.1252135246354847;` `N[a]` gives me `100.125` However, when I try to save my data, `a` via export such as : > `Export["/path/to/file/with/extension/dat", N[a]]` My eventual filename.dat has `100.12521352463548` and not `100.125`. So is the precision of digits/most significant digits for display only? I also tried `NumberForm[a,6]` and I get `NumberForm[100.1252135246354847`18.000543455259304, 6]` in my data file! What am I doing wrong? ## Edit (possible solution): Replacing `N[a]` with `SetPrecision[a,5]` helped. I wasn't sure if I should have this in the ANSWER section because the solution may be quite trivial and may not warrant being in the answer section. Any thoughts on that (whether or not I should answer this question or let the solution remain as an appended "edit")


StringJoin/FileNameJoin doesn't quite work in script

My mathematica script is as follows:               #!/usr/local/bin/MathematicaScript -script          $HistoryLength=0;         $pwf=FileNameJoin[{NotebookDirectory[],FileBaseName[NotebookFileName[]]}];     $parameterfile=StringJoin[$pwf,".dat"];      Export["testcase.dat", {0.333, 100,0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}];     Export[$parameterfile, {0.333, 100, 0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}];      * * * ## It is also uploaded **here** All it does is creates a file name from the `NotebookDirectory` and `NotebookFileName` and saves a bunch of data `{0.333, 100,0, 0, 35.1, 7.02, 0, 2, 1, 5, 10000}` to file with generated filename. It runs fine with the front end. However, it doesn't run from a unix terminal which defeats the purpose of having this script. The error that I get is:               > FrontEndObject::notavail: A front end is not available; certain     > operations require a front end.     >      > FrontEndObject::notavail: A front end is not available; certain     > operations require a front end.     >      > StringJoin::string: String expected at position 1 in     > FileNameJoin[{NotebookDirectory[$Failed],         > FileBaseName[NotebookFileName[$Failed]]}]<>.dat.     >      > Export::chtype: First argument     > FileNameJoin[{NotebookDirectory[$Failed],         > FileBaseName[NotebookFileName[$Failed]]}]<>.dat is not a valid file     > specification.      Am I to understand that I will HAVE to use the front end for when I have `StringJoin` operations? The reason I find `StringJoin` useful is that I have 150 different cases varying in parameters and easily identified by file name. If I can have a script to run all these mathematica cases, it would save a lot of trouble. Any help would be appreciated.


How do I interpret the following syntax?

I have been given some code with the following line               PeriodicExtension[g_, x_] := If[Abs[x] < Pi, g[x], PeriodicExtension[g, x - 2 Sign[x] Pi]]      I do not understand the syntax. I would appreciate if someone can explain what this code does for different values of `x`.


Find sublists of a list match conditions (2)

Needs["TetGenLink`"];         Needs["ComputationalGeometry`"];              long = 100;         broad = 100;         height = 100;              pts = {{0, 0, 0}, {long, 0, 0}, {long, broad, 0}, {0, broad, 0},            {0, 0, height}, {long, 0, height}, {long, broad, height}, {0,              broad, height}};         facets = {{{1, 2, 3, 4}}, {{5, 6, 7, 8}}, {{1, 5, 6, 2}}, {{2, 6, 7,               3}}, {{3, 7, 8, 4}}, {{4, 8, 5, 1}}};              inst = TetGenCreate[];         TetGenSetPoints[inst, pts];         TetGenSetFacets[inst, facets];              inst1 = TetGenTetrahedralize[inst, "pq1.414a4"];         ElemPtsCoord = TetGenGetPoints[inst1];         ElemFacesMadeofPtsIndex = TetGenGetFaces[inst1];         ElemElemsMadeofPtsIndex = TetGenGetElements[inst1];              Graphics3D[GraphicsComplex[ElemPtsCoord, Polygon[ElemFacesMadeofPtsIndex]]]              ElemPtsCoordandIndex = ElemPtsCoord;         Do[PrependTo[ElemPtsCoordandIndex[[i]], i], {i, 1,             Length[ElemPtsCoordandIndex]}           ];              ElemElemsMadeofPtsIndexandIdex = ElemElemsMadeofPtsIndex;         Do[PrependTo[ElemElemsMadeofPtsIndexandIdex[[i]], i], {i, 1,             Length[ElemElemsMadeofPtsIndexandIdex]}           ];             RetainElementsIndex=Range[1,Length[ElemElemsMadeofPtsIndexandIdex]];             ProjectedElemsIndex[ElemPtsCoord_, ElemElemsMadeofPtsIndexandIdex_,        Acen_, Bcen_, Ccen_, R1_, RetainElementsIndex_] := Module[       {RetainElemsMadeofPtsIndexandIndex, ClassifiedElements,         ProjectedElementsIndex},            RetainElemsMadeofPtsIndexandIndex =         ElemElemsMadeofPtsIndexandIdex[[RetainElementsIndex]];            ClassifiedElements = GatherBy[         RetainElemsMadeofPtsIndexandIndex,         Volume[            RegionIntersection[             Ball[{Acen, Bcen, Ccen}, R1],             Simplex[              ElemPtsCoord[[  Delete[#1, 1]  ]]              ]             ]            ] != 0 &];            ProjectedElementsIndex = If[         Volume[           RegionIntersection[            Ball[{Acen, Bcen, Ccen}, R1],            Simplex[             ElemPtsCoord[[  Delete[ClassifiedElements[[1, 1]], 1]  ]]             ]            ]           ] != 0,              ClassifiedElements[[1]],              ClassifiedElements[[2]]         ];       ProjectedElementsIndex =         Union[Flatten[          Take[ProjectedElementsIndex, Length[ProjectedElementsIndex], 1]]];            ProjectedElementsIndex            ]               ProjectedElemsIndex[ElemPtsCoord, ElemElemsMadeofPtsIndexandIdex,       62.84752406439229, 28.984094217780612, 72.55554474676572, 12.5, RetainElementsIndex]      Questions Background: I have a cube sized 100*100*100, I have meshed it with fine meshes. So the mesh elements set is `ElemElemsMadeofPtsIndex`, The mesh points set is `ElemPtsCoord`. And because `ElemElemsMadeofPtsIndex` and `ElemPtsCoord` do not tell us elements(points)' oder. So I add the points(elements) a order number to the first of the sublists: ElemElemsMadeofPtsIndex-> ElemElemsMadeofPtsIndexandIdex ElemPtsCoord-> ElemPtsCoordandIndex. Math Problem: A sphere(ball): the center is located at (Acen, Bcen, Ccen) and radius is R1). and I want to find which elements belong(located in the ball or intersected with the ball) to the zone of the ball. so the problem become to find sublists of list `ElemElemsMadeofPtsIndexandIdex`, which the volume of region which mesh tetrahedron and the ball intersected is not null.


Order of Evaluate for Map

I would like to get a list of variable names as strings. For example,               x = 1;     y = 2;     Map[SymbolName, Unevaluated /@ Unevaluated@{x, y}]      > {"x", "y"} This works well. However, if I use               Map[SymbolName @* Unevaluated, Unevaluated@{x, y}]      It does not work and drops an error message > SymbolName::sym: Argument 1 at position 1 is expected to be a symbol. What's the difference between the two?


Use NDSolve to solve a PDE

I have the following PDE (a master equation, and $P$ is probability density, $0\le x\le1$ and $0\le y\le1$): $$ \partial_t P(x,y,t)=x\partial_xP(x,y,t)+(1-y)\partial_yP(x,y,t)+2P(x,y,t) $$ The initial conditions are $P(x,y,t=0)=\delta(x-0.05,y-0.85)$. For the boundary conditions, if the probability density is going to flow through the boundary, I won't do anything to stop it. ( **How to express the BC in Mathematica?** ) I used the following command:               NDSolve[{D[P[x, y, t], t] ==      x D[P[x, y, t], x] + (1 - y) D[P[x, y, t], y] + 2 P[x, y, t],      P[x, y, 0] == DiracDelta[x - 0.05, y - 0.85]}, P,      {t, 0, 2}, {x, 0, 1}, {y, 0, 1}]      First, Mathematica gave the following warning:               Warning: an insufficient number of boundary conditions have been specified for the direction of      independent variable y. Artificial boundary effects may be present in the solution. >>      Moreover, the result it gave obviously is wrong:               Plot3D[Evaluate[(P[x, y, t] /. %) /. {t -> 0}], {x, 0, 1}, {y, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/dHIrn.png) **My question is** : 1) How can I express the boundary conditions I mentioned 2) How can I make the `NDSolve` work?


DSolve breaks when the ordering of independent variables aren't proper?

I encountered this when trying to solve this problem with `DSolve`:               DSolve[D[p[x, y, t], t] ==             x D[p[x, y, t], x] + (1 - y) D[p[x, y, t], y] + 2 p[x, y, t], p, {t, x, y}]      > DSolve::deqx: Supplied equations are not differential equations of the given > functions. >   >   >     (* Input returned *) >   It's not surprising to see `DSolve` fails in solving PDEs… but why this warning? Even more shocking:               DSolve[D[p[x, y, t], t] ==             x D[p[x, y, t], x] + (1 - y) D[p[x, y, t], y] + 2 p[x, y, t], p, {x, y, t}]      > >     {{p -> Function[{x, y, t}, C[1][x (-1 + y), t + Log[x]]/x^2]}} >   The result changed just because I reordered the independent variables (from `{t, x, y}` to `{x, y, t}`). Is this a bug? Tested in _v9.0.1, Windows Vista 32bit_ and _Wolfram Programming Cloud_.


Getting cdf content from nice Wolfram info graphic

There is a very nice cdf info graphic on the Wolfram Webpage (http://www.wolfram.com/cdf/uses-examples/infographics-full-example.html). I'd like to have a look at the code as I'd like to do something similar. However, they only provide the cdf. Is it possible to extract the code from this? – Thanks.


Where can I get detailed information on how the Plot command works?

The command               Plot[x^2, {x, -3, 3}, PlotStyle -> Arrowheads[{-.025, .025}]] /.Line -> Arrow      produces this output. ![enter image description here](http://i.stack.imgur.com/0WN0q.jpg) What I don't understand is what `Line` has to do with anything. It must be the case that the `Plot` command produces `Line` objects that can be replaced with `Arrow`. I haven't seen anything in the documentation for `Plot` that suggests this is the case. Without `/.Line->Arrow` the plot won't have arrowheads at the ends of the graph of the function.


Wavelets: Relative error vs compression ratio

I need to plot the relative error vs compression ratio diagram of a discrete wavelet transform on an image, but no luck so far .. Here's the problem in short:   1. random_image.jpg   2. compress the image   3. plot the relative error vs compression ratio diagram Here's the code and below is the link I am using as a reference:               cumulativeEnergy[data_] :=       Module[{c = Sort[Flatten[data]^2, Greater]}, Accumulate[c]/Total[c]]          data = (* insert random image*)          wtdata = DiscreteWaveletTransform[data]          wtE = cumulativeEnergy[Last /@ wtdata[Automatic]];          ListLinePlot[Sqrt[1 - wtE]]      The problem is I don't get a curve like in the example.. Tutorial used as a reference Thank you !


Is there an equivalent to MATLAB's linspace?

Does _Mathematica_ have an equivalent to Matlab's `linspace`? I want to make a list with "start", "stop" and "number of points". What is the neatest way of doing this?


Strange Behavior with RegionPlot

Consider the following code.               RegionPlot[Print[{x, y}], {x, -2, 2}, {y, -2, 2}, PlotPoints -> 2]      > >     {-1.996,-1.996} >     {Region`Private`RegionVar[1],Region`Private`RegionVar[2]} >     {-2.,-2.} >     {2.,-2.} >     {-2.,2.} >     {2.,2.} >   My question is: what is `RegionPlot` doing to create the first two lines of output? I do not understand why the first sample point is `{-1.996, -1.996}` and why the second sample point is `{Region`Private`RegionVar[1],Region`Private`RegionVar[2]}`. I am running this in _Mathematica_ 9. I do not recall this happening in an earlier version. **Edit:** I changed the code above to give a better minimal working example. I leave below the code I first gave along with its truncated output.               myFunc[pt_] := Module[ {bool},       bool = Sin[ pt[[1]] ] > 0;       Print[pt, bool];       If[ bool, Return[True], Return[False] ];     ];          RegionPlot[myFunc[ {x, y} ], {x, -2, 2}, {y, -2, 2}, PlotPoints -> 2]      > >     {-1.996,-1.996}False >   > > {Region`Private`RegionVar[1],Region`Private`RegionVar[2]}Sin[Region`Private`RegionVar[1]]>0 >   >     {-2.,-2.}False >   >     {2.,-2.}True >


String to File removing quotation marks

If I print a string to a file it also adds quotation marks to the string. Here is an example:               a = "test \t test"     a >> file     FilePrint["file"]      How can I remove those? And is it possible to use `\t` for a tabulator?


Dynamic Graph visualization

I'm working on a C++ library that will be used to construct and study certain graphs (as in a set of connected vertices, not a function plot). These graphs will be dynamic in nature (and can potentially be very large) and I'm looking for ways to visualize them. I looked at a few solutions such as Gephi which can visualize dynamic graphs, but then decided that this should be something that _Mathematica_ would do well. My C++ library keeps track of a 'lifetime' for each vertex and edge and I can output the graph data any way I need to. Although I've visualized a lot of graphs in Mathematica with `GraphPlot` and `GraphPlot3D` I'm not sure what's the best way to visualize a dynamic graph? I've used `Dynamic` and `Manipulate` extensively and I've been able to use Manipulate to draw a series of successive 'snapshots' of a graph at each time step. The problem with this approach is that you're redrawing the entire graph each time even though only one vertex or edge has changed. Also when you redraw the entire graph there's no guarantee that the vertices will be put in similar places, so adding one edge causes the picture to totally change. This kills the ability to animate the changing graph. What seems to be needed is the ability to change the graph slightly and then locally recompute the graph drawing forces without redrawing the graph from scratch. Is this possible? Something like a hypothetical `GraphPlotDynamic[]`. **Edit** Here is a contrived example showing the problem. The format for each edge is.               {source, target, begin, end}      This creates the graph connectivity.               dynamicGraph =         {{0, 1, 0, 20}, {1, 2, 1, Infinity}, {2, 3, 2, 21}, {3, 4, 3, 22},          {4, 5, 4, Infinity}, {5, 6, 5, Infinity}, {6, 7, 6, 26}, {7, 8, 7, 25},              {8, 9, 8, Infinity}, {9, 10, 9, 24}, {0, 6, 10, 27}, {1, 6, 11, Infinity},          {1, 5, 12, Infinity}, {2, 5, 13, Infinity}, {2, 4, 14, Infinity},          {6, 8, 15, Infinity}, {5, 8, 16, Infinity}, {5, 9, 17, Infinity},          {4, 9, 18, Infinity}, {4, 10, 19, 23}};      Now the graph is rendered with `GraphPlot`. The edges are selected based on whether `t` is within the edge's lifetime.               Manipulate[        GraphPlot[#1 -> #2 & @@@ Select[dynamicGraph, #[[3]] <= t <= #[[4]] &],           VertexRenderingFunction -> (Text[#2, #1] &)], {t, 0, 31, 1}]      This graph has a relatively natural progression of adding nodes in a line then connecting the line by folding it back on itself twice. Then all the outside edges are deleted and you are left with hexagon with all vertices connected to one vertex at the center. But when clicking through the `Manipulate` the graph jumps around at each step so it's hard to keep track of what is being added and taken away. **Edit** Here is an example video of what I'm talking about. This is from Ubigraph and does more than what I'm asking for since it does fancy camera angles and rotations as the graph is being constructed. But what's important is that as the vertices and edges are being added the force directed algorithm is continuously running so the graph is constantly updated. http://ubietylab.net/ubigraph/content/Demos/Animation.html