DSolve doesn't find a solution

I have this partial differential equation (G and M are constants): ![enter image description here](http://i.stack.imgur.com/irS7q.png) and a solution is: ![enter image description here](http://i.stack.imgur.com/6xKu8.png) Mathematica doesn't find any solutions. My code for DSolve is:               DSolve[-2*G*M^2*r*Derivative[0, 2][γ][r, z] + 2*G*M^2*Derivative[1, 0][γ][r, z] +        2*G*M^2*r*Derivative[2, 0][γ][r, z] == 0, γ[r, z], {r, z}]      and as a result I just got an echo: ![enter image description here](http://i.stack.imgur.com/70VyT.png) Any suggestions? Or nothing can be done in this case?


Setting bash environment within external call

I would like to run external command from _Mathematica_. For this I need to have bash environment configured via reading the content of `${HOME}/.bashrc` file. When I execute the following code in _Mathematica_ notebook               ReadList["!echo $PATH", String]      the content of `PATH` variable is not set as it is in `${HOME}/.bashrc`. The same happens when I explicitly load bash configuration file               ReadList["!source ${HOME}/.bashrc; echo $PATH", String]      (strictly speaking the above command makes no effect!). So the question is: is it possible to load the configuration stored in `.bashrc` file in _Mathematica_ external call under the Linux system (of course without explicitly setting e.g. mentioned `PATH` variable is not a solution for me)?


Adding a constant vector to a vector differential equation seems to break NDSolve. Why?

I'm trying to solve a differential equation that's phrased in terms of matrices and vectors. My minimum working example is this:               g = {1, 2}     k = 1.5*IdentityMatrix[2];     d = 2*Sqrt[k];     x0 = {1, 3};     v0 = {0, 0};          soln = NDSolve[{x''[t] == k.x[t], x[0] == x0, x'[0] == v0}, x, {t, 0, 2}]     Plot[Evaluate[x[t] /. soln], {t, 0, 2}]      It works fine, and plots two lines against time. AFAIU, this is the solution the system of differential equations: $ \left[\begin{array}{c} \ddot{x}_{1}\\ \ddot{x}_{2} \end{array}\right]=\left[\begin{array}{cc} 1.5 & 0\\ 0 & 1.5 \end{array}\right]\left[\begin{array}{c} x_{1}\\ x_{2} \end{array}\right].$ But it seems to break if I add a constant vector to the RHS:               g = {1, 2}     k = 1.5*IdentityMatrix[2];     d = 2*Sqrt[k];     x0 = {1, 3};     v0 = {0, 0};         soln = NDSolve[{x''[t] == k.x[t] + g, x[0] == x0, x'[0] == v0}, x, {t, 0, 2}]     Plot[Evaluate[x[t] /. soln], {t, 0, 2}]      Now this should be solving the system: $\left[\begin{array}{c} \ddot{x}_{1}\\ \ddot{x}_{2} \end{array}\right]=\left[\begin{array}{cc} 1.5 & 0\\ 0 & 1.5 \end{array}\right]\left[\begin{array}{c} x_{1}\\ x_{2} \end{array}\right]+\left[\begin{array}{c} 1\\ 2 \end{array}\right]$ But instead,I now get the error "NDSolve::ndfdmc: Computed derivatives do not have dimensionality consistent with the initial conditions. >>". I don't understand why this happens. It seems like the dimensionality of the differential equation matches that of the initial conditions, matches that of the added vector. Why am I getting this error? **EDIT: Thanks for the workarounds! I think this is approaching bug territory. I've filed a complaint here (http://www.wolfram.com/support/contact/email/ ) and encourage others to do the same.**


How to create tournament bracket

I'd like to create a tournament bracket using Mathematica. I've looked around online, but haven't found any examples yet. Can someone show me how to do this? Specifically, I'd like to have a (somewhat) arbitrary number of participants in a double-elimination bracket. **Edit** by belisarius An example of a double elimination bracket follows ![enter image description here](http://i.stack.imgur.com/lfFRj.png) Each team has to be beaten twice to be eliminated. There are a winners and a losers circuit, and when a team loses a match in the winner's side, it enters the losers circuit in an appropriate place, so not to be confronted with past competitors.


Spectral Clustering

I am interested in the following question: How is it possible to check whether an algorithm is working properly? However, this question is too general for the post and I'd like to restrict attention to spectral clustering. Using the standard Gaussian similarity function found in section 2.2 of this paper http://www.kyb.mpg.de/fileadmin/user_upload/files/publications/attachments/Luxburg07_tutorial_4488%5b0%5d.pdf and setting the parameter sigma to 1 I have constructed the following code:               (*Note: Parameter sigma is denoted as epsilon*)          SpectralCluster[data_, k_, ε_]:=Module[{Similarity, Weight, Walk, LRW, Eigenvals, Eigenvecs, Kvecs},         Similarity= With[{tr = Transpose[data]},Function[point, Exp[-Sqrt[Total[(point-tr)^2]]/ε]] /@data];     Weight = DiagonalMatrix[Total /@ Similarity];     Walk = Inverse[Weight].Similarity;     LRW = IdentityMatrix[Length[Similarity]] - Walk;     {Eigenvals, Eigenvecs} = Eigensystem[LRW];     Kvecs = Take[Eigenvecs, k];     ClusteringComponents[Kvecs, k, 1, Method ->"KMeans",DistanceFunction->SquaredEuclideanDistance]]      Before testing the algorithm I generate the following data:               x1=RandomVariate[MultinormalDistribution[{2, 0},{{1, 0},{0, 8}}],25];     x2=RandomVariate[MultinormalDistribution[{4, 0},{{1, 0},{0, 8}}],25];     x3=RandomVariate[MultinormalDistribution[{6, 0},{{1, 0},{0, 8}}],25];     x4=RandomVariate[MultinormalDistribution[{8, 0},{{1, 0},{0, 8}}],25];     pts=Join[x1,x2,x3,x4];     ListPlot[pts]      ![enter image description here](http://i.stack.imgur.com/1cSOK.jpg) Now I input the data               SpecCluster = SpectralCluster[pts, 4, 1]     ListPlot[{pts, SpecCluster}]      and output               {1,2,3,4}      ![enter image description here](http://i.stack.imgur.com/6DNkl.jpg) I've run the algorithm on a few different sets of data (not always generated from the Multinormal Distribution) and always return a set of increasing integers.


How can I eliminate $x_1$ from my two ODEs?

How can I get _Mathematica_ to eliminate $x_1$ in the equations in the first box to achieve the equation in the second box？ ![eguations.png](http://i.stack.imgur.com/uh1pr.png) My code:               Reduce[{       f[t] - k[1] x[1] - B[1] D[x[2], t] - B[3] D[x[1] - x[2], t] == m[1] D[x[1], {t, 2}],       B[3] D[x[1] - x[2], t] - B[2] D[x[2], t] - k[2] x[2] == m[2] D[x[2], {t, 2}]},       {f[t], k[1], k[2], x[2], t, B[1], B[2], B[3], m[1], m[2]}]       _Mathematica_ ' s answer: > >     (x[1] == 0 && f[t] == 0 && k[2] == 0) || (x[1] == 0 && f[t] == 0 && >        x[2] == 0) || (x[1] != 0 && k[1] == f[t]/x[1] && >        k[2] == 0) || (x[1] != 0 && k[1] == f[t]/x[1] && x[2] == 0) >


data visualization on a lattice grid

Is it possible to visualize an array whose elements are angles as actual angles on a lattice grid? E.g., say, if the input is:               {{0, π, π}, {0, 0, π/2}, {π/2, 0, 3 π/3}}      then the graphical visualization of this array would be a 3x3 square lattice grid. On each node of the lattice, there will be an arrow (say, inside a circle) which shows the corresponding value from the array. In the above input, this would mean that the arrow at the first lattice-node would be 0, the second would be π, the third would be π, the fourth (i.e., the first node in the second raw of the lattice grid) would be 0, fifth 0, sixth π/2, etc.


Compile error from If but not from Piecewise

Consider this:               point={1.,2.};     f1 = Compile[{{t, _Real}},        Evaluate[Block[{a, b}, {a, b} = point; If[t > 0., a*b*Sin[t], 0.]]]];     f1[2.]      > CompiledFunction::cfse: Compiled expression a should be a machine-size real > number. >> CompiledFunction::cfex: Could not complete external evaluation at > instruction 5; proceeding with uncompiled evaluation. >>               (*0.909297 a b*)      and this:               f2 = Compile[{{t, _Real}},        Evaluate[Block[{a, b}, {a, b} = point;Piecewise[{{a*b*Sin[t], t > 0.}, {0., True}}]]]];     f2[2.]     (*1.81859*)      Why does the `If` version produce errors while the `Piecewise` one doesn't? From this post I believe the compiler transforms the `Piecewise` function into its equivalent `If` function before compilation, so f1 and f2 should be the same. Why the difference?


Working with a system of differential equations that cannot be solved explicitly

I have to work a lot with three functions $\;o_1(t), o_2(t), o_3(t)\;$ that are solutions to the certain system of differential equations:               Halp = {       D[o1[t], t] == o1[t]*o2[t] + o1[t]*o3[t] - o2[t]*o3[t],        D[o2[t], t] == o1[t]*o2[t] + o2[t]*o3[t] - o1[t]*o3[t],       D[o3[t], t] == o1[t]*o3[t] + o2[t]*o3[t] - o1[t]*o2[t]}     sol = DSolve[Halp, {o1[t], o2[t], o3[t]}, {t}]      The system cannot be solved explicitly with _Mathematica_ , but I do not need the solution. What I would like to do is computing higher order derivatives assuming that $o_1(t)$, $o_2(t)$, and $o_3(t)$ are solutions to the above system. How could I tell _Mathematica_ to do this?


Generating a sound with pitch like Sin[2Pi t] as t steps from 0 to 1

I am trying to generate a sound with pitch that goes up and down like a sine wave from `0` to `2Pi`. So the pitch should be `Sin[2Pi t]` as `t` steps from `0` to `1`. I thought the way to do this would be somehow in pseudocode like make               f = Integrate[E^(Sin[x] + 2), x];      And then               Play[Sin[f[t]], {t,0,2Pi}]      But it seems _Mathematica_ can't integrate `E^(Sin[x] + 2)`? So then I just fooled around and did               Integrate[(Sin[t] + 2), t]      > >     2 t - Cos[t] >                 Play[Sin[(1.2^(2 t - 1 Cos[t])*1000)], {t, 0, 2 Pi}]      and it doesn't do what I want either...


Why does Mathematica fail to solve my equation?

I am trying to solve an equation using _Mathematica_ , but I keep getting the following error > Solve::nsmet: This system cannot be solved with the methods available to > Solve. More importantly, it is running for more than half an hour without giving any solution. I have also tried `Reduce`, but that does not work either. Any suggestions? How I can fix the error? I am new to _Mathematica_. My apologies if this is a very basic question. I am trying to find θ1 (angle)?               x = (e*b*Cos[θ1] + v)^2/(v^2 + e^2*b^2 + 2*e*v*b*Cos[θ1])          Eq2 = a^2 + e*(Sin[θ]- Sin[θ1]) + v/b(θ-θ1)-a*Sqrt[x] ==         a^2*x + e^2*(Cos[θ]-Cos[θ1])^2- 2*a*e*(Cos[θ]-Cos[θ1])*Sqrt[x]          Solve[Eq2, θ1]


why I can't define a commutator operator in this way？

I am trying to define some operators I used frequently.For example, I defined a KroneckerProduct operator as $ \otimes $ as follows: a_$ \otimes $b_:=a.b-b.a and this works fine. Then I want to define a commutator used in quantum mechanics act like follows: $${\left[ {a,b} \right]_ - } = a.b - b.a$$ $${\left[ {a,b} \right]_ + } = a.b + b.a$$ where a and b are matrix. So I naively write the definition in matheamtica as follows: $${\left[ {a{\rm{\_}},b{\rm{\_}}} \right]_ - }: = a.b - b.a$$ $${\left[ {a{\rm{\_}},b{\rm{\_}}} \right]_ + }: = a.b + b.a$$ But this will not work. > 1.So how to define commutator in this form (appearance)? > > 2.and why the definition for a_$\otimes$b_ hold, the similar definition for > commutator [a_,b_]not hold? * * * * * * There is another question which actually should create another post. But I choose just to add it here. If I defined the KroneckerProduct as the operator [CircleTimes] in the way I did, then I found that in parallel computing, I can't simply distribute such a definition of [CircleTimes] like: DistributeDefinitions[$\otimes$] _Mathematica_ doesn't allow me to do that. Of course the 'Parallelize' will not distribute the $\otimes$ definition automatically either. So if an expression contains a $\otimes$, Simply 'Parallelize' it, the computation will get stuck and no answer will come out. So my second question is > how to distribute such a operator definition in parallel computing ?


Using NDSolve solution as initial condition for another NDSolve

I have solved a PDE numerically using `NDSolve`, and I now need to be able to use that solution as an initial condition for another `NDSolve`. Is there a way of doing this?


Calculating orbital period for the logistical map

I have the following MatLab code               clear all     close all          format long     % print all sig figs unless instructed otherwise          %% initial stuff     itotal = 10^8;      % total number of iterates     x = zeros(itotal,1);    % fill orbit with zeros     x(1) = rand;        % random initial condition     a = 1+sqrt(6)+.1;   % parameter of logistic map          %% iterate the map for a long time     for i = 1:itotal-1       x(i+1) = a*x(i)*(1-x(i));     % logistic map, g(x)=ax(1-x)     end          T = 35;         % total points to print     %% print the last T points of the orbit     disp(' ')     disp('  Iterate        X')     disp('---------------------------------------------')     for i = itotal-T+1:itotal                   % only showing T points on the orbit       disp(sprintf('   %10.0f  %15.15f',i,x(i)))     end     disp(' ')          %% determine if there is a periodic orbit of period less than 2^S     S = 26;                 % length of longest periodic orbit (log_2) we can find, maybe?     tol = 10^(-50);             % tolerance within which I believe I've found a repeat     inside=0;               % trigger telling me if I've been inside the 'if' loop below     for i = 0:S             % loop looking for orbit of period 2^(i)       difference(i+1) = norm(x(end)-x(end-2^i));        % compute difference between orbit points       if (difference(i+1) < tol) && (inside == 0)       % am I within tolerance? have I already qualified?         disp(sprintf('This orbit repeats every %s iterates',int2str(2^i)))         inside=1;       % don't come back inside this loop, see what happens without this       end     end      In this code, the current value of `a` has a known attractive orbit. I am attempting to test values of `a` close to the accumulation point of the logistic map, so I need to use higher-precision arithmetic to work with this value, specifically to find orbits of period greater than $2^{20}$, my current record with the MatLab code. I have translated this code to what I think is equivalent Mathematica code.               itotal = 10^8;(* number of iterates *)          x = ConstantArray[0, itotal]; (* fill orbit with zeros *)          x[[1]] = RandomReal[WorkingPrecision -> 10]; (* random initial value *)     a = 1 + Sqrt[6] + .1 (* parameter of logistic map *)          (* iterate the map for a long time*)          Do[x[[i + 1]] = a*x[[i]]*(1 - x[[i]]), {i, itotal - 1}];          (* Pretty Printing *)     Print["Iterate           X"]     Print["-------------------"]     Do[Print[x[[i]]], {i, itotal - 35, itotal, 1}]          (* determine if there is a periodic orbit of period less than 2^S *)          difference[i_+1] := Norm[x[[itotal]] - x[[itotal - 2^i]]];     S = 26; (* length of longest periodic orbit (log_ 2) we can find, maybe? *)     tol = 10^-50; (* tolerance within which I believe I've found a repeat *)     inside = 0; (* trigger telling me if I've been inside the'if' loop below *)     (* loop looking for orbit of period 2^(i) *)     Do[difference[i]       If[(difference[i] < tol) && (inside == 0),          {Print["This orbit repeats every " <> IntegerString[2^i] <> " iterates."],         inside = 1}], {i, 0, S, 1}]      This retains the known `a` for testing. My question has 2 parts:   1. Is this translation accurate? I'm mostly questioning the n+k patterns and the use of lists over vectors, but there may be other things I'm missing. I'm not especially familiar with MatLab, so I did a naïve translation.   2. Is there anything I can do to make this implementation more efficient? It currently runs in about 10 minutes, but I'd like to speed it up, if possible.


what can be the reasons for webmathematica kernel to quit?

I am new to webmathematica. I wanted to know under what circumstances can a kernel quit the processing.


How can I define a function that can accumulate its parameter?

For example, write a function `add`: add[3] return 3 add[4] return 7 add[10] return 17


VertexSize with GraphPlot

I'm constructing a graph using GraphPlot and I want some vertices to have a different size than others, like this:               GraphPlot[{1 -> 2, 2 -> 3}, VertexSize -> {{1, 3} -> Medium}]      However this gives errors. How do I set sizes of individual nodes?


Prohibiting Autorun in a Manipulate?

One of the four possible `AppearanceElements` for `Manipulate` is "ManipulateMenu" which provides a number of features such as bookmarks, pasting snapshots, autorun, etc. I'd like to have some of the elements of the Manipulate menu, but not all of them. In particular, I'd like to remove `Autorun`, as it is not useful or interesting in my application. In fact it is positively undesirable. Is it possible to edit the menu, in particular to remove unwanted items? The documentation suggests not. Alternatively, is it possible to disable `Autorun`? I've tried `AutorunSequencing -> {}` and `AutorunSequencing -> None` but they appear to do nothing (and are not documented).


Extracting box coordinates

> **Possible Duplicate:**   >  Dimensions of the results of Text[] within Graphics[] In writing the following code, I had to figure out what values to give d by trial and error. Is there a way to extract the coordinates of a box directly?               sty[list_] :=       Framed[Style[list, Medium, 12, FontFamily -> "Arial",         Background -> White]]          listy[list_, place_] := Text[sty[Grid[list]], place]          Manipulate[      Graphics[       If[d < .675,        {         listy[{{2, 12, 7}}, {d, 0}],         listy[{{5, 7}}, {2 - d, 0}]         },        {         listy[{{2, 12, 7, 5, 7}}, {.93, 0}]         }        ],       PlotRange -> {{-.5, 2.5}, {-.2, .2}},       ImageSize -> 200,       AspectRatio -> Automatic       ],      {{d, .6, ""}, .6, .77},      ControlPlacement -> Bottom,      Paneled -> False, SaveDefinitions -> True      ]


Change variables in differential expressions

I have a fairly complicated differential expression in terms of a variable r and two unknown functions of r, B[r] and n[r]. I want to do a Taylor expansion of this around r=infinity. I want to do this by defining a new variable x=1/r and changing from r to x within my expression, then expanding around x=0. Say the expression looks (more or less) like               n[r] (3 r B'[r]^2 - 4 B[r] (2 B'[r] + r B''[r]))      How do I turn this from something in terms of {r, n[r], B[r]} to something in terms of {x, n[x], B[x]}? I'm not sure how to get Mathematica to work through the chain rule and change the dependent variable in the derivatives, and I also frequently get errors along the lines of "1/r is not a valid variable." **EDIT**   I've managed to find at least _a_ solution, although I'd imagine Mathematica has far more elegant ways of doing this. Hopefully if there's a cleaner way to do this someone will post it anyway. It would also be nice to have a more general method for changing variables as my way assumes that only up to second derivatives of B[r] and n[r] appear (since that happens to be true for this problem). Anyway, the solution I found was to do a replacement of the type               n[r] (3 r B'[r]^2 - 4 B[r] (2 B'[r] + r B''[r])) /.             {B'[r] -> B'[x]/D[1/x, x],             B''[r] -> D[(B'[x]/D[1/x, x]), x]/D[1/x, x],              n'[r] -> n'[x]/D[1/x, x],             n''[r] -> D[(n'[x]/D[1/x, x]), x]/D[1/x, x],               B[r] -> B[x],                n[r] -> n[x],                 r  -> 1/x}      i.e., literally just replacing all of the derivatives w.r.t. r with derivatives w.r.t. x one by one, then replacing B[r] and n[r] with B[x] and n[x], then replacing r itself with 1/x. Not pretty but it does work. **FURTHER EDIT**   If you want to do something like this, use Maple. Their PDETools has just the right function which I can't seem to find in Mathematica.


Adding a point to an already existing graphic

This is just a follow-up of this post: Beginner 2D animation with maths equations Part of the code is:               circ = RegionPlot[x^2 + y^2 <= radius^2, {x, -radius, radius},      {y, -radius, radius},      Mesh -> 20, MeshStyle -> {{Red}, {Blue}}, BoundaryStyle -> Black,      PlotStyle -> None]      where `radius = 20`. Say that I would like to add a **big dot** at the coordinates `(10,10)` on the above disc. My code is:               circ2 = Show[circ,      Epilog -> Inset[ListPlot[{10, 10}], PlotStyle -> PointSize[0.025]] ]      This however does not work. Can anyone suggest how to add a point on an already made graphic and **save the combined graphic as a single new object**? Thanks a lot...


Plotting basin boundary

How to plot the basin boundary in _Mathematica_?   I have been trying to do this using the system               y''[t] == -R y'[t] + (( Y[1] - y[t])/(Sqrt[(X[1] - x[t])^2 + (Y[1] - y[t])^2 + d^2])^3                           + (Y[2] - y[t])/(Sqrt[(X[2] - x[t])^2 + (Y[2] - y[t])^2 + d^2])^3                           + (Y[3] - y[t])/(Sqrt[(X[3] - x[t])^2 + (Y[3] - y[t])^2 + d^2])^3)                - c y[t]          x''[t] == -R x'[t] + ((X[1] - x[t])/(Sqrt[(X[1] - x[t])^2 + (Y[1] - y[t])^2 + d^2])^3                           + (X[2] - x[t])/(Sqrt[(X[2] - x[t])^2 + (Y[2] - y[t])^2 + d^2])^3                           + (X[3] - x[t])/(Sqrt[(X[3] - x[t])^2 + (Y[3] - y[t])^2 + d^2])^3)                - c x[t]      It is a magnetic pendulum swinging chaotically about `3` other magnets underneath. `R`,`c`,`d` are all constants,where `r` is air resistance, `d` is the vertical distance of the pendulum from the floor, `c` is the sping constant of the pendulum. `X[1]`, `X[2]` and `X[3]` (`Y[1]`,`Y[2]` and `Y[3]`) are the coordinates of the magnets. But I have gotten nowhere.


Plotting continuous functions on integers

How can one plot a continuous function of the variable $x$, say $f(x)$, but only for integer values of $x=n$ with $n\in\mathbb{N}$ - i.e., as it was a List?


Plotting the solution of a 2nd order equation

I have got to solve a second order equation, where the coefficient depend on the parameter $k$: $$(A_k - \omega) (D_k- \omega) - B_kC_k = 0$$ so that also the solution $\omega=\omega(k)$ will depend on $k$. Here's my code. Parameters:               L = 10; l = 1; w = 0.13;      Subscript[ϕ, 0] = 1; β = 0.1; α = 0.06; η = 0.5; d = 1;      λ = 0.1;      Coefficients:               AA = (((1 - w) kk^2 Pi^2 l^2) / L^2) + (α (Subscript[ϕ, 0 ]^2) (1 - λ))/η;     BB = Pi l w (1 + ((1 - λ)^2/2 η))/L;     CC = -β (Subscript[ϕ, 0 ]^2) Pi l kk/ L;     dd = (Pi l (d - w) kk^2 Pi^2 l^2)/ L^2 ;      Then solving:               sol = Last[Simplify[Solve[(AA - ω) (dd - ω) - BB CC == 0, ω]]]      Now, how do I make Mathematica plot this solution as a function of $k$? If I try:               Plot[Evaluate[ω[kk]/.sol], {kk, -10, 10}, PlotRange -> All]      it does not work.


Is there any Robotic Package in Mathematica?

Is there any Package in Mathematica that deals with Robotics and their application?


Simplifying numerical expressions involving special functions

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


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

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


Rotation of Graphics3D like rotating Plot3D

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


Converting StringJoin to StringForm inside Hold

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


"No file exists for resource PasteTemplateString"

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


Triangular lattice with periodic boundary conditions

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


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

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


ListLinePlot with colors from data

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


Text with subscript is automatically Italic

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


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

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


Mouse cursor disappears

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


Define a color function based on color samples obtained from ColorBrewer

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


How determine The most possibility probable with programming

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


How to draw grid lines on top of a plot?

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


Best way to Export a large list of figures?

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


Group dataset on two keys (GroupBy)

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


Mathematica not able to confirm its own solution to differential equation

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


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

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


Statistics confusion

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


How are MemberQ and FreeQ so fast?

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


Show path with arrows in a matrix

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


Is Compress[] compatible between different Mathematica versions?

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


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

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


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

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


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

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


Detecting grid lines in a raster image

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


How does Interpolation really work?

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


How to implement dual numbers in Mathematica?

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


Why does this sum not simplify properly?

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


Prevent package from being opened in a notebook interface

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


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

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


Labeling plots without evaluation

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


Time-efficient manipulation (zeroing) of expression

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


Vertex Names of Subgraph in Order of Connectivity

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


Cropping a plot via a command

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


Some questions about random numbers

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


Are greek symbols causing different evaluation?

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


Showing Two Manipulated Plots Together

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


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

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


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

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


intersection of two lines with a slope slider

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


Hatched bars and bar-specific background in BarChart

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


Import xls data with dates

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


ReadList can't read correctly

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


Using high RasterSize or ImageResolution changes contour pattern

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


Need help with exception handling

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


How to find the positive region of this function?

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


Set defaults for ViewPoint and AxesLabel

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


Plot points, line and plane in one 3D plot

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


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

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


How can I adjust the span between under bar and formula

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


How to get control over DepthFirstScan?

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


Expression evaluation inside of FindRoot inside a Compiled Function

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


Problem with exporting nested Rows/Columns to HTML

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


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

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


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

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


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

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


Convergence in NIntegrate vs Integrate

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


Control variable and body variable decoupling in Manipulate

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


How to solve simultaneous equations faster with Compile?

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