How to generate a list from an iterator and some arbitrary function

Suppose I'd like to generate a table of integers:               Table[i, {i, 10}]      Great; now suppose I want only the integers that are even               Select[Table[i, {i, 10}], EvenQ]      This is fine for small things, but if I'd like to iterate over say $2^{n}$ things, only maybe $n$ of which will satisfy the predicate, it's a pretty terrible way to do it. Is there some good idiomatic way to do it? I could use a `Do` loop (I guess with `Append`ing?) but there must be a better way, right?


Eigenvector Anomaly

I'm trying to compute the eigenvectors for: $$ M = \left( \begin{array}{ccc} 1 & 4 \\\ 4 & 100 \end{array} \right) $$ Both myself and Mathematica report the **eigenvalues** as: $$ \lambda_1 = \frac{1}{2} \left(101+\sqrt{9865}\right) \approx 100.161 \\\ \lambda_2 = \frac{1}{2} \left(101-\sqrt{9865}\right) \approx 0.838647 $$ But when I ask for **eigenvectors** , the answer changes depending on whether I input the numbers as integers or floating-point numbers. When I ask for `Eigenvectors[{{1, 4}, {4, 100}}]` I get: $$ v_1 = \left(\frac{1}{8} \left(-99+\sqrt{9865}\right), 1\right) \approx (0.0403383, 1) \\\ v_2 = \left(\frac{1}{8} \left(-99-\sqrt{9865}\right), 1\right) \approx (-24.7903, 1) $$ When I ask for `Eigenvectors[{{1.0, 4.0}, {4.0, 100.0}}]` I get: $$v_1 \approx (0.0403055, 0.999187) \\\ v_2 \approx (-0.999187, 0.0403055)$$ When I calculate by hand, I get a solution which matches the first query. So, am I going crazy and overlooking some important maths (not unlikely, very tired...) or is this a bug? Possible related issues?:   * Difference In Eigenvectors   * eigenvector bug?


Generic Matrices

A multivariate Gaussian distribution for $k$ dimensions looks like this: $$\frac{1}{\sqrt{(2\pi)^k|\mathbf \Sigma|}}\mathbf e^{ -\frac 1 2 \mathbf x^T \mathbf \Sigma^{-1}\mathbf x }$$ $\mathbf x$ is a $k$-dimensional vector, and $\mathbf \Sigma$ a $k$ by $k$ symmetric positive definite matrix. Now I want Mathematica to integrate this expression over all $\mathbf x$, the result should be 1. How can I do this? Nothing else is known, in particular we don't know the number of dimensions.


Removing not-a-number entries from an array of numbers

I have a list of `{x, y, z}` coordinates from a wavefront sensor I'm working with. However, not all of the imported points have actual values, but they still get imported as `{x, y, "NaN"}`. I'm trying to find a way to get rid of these faulty points, but so far, I can't find a way to identify them. They don't affect some graphs, but I've run into trouble when performing operations on the set of points I've tried several things like `Delete`, `DeleteCases` and `StringTrim`, but to no avail. When I run, `DeleteCases[graph, "NaN"]`, for example, I get back the same set of points. Also, I am using _Mathematica_ 7\. Thanks.


Nonlinear System of ODEs

I want to solve this NonLinear System: $$\Theta_{\xi} = \frac{(1-\lambda)K_{\alpha}}{\beta}\Phi^{2}\Theta+\frac{2\beta-1}{6\beta}\xi\Theta$$ $$\Phi_{\xi} = \frac{1}{2\lambda K_{\alpha}\ \Theta^{3}\Phi+2\beta}\bigg[-3\lambda K_{\alpha}\ \Phi^{2}\Theta^{2}\Theta_{\xi}+\xi\Phi\bigg]$$ where I would like to use $\beta$ as a parameter, whereas $K_\alpha$ and $\lambda$ are known constants. The boundary conditions I have are: $$\Theta[0]=0,\ \Theta[10]=0$$ $$\Phi'[0]=0,\ \Phi'[10]=0$$ I tried to use NDSolve, but I get this error:                \[Lambda] = 0.1; K = 1;          eqn1 = ((1 - \[Lambda]) K)/\[Beta] \[CapitalPhi][x]^2 \[CapitalTheta][x] + (2 \[Beta] - 1)/6 x \[CapitalTheta][x];           eqn2 = \[CapitalPhi]'[x] == (-3 \[Lambda] K \[CapitalPhi][x]^2 \[CapitalTheta][x]^2 \[CapitalTheta]'[x] + x \[CapitalPhi][x] )/(2 \[Lambda] K \[CapitalPhi][x] \[CapitalTheta][x]^3 + 2 \[Beta]);               {xsoln, ysoln} = {\[CapitalTheta], \[CapitalPhi]} /. NDSolve[{\[CapitalPhi]'[x] == eqn2, \[CapitalTheta]'[x] == eqn1, \[CapitalTheta][0] == 0, \[CapitalPhi][0] =       0}, {\[CapitalTheta], \[CapitalPhi]}, {x, 0, 10}]          NDSolve::deqn: Equation or list of equations expected instead of 0 in the first argument{(\[CapitalPhi]^\[Prime])[x]==((\[CapitalPhi]^\[Prime])[x]==(x \[CapitalPhi][x]-0.3 <2>> <<1>>)/(2 \[Beta]+0.2 Power[<<2>>] \[CapitalPhi][<<1>>])),(\[CapitalTheta]^\[Prime])[x]==1/6 <<3>>+<<1>>,<<1>>,0}. >>      etc


Potential hill simulation

I attempted to simulate the motion of a particle approaching to a potential hill. The particle should experience a force of `-1/r^2`, if the equation for the potential hill is `1/r`. So the acceleration for the particle should be `-c/r^2`, where c is an arbitrary proportional constant. The particle is expected to bounce back when close enough to the hill, but it passed through the hill instead, despite of different values of c. Is there anything wrong with my code or the equations of motions. Secondly, when `PlotPoints->10` changed to `PlotPoints->30` in order to obtain an intact potential hill, the program becomes unbearable slow. How to get around this?               Clear[x, y, z, t, ux, uy, bx, by, cnt];     t = -2;     ux = 1; uy = 1;     bx = -1; by = -1;     obx = -1; oby = -1;     cnt = 0.2;     ax[x_, y_] := -cnt*x/( x^2 + y^2)^(3/2)  ;     ay[x_, y_] := -cnt*y/( x^2 + y^2)^(3/2)   ;          field = ContourPlot3D[        1/(x^2 + y^2)^(1/2) - z == 0, {x, -2, 2}, {y, -2, 2}, {z, 0, 50},         PlotPoints -> 10];          particle[t_] := (        bx = ux t + 0.5 ax[obx, oby] t^2;        by = uy t + 0.5 ay[obx, oby] t^2;        bz = 1/(bx^2 + by^2)^(1/2) ;        obx = bx; oby = by;        Graphics3D[{          Red, Sphere[{bx, by, bz}, 0.1]}]);          Dynamic[      Refresh[       Row[{Show[field, particle[t], ImageSize -> {300, 300}],          If[t < 2, t = t + 0.1, t = -2]}]       , UpdateInterval -> 1       ]        ]      ![enter image description here](http://i.stack.imgur.com/OceMq.gif)


Problem importing individual frames from QuickTime file

I am having difficulties with a code I am trying to run. Essentially I want to `Read` in a large `.mov` video file (60000+frames). Then take each frame individually, process it (e.g. crop and identify particles, I can do these steps) and `Export` a text file with processing data (can do), plus the cropped image. I am not sure which functions/the setup to use for reading in a video and exporting an image sequence. I have looked at `Import` with `.mov` files, and can identify the number of frames in the movie:               videof = Import[path <> file <> ".mov", "FrameCount"]      as well as view a single frame               frame1 = Import[path <> file <> ".mov", {"Frames", {n}}]      however there is something wrong in the second line of code; no matter the value of `n` I always get the first image. Advice is much appreciated.


Simultaneous equations

I am trying to solve two simultaneous equations that are claimed to have 145 solutions but I believe they have 143, I want to check I am right before sending an email to my professor. Mathematica is taking an incredible amount of time with this so I thought my code was wrong. Could you please check it for me?               Length[NSolve[{x == Sin[6 Pi y], y == Sin[6 Pi x]}, {x, y}]]      The equations are $y=sin(6 Pi x)$ and $x=sin(6 Pi y)$ apologies if my conjecture is wrong!


Generating an Array of Vectors

I'm working a lot with nested lists of $(x,y)$ coordinates (of a FEM-like mesh, but that's not important), like so:               nodes = { {{0,0}, {0,1}, {0,2}}, {{1,0}, {1,1}, {1,2}} }      This has the nice convenient structure that `nodes[[i,j]]` gives me the $(x,y)$ coordinates of my "$(i,j)$th" node, so that `nodes[[i,j]][[1]]` is my $x$ coordinate and `nodes[[i,j]][[2]]` is my $y$ coordinate. This works nicely for my purposes. How would I construct a _variable_ size array of this kind using `array[]` et. al? If I use for instance               nodes = array[array[X,2],{4,4}]      I get a 4-by-4 array where `nodes[[i,j]]` is of the form `{X[1],X[2]}[1,1]`. This is close to what I want, and I could change a bunch of my code to work with this, but I'd rather not - I'd love to have something where `nodes[[i,j]]` looks like this:               {X[i,j][1], X[i,j][2]}      The reason I'd like to do this is I have defined some functions that take an array of nodes as input and computes some quantity, i.e. `F[nodes_]:= (*something*)`, and I'd like to compute derivatives of this function with respect to each of its variables, i.e. $F_{x_i}$ or $F_{y_j}$. I've tried various things with no success, and I've also tried looking for a similar construct in the documentation and here on SE, but I didn't see anything. Any ideas? Edit: I had too many square braces in some of my code before. Fixed.


This question follows on from my earlier one, Seeking strategies to deploy a function securely without a front end. As it pursues a different track to solve the same problem it seemed distinct enough and perhaps interesting enough to others to merit its own question. I need to deploy a single function into a Windows based technology environment so that the users can call the function from some of their process workflows. The users don't need a front end or user interface of any kind. In fact a front end would cause problems. I have some additional code security concerns, but approaches to that have begun to emerge (see the earlier question referenced above). Running without a front end would also keep code from prying eyes. **Question:** Can one launch a Player Pro kernel independently of the front end via something like a Mathematica Script to run the contents of the computable document without displaying the document itself? References or examples of how to do this appreciated.


Solve non linear system of equations

I am trying to solve a system of two equations with two unknowns. In these equations I have, a part from constants:   * Unknown nr 1, $$D_{\perp}$$   * Unknown nr 2, $$\omega_C$$   * Known function of r: $$\mu(r)$$ The full system looks like: equation1: $$ D_{||}= \frac 1 {2 \omega_0}(-\alpha-1)\sqrt{(-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}+ \frac{\alpha}{2\omega_0}\sqrt{(-2\omega_0-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}+ \frac{1}{2\omega_0}\sqrt{(2\omega_0-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2} $$ and equation2: $$ 1= \mu(r) \frac{\alpha}{2\omega_0} \ln{\left[\frac{-2\omega_0-\omega_C+\mu(r)D_{||}+\sqrt{(-2\omega_0-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}}{-\omega_C+\mu(r)D_{||}+\sqrt{(-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}}\right]}+ \frac{\mu(r)}{2\omega_0} \ln{\left[\frac{2\omega_0-\omega_C+\mu(r)D_{||}+\sqrt{(2\omega_0-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}} {-\omega_C+\mu(r)D_{||}+\sqrt{(-\omega_C+\mu(r)D_{||})^2+(\mu(r)D_{\perp})^2}}\right]} $$ So the solution of the system of equations will be $$D_{\perp}(r),\;\omega_C(r)$$. What I've tried to do is simply                   Solve[{equation1, equation2},{Dorthogonal, omegaC}]      but Mathematica keeps on running forever without any output. I have also tried:                   DorthFun[r_]:=Solve[{equation1, equation2},{Dorthogonal, omegaC}][[1,1]]         omegaCFun[r_]:=Solve[{equation1, equation2},{Dorthogonal, omegaC}][[1,2]]      and it just keeps on running... It doesn't return any errors. Just...eternal running. Forrest Gump Syndrome... I have also tried to solve the system putting $$\mu(r)=1$$ without any change. I have given Mathematica about 20 minutes. Should I give it more time or does this mean that Mathematica cannot solve this? Or is there something I could do differently? Thank you for your help! My code looks like this:                   NSolve[{         Dparallel==1/(2 omega0) Sqrt[(-omegaC + Dparallel)^2 + (Dorth)^2] (-alpha-1)+alpha/(2omega0)Sqrt[(-2omega0-omegaC+Dparallel)^2+(Dorth)^2]+1/(2omega0)Sqrt[(2omega0-omegaC+Dparallel)^2+(Dorth)^2],         1 == alpha/(2omega0)Log[(-2omega0-omegaC+Dparallel+Sqrt[(-2omega0-omegaC+Dparallel)^2+(Dorth)^2])/(-omegaC+Dparallel+Sqrt[(-omegaC+Dparallel)^2+(Dorth)^2])]+1/(2omega0)Log[(2omega0-omegaC+Dparallel+Sqrt[(2omega0-omegaC+Dparallel)^2+(Dorth)^2])/(-omegaC+Dparallel+Sqrt[(-omegaC+Dparallel)^2+Sqrt[(-omegaC+Dparallel)^2+(Dorth)^2]])]         }, {Dorth, omegaC}]


Multiplying SI Prefixes

I'm doing a few calculations and would like to keep my units straight. I figured that using the built-in Units functionality could help with this. However, using SI prefixes doesn't seem to give the desired output. I try executing this code:                In[15]:= A = 4 Milli Meter*Pi*3^2 Micro Meter // N      And instead of getting, say, 113E-9 Meter^2, I get:                Out[15]= 113.097 Meter^2 Micro Milli      Milli, Meter, and Micro are all globally defined names. What am I doing wrong?


Numerical method for solving a polynomial equation

I am looking for a numerical solution of a equation which contains, in general, one polynomial equation with unknown variable x. I have tried `Reduce`, `Solve`, `NSolve` and `FindRoot`, but I'm getting nothing after running my code for a few days. Probably there is solution in some of numerical iterative or other methods, unknown for me.                a1 = Sqrt[2*10^11*3.055*10^-5];      a2 = 0.01;      a3 = 7849;      a4 = 10;      a5 = 50;      a6 = 11;      a7 = 700;           k1 = Rationalize[      Solve[(k (k^3 a1 - I a2 - k (a4 + a5^2 a3)) + x - 2 k a5 a3 a6 -            a3 a6^2) == 0, k][[4]][[1]][[2]], 0];      k2 = Rationalize[      Solve[(k (k^3 a1 - I a2 - k (a4 + a5^2 a3)) + x - 2 k a5 a3 a6 -            a3 a6^2) == 0, k][[1]][[1]][[2]], 0];      k3 = Rationalize[      Solve[(k (k^3 a1 - I a2 - k (a4 + a5^2 a3)) + x - 2 k a5 a3 a6 -            a3 a6^2) == 0, k][[3]][[1]][[2]], 0];      k4 = Rationalize[      Solve[(k (k^3 a1 - I a2 - k (a4 + a5^2 a3)) + x - 2 k a5 a3 a6 -            a3 a6^2) == 0, k][[2]][[1]][[2]], 0];           expr = (I  a1 (k1 - k3) (k2 - k3) (k1 - k4) (k2 - k4))/(      k1 + k2 - k3 - k4) - a7 a6^2;           NSolve[expr == 0, x]


Problem with CurrentValue["MouseOver"] when graphics are wrapped with Deploy

Please take a look at following toy example:               Graphics[{      Dynamic[{       If[CurrentValue["MouseOver"], Red, Blue], Thickness@.05, Line[{{0, 0}, {.5, 0}}]}],      Dynamic[{       If[CurrentValue["MouseOver"], Red, Blue], Disk[{.5, 0}, .2]}]       }, PlotRange -> {{0, .6}, {-.3, .3}}]      > ![enter image description here](http://i.stack.imgur.com/U6aIC.png) You can put cursor over the `Disk` or `Line`. As you can see the `Disk` covers the `Line`, so you can only get: > ![enter image description here](http://i.stack.imgur.com/1jioK.png) or > ![enter image description here](http://i.stack.imgur.com/wUYbr.png) But as soon as we add `Deploy` (`Deploy@Graphics[...`), the `Disk` becomes transparent to the `"MouseOver"` event, and we can get the following result (with cursor on the right place): > ![enter image description here](http://i.stack.imgur.com/Zfhfl.png) This behaviour is so unexpected, I'm tempted to call it a bug. This change in behaviour is huge! In this context, `Deploy` as a quick and nice function seems to be unreliable. :/ V9.0.1 Win7 * * * The walkaround is similar like there: Delay of events detection dependent of “MouseDown” position. But I doubt the reason is the same.


Plot sets in the complex plane

I just want to know if there's a way to plot sets in the complex plane. For example $$A=\\{z\in \mathbb{C},z+e^{z}=0\\},\\\A=\\{z\in \mathbb{C},\Re(z)+e^{z}\geq0\\}.$$


Creating a package of special plots

In my work as a math teacher, I create lots of graphs to illustrate ideas. I have lots of math books and will often try to duplicate a particular style of graph. Below, one very simple example, created with Mathematica. (but as a "one off") ![enter image description here](http://i.stack.imgur.com/22GIY.png) I wish my Mathematica skills were better, I spend too much time grading and lesson planning, and I know I could be more effective with lesson writing if my toolkit was bigger and more robust. So I decided to try to write some functions to create these kinds of plots, and thought it would be best to put them into a package so I could use them easily. I have a program that created the plot, and it works fine, but I'm embarrassed to share it, it's so clunky...I don't care about speed and concise code, I wanted to be able to understand all the steps and pieces...               specialA[xmin_, xmax_, xscale_, ymin_, ymax_, yscale_, xtickmin_,        xtickmax_, xtickinc_, ytickmin_ , ytickmax_, ytickinc_, funclist_,        stylelist_, ratio_] :=       Module [{xvals, lightx, darkx, gridx1, gridx2, xgrid, yvals, lighty,         darky, gridy1, gridy2, ygrid, xticks, yticks},            xvals = Range[xmin, xmax, xscale];       lightx = Select[xvals, Not[IntegerQ[#/5]] &];       darkx = Select[xvals, IntegerQ[#/5] &];       gridx1 = {#, GrayLevel[0.8]} & /@ lightx;       gridx2 = {#, Black} & /@ darkx;       xgrid = Flatten[{gridx1, gridx2}, 1];       yvals = Range[ymin, ymax, yscale];       lighty = Select[yvals, Not[IntegerQ[#/5]] &];       darky = Select[yvals, IntegerQ[#/5] &];       gridy1 = {#, GrayLevel[0.8]} & /@ lighty;       gridy2 = {#, Black} & /@ darky;       ygrid = Flatten[{gridy1, gridy2}, 1];       xticks = Range[xtickmin, xtickmax, xtickinc];       yticks =  Range[ytickmin, ytickmax, ytickinc];            Plot[funclist, {x, xmin, xmax},         PlotStyle -> stylelist,        GridLines -> {xgrid, ygrid},         PlotRange -> {{xmin, xmax}, {ymin, ymax}},         AspectRatio -> ratio,         Ticks -> {xticks, yticks},         ImageSize -> 430,         Epilog -> Text[0, {0, 0}, {1, 1}],        BaseStyle -> {FontSize -> 18, FontFamily -> "Times"}]       ]      So, for example....                   f[x_] := 2 x^2 - x - 8;     g[x_] := -x^2 - 2 x + 2     specialA [-7, 7, 1, -32, 32, 2, -5, 5, 5, -30, 30, 10, {f[x], g[x],        f[x] - g[x], g[x] - f[x]}, {Red, Blue, Green, Magenta}, 2]      I'd welcome any comments on that and welcome any nice plotting routines for "high school math" graphs that others might be using. But here is my real question. I'm no expert but have created a few simple Mathematica packages. I put this function into a package, wrote a usage statement, defined the function. When I use it, I get a grid, but the functions don't display. I am sure this has something to do with contexts , but I just have no clue. How can I improve my function definition, and how would I include it in a working package of similar functions to draw other graphs? (I save my package online in case that would be helpful... https://dl.dropbox.com/u/24411154/grapher.nb) I know this is a huge question, I do appreciate the feedback and help from this group. Tom


How to integrate ParametricNDSolve solution with respect to a parameter?

I have just upgraded to the new version of Mathematica because of its new built-in `ParametricNDSolve` function. I need to solve a first-order non- linear ordinary differential equation that has two parameters. I have no problem obtaining appropriate solutions to this equation, but once I have the solution I need to integrate out the dependence on the parameters. For instance, I would like to write something like               sol=ParametricNDSolveValue[{-y*a'[x]==(a[x]^2-1)f[x]+a[x],a[-10]==0.6},a,{x,-10,10},{y}]     Integrate[sol[y][x],{y,0,1}]      If I have an `InterpolationFunction` which has two arguments I can very easily integrate over one of the two arguments, but this does not seem possible to do with a `ParametricFunction`. The best idea I have had so far is to form an `InterpolationFunction` from the `ParametricFunction` and then integrate from there, but that seems inefficient and I would like something a little faster and more straightforward. Any help would be greatly appreciated.


Equivalent of Python's "all" function in Mathematica

The Python function                def isPrime(n):         return all(n % i for i in xrange(2, n))      checks if a number is a prime number by using `all`. How can I write a function similar to `all` in _Mathematica_?


How get Singular.m package to interact with Singular itself?

I've installed the package `Singular.m` by Kauers and Levandovskyy from http://www.risc.uni-linz.ac.at/research/combinat/software/Singular/ as well as the Singular CAS itself. How, exactly does one get the package to communicate with the Singular system -- specifically to get results back from Singular to Mathematica? In a terminal, I just type `singular` and that starts the system. So at the end of the package `.m` file I modified the final line so it now reads `SingularCommand = "singular"`. Now after I load the package and evaluate one of the interface functions, such as one in the `demo.nb` notebook, I get an error: `Singular::error : Unable to read Singular's output.`


How to save a web page in mathematica?

For a given web page http://www.nytimes.com/, is it possible to save it as : > **first** : only HTML(within css) > > **second** : more elements(include pictures and so on) just like what a browser can do. I have tried this, but it only generates a large picture with plain text.               Export["F:\\nytimes.html", Import["http://www.nytimes.com"], "HTML"]


Is Mathematica a Turing-complete language? If so, how can that be proved? If not, why?


Define a function that returns a function with a variable number of arguments

Previously, I've defined a function with a variable number of arguments with the following method.               x = {x1, x2, x3};     f1 = Function[       Evaluate[x],       x + 1 //       Evaluate     ];     f1 @@ x     Output: {1 + x1, 1 + x2, 1 + x3}      Also, I've defined a function that returned a function as follows.               g[x_] := Function[       {z},       x + z //       Evaluate     ];     f2 = g @@ {z};     f2 @@ {x1}     Output: x1 + z      But when I attempt to put these ideas together, I have an issue. The hang-up seems to be in passing the argument of the first function to the argument of the second. Note that in our second example, above, we weren't passing `x` as an argument to the inner function. However, this is exactly what we want to do:               h[x_] := Function[       Evaluate[x],       x + 1 //       Evaluate     ];     f3 = h @@ x;     f3 @@ x     Output: h[x1, x2, x3][x1, x2, x3]      The desired output is `{1 + x1, 1 + x2, 1 + x3}`. My motivation for writing such a function is to bury it in a package.


I've some data points in Mathematica. I want to plot these in MATLAB. How to do that?

I want to export these data points into matlab and get a plot. Like I've to plot ft vs t. Through the following command- Table[{[Tau], ft[2, 5, [Tau]]}, {[Tau], 0, 15, .01}], i generated some data set. Now how do I export it to MATLAB to plot?


How to convert a sparsearray to a graph?

s = Import["hello.mat"];     t = GraphEmbedding[Graph[s[[1]]], "GridEmbedding"];      I get the following error: > GraphEmbedding::graph: A graph object is expected at position 1 in >   >   >     GraphEmbedding[Graph[SparseArray[<1232>, {223, 223}]], GridEmbedding]. >   I would prefer to do SpringElectricalEmbedding and then GridEmbedding. What should I do? Please help.


How can I get GridEmbedding for my graph?

I evaluate the following               s = Import["hello.mat"];     t = GraphEmbedding[s[[1]], "GridEmbedding"];      and I get the these error messages > GraphPlot::mthd: The value of option Method -> GridEmbedding should be > Automatic, "SpringElectricalEmbedding", "SpringEmbedding", "LayeredDrawing", > "LayeredDigraphDrawing", "RadialDrawing", "HighDimensionalEmbedding", > "CircularEmbedding", "SpiralEmbedding", "LinearEmbedding", or > "RandomEmbedding". > > GraphPlot::grph: SparseArray[<1252>, {240, 240}] is not a valid graph. How can I do `GridEmbedding` for my sparse array `s`?


How can I plot a circular region and lines?

I am having difficulty plotting something along these lines in _Mathematica_. ![Imgur](http://i.imgur.com/l7CTZIy.png) I will explain what is going on here. Basically, I am solving an interval equation $ax=b$, in the first example $a = [1, 20]$ and $b =[3, 4]$ and therefore $b/a = [3/20, 4]$. As you can see from the graph I want a circle representing the projective line. A straight line will come off the two end points of the interval which represents the solutions and those lines will go through the center of the circle and the region bounded by the lines should be shaded in. Similarly the other example below is an unbounded one where $a = [-1,2]$ and $b = [5,100]$ and hence $b/a = (-\infty, -5] \cup [5/2, \infty]$. Same type of plot though, the lines come off $-5$ and $5/2$ on the x axis and go through the center of the circle and the bounded regions are shaded. Could someone please help me plot this?


Using Mathematica to make a graphics array of circles

I need to make .svg file that contains an array of black circles that all have radii of 5 units ad are evenly spaced apart from each other 32 units. The difficulty in creating this design is the sheer number of circles necessary. I will need a 3175 by 3175 array. At first I tried doing this manually in Adobe Illustrator, but then it occurred to me that I could write a code to do it for me in Mathematica.               n = 50;     mat = Flatten[Table[{32 i, 32 j}, {i, 0, n - 1, 1}, {j, 0, n - 1, 1}], 1];     g = Disk[#, 5] & /@ mat;     Export["circle_array.svg", Graphics[g], "SVG"];      Above is the code I wrote, and it for a small number of rows/columns, it works just fine. After it's created, I open it up in Adobe Illustrator, and it looks just fine. However, when I try to increase the number of rows much greater than 100 X 100, after it's exported and I open it up in Adobe Illustrator. I notice that not all the circles are evenly spaced away from each other, and I don't understand why. If anyone could help, it would be greatly appreciated.


Function generating a rule with a Patterns: e.g. toRule[ lhs, rhs] into lhs[x_] -> rhs

I want to create a rule as a function of `z` from a left and right hand side. My (non-working) code and usage is:               toRule[l_, r_] := l[x_] -> r          toRule[f, a+b]      I want the output to be:               (* => f[x_] -> a + b*)      However: when I do this with the code above I get:               (* => f[x$_] -> a + b*)      Where is the $ coming from, and how can I get rid of it?


Restarting Mathematica causes an animation to fail to run

I've tried animating two different sets of 3D plots. Interestingly, one plot will always work, regardless of whether I restart Mathematica, yet another plot will only work in its current Mathematica session. For instance, I have:               h = 1;     α = 1;     H = (1/2)*(p^2 + x^2);     rho[n_] = (1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h];     list = ParallelTable[Plot3D[rho[n], {x, -10, 10}, {p, -10, 10}, PlotRange -> All,     PlotLabel -> Style[n, FontSize -> 40], ImageSize -> 800,      AxesLabel -> {Style[x, FontSize -> 30],        Style[p, FontSize -> 30]}], {n, 0, 10}];     ListAnimate[list, AnimationRate -> 1, AnimationRunning -> False]      This yields: ![enter image description here](http://i.stack.imgur.com/99THp.png): If I save my file and restart Mathematica, while none of my variables are initialize, the animation is still able to run. However, I have another piece of code to make a different animation:               Clear[n]     α = 0.15;     h = 1;     η = 1;     a = -n - Sqrt[1 + 16 r];     r = η^2/(4*α^2);     qrn = (1/2)*(n + 1/2) + (1/4)*Sqrt[1 + 16 r];     c = 1 - 2*qrn;          Clear[x, p]     ψ[p_] = (1/(1 + α*p^2)^qrn)*  Hypergeometric2F1[a, -n, c, (1/2) +    (I/2)*Sqrt[α]*p]          For[i = 0, i <= 2, i++, Clear[list2]]     For[n = 0, n <= 2, n++,      list2[n] = Append[list2[n],      ParallelTable[{x = RandomReal[{-5, 5}], p = RandomReal[{-10, 10}],        NIntegrate[        Exp[I*u*x/h]*         Conjugate[ψ[p + u/2]]*ψ[p - u/2], {u, -10000,          10000}, MaxRecursion -> 12]}, {40}]]] // AbsoluteTiming     Animate[ListPlot3D[list2[n][[2]], PlotRange -> All, ImageSize -> 400], {n, 0, 2, 1}, AnimationRunning -> False]      This gives: ![enter image description here](http://i.stack.imgur.com/IWGNy.png) After saving, and restarting Mathematica, I now get: ![enter image description here](http://i.stack.imgur.com/fN0Ge.png) Creating my animation with 40 points only takes a couple seconds, so it isn't terrible that I'd have to recreate it. However my plan is to increase the number of points to more than 12000 and increase `n` to 10, which will take much more time than a couple seconds. Why does one animation run after re-opening Mathematica, yet another animation will give me an error message? As a related question, is there a way for Mathematica to always remember the values of my variables, even after restarting Mathematica? Thanks.


How do I find the value of specific printing options?

I'd like to programmatically save (and then temporarily change and restore) specific printing options. I get as far as               Options[Notebook, PrintingOptions]      but don't know what to do next to extract specific options, for example `PrintingMargins`, from the (long) resulting list.


Dataset and string conversion, using Internal`StringToDouble

i'm trying to get familiar with the new Dataset-stuff in Mathematica 10. As it will (hopefully) provide some benefit for me, I have started to convert my app to move from list and list of rules to Associations and Datasets. Starting point for me is an XML object, which is converted to a Dataset now. I was hoping to reduce the programming code by e.g. applying functions to multiple columns at once. This is an example Dataset:               testset = Dataset[{<|"Element" -> "A", "a" -> "529251", "b" -> "520358"|>, <|     "Element" -> "B", "a" -> "51"|>, <|"Element" -> "C",      "a" -> "177"|>, <|"Element" -> "L", "a" -> "125"|>, <|     "Element" -> "S", "a" -> "1343"|>}]      This gives: ![dataset](http://i.stack.imgur.com/QOSPH.png) As the XML sometimes contains integers and reals in scientific form, I'm using               Internal`StringToDouble      to convert the stuff:               fnStr2Real[x_,r_:0]:=If[Head[x]===Missing,r,Internal`StringToDouble[x]]     SetAttributes[fnStr2Real, {Listable}];     testset[fnStr2Real, {"a", "b"}]     (* Trace yields *)     (* Query[fnStr2Real, {"a", "b"}][testset] *)      The issue: there is some kind of rounding in the resulting recordset: ![result](http://i.stack.imgur.com/2Wvkh.png) If I apply my function directly to my list or association, everything is fine:               Function[x, fnStr2Real[#[x] & /@ Normal[testset]]] /@ {"a", "b"}     (* {{529251., 51., 177., 125., 1343.}, {520358., 0, 0, 0, 0}} *)      I know that Internal`StringToDouble is an internal function, but I found several posts in this forum using it, and I really like it! Is there an issue with M10, Dataset and Internal`StringToDouble? Are there any other robust string coversion functions availabe which can handle integers, reals and reals in scientific form **inside a dataset**? Thanks!


How to combine the sum of two rational polynomials into a single rational polynomial

I have browsed the web and found no information. I have two rational polynomials $f1(x,y)$ and $f2(x,y)$. When I perform `f1 + f2`, I always get two separate functions. However, I would like to combine them into one rational expression. How do I do that?


Save state of buttons, sliders, listpicker in enterpriseCDF?

How do you make enterpriseCDFs save the state of buttons sliders, listpickers etc? I manipulated a CDF and saved it on exit but all the buttons etc were reset when I started it again. I've made a simplified example: If you execute the last line it produces a toggler bar and a button in a single output cell. I export that cell as a stand alone enterprise CDF. When I open it in cdf player, toggle a few buttons, save, close and reopen, the state is reset to the original first three buttons pressed. Is it possible to get the state of the buttons to be remembered across saves?               data[n_] := Range[n];     series = {1, 2, 3};     cdf =        DynamicModule[{},          Grid[{           {TogglerBar[Dynamic[series], Range[6]]},           {Dynamic[              PopupWindow[Tooltip[Button["Show data"], data[series]], data[series],                WindowSize -> All,                WindowTitle -> "data",                 WindowElements -> {"VerticalScrollBar", "HorizontalScrollBar","StatusArea"},                ScrollingOptions ->                   {"HorizontalScrollRange" -> Automatic, "VerticalScrollRange" -> Automatic}],               TrackedSymbols :> Full]}},           Alignment -> {Top, Top}],           SaveDefinitions -> True];     cdf      I also tried exporting with the command:               CDFDeploy[NotebookDirectory[] <> "testCDF.cdf", cdf,        "Method" -> "Standalone", "Target" -> "PlayerPro"];      with same result (not sure if target needs to be playerpro though; the aim was for it to be an enterpriseCDF state-savable with the standard player.


Using function with multiple definitions in Manipulate

I'm trying to use `Manipulate` to visually try out different values of lambda in a Box-Cox transformation. I've created a `boxcox` function with two definitions to deal with both the normal case and the case when lambda is 0:               boxcox[data_, 0] := Log[data]     boxcox[data_, l_] := (data^l - 1)/l      Then I use this function inside `Manipulate` but I keep getting tons of errors. It looks like Manipulate is only using the general definition and starts complaining about dividing by zero.               Manipulate[      pdata = Partition[boxcox[data, u], 12];      ranges = Max[#] - Min[#] & /@ pdata;      means = Mean[#] & /@ pdata;      mrdata = Transpose[{means, ranges}];      mrlm = LinearModelFit[mrdata, x, x];      Show[       ListPlot[mrdata, Axes -> False, Frame -> True,         AxesOrigin -> {Automatic, 0}],       Plot[mrlm[x], {x, Min[means], Max[means]}]       ],      {u, 0.00, 1.00}      ]      Here is the data I'm using in case it matters:               data = {154., 96., 73., 49., 36., 59., 95., 169., 210., 278., 298., 245., \     200., 118., 90., 79., 78., 91., 167., 169., 289., 347., 375., 203., \     223., 104., 107., 85., 75., 99., 135., 211., 335., 460., 488., 326., \     346., 261., 224., 141., 148., 145., 223., 272., 445., 560., 612., \     467., 518., 404., 300., 210., 196., 186., 247., 343., 464., 680., \     711., 610., 613., 392., 273., 322., 189., 257., 324., 404., 677., \     858., 895., 664., 628., 308., 324., 248., 272.}


Text replacement rules in $FrontEnd?

I want to set up a part of my Mathematica package so that typing `<``-``Space` is replaced with the left arrow character (`←` or `\[LeftArrow]`) just like it does with `-``>``Space`. Does anyone know how to do this? I looked briefly at event handling but didn't see anything immediately useful. I already know, of course, that `Esc``<``-``Esc` will insert `←`, and that doing so is not that much additional effort, but I'm more interested in the concept involved here. Any ideas?


Some way to identify the source of a notebook file?

Is there a way to tell where a Mathematica file came from, meaning some type of machine ID (yes, I know about `$MachineID`). I want to be able to identify students who are sharing files, i.e. one student creating the file and giving it to others. Anti-cheating is what I'm trying to accomplish.


Detect each polygons in an image

Considering this image: ![](http://i.imgur.com/Y87duSz.jpg) Is there a way to colorize each tiles independently? My problem is that               img = Import["http://i.imgur.com/Y87duSz.jpg"];     Colorize@img      gives ![Mathematica graphics](http://i.stack.imgur.com/ENWxM.png) where polygons with very light colours are merged. Note that `EdgeDetect[img, 1, .05]` produces: ![Mathematica graphics](http://i.stack.imgur.com/v4q0C.png) if it can help. * * * **Ideally** , the idea would be to colour the tiles independently (`Colorize` colours them in terms of their "blackness"). That would imply that one detects the polygons and recreate them, which is harder than "only" colouring them in terms of their pre-existing colours. Please note I have absolutely no knowledge in image-processing.


Can the Notation function support complex structures on its left hand side?

In my investigation of the possibilities offered by the Notation package, I came over a limitation in the complexity of the left hand side symbol. For instance, although I am able to enter                Notation[        ParsedBoxWrapper[          OverBar[SuperStar[af]]]        \[DoubleLongLeftRightArrow]        ParsedBoxWrapper["afstarbar"]]      without Mathematica complaining, **evaluating** `afstarbar` **returns an incorrectly formatted symbol** (the whole symbol is replaced by a red error square instead of displaying $\overline{af^*}$). The output is:                OverBar[SuperStar[$CellContext`af]]           An unknown box name (OverBar) was sent as the BoxForm for the expression.      Check the format rules for the expression.      I am unfamiliar with the concept of "boxing", but I tried the following:               Notation[       ParsedBoxWrapper[         MakeBoxes[           OverBar[SuperStar[af]]]]       \[DoubleLongLeftRightArrow]       ParsedBoxWrapper["afstarbar"]]      And the display is slightly better, as the $af^*$ is here, but the bar is replaced by the red error square and the output is:               \!\(\*OverscriptBox[     SuperscriptBox[\(af\), \(*\)],      Notation`Private`singleBlank[]]\)          An unknown box name (Notation`Private`singleBlank) was sent as the BoxForm      for the expression. Check the format rules for the expression.      Any trick on how to get the symbol to display correctly with the Notation package?


Dynamically updating interactive objects in Mathematica

Is it possible to create interactive code in Mathematica (via EventHandler[] or Manipulate[] perhaps) that continually updates some calculation based on external data in the time when no user input is received? As a trivial example, code that shows the current time, with seconds, continually updating, and which allows the user to click on any of the numbers to change their color. Thank you.


Winkel Tripel and Robinson Projections?

How can I do WorldPlot with the WorldProjection -> Winkel Tripel or Robinson projections. Mathematica has Mollweide and several others defined, but not these popular projections adapted by National Geographic.


How do I emulate MATLAB's comet plot?

I have tried the following code:               ParametricPlot[{Sin[12 u] Cos[u], Sin[12 u] Sin[u]}, {u, 0, 2 Pi}]      and it produced the following image: ![Flower](http://i.stack.imgur.com/0ZgdU.png) MATLAB has a `comet` command that will draw this parametric plot in real time, allowing the viewer to watch as the particle traces out the plot. Is there a way to do this in _Mathematica_?


How to find derivative of a numerical solution, where precision is ambiguous?

I am trying to take the derivative of a numerical solution. I am concerned that the way I'm doing this may be problematic due to numerical error; I think there must be a better way but I'm not very experienced in Mathematica. The relevant function is called GammaFcn and is defined as follows:               K = 10; c = 1; a = 1; b = 3; d = .01;  tradeoff = 1; mig = .002;     N1[x_] := K*(1 - c*x + b*x^a - mig);     f[x_, y_, t_] := 1/(1 + N1[x]*E^(c*t*(y - x)));     Gstar[x_, y_, t_] := s*(y*f[x, y, t] + x*(1 - f[x, y, t]));     sStar[x_, y_, t_] :=      s /. NSolve[(1 - s/K) + b*(Gstar[x, y, t]/s)^a -        x*c*(1 - f[x, y, t]) - y*c*f[x, y, t] - mig == 0, s][[1]]     N2[x_, y_, t_] := f[x, y, t]*sStar[x, y, t];     Beta1[x_] := mig*N1[x];     Estar[x_] := (d)/(Beta1[x]);     Istar[x_] := 1 - Estar[x];     lambda[x_] := Beta1[x]*Istar[x];     I1star[SigmaI_, x_] :=     Estar[x]*(1 - Estar[x])*mig*N1[x]/(d + SigmaI*lambda[x]);     M1[SigmaI_, p_, q_, t_, z_] := Sum[z^(n)*(d + SigmaI*Istar[p]*mig*N1[p])* E^(-t*(d + SigmaI*Istar[p]*mig*N1[p]))* E^(-N1[q]*mig*t)*(N1[q]*mig)^n*t^n/n!, {n, 0, Infinity}]     M2[p_, q_, t_, z_] := Sum[z^(n)*((d)*E^(-t*(d))* E^(-mig*(sStar[q, p, t] - N2[q, p, t])*t)*(mig*(sStar[q, p, t] - N2[q, p, t]))^n*t^n/n!), {n, 0, Infinity}];     M3[p_, q_, t_, z_] := Sum[z^(n)*((d)*E^(-t*(d))* E^(-mig*N2[p, q, t]*t)*(mig*N2[p, q, t])^n*t^n/n!), {n, 0, Infinity}];     Part1[SigmaI_, p_, q_, z_] := NIntegrate[M1[SigmaI, p, q, t, z], {t, 0, Infinity}]     Part2[p_, q_, z_] := NIntegrate[M2[p, q, t, z], {t, 0, Infinity}]     Part3[p_, q_, z_] := NIntegrate[M3[p, q, t, z], {t, 0, Infinity}]     Const1[SigmaI_, Res_, New_] := (d/(d + SigmaI*Istar[Res]*mig*N1[Res]));     Correct[SigmaI_, Res_, New_, Z_] := Const1[SigmaI, Res, New]*Part1[SigmaI, Res, New, Z] + (1 - Const1[SigmaI, Res, New])*(Part1[SigmaI, Res, New, Z]*      Part2[Res, New, Z])          GammaFcn[SigmaI_, p_, q_, z_] := (1 - Estar[p] - I1star[SigmaI, p]) + Estar[p]*Correct[SigmaI, p, q, z] + I1star[SigmaI, p]*(SigmaI*Part3[p, q, z] + (1 - SigmaI));      I am interested in solutions to GammaFcn[SigmaI, p, q, z]=z, where 0>z>1; suppose these solutions are given by a function GammaFcnFixedPt[SigmaI, p, q]. In particular, I want to calculate the first derivative of GammaFcnFixedPt with respect to p at the point p=q, with some fixed SigmaI and q. I do this with the following function, for some small epsilon (because when p=q, GammaFcn=1):               GammaFcnFixedPtDeriv[SigmaI_, q_, epsilon_] := (-1 + z /. FindRoot[GammaFcn[SigmaI, q + epsilon, q, z] - z, {z, .99}])/  epsilon      My problem is that when I do this, when epsilon gets sufficiently small, the results diverge. So with decreasing epsilons, the function will appear to be converging onto the derivative, but then (presumably due to precision errors), it diverges. Here are pairings of epsilon and the approximated derivative (from above function), for SigmaI=.1, q=.3. : {1/10, -0.200505}, {1/10^2, -1.44905}, {1/10^3, -0.901373}, {1/10^4, -0.886587}, {1/10^5, -0.886699}, {1/10^6, -0.886358}, {1/10^7, -0.847299}, {1/10^8, -0.297589}, {1/10^9, 0.969691} So in the above pairings, before epsilon goes below 1/10^7, there it looks as though the sequence is approaching somewhere around .88, but thereafter diverges quickly. Again I assume this is due to some machine error; but I'm not positive it is even due to this error. But if this is the case, how do I know what epsilon to pick for the most accurate derivative? If I add "PrecisionGoal -> 10" to the integrals in the code in the first block above:               Part2[p_, q_, z_] := NIntegrate[M2[p, q, t, z], {t, 0, Infinity}, PrecisionGoal -> 10]     Part3[p_, q_, z_] := NIntegrate[M3[p, q, t, z], {t, 0, Infinity}, PrecisionGoal -> 10]      {1/10^1, -0.200505}, {1/10^2, -1.44905}, {1/10^3, -0.901373}, {1/10^4, -0.886587}, {1/10^5, -0.886699}, {1/10^6, -0.886431}, {1/10^7, -0.855601}, {1/10^8, -0.0572474}, {1/10^9, -13.9658} And doing the same thing with PrecisionGoal->12 gives: {1/10^1, -0.200505}, {1/10^2, -1.44905}, {1/10^3, -0.901373}, {1/10^4, -0.886587}, {1/10^5, -0.886699}, {1/10^6, -0.886431}, {1/10^7, -0.855601}, {1/10^8, -1.83026}, {1/10^9, -13.9658} When I set it much higher than that it takes a long time. So how can I know that the derivative is converging to (in this case) approximately -0.887, rather than convergence not occurring (limit not existing)? And is there a better way to find the derivative than I have done? Thanks very much.


Running .NET/Link on Mono (On MacOS or any UNIX or Linux Distro)

Has anyone have any luck running .NET/Link on Mono? When I run .NET/Link to call Mathematica from within a Mono program, this is the error message I receive.               Unhandled Exception:     System.TypeInitializationException: An exception was thrown by the type initializer for Wolfram.NETLink.Internal.NativeLink ---> System.DllNotFoundException: mathlink       at (wrapper managed-to-native) Wolfram.NETLink.Internal.MacMathLinkAPIProvider:MLBegin (intptr)       at Wolfram.NETLink.Internal.MacMathLinkAPIProvider.extMLBegin (IntPtr zero) [0x00000] in <filename unknown>:0        at Wolfram.NETLink.Internal.NativeLink..cctor () [0x00000] in <filename unknown>:0        --- End of inner exception stack trace ---       at Wolfram.NETLink.MathLinkFactory.createMathLink0 (System.String cmdLine, System.String[] argv) [0x00000] in <filename unknown>:0        at Wolfram.NETLink.MathLinkFactory.CreateMathLink (System.String cmdLine) [0x00000] in <filename unknown>:0        at Wolfram.NETLink.MathLinkFactory.createKernelLink0 (System.String cmdLine, System.String[] argv) [0x00000] in <filename unknown>:0        at Wolfram.NETLink.MathLinkFactory.CreateKernelLink (System.String cmdLine) [0x00000] in <filename unknown>:0       Now the C# code for calling Mathematica is:                   _kl = MathLinkFactory.CreateKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'");      The same argument worked for J/Link, but for some reason does not work on NETLink.


How do I create a matrix of functions?

I'm trying to create a matrix in which the elements are functions of two variables, but I can't figure out how to do it. Is it possible? The only way I could figure out is to define the matrix in terms of two variables, then replace those variables with values later on. Here's my code:               row1 = {};     row2 = {};     For[ii = 1, ii <= Length[modes], ii++,       {l, m} = modes[[ii]];       G1lm = sglm[-2, l, m, \[Theta]] + (-1)^l sglm[-2, l, -m, \[Theta]];       G2lm = sglm[-2, l, m, \[Theta]] - (-1)^l sglm[-2, l, -m, \[Theta]];       AppendTo[row1, G1lm Cos[m \[Phi]]];       AppendTo[row1, G1lm Sin[m \[Phi]]];       AppendTo[row2, G2lm Sin[m \[Phi]]];       AppendTo[row2, -G2lm Cos[m \[Phi]]];       ];     proj = {row1, row2};      Theta and Phi are my variables. Later on, when I want proj for a specific Theta and Phi I use replace:               pN = proj /. {\[Theta] -> a, \[Phi] -> b};      where a and b are some numbers. The problem with this solution is that if I use Theta and Phi for something else later on, say I set Theta = 0.5, then proj will permanently have Theta = 0.5, regardless of the replace I use. This happened to me: I was calling proj in a loop, but I kept getting the same results. After ripping my hair out for a few hours, I realized I had Theta set to a specific value in a block of code further up in my notebook. The simple solution is to simply not use Theta and Phi anywhere else in the notebook, but that doesn't seem very stable. The root problem here is I'm using global variables to do something that should really be local to proj, but I don't know how to fix that. The ideal would be if I could somehow make proj a function of Theta and Phi so that later on I can simply do `pN = proj[a,b]`. I know how to make the Gnlm's functions of theta, but then I don't know how to make row1, row2, and by extension proj, functions of Theta (and Phi). Any help would be greatly appreciated.


How to use Compile with NDSolve function for large no of differential equations?

Matrix `M[t]` and and Hamiltonian of same order `L^n x L^n`.               L=3; n=3;tmax = 2;     Rho[t_] = Table[M[i,j][t], {i,L^n}, {j,L^n}]; //Timing          Rho0=ParallelTable[M[i,j][0],{i,L^n},{j,L^n}];     Hop[t_, i_] =     Transpose[       Table[If[i == j, 1, 1+Cos[t]], {i, {1}}, {j, L}]].Table[If[i == j, 1, 1+Sin[t]^2], {i, {2}}, {j, L}];          I1[i_Integer] := I1[i]=IdentityMatrix[L^(i-1)];     I2[i_Integer] := I2[i]=IdentityMatrix[L^(n-i)];          H[t_] = Sum[FixedPoint[ArrayFlatten, I1[i] \[TensorProduct] Hop[t,i]      \[TensorProduct]I2[i]],{i,n}];      I have made a code for large no. of time dependent differential equations with initial values. I want to compile this for using NDSolve. Here is my code...               Rho1[t_] =     Table[         D[Rho[t],t][[i,j]] == H[t][[i,j]],         {i,L^n}, {j,L^n}]; // Timing          Fun[t_]= -I (#1.#2 - #2.#1)&[H[t],Rho[t]];     Eq0[i_,j_]:=If[i == 1 && j == 1,#==1.,#==0. ]&[Rho0[[i,j]]];     Eq0a=ParallelTable[Eq0[i,j],{i,L^n},{j,L^n}];     Eqsopwo[t_]=Join[Thread /@ Thread[D[Rho[t], t] == Fun[t]],Eq0a]//Flatten;     \[Rho]Termsop[t_]=Rho[t]//Flatten;          sol= NDSolve[Eqsopwo[t],Diagonal[Rho[t]],{t,0,tmax},DependentVariables->\[Rho]Termsop[t],MaxSteps->10^5,MaxStepFraction-> 1/50, Method-> {"EquationSimplification"->"Solve"}]//Chop;     Plot[Evaluate[{Re[Diagonal[Rho[t]]]}/.sol],{t,0,tmax},PlotRange->All]


No Symbols Matching $InterfaceEnvironment

I'm running a webMathematica server (running Mathematica 9) and am getting some weird stuff in the log - specifically, I keep getting the following message:               General pool request background 61 > [      ] Input MSP`Utility`DestroyRequest[] generated message:     Remove::rmnsm: There are no symbols matching "Global`$InterfaceEnvironment".      I can't find any documentation for this, so it's possible that this is a user created symbol that I'm not seeing, but I think this is unlikely. Is this error something I should worry about?


Proper treatment of roots and powers in Series?

I have the following problem in _Mathematica_ 9 on Linux. I let _Mathematica_ compute the `Series` expansion:               Block[{$Assumptions = {r, p}\[Element] Reals},            Series[Log[r^2 - Sqrt[r^4 + p^2]], {p, 0, 0}]     ]      But the output is a rather disappointing naked infinity:               Log[r^2 - Sqrt[r^4]] + O[p]^1      Similarly, for:               Block[{$Assumptions = {p, r} \[Element] Reals},            Series[1/(r^2 - Sqrt[r^4 + p^2]), {p, 0, 0}]     ]      I get:               1/(r^2 - Sqrt[r^4]) + O[p]^1      Why is _Mathematica_ handing me naked infinities like that, even though I specified that the computation is to be carried out in the real numbers? What do I do wrong? How can I avoid this? EDIT: To make my point more clear, I would expect the Series to give results like $$\log(c_1 p^2)+O(p^1)$$ and $$\frac{1}{c_2 p^2}+O(p^1)$$ as a regulated infinity, instead of $\log(0)$ and $\frac{1}{0}$.


A Case of DeleteCases for WeatherData

I am trying to use `ListVectorPlot` in combination with `WeatherData` and `CountryData` to show wind velocity vectors over a given country. The problem I am having stems from "NotAvailable" and "NotApplicable" data from a function in which the wind's velocity vector is constructed. The function is               WindFoo[x_, y_] := -WeatherData[{y, x}, "WindSpeed"] {1/Cos[y °],         1} Through[{Sin, Cos}[WeatherData[{y, x}, "WindDirection"] °]]      Note: I am not able to display the degree symbol, so it is written out in the above code. How can the code above be modified to exclude the cases of "NotAvailable" and "NotApplicable" data to work in manner similar to the wind velocity vectors shown over Australia in the following tutorial: http://blog.wolfram.com/2009/01/13/visualizing-weather-patterns-in- mathematica-7/


How to control the order of meshing？

I want the first pic，but i got the second. What can I do? ![enter image description here](http://i.stack.imgur.com/HS45U.png) ![enter image description here](http://i.stack.imgur.com/NJKfa.png) Below if the code to produce the second pic:               data = {{14.808253637272422`,          5.992415735398138`, -10}, {14.937895181494618`,          5.835230243884557`, -10}, {15.104476099263962`,          6.190504320078969`, -10}, {15.549905577158725`,          6.242337037739479`, -10}, {16.214292480395272`,          5.946484831244263`, -10}, {17.172819193670374`,          6.044620763590807`, -10}, {14.808281657120743`,          5.992346489742819`, -5}, {14.937944420202394`,          5.83506166050832`, -5}, {15.104458590180693`,          6.1905995697624006`, -5}, {15.549909194291196`,          6.242289007293565`, -5}, {16.21428558314019`,          5.946304785847829`, -5}, {17.172828128632702`,          6.044675503473975`, -5}, {14.808370059168467`, 5.992128021118139`,          0}, {14.93796801813446`, 5.834980865961923`,          0}, {15.104521660293425`, 6.190256467374961`,          0}, {15.549917959537805`, 6.242172617112528`,          0}, {16.214298214579777`, 5.946634515939104`,          0}, {17.172827172286173`, 6.044669644434473`,          0}, {14.808196500526428`, 5.992556937854838`,          5}, {14.937952476296239`, 5.835034078072448`,          5}, {15.104459789437353`, 6.190593045787643`,          5}, {15.549890996009355`, 6.242530654951938`,          5}, {16.21428524490538`, 5.946295956593386`,          5}, {17.17285709312181`, 6.044852953886377`,          5}, {14.808354331354467`, 5.992166889379481`,          10}, {14.937875586457652`, 5.835297333327767`,          10}, {15.1044365297471`, 6.190719578861889`,          10}, {15.549897447086584`, 6.242444993694446`,          10}, {16.214291019501033`, 5.946446696177589`,          10}, {17.172815114360944`, 6.044595771776242`, 10}};          pica = Graphics3D[Sphere[data, 0.1]]          picb = ListPlot3D[data, InterpolationOrder -> 1,        MeshFunctions -> {#2 &, #3 &}, Mesh -> All, PlotRange -> All]          Show[pica, picb]


Using Collect to gather explicitly imaginary terms

Collect[Expand[(x + I y)^6], I]      yields               x^6 + 6 I x^5 y - 15 x^4 y^2 - 20 I x^3 y^3 + 15 x^2 y^4 + 6 I x y^5 - y^6      How can I obtain               x^6 - 15 x^4 y^2 + 15 x^2 y^4 - y^6 + (6 x^5 y - 20 x^3 y^3 + 6 x y^5) I


Creation of one column matrix

I want to create an one column matrix with the 1st element to be -1, and all the other elements to be zero. However, I want to be able to make a matrix of this kind with arbitrary dimension, that is, an arbitrary number of rows.


How to find a max point from discrete data of function?

I have a lot of points like $\\{\\{x_1,y_1,z_1\\},\\{x_2,y_2,z_2\\},...,\\{x_n,y_n,z_n\\}\\}$ which obtained by a function $z=f[x,y]$, and I want to find the max point of $z$, say $z_i$, and return the point coordinents $\\{x_i,y_i,z_i\\}$. How do I do? I have checked the help, but find there is no function can return the point coordinents from a list.


How to drop the identical rows and columns of a matrix?

I'm currently trying to find a way to eliminate from a square matrix of generic dimension the duplicate (up to sign) rows and columns, obtaining a smaller dimensional matrix. I searched around here but I couldn't find an answer, neither I managed to combine methods for list manipulation in order to arrive at my result. I'll make an example in order to clarify. Suppose I have a matrix of this form: $$ \left(\begin{array}{cccccc} x_1 & w_2 & -x_1 & -w_1 & -w_2 & w_1\\\ z_2 & x_2 & -z_2 & z_1 & -x_2 & -z_1 \\\ -x_1 & -w_2 & x_1 & w_1 & w_2 & -w_1\\\ -y_2 & y_1 & y_2 & x_3 & -y_1 & -x_3\\\ z_2 & x_2 & -z_2 & z_1 & -x_2 & -z_1\\\ y_2 & -y_1 & -y_2 & -x_3 & y_1 & x_3\\\ \end{array} \right) $$ I want to eliminate rows and columns 3,5,6, (copies of 1,2,4) ending up with the matrix $$ \left(\begin{array}{ccc} x_1 & w_2 & -w_1\\\ z_2 & x_2 & z_1\\\ -y_2 & y_1 & x_3\\\ \end{array} \right) $$ I would like to implement this operation so that it can act on matrices of arbitrary dimension. Thank you very much! Stefano


Can anyone help to solve this set of coupled ODE?

After some time Mathematica just give me the same thing while I was trying to solve: DSolve[{3 E^(-[Lambda]2 [Phi]0) r a[r] - 1/2 [Lambda]1 [Phi][r] + 3/8 E^(-[Lambda]2 [Phi]0) [Lambda]1 [Phi][r] - 1/2 [Lambda]2 [Phi][r] + 3/2 E^(-[Lambda]2 [Phi]0) r^2 Derivative[1][a][r] - 2 Derivative[1][b][r] + 3/2 E^(-[Lambda]2 [Phi]0) Derivative[1][b][r] - r [Lambda]2 Derivative[1][[Phi]][r] + r^2 !(*SuperscriptBox[(b), * TagBox[ RowBox[{"(", "3", ")"}], Derivative], MultilineFunction->None])[r] == 0, -((6 b[r])/r^2) - (3 [Lambda]1 [Phi][r])/(8 r) + ( E^([Lambda]2 [Phi]0) [Lambda]1 [Phi][r])/(2 r) + ( E^([Lambda]2 [Phi]0) [Lambda]2 [Phi][r])/(2 r) - 21/2 r Derivative[1][a][r] + (9 Derivative[1][b][r])/(2 r) + ( 2 E^([Lambda]2 [Phi]0) Derivative[1][b][r])/r + E^([Lambda]2 [Phi]0) [Lambda]2 Derivative[1][[Phi]][r] - 9/2 r^2 (a^[Prime][Prime])[r] - 3 (b^[Prime][Prime])[r] - E^([Lambda]2 [Phi]0) r !(*SuperscriptBox[(b), * TagBox[ RowBox[{"(", "3", ")"}], Derivative], MultilineFunction->None])[r] == 0, -((2 [Lambda]1 a[r])/r) + ( 8 E^([Lambda]2 [Phi]0) [Lambda]1 a[r])/(3 r) - ( 8 E^([Lambda]2 [Phi]0) [Lambda]2 a[r])/(3 r) - ( 4 [Lambda]1 b[r])/r^3 + ( 16 E^([Lambda]2 [Phi]0) [Lambda]1 b[r])/(3 r^3) - ( 16 E^([Lambda]2 [Phi]0) [Lambda]2 b[r])/( 3 r^3) - ([Lambda]1^2 [Phi][r])/r^2 + ( 4 E^([Lambda]2 [Phi]0) [Lambda]1^2 [Phi][r])/(3 r^2) + ( 4 E^([Lambda]2 [Phi]0) [Lambda]2^2 [Phi][r])/(3 r^2) + ( 16 E^([Lambda]2 [Phi]0) [Lambda]2 Derivative[1][b][r])/( 3 r^2) - ( 8 E^([Lambda]2 [Phi]0) [Lambda]2 (b^[Prime][Prime])[r])/( 3 r) + ([Phi]^[Prime][Prime])[r] == 0}, {a[r], b[r], [Phi][r]}, r] or you can use: $DSolve[{3 E^(-\\[Lambda]2 \\[Phi]0) r a[r] - 1/2 \\[Lambda]1 \\[Phi][r] + 3/8 E^(-\\[Lambda]2 \\[Phi]0) \\[Lambda]1 \\[Phi][r] - 1/2 \\[Lambda]2 \\[Phi][r] + 3/2 E^(-\\[Lambda]2 \\[Phi]0) r^2 Derivative[1][a][r] - 2 Derivative[1][b][r] + 3/2 E^(-\\[Lambda]2 \\[Phi]0) Derivative[1][b][r] - r \\[Lambda]2 Derivative[1][\\[Phi]][r] + r^2 \\!\\(\\*SuperscriptBox[\\(b\\), \\* TagBox[ RowBox[{"(", "3", ")"}], Derivative], MultilineFunction->None]\\)[r] == 0, -((6 b[r])/r^2) - (3 \\[Lambda]1 \\[Phi][r])/(8 r) + ( E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]1 \\[Phi][r])/(2 r) + ( E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 \\[Phi][r])/(2 r) - 21/2 r Derivative[1][a][r] + (9 Derivative[1][b][r])/(2 r) + ( 2 E^(\\[Lambda]2 \\[Phi]0) Derivative[1][b][r])/r + E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 Derivative[1][\\[Phi]][r] - 9/2 r^2 (a^\\[Prime]\\[Prime])[r] - 3 (b^\\[Prime]\\[Prime])[r] - E^(\\[Lambda]2 \\[Phi]0) r \\!\\(\\*SuperscriptBox[\\(b\\), \\* TagBox[ RowBox[{"(", "3", ")"}], Derivative], MultilineFunction->None]\\)[r] == 0, -((2 \\[Lambda]1 a[r])/r) + ( 8 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]1 a[r])/(3 r) - ( 8 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 a[r])/(3 r) - ( 4 \\[Lambda]1 b[r])/r^3 + ( 16 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]1 b[r])/(3 r^3) - ( 16 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 b[r])/( 3 r^3) - (\\[Lambda]1^2 \\[Phi][r])/r^2 + ( 4 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]1^2 \\[Phi][r])/(3 r^2) + ( 4 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2^2 \\[Phi][r])/(3 r^2) + ( 16 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 Derivative[1][b][r])/( 3 r^2) - ( 8 E^(\\[Lambda]2 \\[Phi]0) \\[Lambda]2 (b^\\[Prime]\\[Prime])[r])/( 3 r) + (\\[Phi]^\\[Prime]\\[Prime])[r] == 0}, {a[r], b[r], \\[Phi][r]}, r]$


how to define roots of an equation as a function?

I need to solve an equation depending on 3variables in only one variables and define the roots as a function of the remaining variables? I used some thing like that:               root[x_,y_]:=Solve[x^2+y^2+z^2==0,z][1];      but it doesn't ?


Testing if a specific expression is a solution for ordinary differential equation

I would like to know what is the full command details of wanting to test if a specific expression is a solution for ordinary differential equation (without using DSolve). Thanking you in advance for your assistance.


how can I make a control for my vector equation in my simulation?

I'm trying to build a control selector or menu for equations to put into my curvature simulations. However all the code I've tried hasn't worked.Does anyone know how I could make a control selector or menu for a position vector r[t] in my simulation?               r[t_] := {3 Cos[t], Sin[t]}     uT[t_] := Simplify[r'[t]/Norm[r'[t]], t \[Element] Reals]     vN[t_] := Simplify[uT'[t]/Norm[uT'[t]], t \[Element] Reals]     x[t_] := r[t][[1]]     y[t_] := r[t][[2]]          y2[t_] = r[t] + ((1/(uT[t]/r'[t])) vN[t])          OlcusionPoint[t_] := y2[t][[1]]     (*-((((x'[t])^2+(y'[t])^2)*y'[t])/((x'[t]*y''[t])-(x''[t]*y'[t])))*)     OclusionPoint2[t_] := y2[t][[2]]          (*+((((x'[t])^2+(y'[t])^2)*x'[t])/((x'[t]*y''[t])-(x''[t]*y'[t])))*)     Manipulate[      Show[Graphics[{RGBColor[0.6, 0.6, 0.8],          Disk[{OlcusionPoint[t], OclusionPoint2[t]},           Abs[1/(uT[t]/r'[t])]]}],        ParametricPlot[{x[t], y[t]}, {t, 0, 2 Pi}],        Graphics[{PointSize[.025], Point[{x[t], y[t]}]}]], {t, 0.0001,        2 Pi}]


Nested function problem

I have trouble defining the following function in _Mathematica_               sp[M_, u_] := 1/Sum[u^k M!/(M - k)!, {k, 0, M}]      After defining it _Mathematica_ displays an error. And in fact it prints a pair of values, but my application requires only one, i.e 2 argument function. As the result I need to plot this function in 3D with `u` changing from `0.01` to `1`, and `M` changing `1` to `100`. Any suggestions?


marking the points of x-intercept on a plot

OK, I have a nice plot of some oscillating motion. I can read some stuff off the graph, but I thought it would be cool to show a dot where the curve hits the x-axis and a little label showing the coordinates, and thus get a direct measure of the period of oscillation. (I know there are equations for that but that's not quite the point of the exercise). Anyhow, here's the code I am using               Clear[x1, x2, v1, v2];Clear[x1, x2, v1, v2];     ti = 0; tf = 4.; delta = (1/40);     x1[ti] = -0.04; x2[ti] = -0.04; v1[ti] = 0.0; v2[ti] = 0.0;     m1 = 0.1890; m2 = 0.1898; k = 3.65; kc = 3.5;     Do[ F1[t] = -k*x1[t] - kc*(x1[t] - x2[t]);       F2[t] = -k*x2[t] - kc*(x2[t] - x1[t]);      v1[t + delta] = v1[t] + (F1[t]/m1)*delta;       v2[t + delta] = v2[t] + (F2[t]/m2)*delta;     x1[t + delta] = x1[t] + v1[t + delta]*delta;          x2[t + delta] = x2[t] + v2[t + delta]*delta,      {t, ti, tf, delta}]      x1data = Table[{t, x1[t]}, {t, ti, tf, delta}];     x1plot = ListPlot[x1data, AxesLabel -> {"t", "x1"}, Joined -> True]      and with it I get a nice graph. I tried using NSolve and didn't get any output at all. So I think NSolve must not be geared to this. Understand I am a rank beginner with Mathematica. So it's ok to assume I am stupid :-) And I know that there are likely more efficient ways to do the curve and such; this is a lab exercise tho. We're testing a simulation against the real data. thanks!


Real and Imaginary parts of solutions to a complex linear ODE system

Consider a complex linear ODE system $x'=Ax$, where $$A=\left( \begin{matrix} 0&1\\\ -2&-i \end{matrix}\right). $$ One can first find the eigenvalues and eigenvectors using `JordanDecomposition` and get the general solutions with `MatrixExp`. Here is my **question** :   Is there a quick way in _Mathematica_ that I can get the solution in the form such that the real and imaginary parts are separated: $$ v(t)=c_1v_1(t)+c_2iv_2(t) $$ where $v_1(t),v_2(t)\in{\mathbb R}$?


Programming paradigm change

I'm new to Mathematica, I've been learning by myself, and, being a Java developer for some time, it makes it hard to adapt. I've tried to solve a Reddit challenge, and I came up with this solution:               str = "[can {and it(it (mix) up)} look silly]"     total = ""     str = StringTake[str, {2, -2}]     inix[strn_] :=        Min[StringPosition[strn, "["], StringPosition[strn, "{"],        StringPosition[strn, "("]];     finix[strn_] :=        Max[StringPosition[strn, "]"], StringPosition[strn, "}"],        StringPosition[strn, ")"]];         howmany[strn_] :=        Length[StringPosition[strn, "["]] +        Length[StringPosition[strn, "{"]] +        Length[StringPosition[strn, "("]];     brackets[x_, y_] :=        If[x != \[Infinity], (total =           StringTake[str, {1, x - 1}] <> " " <>           StringTake[str, {y + 1, -1}] <> " " <> total;           str = StringTake[str, {x + 1, y - 1}]) ,           (total = str <> " " <> total; str = "")];          Do[brackets[inix[str], finix[str]], {i, howmany[str] + 1}];     StringSplit[total, Whitespace]     StringJoin[Riffle[%, " "]]      Is there a better solution? From seeing some Mathematica code, this looks to be terribly big code. I would want just some pointers on how to improve.


How to set the NDSolve method to LSODA

* I notice that off all the `Method` options available for `NDSolve[...]`, `LSODA` is invoked quite automatically for stiff equations when `Method -> Automatic`. Is there a way to set the `Method -> LSODA`? I ask because as `LSODA` switches between Adams' and Gear's method, it should have sub-options to it that I could set (like order etc.)?   * Under `tutorial/NDSolveStiffnessSwitching` I encountered `Needs["DifferentialEquations`NDSolveProblems"]`. What other example problems are available and where can I find documentation on them? * * * Edit (03/24/2011): In light of comments made to this post, I'd also refer readers to page 409 of "The Mathematica Guidebook for Numerics". Springer has this book online and can be found here.


Positioning Vertices in a Graph

I made a graph that has a given number at each vertex: ![Lattice Graph for D_16](http://i.stack.imgur.com/NWURD.png) I want to place vertex 1 above vertex 2 if value of vertex 1 is larger than of vertex 2. And also, vertices with same value should be located on the same horizontal line. Above graph satisfies the condition. (I think because of luck.) But, another graph constructed by the same function does not satisfy it: ![Lattice Graph for D_10](http://i.stack.imgur.com/ZeKeU.png) Here 5 is not above 2. How can I implement this condition? (The height of the gap between 2 and 5 does not need to be exactly 3 times the height gap between 1 and 2.) ==== Editted ==== Here is the code for function makes the graph. (I simplified it.)               LatticeGraph[group_] :=         Module[{subgroup = (*omitted*), nodes, edges, list},             nodes = Table[Property[Labeled[i, Placed[subgroup[[i]], Center]],(*VertexStyle Omitted*)], {i, 1, Length[subgroup]}];             list = {(*Omitted and it's used for generate edges*)}             edges = {(*Omitted and it was just the list of v1->v2*)};                  Graph[nodes, edges, VertexSize -> Large,EdgeShapeFunction -> GraphElementData["Line"], ImagePadding -> 20]]


Density matrix - Mathematica

I would to write a density matrix "matr" related to a quantum system in a mixed state. "Ham" is the Hamiltonian of N-spin system. The code I wrote is:               {evl, eve} = Quiet[Eigensystem[Ham]];     ord = Ordering[evl];     evl = evl[[ord]];     eve = eve[[ord]];     matr = ConstantArray[0, {2^(Nspin/2), 2^(Nspin/2)}];     Monitor[Do[re = matrix[eve[[1]], a2, a1, Nspin];       matr[[a2, a1]] = re; matr[[a1, a2]] = re, {a1, 1, 2^(Nspin/2)}, {a2,         1, a1}], {a1, a2}]      The time needed to solve the problem for a large number of Nspin it's quite long. I woul like to know if is possible to modify the code in order to make the process faster.


Parallelization of REvaluate[]?

Is there a way to run several RLink computations via REvaluate[] in parallel, e.g. with ParallelTable[]?


Create a Matrix out of two matrices

I have two matrices `A = {{a1,a2},{b1,b2}}` and `B = {{x1,x2},{y1,y2}}`. I would like to create out of these matrices a new matrix `C={{{a1,x1},{a2,x2}},{{b1,y1},{b2,y2}}}` which I would like at the end transform to this form `{{a1,x1},{a2,x2},{b1,y1},{b2,y2}}`. Of course, I am looking for a solution to the general case. Thanks.


Plot hermite spline

I'm new to Mathematica and cannot figure out a way to plot a 2d hermite spline. My points are: $p_0=\\{143.05;195.606\\};$ $p_1=\\{159.373;181.845\\};$ $p_2=\\{160.891;179.26\\};$ $p_3=\\{176.423;171.878\\};$ I need to plot the spline from $p_0$ to $p_1$ I calculate Catmull-Rom tangents in the following way: $\left(t_1=0.5 \left(p_2-p_0\right);\right)$ $\left(t_2=0.5 \left(p_3-p_1\right);\right)$ Calculating the weights: $$ \left(h_1(\text{t$\\_$})\text{:=}2 t^3-3 t^2+1;\right) \left(h_2(\text{t$\\_$})\text{:=}3 t^2-2 t^3;\right) \left(h_3(\text{t$\\_$})\text{:=}t^3-2 t^2+t;\right) \left(h_4(\text{t$\\_$})\text{:=}t^3-t^2;\right) $$ And finaly the spline function: $$ P(\text{t$\\_$})\text{:=}\left\\{h_1 p_1.x+h_2 p_2.x+h_3 t_1.x+4 h_4 t_2.x;h_1 p_1.y+h_2 p_2.y+h_3 t_1.y+4 h_4 t_2.y\right\\}; $$ And trying to plot it: $$\text{ParametricPlot}[\\{P(t)\\},\\{t,0,1\\}]$$ But I'm getting some strange errors:               SetDelayed::write: Tag Plus in (1-3 t^2+2 t^3)[t_] is Protected. >>      What does it mean? Please provide me with a complete solution to plotting a hermite spline. Thanks! **UPDATE:** My mathematica code is:               Subscript[p, 0] = {143.0497; 195.6056};     Subscript[p, 1] = {159.3734; 181.8449};     Subscript[p, 2] = {160.8912; 179.2604};     Subscript[p, 3] = {176.423; 171.8781};          Subscript[t, 1] = (Subscript[p, 2] - Subscript[p, 0]) * 0.5;     Subscript[t, 2] = (Subscript[p, 3] - Subscript[p, 1]) * 0.5;          Subscript[h, 1][t_] := 2 * t^3 - 3*t^2 + 1;     Subscript[h, 2][t_] := -2*t^3 + 3*t^2;     Subscript[h, 3][t_] := t^3 - 2*t^2 + t;     Subscript[h, 4][t_] := t^3 - t^2;          P[t_] := {Subscript[h, 1][t] * Subscript[p, 1].x +          Subscript[h, 2][t] * Subscript[p, 2].x +          Subscript[h, 3][t] * Subscript[t, 1].x +          Subscript[h, 4] [t]* Subscript[t, 2].x;         Subscript[h, 1][t] * Subscript[p, 1].y +          Subscript[h, 2][t] * Subscript[p, 2].y +          Subscript[h, 3][t] * Subscript[t, 1].y +          Subscript[h, 4][t] * Subscript[t, 2].y};          ParametricPlot[{P[t]}, {t, 0, 1}]


How to express an expression with only ArcTan and ArcTanh?

I have an expression which is simply               (j/k) x^(j/k) LerchPhi[x,1,j/k)]       where `0 < j < k`. Manually I have been able (tedious work) to obtain only `ArcTan`'s and `ArcTanh`'s. How could I ask _Mathematica_ to do this automatically in the most compact form ?


Defining and evaluating new continuous distributions based on Mathematica's distributions

A number of functions operate with Mathematica's set of distributions e.g.               Through[{Mean, StandardDeviation, Variance}[UniformDistribution[{umin,umax}]]]      which returns the correct result                   {(umax + umin)/2, (umax - umin)/(2 Sqrt[3]), 1/12 (umax - umin)^2}      However, when I add two continuous distributions, thus creating a kind of annular distribution, it will not be evaluated.               Through[{Mean, StandardDeviation, Variance}[       UniformDistribution[{umin, umax}] -         UniformDistribution[{\[Epsilon] umin, \[Epsilon] umax}]]]      I think I had a very good look at the Mathematica documentation but I simply could not find any indication of how to define "my own distribution". Please note, that I know how to handle such functions, i.e., how to calculate the `Mean` ... The issue of this question is, are there ways in Mathematica, I have missed, that allow me to use Mathematica's functionality on distributions with my distributions I have defined using Mathematica's distributions.


Using a predicate to control the application of a rule in a replacement

How can I make a replacement rule that will only be applied to those parts of an expression that will not break a condition placed on the whole expression? For example, suppose I have $\frac{xy}{(x-y)(x+y)}$ and I want to change $y$ to $x$ getting the result $\frac{x^2}{(x-y)2x}$; i.e., without turning original expression into infinity. Further, I don't want the replacement to raise warnings or errors. At the least, I need a way to do a replacement just once, which seems like it should be very easy, but I have no idea how to do it. I came up with               ReplaceOnce[expr_, rule_Rule] := MapAt[# /. rule &, expr, Position[expr, rule[[1]]][[1]]]      How can I get to my goal from here?


Faster Alternatives to DateDifference

I need a faster implementation of `FractionOfYear` and `FractionOfMonth`, which do the following: **Input:** A time/date specified by `{y_, m_, d_, h_, n_, s_}` **Output:** A real number from 0 to 1 representing the fraction of the year or month that the given time/date spec occurs in. Leap days and leap seconds complicate things, so I thought I could just rely on `DateDifference`, but it is too slow:               RandomDateList[] := {RandomInteger[{1800, 2100}], RandomInteger[{1, 12}], RandomInteger[{1, 28}], RandomInteger[{0, 23}], RandomInteger[{0, 59}], RandomInteger[{0, 59}]};     RandomDates[n_] := Table[RandomDateList[],{n}]          secondOfYear[{y_, m_, d_, h_, n_, s_}] :=         First[DateDifference[{y - 1, 12, 31, 24, 0, 0}, {y, m, d, h, n, s},                     "Second"]] / First[DateDifference[{y - 1, 12, 31, 24, 0, 0}, {y, 12, 31, 24, 0, 0}, "Second"]]          secondOfMonth[{y_, m_, d_, h_, n_, s_}] := First[DateDifference[{y, m, 1, 0, 0, 0},      {y, m, d, h, n, s}, "Second"]]/First[DateDifference[{y, m, 1, 0, 0, 0}, If[m==12, {y+1, 1, 1, 0, 0, 0}, {y, m+1, 1, 0, 0, 0}], "Second"]]      `AbsoluteTiming [secondOfYear /@ RandomDates[1000]]` takes 6 seconds. There must be a faster easier way of doing this! I'll accept the first answer that takes under a second for 100,000 elements.


Mathematica Opens Each Session With Beep

First off, I am using Mathematica 8.0 and Mac OS X 10.7.4. Recently, when starting a new Mathematica session, I am confronted with an error beep and message window stating "The file you tried to open was not found or could not be opened." That said, I can simply click OK, and the error box vanishes which seemingly no more problems. This is potentially a problem for me, because I have scripts set up on my computer that instruct Mathematica to open at particular times, then do particular tasks. I also want to add that I am using Dropbox to access Mathematica files in the cloud, but I never open and evaluate any one file in the cloud at the same time. Any advice or thoughts would be appreciated.


LibraryLink parallel performance

I'm trying to use a LibraryLink function in parallel. It is an embarrassingly parallel problem, so that no dependency between those parallel tasks. However I can only get the parallel efficiency about 0.68. So is it possible to increase this parallel efficiency, or that is just the best I can expect from Mathematica? Here is a simplified example and some benchmark of the performance. The test was performed in version 9 for linux on Red Hat Enterprise Linux 6, on a computer node with 16 cores (two 8-Core Sandy Bridge Xeon E5-2670 64-bit processors). **Define of the library function**               lf = Compile[{{n, _Real}},        Sum[Sin[Sin[Exp[I x]]]^2, {x, 0., 1000 n, 0.1}],        CompilationTarget -> "C"];          lf[10] // AbsoluteTiming     (*{0.028269, 2.3085 + 0.363265 I}*)          LCM[2, 4, 6, 8, 10, 12, 14, 16]     (*1680*)      **Test the performance using different parallel methods** single evaluation time 0.028 second               lf[10] // AbsoluteTiming     (*{0.028207, 2.3085 + 0.363265 I}*)          tSerial = AbsoluteTiming[Sum[lf[10], {x, 1, 1680}]][[1]]     (*47.253332*)      Method->"FinestGrained"               speedupIdeal = Table[{n, n}, {n, 2, 16, 2}];     timeIdeal = Table[tSerial/n, {n, 2, 16, 2}];     timeFG = Table[       CloseKernels[]; LaunchKernels[n]; DistributeDefinitions[lf];       {n, AbsoluteTiming[          ParallelSum[lf[10], {x, 1, 1680}, Method -> "FinestGrained"]][[1]]},       {n, 2, 16, 2}]     (*{{2, 27.148232}, {4, 14.178885}, {6, 9.885146}, {8, 7.751356}, {10,        6.633211}, {12, 5.887295}, {14, 4.141049}, {16, 3.978317}}*)      Method->"EvaluationsPerKernel"->1               time1perK = Table[       CloseKernels[]; LaunchKernels[n]; DistributeDefinitions[lf];       {n, AbsoluteTiming[          ParallelSum[lf[10], {x, 1, 1680},            Method -> "EvaluationsPerKernel" -> 1]][[1]]},       {n, 2, 16, 2}]     (*{{2, 24.009900}, {4, 12.616673}, {6, 8.320600}, {8, 6.372430}, {10,        5.095200}, {12, 4.477966}, {14, 4.131756}, {16, 3.680885}}*)      Method->"CoarsestGrained"               timeCG = Table[       CloseKernels[]; LaunchKernels[n]; DistributeDefinitions[lf];       {n, AbsoluteTiming[          ParallelSum[lf[10], {x, 1, 1680}, Method -> "CoarsestGrained"]][[1]]},       {n, 2, 16, 2}]         (*{{2, 23.918878}, {4, 13.041166}, {6, 8.958082}, {8, 6.629995}, {10,        5.615827}, {12, 4.408525}, {14, 4.123634}, {16, 3.507930}}*)      compare speedup               ListPlot[{       speedupIdeal,       timeFG /. {x_, y_} -> {x, tSerial/y},       time1perK /. {x_, y_} -> {x, tSerial/y},       timeCG /. {x_, y_} -> {x, tSerial/y}       }, PlotRange -> All, Joined -> True, Mesh -> All, Axes -> False,       Frame -> True, FrameLabel -> {"number of kernel", "speedup"},       FrameStyle -> Large,       PlotLegends ->        LineLegend[{"ideal", "FinestGrained", "EvaluationsPerKernel\[Rule]1",          "CoarsestGrained"}]]      ![enter image description here](http://i.stack.imgur.com/NqMe3.jpg) * * * **Update** In order to test whether this slow down comes from the LibraryLink or just the parallel mechanism, here are two tests. The first one using a function that only compiled to the virtual machine, the second one without compile. **Compile to VM** The same as above, just change               lf = Compile[{{n, _Real}},        Sum[Sin[Sin[Exp[I x]]]^2, {x, 0., 1000 n, 0.1}]]      ![enter image description here](http://i.stack.imgur.com/BIkzi.jpg) **No compile** The same as above, but change               lf = Function[{n}, Sum[Sin[Sin[Exp[I x]]]^2, {x, 0., 1000 n, 0.1}]]      and also all `lf[10]` were changed to `lf[1]` to account for the slowness of uncompiled function. ![enter image description here](http://i.stack.imgur.com/zijYU.jpg)


Rasterize uses default stylesheet if ImageSize is specified

If I make a style definition which affects `GraphicsBox`, the style is used by `Rasterize` _unless_ I specify an explicit `ImageSize`. For example, I set a style for `GraphicsLabel`: ![enter image description here](http://i.stack.imgur.com/juvzS.png) Then I can rasterize a plot and the defined style is used:               p = Plot[x, {x, 0, 1}];     Rasterize[p]      ![enter image description here](http://i.stack.imgur.com/ZqPsJ.png) But if I specify the `ImageSize` the default style is used instead:               Rasterize[p, ImageSize -> 200]      ![enter image description here](http://i.stack.imgur.com/0T7yK.png) I would be interested to know why this happens and how I can work around it, i.e. rasterize at a specific size using the local style definitions.


Solving Heat equation

I want to compute the exact solution of the heat equation but I got an error. u(x,t) (equation of transmition of heat) is the solution of this differential equation: $$du/dt - \alpha d^2u/dx^2 = 0$$ $$u(x,0) = g(x) = 1/(1+x^2)^{0.25}$$ $$ u(-10,t) = u(10,t) = 0$$ $\alpha = 2/10$ I computed:               pde = D[u[x, t], t] - 0.2 D[u[x, t], {x, 2}] == 0     DSolve[pde, u[x, 0] == 1/(1 + x^2)^0.25`, u[-10, t] == 0, u[10, t] == 0, u[x, t], {x, t}]      However, I got an error: DSolve::dsvar: u[-10,t]==0 cannot be used as a variable. >> What am I doing wrong? Thanks for your help.


Specific entry of inverse of large matrix

Given a large (say 10x10) sparse Hermitian matrix with symbolic entries, I need four specific entries of the inverse matrix. It seems wasteful to me to compute 100 entries of which I only need a few in the end. Is there a way to compute a small number of specific entries of the inverse matrix that is significantly more efficient than finding the inverse matrix and then extracting the elements? Here's an example. N is half the dimension of the matrix. For N = 8, inverting takes 51 seconds on my university's computer, and we would ideally like to reach much larger N.               A = Table[If[Abs[i - j] == 1, (j - i) a, 0], {i, #}, {j, #}] &;     B = Table[If[Abs[i - j] == 1, b, 0], {i, #}, {j, #}] &;          \[Sigma]1[N_] := B@N + Table[         If[Abs[i - j] == 0, 2 \[Mu], 0] + If[i == j == 1, -x, 0] +           If[i == j == N, -x, 0]         , {i, N}, {j, N}];     \[Sigma]2[N_] := -B@N + Table[         +If[i == j == 1, -y, 0] + If[i == j == N, -y, 0]         , {i, N}, {j, N}];          (* Elements of M *)     el[N_, i_, j_] := Which[i <= N && j <= N,       \[Sigma]1[N][[i, j]], i > N && j > N,       \[Sigma]2[N][[i - N, j - N]], i > N && j <= N,       A[N][[i - N, j]], i <= N && j > N,       -A[N][[i, j - N]]]           M[N_] := Table[el[N, i, j], {i, 2 N}, {j, 2 N}];      Daniel Lichtblau's idea `LinearSolve[M@8,UnitVector[16,8]]` takes 4.1 seconds, so it is certainly much faster than inverting the entire matrix, even if it has to be done seperately for each entry.


Georeferenced bitmaps

The command `Export["filename.jpg", graphic]` will export the graphic object `graphic` to the file `filename.jpg` in versions > 8 (at least). TIFF's are also used. I am interested in georeferenced bitmaps which can be used with various GIS's, and the default export command does not produce appropriate files. Has anybody found a way of exporting graphics in such a way that they are georeferenced?


Define a function with the condition that it must be positive

I have a function `f(x)` and I want to define a new function `g(x)` that is equal to `f(x)` only when `f(x)` is positive. What is the right way to do that? Sorry for this silly question, but I cannot find the proper way to accomplish this simple task in _Mathematica_.


AccuracyGoal, PrecisionGoal, WorkingPrecision and NDSolve

I'm trying to understand exactly what `WorkingPrecision`, `AccuracyGoal` and `PrecisionGoal` mean for the result of `NDSolve`. I presume `WorkingPrecision` simply means the number of decimal places used internally by _Mathematica_ at various points throughout the calculation on its scratchpad, and therefore essentially gives upper limit to what the accuracy/precision of final result can be. Now I understand Accuracy/Precision somewhat in the lab sense (Accuracy is how close you are to the true value, Precision is how repeatable the value you get is in some sense; or to use the dartboard analogy-if you're near the bullseye that's accurate-if you hit the the outskirts in the same place 100 times that's precise but not accurate), but not sure I know how these correlate to the _Mathematica_ concepts... If I set `AccuracyGoal->3`, `PrecisionGoal->4` in `NDSolve`, what does that say about the function I get spat out? It looks like the definition on the help pages is that `AccuracyGoal` of 3 would mean 3 significant figures are correct, whereas `PrecisionGoal` of 4 would give 4 digits after the decimal are correct... e.g if the answer spat out is $89.7895$. What does it mean though in this case to say 3 significant figs are correct, but 4 digits after decimal place are also correct? Seems inconsistent (just a rule of thumb?). The help pages also state: > With `AccuracyGoal->a` and `PrecisionGoal->p`, _Mathematica_ attempts to > make the numerical error in a result of size be less than > $10^{-a}+|x|10^{-p}$ Does this mean if I did have `AccuracyGoal->3`, `PrecisionGoal->4` and `NDSolve` spat out $89.7895$ the numerical error would be $10^{-3}+89.7895\cdot 10^{-4}=0.0997895$ ? so my answer is really $89.7895\pm 0.0997895$ ? or is there a different definition of numerical error here? Thanks for any clarifications.


Double integral with variable in the limits

I'm trying to solve this integral: $$ \left(\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi}\sigma}e^\frac{-x^2}{2\sigma^2}\left(\int_{x}^{\infty}\frac{1}{\sqrt{2\pi}\sigma}e^\frac{-(y-\mu)^2}{2\sigma^2}dy\right)^ndx\right)^k $$ and that is what i found in one of post:               NIntegrate[((1/(Sqrt[2*Pi]*\[Sigma]))*Exp[-(x^2/(2*\[Sigma]^2))])*        ((1/(Sqrt[2*Pi]*\[Sigma]))*      Exp[-((y - \[Mu])^2/(2*\[Sigma]^2))]),       {x, -Infinity, Infinity}, {y, x, Infinity}]^k      dont know where to put the 'n' power ?


how to generate mesh functions according to more that one condition?

how to generate mesh functions according to more than one condition? This plot will have mesh according to z:               Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}, MeshFunctions -> {#3 &}]      This plot will have mesh according to x:               Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}, MeshFunctions -> {#3 &}]      how to generate MeshFunctions with more that one conditions? I want something like this:               Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2},       MeshFunctions -> {#1 || #3 &}]


Matrix Rotation

If I have a matrix of any size, say $\begin{pmatrix} 72 & 32 & 64 \\\ 18 & 8 & 16 \\\ 63 & 28 & 56 \\\ \end{pmatrix}$ $\begin{pmatrix} 72 & 32 \\\ 18 & 8 \\\ 63 & 28 \\\ \end{pmatrix}$ How can I rotate/transform it exactly 45 Degrees (diagonal becomes row) to look like below matrix (preferably sparse array) (not as image) ? Prefer a generic solution Imagine looking towards 63 in the above matrix diagonally from 64 and fill the space between numbers with zero ![diagram for rotating a matrix](http://i.stack.imgur.com/stwgt.png) ![another diagram](http://i.stack.imgur.com/13NRe.png) $\begin{pmatrix} 0 & 0 & 64 & 0 & 0 \\\ 0 & 32 & 0 & 16 & 0 \\\ 72 & 0 & 8 & 0 & 56 \\\ 0 & 18 & 0 & 28 & 0 \\\ 0 & 0 & 63 & 0 & 0 \\\ \end{pmatrix}$ $\begin{pmatrix} 0 & 32 & 0 & 0 \\\ 72 & 0 & 8 & 0 \\\ 0 & 18 & 0 & 28 \\\ 0 & 0 & 63 & 0 \\\ \end{pmatrix}$ **Background**               below function f generates outer product of digits     f = Outer[Times, ##] & @@ IntegerDigits /@ # &     f[{123, 456}]               4   5   6     8   10  12     12  15  18      When this Matrix is rotated 45 degrees               rotate45@f[{123, 456}]          0   0   6   0   0     0   5   0   12  0     4   0   10  0   18     0   8   0   15  0     0   0   12  0   0      Total of rotated matrix results in               Total@rotate45@f[{123, 456}]          4  13       28      27      18      Adding above list in following way result is 123 * 456 .               04      13       28        27         18      56088      I am trying to create a demonstration to depict this in an interesting way _will share the details when done_. See this for further details


how to solve this ode problem?

NDSolve::ndnum: Encountered non-numerical value for a derivative at x \ == 0.`. >> ![enter image description here](http://i.stack.imgur.com/589Md.png)


Assumptions for simplifying a long equation

I'm having trouble combining assumptions with the execution of `Simplify` in a long equation. The idea is to separate imaginary and real parts of a complex equation. Therefore I am trying to assume the variables as reals.               Simplify[-Re[(a+I b) (2-c-d-I e-I f)],       {a ∈ Reals, b ∈ Reals, c ∈ Reals, d ∈ Reals, e ∈ Reals, f ∈ Reals}]          But the output is just ignoring the assumptions. How should I implement it?


Adjusting the pixel values underlying a morphological component when computing an "IntensityCentroid"

When calculating an `"IntensityCentroid"` with `ComponentMeasurements`, i.e. for an image $I$ and set of components $C$, calculating:               ComponentMeasurements[{C, I}, "IntensityCentroid"][[All, 2]]      Is there an easy way for me to threshold or manipulate the underlying pixel values used to compute the intensity centroid? Specifically, I would like to subtract the minimum or mean pixel value in the region defined by the morphological component from all other pixel values in that region, or Floor (i.e. set to zero) pixel values below a certain threshold. Again, I would like to do this locally in the context of each morphological component rather than globally on the image $I$. Is this possible without a lot of work? **Motivation:** Say you're attempting to determine the center of some object to sub-pixel accuracy. If you have a significant amount of "local" background noise (s.t. global thresholding works poorly), a calculated `"IntensityCentroid"` will be biased towards the `"Centroid"` of the morphological component, and this will become worse with the morphological component's size (relative to the size of the object of interest). As such, it would be fantastic to be able to manipulate and do local thresholding on pixels strictly in the region defined by a particular morphological component. Here is an example image (a 450 x 449 pixel PNG file): ![enter image description here](http://i.stack.imgur.com/olryT.png)


Labeled and Graph don't mix?

In an attempt to create a legend for a graph drawing, I find that Labeled only works without the position options (except for `Center`).                  Graph[Range[2], {       Labeled[DirectedEdge[1, 2], "BEFORE"]}]      ![enter image description here](http://i.stack.imgur.com/MeuUW.jpg) But               Graph[Range[2], {       Labeled[DirectedEdge[1, 2], "BEFORE", Bottom]}]      ![enter image description here](http://i.stack.imgur.com/dlFmc.jpg) Similarly for the other `Labeled` position options like `Top`, `Left`, `Right`. Also, adding ImagePadding doens't help. I've tried some - but not all - `Labeled`'s other options:               {Alignment -> {Center, Baseline}, Background -> None,       BaselinePosition -> Automatic, BaseStyle -> {},       DefaultBaseStyle -> "Labeled", DefaultLabelStyle -> "LabeledLabel",       Editable -> Automatic, Frame -> None, FrameMargins -> 0,       FrameStyle -> Automatic, ImageMargins -> 0, ImageSize -> Automatic,       LabelStyle -> {}, RotateLabel -> False, RoundingRadius -> 0,       Selectable -> Automatic, Spacings -> Automatic,       SyntaxForm -> Automatic}      Known issue?


Random numbers that sum up to specific value

I would like to generate a list with random numbers, which add up to a specific value.               While[Total[x] == 28, x = RandomInteger[{0, 28}, 5];Print[x]]      The random number list should be returned if their sume is 28. Unforunately, this loop does not work. :( Can anybody help me?


How to simultaneously change the color and thickness in ContourStyle?

When plotting contours with `ContourPlot`, one can use the option `ContourStyle` to change the contours of the plot. With the instruction,               ContourPlot[f[x,y],{x,-1,1},{y,-1,1},ContourShading -> False, Contours -> Range[1,10], ContourStyle -> ColorData[10] /@ Range[10]]      I am able to change the colors of the contours, but they are thin. On the other hand, if I use the instruction               ContourPlot[f[x,y],{x,-1,1},{y,-1,1},ContourShading -> False, Contours -> Range[1,10], ContourStyle -> Thick]      I am able to draw thicker contour lines, however, they are black. I would like to draw the same contours **simultaneously thicker and colored**. How could I proceed ? Mathematica seems to indicate to use `Directive[...]`, but I have not been able to use it...


About auto-compiling and performance between Do and Fold

I was investigating how `Fold` could improve performance vs `Do`. I tested the code               AbsoluteTiming[        sum = 1.0;        inc = 1.0;        Do[inc = inc*Sin[10.5]/i; sum = sum + Tan[inc], {i, 10^5}];        sum]      The output is               Out[] = {2.303896, 0.105747}      I have hoped that using `Fold` could improve the performance:               AbsoluteTiming@          Fold[{#[[1]]*Sin[10.5]/(#2 + 1), #[[2]] + Tan@#[[1]]} &,             {Sin[10.5], 1.0}, N@Range[10^5]]      However, this code is not faster:               Out[] = {2.471189, {-5.537337857006675*10^-462146, 0.105747}}      I have some questions concerning the above example: (1) [Partially solved. See EDIT] Why the `Fold` here is not faster? I thought it should have been auto-compiled and thus faster. But it didn't. (2) [Solved. See EDIT] Here Mathematica is using precision much higher than double precision (by having number as small as 10^{-462146}). Would it be possible to set precision to boost performance? I tried `SetPricision` and `SetAccuracy`. The precision changes but it doesn't improve performance. (3) [Solved. See Mr. Wizard's example in his answer] Another problem of `Fold` is that one has first to generate a long list (length 10^5 in this example). For much larger list, the `Fold` method may use too much memory. Is it possible to use functional way (not necessarily `Fold`) in a more memory- efficient way? Thank you very much! PS: I met this question when trying to reproduce Mr.Wizard's answer of the below thread, with some modifications. I can reproduce Wizard's result, where `Fold` boots the performance greatly compared with `Do`. But I don't understand why my above example is not as good. Alternatives to procedural loops and iterating over lists in Mathematica **EDIT:** (a) Rojo's comment is the answer of (2): `SetSystemOptions["CatchMachineUnderflow" -> False]` (b) About the performance of Fold: on Mathematica v7 after disabling `CatchMachineUnderflow`, the Fold code is 10x faster then Do code. However, on Mathematica v9 the Fold code is a bit slower than Do. This seems like a regression in Mathematica. For comparison, this code has 10x improvement than the Do version: `Fold[# + Sin[#2] &, 1.0, Range[10^6]]` both on v7 and v9.


How to substitute numeric values in a symbolic Jacobian matrix?

I have a multi-variate function from $\mathbb{R}^n\to\mathbb{R}^n$. Choosing any desired initial vector, we can produce the corresponding function value, which is a vector as follows. The main problem lies in the computation of the Jacobian matrix. In the code below:               dim = 10;     X = Table[Subscript[x, i], {i, 1, dim}]     f[x_] := (n = Length[x];         Table[If[i <= n - 1, x[[i]] x[[i + 1]] - 1, x[[1]] x[[n]] - 1], {i,           1, n}]);     f[X]     J[X] = D[f[X], {X}];     J[X]     Y0 = Table[2, {i, 1, dim}];     f[Y0]     J[Y0]      the Jacobian (the differentiation of `f[x]`) is defined (theoretically) correctly, but I cannot plug any data to obtain the numerical values of the Jacobian matrix!? It would be appreciated if anyone take a look and give some suggestions to find `J[Y0]` correctly? Here `Y0` is the initial vector chosen arbitrary.


How can I make the Cartesian product of a list with itself?

I'm trying to build the table               {{1, 1}, {1, 2}, {2, 1}, {2, 2}}      given the list               {1, 2}      I can do it like this               Flatten[Table[{x1, x2}, {x1, {1, 2}}, {x2, {1, 2}}], 1]      But how can I do this given a very long list, say {1, 2, 3, ..., 100}? I've searched the documentation on `Nest` and `Fold`, but didn't find a solution.


How to use $\LaTeX$ for typesetting labels and titles in Mathematica

I need to typeset large number of equations to be used for `PlotLabel` and `Titles` and such. These have to look nice. Hence I use `TraditionalForm` with `HoldForm` and this works well, except for a tiny little annoying thing. This below is just an example:               TraditionalForm[HoldForm[(v/w) Sin[w t]]]      displays as $\frac{v \ \sin(t)}{w}$ and not as $\frac{v}{w} \sin(t)$. In otherwords, the `Sin[x]` was put in the numerator as well, where I'd like it to remain on its own as was typed. I used `()` above as a hint to leave `Sin[]` alone, but this hint did nothing. An easy fix is to use `HoldForm` around each small sub-expression as follows               TraditionalForm[Row[{HoldForm[(v/w)], HoldForm[Sin[w t]]}]]       which now generates $\frac{v}{w} \sin(t)$ But the above is a small example. I have much larger equations, and would be nice if I could tell _Mathematica_ when I type it, using `()` or another trick, to please not group these subexpression as it did in the above example (I'd like the equations to look exactly as they appear in the text book. It is not a big issue really to use `HoldForm` many times to force the shape to look exactly as I wanted, but just thought to check if someone knows an easier way to do this other than what I have shown. I just had a thought! is it possible to use $\LaTeX$ directly to typeset things in _Mathematica_ for purpose of display? i.e. it would be nice if one can write _something_ like `Text["$\frac{v}{w} \sin(t)$"]` and have _Mathematica_ interpret this as $\LaTeX$, and typeset it as $\LaTeX$ output. If possible, I can just write everything in $\LaTeX$ as strings, and problems solved. What I mean by the above is as follows (only to help explain the point): In MATLAB I can do this:               text(.5,.5,'$\frac{v}{w} \sin(t)$','interpreter','latex','FontSize',18)      which generates ![LaTeX'd formula](http://i.stack.imgur.com/J6D0u.png) Notice I had to tell MATLAB to use the $\LaTeX$ interpreter. But that is all. It will be really nice to be able to do something like this in _Mathematica_ if possible. Using `String`s also avoids many other problems when typesetting symbolic expressions in _Mathematica_ since a string is inert and a raw `Symbol` and can't have value other than itself. Thanks.


How to plot a x bar control chart?

Does anyone know how to plot a x bar control chart? With mu=12.5, sigma=.8? I have searched all over mathematica documentation center but still couldn't figure out how?


Getting data through a serial port

I need to receive data from a serial port and save it to a list so I can use it later. Since the input will depend on human interaction, My program must keep running and saving as long as data is available from the port. Whats the best way to do that?


Graphically representing error in a Riemann Sum

I am trying to graphically represent the error in a Riemann sum. My current code looks like:                   Show[DiscretePlot[Log[t], {t, 1, 10, 1}, ExtentSize -> Left, PlotMarkers -> "Point"],                Plot[Log[t], {t, 1, 10}]]      ![The output of the above code](http://i.stack.imgur.com/gZCcT.png) I would know like to plot JUST the curve-linear triangles above the plot of ln(x) that represents the error in the Riemann Sum.


How to combine DifferenceRoot objects for odd and even-indexed terms

I'm trying to analyze a certain infinite sequence $S$, indexed by positive integers starting from $1$. It can be split into two subsequences:   * $S^{odd}$ by removing all even-indexed elements and keeping all odd-indexed ones, and   * $S^{even}$ by removing all odd-indexed elements and keeping all even-indexed ones. Each of these two sequences has its own indexing by positive integers starting from $1$, so indexes of their elements do not match indexes of corresponding elements in $S$, e.g. $S^{odd}_3=S_5$, $S^{even}_2=S_4$. I got two different `DifferenceRoot` expressions representing $S^{odd}$ and $S^{even}$. I would like to merge them into a single `DifferenceRoot` expression representing $S$. I suppose I need to somehow align their indexing and then use `DifferenceRootReduce`. > What is the simplest way to do that?


Getting all physical units with prefixes

How we can get the list with all physical units and prefixes from WolframAlpha and make symbols from the result to be equal their corresponding quantities like described in this post?