How Do I Perform Simple Operations On The Elements of a Table?

I have been using the function `HistogramList` to generate frequency tables off a data set. The code looks like this:               frequencytable=HistogramList[dataA,{-0.5, 6.5, 1},"PDF"][[2]]      with a numerical output of: > 0.0152, 0.0937, 0.0234, 0.2969, 0.2500, 0.0781, 0.0312 Here is my question. I would like to add the three numbers at the right hand side to one another. Next, I would like to add the three numbers at the left hand side to one another. Last, I would like to subtract the sum of the three numbers on the left from the sum of the three numbers on the right. How do I do that?


Is garbage collection broken in version 10.0.0?

In version 10.0.0 under Windows I am observing the following behavior:               Do[Module[{foo}, foo[x_] := 1; foo[0]], {10}]          Names["foo$*"]      > >     {"foo$593", "foo$594", "foo$595", "foo$596", "foo$597", "foo$598", >      "foo$599", "foo$600", "foo$601", "foo$602"} >   I am aware that in past versions `Module` Symbols were sometimes not garbage collected but never in such a simple case as this as far as I know. The code above returns `{}` in version 7, as one would expect. Do I have something wrong with my configuration or is this behavior reproducible?   Assuming the latter is there an explanation for this other than a bug?


Series plot will not display properly (Fourier Series)

c1[n_] := 1/2/Pi Integrate[Sign[x] Exp[-I n x], {x, -Pi, Pi}];      c2[n_] = Simplify[c1[n], Assumptions -> Element[n, Integers]];      c[n_] := If[n == 0, c1[0] = 0];     f5[x_] = Sum[c[k] Exp[I k x], {k, -10, 10}];      Plot[{f5[x], Sign[x]}, {x, -Pi, Pi}]      I am trying to plot the $Sign[x]$ function and the series: $\displaystyle\sum_{n=-\infty}^\infty \dfrac{i(-1)^n - i}{n\pi}e^{inx} $ (which should be the answer to the integral in the code) on the same graph, but I cannot seem to get it to work. It displays no error, just an empty graph.


Integral of GeneratingFunction

I know that GeneratingFunction can be used to compute the generating function $\sum_{n=0}^\infty a_n x^n$ of a sequence $(a_n)_n$ via               GeneratingFunction[a[n],n,x]      I also know that polynomial (in $n$) coefficients of the general term $a_n$ of the sequence result in an expression involving derivatives of the generating function, e.g.               GeneratingFunction[n a[n],n,x]     (* x (GeneratingFunction^(0,0,1))[a[n],n,x] *)      This does not seem to happen with rational (in $n$) coefficients, which would lead to indefinite integrals of the generating function. For example I would expect the input               GeneratingFunction[a[n]/(n + 1), n, x]      to result in               (*1/x Integrate[GeneratingFunction[a[n],n,y],{y,0,x}]*)      or               (*1/x GeneratingFunction^(0,0,-1))[a[n],n,x]*)      but this does not seem to be the case. **I thus have the following question:** Is it possible to get Mathematica to compute the generating function of a linear combination of lagged values of $a_n$ with rational (in $n$) coefficients in terms of derivatives and integrals of the generating function of the sequence $(a_n)_n$?


How to set Block local variables by code?

I need to create a user defined Block function where the Block variables values are defined by code. For example, imagine I have:               SetAttributes[myBlock1,HoldAll]     myBlock1[args_]:=Block[{a=1,b=2,c=3,d=4},args]     myBlock1[{a,b,c,d}]      > {1, 2, 3, 4} Now, what I need is something like:               SetAttributes[myBlock2,HoldAll]     varList={"a","b","c","d"};          myBlock2[args_]:=Module[{varArgs},         varArgs=MapIndexed[ToString@Row[{#1,"=",#2[[1]]}]&,varList];         ToExpression@ToString@Row[{"Block[",varArgs,",",ToString@args,"]"}]     ]          myBlock2[{a,b,c,d}]      > {1, 2, 3, 4} The above function works, but it's very clumsy (using `ToExpression`) and error susceptible. I tried something like:               SetAttributes[myBlock3,HoldAll]     varList={"a","b","c","d"};          myBlock3[args_]:=ReleaseHold[Hold@Block[varDef,args]/.varDef:>MapIndexed[(Evaluate@Symbol[#1]=#2[[1]])&,varList]]     myBlock3[{a,b,c,d}]      But without success in the "variables injection". One important point is that a, b, c and d should not scape from the block scope. How can I do that?


Is there a way to speed up Simplify and/or PolynomialReduce Modulus-> 2?

I'm trying to simplify a series of equations with at most 64 input terms. As the number of terms involved in the equations increase, the runtime seems to grow exponentially.   Does anyone know of ways to decrease the running time of a process like this?: http://pastebin.com/LJrdsCVD (had to use pastebin because the equation is long. the below example uses FullSimplify and is also very slow.)               FullSimplify[Last[Last[PolynomialReduce[      {(a10*(b10+a01 b01 (a02+b02) (a03+b03)(a04+b04)         (a05+b05) (a06+b06) (a07+b07) (a08+b08) (a09+b09) (1+b10)+a00 b00 (a01+b01)         (a02+b02) (a03+b03) (a04+b04) (a05+b05) (a06+b06) (a07+b07) (a08+b08) (a09+b09)         (1+b10)+(a04 a05 a06 a07 a08 a09 b04+a05 a06 a07 a08 a09 b05+a04 a06 a07 a08 a09 b04         b05+a06 a07 a08 a09 b06+a04 a05 a07 a08 a09 b04 b06+a05 a07 a08 a09 b05 b06+a04 a07         a08 a09 b04 b05 b06+a07 a08 a09 b07+a04 a05 a06 a08 a09 b04 b07+a05 a06 a08 a09 b05         b07+a04 a06 a08 a09 b04 b05 b07+a06 a08 a09 b06 b07+a04 a05 a08 a09 b04 b06 b07+a05         a08 a09 b05 b06 b07+a04 a08 a09 b04 b05 b06 b07+a08 a09 b08+a04 a05 a06 a07 a09 b04         b08+a05 a06 a07 a09 b05 b08+a04 a06 a07 a09 b04 b05 b08+a06 a07 a09 b06 b08+a04 a05         a07 a09 b04 b06 b08+a05 a07 a09 b05 b06 b08+a04 a07 a09 b04 b05 b06 b08+a07 a09 b07         b08+a04 a05 a06 a09 b04 b07 b08+a05 a06 a09 b05 b07 b08+a04 a06 a09 b04 b05 b07         b08+a06 a09 b06 b07 b08+a04 a05 a09 b04 b06 b07 b08+a05 a09 b05 b06 b07 b08+a04 a09         b04 b05 b06 b07 b08+(a09+a08 (a07 b07+a06 b06 (a07+b07))+(a08+a07 b07+a06 b06         (a07+b07)) b08+a05 b05 (a06+b06) (a07+b07) (a08+b08)+a04 b04 (a05+b05) (a06+b06)         (a07+b07) (a08+b08)) b09+a03 b03 (a04+b04) (a05+b05) (a06+b06) (a07+b07) (a08+b08)         (a09+b09)+a02 b02 (a03+b03) (a04+b04) (a05+b05) (a06+b06) (a07+b07) (a08+b08)         (a09+b09)) (1+b10)))},            {a00^2 - a00, b00^2 - b00, a01^2 - a01, b01^2 - b01, a02^2 - a02, b02^2 - b02,         a03^2 - a03, b03^2 - b03, a04^2 - a04, b04^2 - b04, a05^2 - a05, b05^2 - b05,        a06^2 - a06, b06^2 - b06, a07^2 - a07, b07^2 - b07, a08^2 - a08, b08^2 - b08,        a09^2 - a09, b09^2 - b09, a10^2 - a10, b10^2 - b10, a11^2 - a11, b11^2 - b11,         a12^2 - a12, b12^2 - b12, a13^2 - a13, b13^2 - b13, a14^2 - a14, b14^2 - b14,         a15^2 - a15, b15^2 - b15, a16^2 - a16, b16^2 - b16, a17^2 - a17, b17^2 - b17,        a18^2 - a18, b18^2 - b18, a19^2 - a19, b19^2 - b19, a20^2 - a20, b20^2 - b20,         a21^2 - a21, b21^2 - b21, a22^2 - a22, b22^2 - b22, a23^2 - a23, b23^2 - b23,        a24^2 - a24, b24^2 - b24, a25^2 - a25, b25^2 - b25, a26^2 - a26, b26^2 - b26,        a27^2 - a27, b27^2 - b27, a28^2 - a28, b28^2 - b28, a29^2 - a29, b29^2 - b29,         a30^2 - a30, b30^2 - b30, a31^2 - a31, b31^2 - b31},            {a00, b00, a01, b01, a02, b02, a03, b03, a04, b04, a05, b05, a06, b06, a07, b07,         a08, b08, a09, b09, a10, b10, a11, b11, a12, b12, a13, b13, a14, b14, a15, b15,         a16, b16, a17, b17, a18, b18, a19, b19, a20, b20, a21, b21, a22, b22, a23, b23,         a24, b24, a25, b25, a26, b26, a27, b27, a28, b28, a29, b29, a30, b30, a31, b31},     Modulus -> 2]]]]


How to generalize and speed up this program?

There is a vector whose length is $n*m$, we can part it into $n$ sections in order. I want to define a function to compare the $i$-th and $i+1$-th section and find the minimum. The program for $n=m=3$ is as following:               f[x_] := Min[     Total[Total[Boole[Thread[x[[1 ;; 3]] < ##]]] & /@ x[[4 ;; 6]]],      Total[Total[Boole[Thread[x[[4 ;; 6]] < ##]]] & /@ x[[7 ;; 9]]],      Total[Total[Boole[Thread[x[[7 ;; 9]] < ##]]] & /@ x[[1 ;; 3]]]];      Could we generalize it to               f[x_,n_,m_] := Min[     Total[Total[Boole[Thread[x[[1 ;; m]] < ##]]] & /@ x[[m+1 ;; 2*m]]],      Total[Total[Boole[Thread[x[[m+1 ;; 2*m]] < ##]]] & /@ x[[2*m+1 ;; 3*m]]],      ....     Total[Total[Boole[Thread[x[[(n-1)*m+1 ;; n*m]] < ##]]] & /@ x[[1 ;; m]]]];      By the way, could we speed up this code? Any help or suggestion will be appreciated!


Differentiating a Cumulative Distribution Function which has a discontinuity at $0$

I want to take the derivative of a distribution function which has a discontinuity at $0$. Here is the function:               temp0[x_] :=If[Element[x, Reals], Sqrt[Pi]*(Erfc[(-2 + Log[2])/(2*Sqrt[2])] + (1 + Erf[(1 +Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2])/Sqrt[2]] - Erfc[(-2 + Log[2])/(2*Sqrt[2])])*UnitStep[-Log[2]/2 - Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]]) + Sqrt[(2*Pi)/E]*(Erf[Log[2]/(2*Sqrt[2])] - Erf[Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]/Sqrt[2]])*UnitStep[-Log[2]/2 + Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]] + 2*Sqrt[Pi]*(-Erf[(2 + Log[2])/(2*Sqrt[2])] + Erf[(1 + Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2])/Sqrt[2]])*UnitStep[-Log[2]/2 + Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]] + Sqrt[(2*Pi)/E]*(Erf[Log[2]/(2*Sqrt[2])] + Erf[Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]/Sqrt[2]])*UnitStep[Log[2]/2 + Piecewise[{{(x - Log[2])/2, x < 0}}, (x + Log[2])/2]], Integrate[(Sqrt[2]*UnitStep[-y - Log[2]/2] + 2*((Sqrt[2] - E^y)*UnitStep[y - Log[2]/2] + E^y*UnitStep[y + Log[2]/2]))/E^((1 + y)^2/2), {y, -Infinity, Piecewise[{{(x - Log[2])/2, x < 0}, {(x + Log[2])/2, x >= 0}}, 0]}, Assumptions -> NotElement[x, Reals]]]/(Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])] + Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 + Log[2])/(2*Sqrt[2])]))      If I plot it I get ![enter image description here](http://i.stack.imgur.com/mmQsg.png) The result of the derivation should be a density function. I used               fx0[x_] := D[temp0[x], x]      to get the density function but it didnt help me. Do you know how can I ignore the discontinuity at $0$ for the derivation? Thank you very much.


How can I simulate this animation of checking for prime numbers?

![enter image description here](http://i.stack.imgur.com/PuK0W.gif) I can only implement a very simple one, I want to make my code look like that. Any better ideas?               Manipulate[       Partition[ Table[ If[ PrimeQ @ i, Framed @ i, Style[i, Gray]], {i, 1, j, 1}], 10],       {{j, 10}, 1, 100, 1}]


Integrating special functions

I would like to integrate the following function with Legendre polynomial and Gamma function. I am open to suggestions.               (* assumptions = {s > 0, α > 0} *)          Φ[s_, x_, α_] := (-1)^s Sqrt[(s α)/Gamma[1 + 2*s]]                       LegendreP[s, s, Tanh[α x]]          a1 =  Integrate[x Φ[s, x, α]^2, {x, -∞, ∞}]


Why does ParallelTable give different answer than Table

Consider the following code               a0 = 6.;     ls1 = ParallelTable[k, {k, -π/a0, π/a0, π/a0/100}];     ls2 = Table[k, {k, -π/a0, π/a0, π/a0/100}];     ls1 == ls2     (*False*)      Why does `ParallelTable` give different answer than `Table` and how to fix it?


Unexpected Behaviour with local variables and ToExpression

I encountered an unexpected behaviour in my mathematica-code, and want to understand whether that's a mathematica bug, or a misinterpretation on my side.               MainVar = 1;     Carrier = "MainVar";     f[] := (       Module[{MainVar},          MainVar = 3;         Print[MainVar];         Print[Carrier];         Print[ToExpression[Carrier]]     ])     f[] (* 3, MainVar, 1 *)      I would have expected that `Print[ToExpression[Carrier]]` gives me `3`, because `Carrier` points to `MainVar`, which has the value `3`. When I use `MainVar` as global variable (as Eldo suggested below), I get the expected `3`. So my question is: > Why does `ToExpression[Carrier]` give me `1` when I use `MainVar` as a local > variable, even if both `MainVar` and `Carrier` have the correct values?


I have the roots; how can I find an equation that they will satisfy?

I have two solutions; I want is to find an equation that these solutions satisfy using mathematica. The solutions are $x= \frac{{(26-k)}^2}{26}$ and $y= \frac{{k}^2}{26}$. I know by hand computing that $x$ and $y$ satisfy $\sqrt{x}+\sqrt{y}=\sqrt{26}$; How can I show this using _Mathematica_?


Does it help to do any preprocessing before `FindSequenceFunction`?

I am always amazed how smart `FindSequenceFunction` can be in discovering general term formula for a sequence of rational numbers. The documentation says it can work not only with rational sequences (and if fact I saw this in several simple cases).   * Have you found it useful to do some preprocessing of a sequence when it consists not of rational numbers? For example, if every element has a form $p_n+q_n\sqrt2$, do you try to separate sequences $p_n$ and $q_n$.   * How do you handle sequences of symbolic polynomial `Root`s?    * Do you use any standard code for preprocessing?    * Maybe you noticed that some preprocessing helps with rational sequences as well?


Arrowhead as MeshStyle or PlotMarkers for ListLinePlot

Is it possible to use the `Meshstyle` option of the `PlotMarkers` option in `ListLinePlot` to have `Arrowheads` as a point marker, obviously pointing in the positive direction of the line at that point? Using the example below, what sort of function would I need in the `MeshStyle` option.               ListLinePlot[Range[10]^2]      If not, what alternative solution might exist?


Solving an Equation (Recursively)

I have the following Values: $a[0]=1;a[1]=0;a[2]=0;a[3]=0;a[4]=\frac{g_2}{20};a[5]=0$. I need to compute the value of $b[n]$ in the following equation $$a[n]=\sum _{m=0}^{n} (m-2) \;\;a[m] \;\;b[n-m]$$ where $n=0,1,2,3,4,5$. For $n=0$, I get the value of $b[0]$. For $n=1$, I get the value of $b[1]$ using the value of $b[0]$. For $n$th iteration, I get the value of $b[n]$ using the values of $b[n-1],b[n-2],\dots,b[0]$. The values of $b[n]$ will then be used to solve for another variable, say, $c[n]$, for $n=0,1,2,3,4,5$. Is there any simple way of doing this in Mathematica? I am basically doing one iteration at a time (using the Solve command), which is very tedious. Thanks, Radz.


Is there an equivalent of "shiftdim" of MATLAB?

Recently I'm spending my time implementing some computer vision algorithms, which usually handle a large amount of data. The problem I'm facing now is that I have to reform my video data to pass it to `Fourier`. To be precise, I'm trying to apply a temporal filter to video, whose dimension is **Time*X*Y*Channel** , while I want to apply `Fourier` to `video[[All, x, y, c]]` (`x`,`y`,`c` are some integers). I've already tried to naively reform the data using `Table`. It works like charm for small data, but for large data, reforming alone takes long and consumes too much memory. (Took about 4 minutes and 3~4 GB of memory to handle data < 100 MBytes) MATLAB's `shiftdim` sounds like a nice solution, while I failed to find an equivalent or workarounds for _Mathematica_. (Or maybe my approach is wrong?) ## In short: > Is there any way to efficiently reform a multi-dimensional array, just like > `shiftdim`?


Mathematica not responding

I am working in the field of applied physics. Some body suggested me to use Mathematica for plotting graphs and programming. After going through some tutorials, I have written the following code but whenever I am trying to evaluate the notepad, it takes forever to evaluate. I have halted the code after half an hour. Kindly suggest, how to evaluate the following code?               (*Define all parameters and constants*)     (* For Copper material*)     Clear[xi, s];     lmd = 9.4*10^10 ;(*Lambda*)     mu = 4.0*10^10;   (*mu*)     kp = 10^10; (*kappa*)     eps0 = 10^(-9)/(36*Pi);     mu0 = 4*Pi*10^(-7);     H0 = 10^7;     nu = 0.0268*10^8; (*Nu*)     T0 = 293; (*Initial value of temperature*)     ro = 1.74*10^3; (*rho*)     gm = 0.779*10^(-5); (*gamma*)     j = 0.2*10^(-19); (*microintertia*)     ce = 383.1; (*Ce*)     ks = 1.7*100; (* K* *)     a = 0.1; (*two temperature parameter*)     sig0 = 2.2*10^7;(*sigma_not*)     (*xi=0.2; (*fourier parameter*)     s=0.7;(*laplace parameter*)*)     tau1 = 0*8.765*10^(-13); (*relaxation parameter*)     tau0 = 6.131*10^(-13); (*relaxation parameter*)     eta = ro*ce/ks;(*eta*)     c0 = Sqrt[(lmd + 2*mu + kp)/ro];          (*Define all coefficients of partial differential equations*)     a1 = lmd + 2 mu + kp;     a2 = c0^2*eps0*mu0*H0^2;     a3 = nu*T0;     a4 = ro*c0^2;     a5 = mu + kp;     a6 = kp^2/(gm*eta^2*c0^2*(mu + kp));     a7 = 2 kp/(c0^2*eta^2*gm);     a8 = ro*j*c0^2*eta/gm;     a9 = ro*ce/(ks*eta);     a10 = nu/(ks*eta);     a11 = a*c0^2*eta^2;     a12 = lmd/(lmd + 2 mu + kp);     a13 = mu/(lmd + 2 mu + kp);     a14 = (mu + kp)/(lmd + 2 mu + kp);     a15 = eta/sig0*mu0;     a16 = eta/(sig0*mu0*c0);     a17 = c0^2*eps0*eta^2/(sig0^2*mu0);     (* Now define the coefficients of total differential equation*)     alp1 = xi^2 + (a2 + a4)*s^2/a1;     alp2 = a3*(1 + tau1*s)/a1;     alp3 = xi^2 + (a2 + a4)*s^2/a5;     alp4 = xi^2 + a7 + a8*s^2;     alp5 = a9*(s + tau0*s^2);     alp6 = a10*(s + tau0*s^2);     alp7 = xi^2 + 1/a11;     alp8 = 1 + a11*alp5;     alp9 = xi^2 + a11*alp5*alp7;     alp10 = a11*alp2*alp6 + alp2;     alp11 = a11*alp2*alp6*(xi^2 + alp7) + alp1*alp2 + alp9;     alp12 = a11*alp2*alp6*alp7*xi^2 + alp9*alp11;     alp13 = alp3 + alp4 + alp6;     alp14 = alp3*alp4 + a6*xi^2;     alp15 = alp11/alp10;     alp16 = alp12/alp10;          (* Now define the roots of total differential equation*)     m1 = Sqrt[(alp13 + Sqrt[alp13^2 - 4*alp14])/2];     m2 = Sqrt[(alp13 - Sqrt[alp13^2 - 4*alp14])/2];     m3 = Sqrt[(alp15 + Sqrt[alp15^2 - 4*alp16])/2];     m4 = Sqrt[(alp15 - Sqrt[alp15^2 - 4*alp16])/2];          (*Now define the constants obtained after solving boundary conditions*)               theta0 = 0.1;(*magnitude of temperature taken in boundary conditions*)               alp17 = -I*(xi^2*a13 + alp3*a14) (alp1 - xi^2*a12)/(xi*(1 - a12));     alp18 = I*xi*(a14 + a13);     del1 = alp17*(m2^2 - alp3) - alp18*m1*m3*(m1^2 - m2^2);     del2 = alp17*(m1^2 - alp3) + alp18*m2*m4 (m1^2 - m2^2);     aa1 = I*alp2*(alp1 - xi^2*a12)*(m2^2 - alp3)*(del1 + del2)*        theta0/(xi*           m1*(1 - a12)*(m1^2 -              m2^2)*((m3^2 - alp1)*del2 + (m4^2 - alp1)*del1));     aa2 = -I*alp2*(alp1 - xi^2*a12)*(m1^2 - alp3)*(del1 + del2)*        theta0/(xi*           m2*(1 - a12)*(m1^2 -              m2^2)*((m3^2 - alp1)*del2 + (m4^2 - alp1)*del1));     aa3 = alp2*del2*theta0/((m3^2 - alp1)*del2 + (m4^2 - alp1)*del1);     aa4 = alp2*del1*theta0/((m3^2 - alp1)*del2 + (m4^2 - alp1)*del1);               (* Now define the functions to be plotted*)          phi[x3_] := (m1^2 - alp3)*aa1*E^(-(m1*x3)) + (m2^2 - alp3)*aa2*         E^(-(m2*x3));     theta[x3_] :=        1/alp2*((m3^2 - alp1)*aa3*E^(-(m3*x3)) + (m4^2 - alp1)*aa4*           E^(-(m4*x3)));     u1[x3_] := (m1*aa1*E^(-(m1*x3)) + m2*aa2*E^(-(m2*x3))) +         I*xi*(aa3*E^(-(m3*x3)) + aa4*E^(-(m4*x3)));     u3T[x3_] :=        Re[I*xi*(aa1*E^(-(m1*x3)) + aa2*E^(-(m2*x3))) - (m3*aa3*            E^(-(m3*x3)) + m4*aa4*E^(-(m4*x3)))];      u3L[x3, x1] := Evaluate[InverseFourierTransform[u3T[x3], xi, x1]];     u3[x3, x1, t] := Evaluate[InverseLaplaceTransform[u3L[x3, x1], s, t]];     (* Now evaluate the function *)     x1 = 0; t = 0.1;     u3[x3, x1, t]


Specifying Range of RSolve

When I input               RSolve[{0 == q[n + 1]^2 + 3 q[n + 1] + 2 q[n + 1] q[n] - 6 q[n] + q[n]^2, q[0] == 1}, q[n], n]      I get two complicated-looking complex solutions:               {{q[n] -> 1/4 I ((-2 + I) + 4 I^n - (2 + 5 I) I^(2 n) - (2 + 2 I) I^n Sqrt[5] + (2 + 2 I) I^(2 n) Sqrt[5])}, {q[n] -> -(1/4)I ((2 - I) - 4 I^n + (2 + 5 I) I^(2 n) - (2 + 2 I) I^n Sqrt[5] + (2 + 2 I) I^(2 n) Sqrt[5])}}      There should be just one solution for each $n$ that is between 0 and 1, and I'd like only to see those. How can I achieve that?


How to partition MatrixPlot graphics?

Is there an easy approach - hopefully built-in - to partitioning `MatrixPlot` graphics into rows or columns (or both) of graphics sharing the same underlying options? For example, in the following graphic, the red rectangles indicate where partitions should occur, and the respective sub-Rasters (along with `FrameTicks` etc) can then be reorganized using `Row` ![enter image description here](http://i.stack.imgur.com/CmSYk.png) This particular graph (excluding the rectangles which were generated in `Epilog`) has `Length` 6, of which all but the first `Part` are related to options. But it's tedious to even list what parts of the partitions component correspond to which parts, which subsequently must be modified - for example `FrameTicks` are to be repositioned (reindexed). Obviously, because the "heatmap" color scale is shared among all the members of the desired partition, it's not feasible to partition the matrix prior and then mapping through `MatrixPlot`


How to localize symbols on the right-hand side of Rule when using ReplaceAll?

I am frustrated by the following:               {1, 2, 3.0} /. a_Integer -> a + 1      The `a` on the left side of the arrow is localized and appears in green whereas its sibling on the right side is blue. Consequently, I have to write:               Block[{a}, {1, 2, 3.0} /. a_Integer -> a + 1]      to avoid naming conflicts. It doesn't make sense to me that, within one inbuilt function, a variable is treated differently. I already got some hard to find errors because I forgot to block. What did I overlook here?


How can I propagate an asymmetric error in a function about the central value?

If I have some asymmetric error about the central value in x and y, then how can it be propagated in a function `f[x, y, z]`? For example, given               f[x, y, z] = 2*x^2 + 3*y^3 + z       and `x = 1.2` with error (+0.4,-0.3) and `y = 2.3` with error (+0.3, -0.5), how can I plot `f` as a function of `z` showing these errors?


Find maximum value of interpolation function - obviously wrong result

Minimizing and maximizing interpolation function has already been asked and answered, see here for example. Yet, I observe a strange behaviour. Well, I can understand that the wrong guess of Mathematica is due to several maxima, but still I'm surprised I don't manage to get a better result. ## Generation of the considered function Here is how I get the interpolation function `Theta[t]`:               OmegaS = 1.32; OmegaP = 1; l0 = 1; tmax = 100;          eqn1[t_] = r''[t]/l0 - r[t]*theta'[t]^2/l0 + OmegaS^2*(r[t]/l0 - 1) - OmegaP^2*Cos[theta[t]];     eqn2[t_] = r[t]*theta''[t]/l0 + 2 r'[t]*theta'[t]/l0 + OmegaP^2*Sin[theta[t]];          sol = NDSolve[{eqn1[t] == 0, eqn2[t] == 0, r[0] == .9, r'[0] == 0,      theta[0] == 0.001, theta'[0] == 0}, {r, theta}, {t, 0, tmax}][[1]];          Theta[t_] = theta[t] /. sol      This is what `Theta` looks like:               Plot[Theta[t], {t, 0, 100}, PlotRange -> All,  AxesLabel -> {"t", "Theta(t)"}]      ![plot Theta](http://i.stack.imgur.com/iIIKh.png) ## Attempts to identify the maximum I now want to find the maximum of `Theta[t]` for $t\in[0,100]$. I underline that the peak could be _anywhere_ in $[0,100]$ so I cannot indicate any relevant initial guess. I tried all the following solutions, which obviously give an incorrect result:               MaxValue[{Theta[t], 0 <= t <= tmax}, t]     (* 0.243314 *)     NMaxValue[{Theta[t], 0 <= t <= tmax}, t]     (* 0.243314 *)     FindMaximum[{Theta[t], 0 <= t <= tmax}, t]     (* {0.000999881, {t -> 0.0146385}} *)     Maximize[{Theta[t], 0 <= t <= tmax}, t]     (* {0.243314, {t -> 92.1206}} *)     NMaximize[{Theta[t], 0 <= t <= tmax}, t]     (* {0.243314, {t -> 92.1206}} *)      The best (inelegant) way I found to approximate the maximum is brute-force:               Max[Table[Theta[i], {i, 0, tmax, .001}]]     (* 0.687071 *)      ## Question Do you know:   * why my attempts fail?   * a good way to find the (global!) maximum?


How are parameters evaluated for a Plot in Manipulate

I am trying to get my head around how `Manipulate` evaluates functions in a Plot. I have read the introduction to Manipulate, and introduction to Dynamic, but I still can't figure it. For my specific example, I have a function `bigA` parameterised by `m1` and `m2` (this relates to question),               bigA[t_]:= (m1+m2) ((m1 m2 t)/(m1+m2)^3)^0.25      So when I try to plot it in Manipulate,               Manipulate[      Plot[bigA[t], {t, 1, 10}],      {{m1, 1.4}, 0.8, 3},      {{m2, 1.4}, 0.8, 3}]      Nothing appears. I presume this is because `m1` and `m2` aren't being evaluated. But I don't know what the order is supposed to be. # Edit The thing is, this seems to work when I `Evaluate` and don't plot, i.e,               Manipulate[Evaluate@bigA[t],      {{m1, 1.4}, 0.8, 3},      {{m2, 1.4}, 0.8, 3}]      So couldn't I just stick a `Plot` command in there somewhere?


Manipulate using a variable defined outside of the manipulate function

I want to do something like this:               expr := x^e;     Manipulate[Plot[expr, {x, 0, 4}], {e, 1, 3}]      But the plot shows up empty. Yes, it works if I do:               expr[x_,e_] := x^e;     Manipulate[Plot[expr[x,e], {x, 0, 4}], {e, 1, 3}]      But I don't want to do that. Why? Because the function I'm actually working with has about a dozen variables. I want to be able define my function just as as expression (that I use in many places throughout my notebook, in addition to this particular Manipulate) so that I don't have to bother with remembering the order in which I defined the dozen or so variables that comprise the function definition. This way I can substitute values into my function using ReplaceAll as I see fit. My approach has been working fine as I continue to shape this function, but using Manipulate becomes very cumbersome. I want to manipulate several of these variables without having to worry about typing a whole lot of code. Is there a way I can keep the definition of my function as a simple Set or SetDelayed (without the pattern matching) but change something about my Manipulate expression to make the Manipulate function actually manipulate symbols that are not do not explicitly occur within the Manipulate expression? Thanks!


Evaluation in Manipulate

I have an expression assigned to a variable. For example:               exp1 = a*x+b      Now I would like to plot it using something like this               Manipulate[      Plot[Evaluate[ex99], {x, 0, 1}],      {a, 0, 1},      {b, 0, 1}]      I can see 'a' and 'b' being properly substituted by 'Evaluate', but Plot does not work as expected. I suspect it has something to do with 'x' substitution. How can I fix that? Thanks!


Abridging Lists of Equations within NDSolve, Manipulate

I have a pretty little `NDSolve` function that I've finally decked out with manipulatable (by sliders) coefficients, which changes the graph in real time. However, I used dummy equations in making sure I could set up the system I want, which I have as you can see by simply copy-pasting:               Manipulate[      Plot[       Evaluate[{a[t], b[t], c[t]} /.         NDSolve[          {a'[t] == -k1f*a[t] + k1r*b[t],           b'[t] == k1f*a[t] - k1r*b[t] - k2f*b[t],           c'[t] == k2f*b[t],           a[0] == a0,           b[0] == 0.0,           c[0] == 0.0},          {a, b, c}, {t, 0, 1500}, MaxSteps -> 1000, AccuracyGoal -> 10]],       {t, 0, 1500}, PlotRange -> {{0, 1500}, {0, 0.11}},        AxesLabel -> {"Time (Seconds)", "Concentration"},       PlotStyle -> {{Red, Thickness[0.008]}, {Green,           Thickness[0.008]}, {Blue, Thickness[0.008]}}],      {{k1f, 0.01, Subscript[k, 1]}, 0, 0.02},      {{k1r, 0.01, Subscript[k, -1]}, 0, 0.02},      {{k2f, 0.01, Subscript[k, 2]}, 0, 0.02},      {{a0, 0.1, Subscript[a, init]}, 0, .2}]      All I want is to rename my equations `(a'[t], b'[t], c'[t])` in the first argument of `NDSolve` to a nickname, eqns, to simplify looking at them when they aren't the dummy 3 equations but are my real 150 equations, instead. But `eqns = {a'[t] == -k1f*a[t] + k1r*b[t], ...` as is done in the first argument of `NDSolve` above, followed by `NDSolve[z,{a, b, c}, etc.] returns a ridiculous number of errors. Where am I going wrong? _**Answered!_** For those of you still confused after reading the original question's answer (linked above), please see the comments for a short answer as to how to address my scenario specifically.


Manipulate gives the output as a blank plot, but I'm not sure why

I'm using Mathematica 9 to try to manipulate a 3D plot. My code is:               Clear[f, α, n]     n = 0;     f = (1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h] - (2/3)*α*     p^3*D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h], p,      p] - (1/3)*α*p^2*     D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h],      p] + (1/2)*α^2*((39/9)*p^4*       D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h], p, p] + (28/9)*       p^5*D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h], p, p,         p] + (4/9)*p^6*       D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h], p, p, p,         p] + (6/9)*p^3*       D[(1/Pi)*(-1)^n*Exp[-2*H/h]*LaguerreL[n, 4 H/h], p])     Manipulate[Plot3D[f, {x, -10, 10}, {p, -10, 10}, PlotPoints -> 200, PlotRange -> All], {α, 0, 1, 1}]      where $h=1$ and $H=\frac{1}{2}(x^2+p^2)$. This, however, just gives a blank plot. ![enter image description here](http://i.stack.imgur.com/a3x8j.png) Evaluating the function manually, I find that it is equal to: $\frac{e^{-p^2-x^2}}{\pi }-\frac{1}{3} 2 \alpha p^3 \left(\frac{4 p^2 e^{-p^2-x^2}}{\pi }-\frac{2 e^{-p^2-x^2}}{\pi }\right)+\frac{2 \alpha p^3 e^{-p^2-x^2}}{3 \pi }+\frac{1}{2} \alpha ^2 \left(\frac{13}{3} p^4 \left(\frac{4 p^2 e^{-p^2-x^2}}{\pi }-\frac{2 e^{-p^2-x^2}}{\pi }\right)-\frac{4 p^4 e^{-p^2-x^2}}{3 \pi }+\frac{4}{9} p^6 \left(-\frac{48 p^2 e^{-p^2-x^2}}{\pi }+\frac{12 e^{-p^2-x^2}}{\pi }+\frac{16 p^4 e^{-p^2-x^2}}{\pi }\right)+\frac{28}{9} p^5 \left(\frac{12 p e^{-p^2-x^2}}{\pi }-\frac{8 p^3 e^{-p^2-x^2}}{\pi }\right)\right)$ In Manipulate, if I manually replace f with this function, I get exactly what I want.               Manipulate[ Plot3D[E^(-p^2 - x^2)/π -    2/3 p^3 (-((2 E^(-p^2 - x^2))/π) + (       4 E^(-p^2 - x^2) p^2)/π) α + (   2 E^(-p^2 - x^2) p^3 α)/(3 π) + 1/2 (13/3 p^4 (-((2 E^(-p^2 - x^2))/π) + (         4 E^(-p^2 - x^2) p^2)/π) +        28/9 p^5 ((12 E^(-p^2 - x^2) p)/π - (         8 E^(-p^2 - x^2) p^3)/π) +        4/9 p^6 ((12 E^(-p^2 - x^2))/π - (         48 E^(-p^2 - x^2) p^2)/π + (         16 E^(-p^2 - x^2) p^4)/π) - (4 E^(-p^2 - x^2) p^4)/(      3 π)) α^2, {x, -10, 10}, {p, -10, 10},   PlotPoints -> 200, PlotRange -> All], {α, 0, 1, 1}]      ![enter image description here](http://i.stack.imgur.com/3rAuy.png) Does anyone know why this difference occurs? How would I bypass this so that my first piece of code will work, that is, without having to manually input f i.e. get my second image as an output using my first piece of code? My goal is to be able to have Manipulate control the values of both n and $\alpha$. Thanks


Manipulate and ListPlot

I have a $300$ by $2$ matrix called `r` which its elements depend on parameter `g`. I would like to plot this matrix and change the `g` to see how the graph changes. I have used this code:               Manipulate[ListPlot[r], {g, 0, 10}]       However, nothing happens. If I determine the parameter `g`, then I can plot it with `ListPlot[r]`. But, when I use manipulate, I cannot plot it. Any suggestion? Thank you in advance.


Scoping problem with Manipulate

Consider the following simple code:               f = Sin[a x];     Manipulate[       Plot[f, {x, 0, 10}],        {a, 0, 10}]      Manipulate takes `f` to be a variable which has no value. I tried to evaluate `f` as follows:                Manipulate[        Plot[Evaluate @ f, {x, 0, 10}],         {a, 0, 10}]      but now I still have a problem with the scope of `a`. I know one way to do what I want, which is to define `f` as a function of `a` as follows:               f[a_] := Sin[a x];     Manipulate[       Plot[f[a], {x, 0, 10}],        {a, 0, 10}]      But what if I have many variables and I want to manipulate over all of them? Is there any way to make `Manipulate` substitute `f` by its value and take all of its symbols as a variables to be manipulated?


Manipulate and global assignments

I've a (perhaps too) basic questions that has been bugging me for a while. Manipulate seems to ignore global assignments. For instance the following does not result in the obvious output one would expect:               a = x*b;     Manipulate[Plot[a, {x, 0, 1}], {b, 1, 2}].      Instead, to had a 45 degree line, one had to redefine the a object within manipulation:               Manipulate[x*b;Plot[a, {x, 0, 1}], {b, 1, 2}].      Is there a way to have `Manipulate` to use the global assignment `a=x*b`? Thanks!!


Efficient JSON parser for Mathematica

Im looking for a efficient way of parsing JSON data in _Mathematica_. I am having a lot of problems with `ImportString` because it uses Java, is too slow, and uses too much memory (and, also, sometimes it just returns Null). Do you know how to write a function for JSON parsing in _Mathematica_ , or how to use any C/C++ (or other efficient) library from _Mathematica_?


How do I define the domain of a function?

I have a function of two variables, `f[x_, y_]`, and I would like to restrict the domain to values of `x` and `y` greater than zero. How do I do this? I also want to plot the function for restricted values. I have tried to use `RegionFunction -> Function[{x, y}, ...]`, but this doesn't work.


Arbitrary depth patterns/rules

_Temporary message: I am now really confused. I am not sure how using Power and Unevaluated together works in the examples below._ While answering this question, I stumbled upon the following. We have               Power[Unevaluated[       Power[Power[Power[Power[Power[Times[1, a1], a2], a3], a4], a5],         a6]], a7]      -> Power[Power[Power[Power[Power[Power[a1,a2],a3],a4],a5],a6],a7] Where there seems to be some rule involving deeply nested patterns at work (correct me if I'm wrong). Compare this with               Power[Unevaluated[       Power[Power[Power[Power[Power[Times[2, a1], a2], a3], a4], a5],         a6]], a7]      -> Power[Unevaluated[Power[Power[Power[Power[Power[Times[2,a1],a2],a3],a4],a5],a6]],a7] Where nothing happens. Note also that               a2 = 3;     Power[Unevaluated[Power[Times[2, a1], a2]], a3]      -> Power[Unevaluated[Power[Times[2, a1], a2]], a3] But that               Clear[a1, a2];     a1 = 3;     Power[Unevaluated[Power[Times[2, a1], a2]], a3]      -> Power[Power[6,a2],a3] **Most importantly** , note that               Clear[a1, a2, a3, f];     f[1] = 2;     Power[Unevaluated[Power[f[1], a2]], a3]      -> Power[Power[2,a2],a3] Whereas               Clear[a1, a2, a3, f];     f[] = 2;     Power[Unevaluated[Power[f[], a2]], a3] // FullForm      -> Power[Unevaluated[Power[f[],a2]],a3] We have               FullForm /@        Trace[Power[Unevaluated[Power[Power[Times[1, b], c], d]], e],         TraceOriginal -> True] // Column      ->               (*output*)     HoldForm[Power[Unevaluated[Power[Power[Times[1,b],c],d]],e]]     List[HoldForm[Power]]     List[HoldForm[e]]     HoldForm[Power[Power[Power[Times[1,b],c],d],e]]     HoldForm[Power[Power[Power[b,c],d],e]]     List[HoldForm[Power]]     List[HoldForm[Power[Power[b,c],d]]]     List[HoldForm[e]]     HoldForm[Power[Power[Power[b,c],d],e]]      I am not sure if what to conclude from this. Note that               Power[Hold[Times[1, 2]], 2] // FullForm      -> Power[Hold[Times[1,2]],2] so that Times is of course not cleared if there is a function with attribute HoldAll surrounding it. Note that the test functions below also depend on this. **Not so important: Tools** The following are tools to play with larger expressions like this               (*warning! might clear unexpected variables!*)     Clear @@ Names["arg*" | "a" | "b"]          SetAttributes[holderToken, HoldAll];     tester = And[First[#] == {}, Length[#[[2]]] == kkkk + 1,          Last[#] == {}] &;     headFinder =       Function[        ReplaceAll[         Unevaluated@Unevaluated@           Cases[            #,            head, Infinity, Heads -> True            ]         ,         {{head -> Unevaluated}, {head -> Power}, {head -> Times}}          ]        ];          expression :=       With[{compoWithHeldArg =          Unevaluated @@           (            DeleteCases[             Hold@              Evaluate[(Composition @@                       Array[With[{argu = Symbol["arg" <> ToString[#]]},                      Function @@ {argu, Power[argu, a[#]]}] &, kkkk])[                holderToken[Times[1, b]]]]             ,             holderToken, Infinity, Heads -> True             ]            )         }        ,             Power[compoWithHeldArg, a[0]]             ];      We then have               kkkk = 12;     tester@headFinder@expression      -> True and               kkkk=12;     expression // FullForm      -> Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[b,a[12]],a[11]],a[10]],a[9]],a[8]],a[7]],a[6]],a[5]],a[4]],a[3]],a[2]],a[1]],a[0]] and we see that                    Unevaluated @@           (            DeleteCases[             Hold@              Evaluate[(Composition @@                       Array[With[{argu = Symbol["arg" <> ToString[#]]},                      Function @@ {argu, Power[argu, a[#]]}] &, kkkk])[                holderToken[Times[1, b]]]]             ,             holderToken, Infinity, Heads -> True             ]            )//FullForm      -> Unevaluated[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Power[Times[1,b],a[12]],a[11]],a[10]],a[9]],a[8]],a[7]],a[6]],a[5]],a[4]],a[3]],a[2]],a[1]]] Where the Times is still present. So indeed applying Power[#,2]& to the expression above clears the Times. **Deep pattern** If we don't want to make any replacements, but just a deep pattern, we can recursively define a pattern as follows               Clear[patt];     patt = (_?AtomQ) | f[x_ /; MatchQ[x, patt]];      We then have               MatchQ[f[f[1]], patt]      (-> True) **A function that acts a bit like Power** Maybe something similar is going on with Power. That is, there is some pattern that searches in a deep way (maybe some kind of expressions that it can simplify), but the rule applied is trivial. I am confused and I thought the Times that was found was actually replaced by the same rule that (/whose pattern) found it. Now I am not sure if we should even speak of a rule in this case. I can make a function that works (at least a bit) like Power in very limited cases.               ClearAll[shortCondition]     SetAttributes[shortCondition, HoldAll]     shortCondition[x_] :=       MatchQ[Unevaluated[x],        HoldPattern[        Times[___, 1, ___] | power[xxxx_ /; shortCondition[xxxx], _]]]          ClearAll[power]     power[x_ /; shortCondition[x], n_] := power[x, n]      We then have               power[Unevaluated[power[Times[1, 2], e]], d]      -> power[power[2, e], d] -> power[2, 2] Whereas               power[Unevaluated[power[Times[2, 2], e]], d]      -> power[Unevaluated[power[Times[2, 2], e]], d] However, I think we should conclude from the Trace further above that Power works a little differently. **The new question is** : How can we simulate the behavior of Power, especially the aspect of it that seems to apply rules deeply in the expression that is one of its arguments. . . . . . **Old text, which seems to distract now** The more complicated problem of also making a non trivial replacement seems very difficult, but I'd still like to know if somebody knows if there is a way. If we also want to make a replacement , that makes things difficult. In the example in which f has a recursive pattern, we might want to replace the atom found by 0. In the example of power we might want to replace Times[a_ **,1,b_** ] by Times[a,b]. I think it is pretty unlikely that there is an elegant way of doing things. I had some hope that there would be a way make replacements in a general way, as I believed Power might work in this way. Now I don't think Power works in this way, but I still curious. As a small remark, not that we of course have               MatchQ[f[f[1]], (___f)[1]]      -> False and               MatchQ[Unevaluated[Sequence[f, f, f][1]], ___[1]]      Repeated and PatternSequence also seemed like they were maybe the way to go. But maybe not. **The question was** : Is it possible to define a rule in such a way that it determines whether an expression is of the form               f[___, f[___, ...[f[___, x_head ,___]] ,___], ___]      where the ...[] means that f is applied an arbitrary number of times in this way, and "do something with x on the RHS"? To clarify, we might want to define something like               f[___, f[___, ...[f[___, x_Integer ,___]] ,___], ___]:= x      Or in case of power               power[power[z...[Times[1,x_]],y_],z1_]:=power[power[z[x],y],z1]      where I have given the pattern of "repetitively applying power" the name z. A way of writing this in that might be parseable by Mathematica could be               z...power[Times[1,x_],y_]:=z[x,y]      Possibly the answer is: maybe in version 13. But any feedback is welcome :)


How make f[{x,y}] evaluate as f[x,y]?

I frequently encounter the situation where I have a function of two real variables defined, e.g.:               f[x_, y_] := 9 - x^2 - y^2      But then I need to feed into `f` not just two numbers but rather a pair, i.e., a 2-element list, e.g.:               p = {3, 4};     f[p]      How might this be done simply -- _without_ having to make a separate definition               f[{x_, y_}] := f[x, y]       Naively I used to expect that the following would work:               f[Sequence[p]]      But it doesn't. What does work, though, is:               f[Sequence @@ p]      Are there other, simpler techniques? I bring this up as an advocate for relatively new users of _Mathematica_ , because I think `Sequence` along with `Apply` is much too sophisticated for them! Note: The root cause is the typical "abuse of notation" in math, where a "function of two real variables" is really a function of ordered pairs of reals but the notation $f(x, y)$ obscures that.


How does FindShortestTour work?

How are `FindShortestTour` and the algorithms therewithin implemented internally? Also: Can I access some form of incremental, in-progress result during evaluation? _(e.g.: PCB autorouting)_ ![enter image description here](http://i.stack.imgur.com/74boo.png)


Using a variable for two different purposes

I want to name a bunch of tables after the OEIS entries which describe them. Is there any way to use these names for both the table name and the link at the same time? The second line uses the entry number as a variable: could I use the hyperlink in its place? This would allow clicking the link to reference the documentation from any place the file is referenced.               lcm[n_] := Module[{a = 1}, For[b = n, b > 1, b--, a = LCM[a, b]]; a]     A002944 = Table[lcm[n]/n, {n, 1, 15}]     Hyperlink["A002944", "http://oeis.org/A002944"]     Hyperlink[A002944[[1 ;; 6]], "http://oeis.org/A002944"]        **Edit** The last line displays the first few characters of the sequence, so I can click it to see more.


Is there an open source implementation of Mathematica-the-language?

I've seen questions before such as "What is the best open-source equivalent for Mathematica?", but that specific question (and that line of inquiry in general) cares more about the computer algebra system and less about the core language and its unique and powerful features. My interest in Mathematica come from a slightly different angle--namely, I find a tremendous amount of value in the power and flexibility of the _language_ that Mathematica implements (I think of it as a slightly less scary looking syntax for Lisp with some very novel additions such as the powerful pattern matching system). **Are there any projects that have made a concerted effort to build a Mathematica-the-language work-alike instead of focusing on the Computer Algebra System?** Mathics is the closest project I've found so far (since it does, in fact, try to stay faithful to Mathematica syntax where it can), but even it pitches itself as a computer algebra system. And it was written in Python, which isn't bad by itself, but it sets itself up to not be as fast as Mathematica for computationally intensive tasks. It seems to me that Wolfram Research would actually benefit tremendously from having an even bigger programmer community around Mathematica as a language and developer platform, because more packages would be produced to solve more off-the-shelf programming problems (just like almost any other programming language). An open (or at least freely available) implementation of the core programming language wouldn't even dilute their secret sauce which I would say primarily lies in Mathematica's base of mathematical rules and algorithms, in the scientific computing tools that they've bundled into one enormous and broad package, and into the insanely well-integrated notebook experience that they should have no trouble keeping ahead of any kind of open source project.


How to take conjugate of a function?

Naïvely this is what happens and it obviously is not helpful!               In[7]:= Conjugate[SphericalHarmonicY[1, 1, θ, ϕ]]          Out[7]= -(1/2) E^(-I Conjugate[ϕ]) Sqrt[3/(2 π)] Conjugate[Sin[θ]]      So I tried stating initially that $\theta$ and $\phi$ are reals - but still that doesn't seem to have helped any bit,                In[8]:= θ ∈ Reals; ϕ ∈ Reals;             In[9]:= SphericalHarmonicY[1, 1, θ, ϕ]            Out[9]= -(1/2) E^(I ϕ) Sqrt[3/(2 π)] Sin[θ]            In[10]:= Conjugate[SphericalHarmonicY[1, 1, θ, ϕ]]            Out[10]= -(1/2) E^(-I Conjugate[ϕ]) Sqrt[3/(2 π)] Conjugate[Sin[θ]]      Kindly tell me how to do this? (...I want to calculate sums like $\sum\limits_{m=-\ell}^{\ell}\vert Y_{l,m} (\theta,\phi)\vert^2$...)


Is there anything like a C pointer (or returning a reference) in $Mathematica$?

I want to do in _Mathematica_ what the following does in C.               int array[7] = {0, 0, 0, 0, 0, 0, 0};          int& foo(size_t idx)     {         return array[idx];     }          foo(4) = 43;          // array should now be {0, 0, 0, 0, 43, 0, 0}      In other words, I'd like to use `=` to assign to a reference (to some variable outside the scope of the function) returned by a function. I did read a few threads about references, but it seemed I'd have to "overload" the `=` operator (if that's even possible) to make things work. * * * ### Background I wouldn't be surprised if such practice were discouraged in _Mathematica_ , but would still appreciate the knowledge, as well as alternatives. My motivation for this is in trying to write a tool for non-programmers (or those with mostly C backgrounds but completely unfamiliar to _Mathematica_ ) for rapid testing of hypotheses, and the tool must be _intuitive, familiar, and easy to pick up_ (else I'm afraid my pitch to use _Mathematica_ wouldn't gain traction). To be more specific, the tool would analyze time-series data, the user specifying an expression to be run per time-step; and that expression would have "access" to a (pseudo-)array, say, `price`, such that `price[0]` refers to the _current_ price, `price[-1]` refers to the _previous_ price, etc.--so `price[0]` refers to a different price at each timestep. Of course C doesn't allow negative indexing; I just thought it'd be most intuitive that way--so my plan was to implement `price` as a function, and retrieve values from an array behind-the-scenes. You can probably see already where this is going: I'd also like for users to be able to _assign_ to `price[0]`, and that's where I'm stuck. I know I could (and perhaps _should_ ) just write a separate function like `set_price[0, val]`, but this would take away from the aesthetic goal I'm trying to achieve to win everyone over. I'm open to alternative ideas that may keep aesthetic though not in the same way.


Creating a 3D List Line Plot From Discrete Points

Given the following Runge-Kutta ODE solver and the graphical output below, how do I get a 3D line plot instead of a 3D point plot? I see that there is no ListLinePlot3D function, so I thought it might be possible to convert the tables of values T1, T2 and T3 into interpolating functions and then use the ParametricPlot3D function to plot the solution in its line form instead of point form. Currently though I'm having a little trouble with the interpolating function + ParametricPlot3D output, as I just get an empty box.               Remove["Global`*"]     (*dx/dt=*)f[t_, x_, y_, z_] := \[Sigma] (y - x);     (*dy/dt=*)g[t_, x_, y_, z_] := x (\[Rho] - z) - y;     (*dz/dt=*)p[t_, x_, y_, z_] := x y - \[Beta] z;     \[Sigma] = 10;     \[Rho] = 28;     \[Beta] = 8/3;     t[0] = 0;     x[0] = 1;     y[0] = 1;     z[0] = 1;     tmax = 2000;     h = 0.01;          Do[      {t[n] = t[0] + h n,            k1 = h f[t[n], x[n], y[n], z[n]];       l1 = h g[t[n], x[n], y[n], z[n]];       m1 = h p[t[n], x[n], y[n], z[n]];            k2 = h f[t[n] + h/2, x[n] +  k1/2, y[n] + l1/2, z[n] + m1/2];       l2 = h g[t[n] + h/2, x[n] +  k1/2, y[n] + l1/2, z[n] + m1/2];       m2 = h p[t[n] + h/2, x[n] + k1/2, y[n] + l1/2, z[n] + m1/2];            k3 = h f[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];       l3 = h g[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] + m2/2];       m3 = h p[t[n] + h/2, x[n] + k2/2, y[n] + l2/2, z[n] +  m2/2];            k4 = h f[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];       l4 = h g[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];       m4 = h p[t[n] + h, x[n] + k3, y[n] + l3, z[n] + m3];            x[n + 1] = x[n] + 1/6 (k1 + 2 k2 + 2 k3 + k4);       y[n + 1] = y[n] + 1/6 (l1 + 2 l2 + 2 l3 + l4);       z[n + 1] = z[n] + 1/6 (m1 + 2 m2 + 2 m3 + m4);       }, {n, 0, tmax}]          T1 = Table[{t[i], x[i]}, {i, 0, tmax}];     T2 = Table[{t[i], y[i]}, {i, 0, tmax}];     T3 = Table[{t[i], z[i]}, {i, 0, tmax}];          ListLinePlot[T1]     ListLinePlot[T2]     ListLinePlot[T3]          ListPointPlot3D[Table[{x[t], y[t], z[t]}, {t, 0, tmax}]]          I1 = Interpolation[T1]     I2 = Interpolation[T2]     I3 = Interpolation[T3]     ParametricPlot3D[{I1[t], I2[t], I3[t]}, {t, 0, tmax}]      What I'm looking to do is essentially get the following Lorenz Attractor point graph into a line graph form: ![enter image description here](http://i.stack.imgur.com/EJ4sb.png) Any help would be appreciated, thanks guys.


Will custom fonts in my notebook be carried over?

In my notebook, I have Open Sans (a free font) as a text font and Consolas (a paid font) as a code font. Those fonts are coded into the stylesheet of my notebook. My question is: if I send someone a copy of my notebook, will it be rendered in those fonts or will they become default Mathematica fonts (IIRC Arial and Courier--yuck!)?


Stacked Line Graph with fragmented data

Let's start with what I already found on the internet:               data = {{10, 4, 3, 0, 8, 8, 10, 8, 9, 10},              {2, 1, 2, 15, 5, 8, 7, 10, 9, 15},             {1, 4, 8, 1, 2, 8, 12, 10, 9, 15}};          ListLinePlot[Accumulate[data], Filling -> {1 -> {Axis, LightRed},          2 -> {{1}, LightOrange}, 3 -> {{2}, LightBlue}}, PlotStyle -> {Red, Orange, Blue}]      This one will produce a stacked graph like the one i want: ![enter image description here](http://i.stack.imgur.com/23Wnu.png) but the data I have is not directly usable like in this example because accumulate wouldn't work unless I process data in some way. * * * Let's say the data i have is something like this:               data = {      { {1, 10}, {3, 94.94}, {5, 41.52}, {10, 15.25}, {100, 2.19} },      { {4, 2.35}, {8, 10.64}, {12, 90.28}, {36, 50.74} },      { {2, 11.55}, {10, 15.65}, {20, 41.81} },      { {1, 20.13}, {3, 57.44}, {5, 42.74}, {10, 3.59}, {40, 2.05}, {100, 2.05} },      { {4, 13.74}, {20, 65.49}, {40, 112.62}, {80, 10.42} }};      If plot all together with a `ListLinePlot`, this is what I will get:               ListLinePlot[Table[data[[i]], {i, 1, Length[data] - 1}], Filling -> Axis]      Where each line is the junction of points for each set.. ![enter image description here](http://i.stack.imgur.com/4D477.png) I would like to obtain a stacked graph exactly with these lines. Could you help me to achieve this result? Best Regards PS: if possible would be cool see both cases where the values outside domains gives 0 contribute or the case were we continue using the same angular coefficient for the borders like in this image: ![enter image description here](http://i.stack.imgur.com/Z5S8K.png) With the functions gets anyways = 0 if value < 0 :)


Neumann boundary conditions in NDSolve over nontrivial region

The problem I would like to solve involves diffusion in the following region               reg = ImplicitRegion[-5 <= x <= 5 && -5 <= y <= 5 && x^2 + y^2 >= 1^2, {x, y}];     RegionPlot[reg, AspectRatio -> Automatic]      ![Region over which to solve PDE](http://i.stack.imgur.com/oYg6S.gif) Additionally, there is an interaction potential $v$ acting in this region:               v = Function[{x, y}, -E^(-x^2 - y^2)];     Plot3D[v[x, y], {x, -5, 5}, {y, -5, 5}, RegionFunction -> Function[{x, y, z}, x^2 + y^2 > 1^2], PlotRange -> {-1, 1}, PlotPoints -> 50]      ![plot of interaction potential](http://i.stack.imgur.com/AwIcF.gif) Physically, I would like to model 2D diffusion confined to this region, in the presence of the biasing potential given by $v$. So what I need to do is solve the PDE $\vec{\nabla} \cdot \left[\vec{\nabla}u(x,y) + u(x,y) \vec{\nabla}v(x,y)\right] = 0$ subject to the boundary conditions $u(x,-5) = 1$ $u(x,5) =0$ to impose an overall flux, and with zero-flux boundary conditions at the boundary where $x^2 + y^2 = 1$, (as well as on the sides where $x = \pm 5$). So I proceed as follows in Mathematica (10.0.0):               op = Div[Grad[u[x, y], {x, y}] + u[x, y] Grad[v[x, y], {x, y}],{x, y}];     bc = {DirichletCondition[u[x, y] == 1, y == -5],DirichletCondition[u[x, y] == 0, y == 5]};      Note that I did not specify boundary conditions for the circular boundary, nor for the sides $x = \pm 5$, because according to the NDSolve/NeumannValue documentation, these should default to zero-flux boundary conditions.               sol = NDSolve[{op == 0, bc}, u, {x, y} \[Element] reg, Method -> {"FiniteElement","MeshOptions" -> {MaxCellMeasure -> 0.005}}]      The solution looks like this:               Plot3D[Evaluate[u[x, y] /. sol], {x, y} \[Element] reg, PlotRange -> All, AxesLabel -> {"x", "y"}]      ![Solution of the PDE](http://i.stack.imgur.com/kpXug.gif) Now, this is not quite what I expected, for the following reason:if the PDE is solved correctly, with zero-flux boundary conditions, then the flux into the box (at y = -5) should equal the flux out of the box (at y = 5). You can sort of tell that this is not the case from the plot above, but plotting the normal derivative at the boundaries $y = \pm 5$ makes it clear:               Plot[{Evaluate[(Derivative[0, 1][u][x, 5] + u[x, 5] Derivative[0, 1][v][x, 5]) /.sol],     Evaluate[(Derivative[0, 1][u][x, -5] + u[x, -5] Derivative[0, 1][v][x, -5]) /. sol]}, {x, -5, 5}, PlotRange -> {-0.2, 0}]      ![normal derivatives](http://i.stack.imgur.com/RaMm4.gif) Integrating these will give the flux in and the flux out. Clearly the flux in is not equal to the flux out. Since I have checked to make sure that the PDE $\vec{\nabla} \cdot \left[\vec{\nabla}u(x,y) + u(x,y) \vec{\nabla}v(x,y)\right] = 0$ is obeyed in the interior of the region, it seems that I am not correctly setting the Neumann boundary condition at the circular boundary $x^2 + y^2 = 1$. The boundary condition that I _want_ is $\left[\vec{\nabla}u(x,y) + u(x,y) \vec{\nabla}v(x,y)\right] \cdot \vec{n} = 0$ but I _believe_ that the boundary condition that I'm _getting_ is simply $\left[\vec{\nabla}u(x,y)\right] \cdot \vec{n} = 0$ How can I impose the correct boundary condition? Have I misunderstood the documentation, which seems to say that my desired boundary condition is the default?


Why does the function Evaluate speed up one function by orders of magnitude and another function not at all?

I've got two functions, one sample function (function 1) i've created for demonstartion purposes here, and my actual function. The function Evaluate speeds up the sample function by orders of magnitude but it doesn't do anything with my actual function (function 2). Function 1:               a[x_] := x^2     g[b_, x_, y_, z_] := b a[x] + x y^2 + x z^2;     f[b_, y_, z_] := (buffer = Minimize[g[b, x, y, z], x];        xmin = x /. buffer[[2]];        g[b, xmin, y, z]);          start = SessionTime[];     Plot3D[f[2, y, z], {y, 0, 4}, {z, 0, 4 - y}, PlotPoints -> 3]     SessionTime[] - start          start = SessionTime[];     Plot3D[Evaluate@f[2, y, z], {y, 0, 4}, {z, 0, 4 - y}, PlotPoints -> 3]     SessionTime[] - start      First Plot:               start = SessionTime[];         Plot3D[f[2, y, z], {y, 0, 4}, {z, 0, 4 - y}, PlotPoints -> 3]         SessionTime[] - start      takes about 16 seconds. Second Plot:               start = SessionTime[];     Plot3D[Evaluate@f[2, y, z], {y, 0, 4}, {z, 0, 4 - y}, PlotPoints -> 3]     SessionTime[] - start      takes only 0.2 seconds. $$$$ $$$$ Function 2:               bindeaa[e0_] := e0;     c[e0_] := 40 e0;     bindeab[e0_] := 1.27 e0;          alpha[gamma_, p_, epsilon_] := p (gamma - epsilon);     beta[b_, epsilon_, n2_] := b epsilon^2 n2^(3/2);                    eisl[b_, e0_, g_, gamma_, p_, epsilon_, n2_, x_] :=        g c[e0] (epsilon)^2 - bindeaa[e0] +         e0 ((-2 Log[E^(1/2) x])/x^2 + alpha[gamma, p, epsilon]/x +            beta[b, epsilon, n2]/x^(3/2));          eislminx[b_, e0_, g_, gamma_, p_, epsilon_, n2_?NumericQ] :=       Module[{minxzwischen, minx,         x}, (minxzwischen =          FindMinimum[{eisl[b, e0, g, gamma, p, epsilon, n2, x],            0 < x }, x];        minx = x /. minxzwischen[[2]];        eisl[b, e0, g, gamma, p, epsilon, n2, minx])]           start=SessionTime[]      Plot[eislminx[10, 1, 0.7, 0.3, 4.9, 0.05, n2], {n2, 0, 10},       PlotPoints -> 3, PlotRange -> {-.93, -.82}]      SessionTime[] -start      Both Plots take the same time, about 3.2 seconds. Does anybody know why Evaluate speeds up function 1 but not function 2?


PolarPlot render oddities

I apologize if this is a obvious question and answer, I don't often use _Mathematica_ to display plots or graphics in general to be honest. So, I was tutoring my cousin yesterday in relation to Polar functions and decided to bring up _Mathematica_ to illustrate some of the ideas we were discussing. I quickly typed a one line command into _Mathematica_ 8 and got an odd result. When rendering a polar function, _Mathematica_ took a few seconds to make it smooth. Prior to this it has too many lines (see picture, before is on left and after is on the right.) The code is:               Manipulate[PolarPlot[Sin[nS*t], {t, -5 Pi, 5 Pi}], {nS, 1, 20, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/muNQP.png) Does anyone know why this is happening and if there is a way to make Mathematica render smooth at first?


How to maintain a smooth surface in CDFs while playing?

I created a CDF for viewing the Möbius Band, and its generation. https://www.dropbox.com/s/e3af0xelbbqjfhd/Cinta_Moebious_Rafa.cdf But: 1.- When it´s PAUSED the surface is soft and you can see with quality. 2.- But when you are playing and move the segmente that generate Möbius Band, .... the band seems to be less quality, and you can see point-squares, instead a soft line in the border. ...as you can see: ![enter image description here](http://i.stack.imgur.com/yWkJ9.jpg) How can i do to maintain the surface .... soft!! Any option in SaveDefaults?.... to save more points??? \------------- This code is edited after cormullion message f[u_] = {2 Sin[u], 2 Cos[u], 0} g[u_] = {0, Sin[u/2], Cos[u/2]} Manipulate[ Show[ ParametricPlot3D[f[u] + v g[u], {v, -1, 1}, {u, 0, 2 Pi}, PlotRange -> {-3.2, 3.2}, Axes -> True, AxesLabel -> {x, y, z}, Mesh -> None, ExclusionsStyle -> {None, Red}, PlotStyle -> Directive[Green, Opacity[0.75`], Specularity[White, 20]], PerformanceGoal -> "Quality"],                 ParametricPlot3D[f[u] + v g[u], {v, -1, 1},         PlotRange -> {-3.2, 3.2}, Axes -> True, AxesLabel -> {x, y, z},         Mesh -> 1, MeshShading -> {Red, Blue}, PlotStyle -> Thick],         PerformanceGoal -> "Quality"], {u, 0, 2 \[Pi], Appearance -> "Open"},            Style[" En Verde vemos la famosa Cinta de Mobius", Darker@Green],       Style[" También vemos la barra que la genera, al ir girando su \       centro sobre el plano z=0, a la vez que la barra gira un ángulo de \      180º. Dicha barra la pintamos de dos colores para ver su \      orientación", Darker@Gray],      Style[" La Parte Azul=Parte positiva", Darker@Blue ],       Style[" La Parte Roja=Parte Negativa", Darker@Red],      Style["IMPORTANTE: Fijarse como la barra comienza cabeza arriba, \      pero, tras completar el movimineto de los 360º, llega cabeza abajo",        Darker@Orange],      Style["Creado y Diseñado por: Rafaorly@gmail.com", Darker@Blue],        SaveDefinitions -> True]      * * *


Plot using Manipulate or Animate

> **Possible Duplicate:**   >  PolarPlot render oddities When I use manipulate or animate function, the result shows a non-smooth plot. How to make the manipulate or animate commands show good and smooth plot?


Extracting the integers from a list

I have a list where the elements are Reals and Integers. How can I extract the Integer? For example, if I have `{1, 2, 3.4, 9.9}`, how can I get `{1, 2}`?


Documentation searches hang frequently: Anyone else dealing with this?

I've been struggling with a number of hangs, dynamic timeouts, and outright crashes when using the search/documentation center in version 9. I've tried uninstalling/reinstalling and clearing preferences/cache on start-up, praying for a paclet update---but nothing seems to help. One easily reproducible crash involves searching via the F1 key. On my machine (Windows 7, 64-bit), following the steps below, fails 100% of the time. (This is the simplest example I've taken the time to document; there seem to be many others.)   1. With a fresh session (not always reproducible with just a fresh kernel), type something in the front-end. This could be text (in a text cell) or input (in an input cell) such as: `something` (and leave it unevaluated---if in an input cell)   2. Now highlight that input and hit "F1" to perform a search. This will either return a dynamic timeout warning, or momentarily freeze the front-end and do nothing.   3. Now use your cursor to select `something` again and try "F1" a second time. This will perform the search as desired. _Can anyone reproduce this issue?_ **UPDATE 1:** Upgrading to 9.0.1 only partially addresses the issue. To illustrate, start a fresh session/kernel, type `something` and then hit F1 ( _without_ manually highlighting `something`). A similar hangup will occur. As Albert points out in his answer, this hangup does not seem to occur with F1 searches on built-in symbols, highlighted or not. Finally, FWIW, I suspect Albert's observation relates to another way I've encountered errors. Quite often when I come across some unfamiliar mathematical terminology on stackexchange, I reflexively copy and paste the term---from my browser, to the search field of the documentation center (which is almost always open when I'm working). Frequently this will generate the same type of error or worse. I suspect it has to do with whether or not the search term is either a built-in symbol or already indexed somehow. **UPDATE 2:** I recently decided to wipe my machine and reinstall everything from the OS up. Eventually I got around to installing Mathematica (from the exact same installer used previously). Much to my surprise, even without applying either of the two fixes, the hangups seem to be gone (or at least below what I can perceive). Just wanted to document this. Will report back if anything changes.


Simplifying fractions

What `ComplexityFunction` (or other technique) can I use to have Mathematica pull things out of fractions? I have a rational function of several variables and I'd like to have Math'ca simplify, e.g.,               x(... + y(... + wz)) + ...     --------------------------                 xyz      to               x(... + y(...)) + ....     ---------------------- + w               xyz      ? I've already told it that the relevant variables (in the denominator) are nonzero. I was thinking of counting complexity as `LeafCount` plus the `LeafCount` of numerators, but I'm not sure how to do that.


Solve Differential equation system

I've tried to solve this differential equation system, buy without any luck. ![enter image description here](http://i.stack.imgur.com/1VaGh.png) This is my code:               RSolve[{x'[t] == x[t] - y[t], y'[t] == 5 x[t] - 3 y[t], x[0] == 1, y[0] == 2}, {x[t],     y[t]}, t]      Can anyone tell me what I've done wrong?


Creating a conditional table

I'm trying to create a conditional table. Let's say I want to have such result: {1,2,3,4,5,0,0,0,0,0}. The idea is to create a table of n elements (10 in a given example), but when one element takes a specific value (5 in my example), then all of the remaining elements must take provided value (let's say zero). It's important not to use IF checking every element whether it satisfies provided condition.


Error computing sum of sum of digits

I've defined a function that computes the sum of the base-b digits of n:               DigitSum[n_, b_] := Total[IntegerDigits[n, b]]      Then I defined a function that computes the sum of the base-b digits of all of the integers up to x:               CumDigitSum[x_, b_] := Sum[DigitSum[n, b], {n, 1, x}]      Using these functions, I get               CumDigitSum[1000000,10]=27000001      which is correct. But then for larger inputs I get nonsense like               CumDigitSum[1000001,10]=500011500011      If I work in a different base, the same thing happens: at exactly 1000001, Mathematica begins computing the sum incorrectly. If I bypass my user-defined functions and just write what I mean, I get the correct answer:               Sum[Total[IntegerDigits[n, 10]], {n, 1, 1000001}] = 27000003      Any idea what could be happening here?


How to efficiently select elements from a Hash?

How can I write an efficient version of the following selection statement:               Keys[Select[hash, # < constant &]]; // AbsoluteTiming      hash can be made from:               hash = Association[Table[i -> i^2, {i, 1, 10^6}]];      On my computer, a last year MacBook Pro, it takes almost a half second. However, this is non an acceptable time for working with Hashs. Any other ways to do that? Thank you very much.


Suitability of Mathematica as platform for engineering calculations and programs

I am considering using Mathematica with Wolfram Workbench as a standard platform for calculations and programs in a large engineering department. I am looking for a solution that would provide better validation, documentation and revision control than Excel spreadsheets with VisualBasic macros. Additional benefits would be to use built-in functionality to reduce development effort and to allow engineers to use code interactively instead of in a black-box mode. I have used Mathematica and WebMathematica for individual projects in the past, and am familiar with the various customer examples that Wolfram advertises. However, I don't have experience or examples of using Mathematica across a large engineering department. I expect that we would develop packages for various back end functionality (likely on the order of 20,000+ lines of code), and users would access it either directly in the notebook, through CDF applications or through WebMathematica depending on the application. Is Mathematica suitable for this type of use? Can average users learn Mathematica without too much trouble and become productive quickly? Is there a better solution you would suggest evaluating?


How to track objects in video

I have a video that contains object moving in one direction, is it possible to track the objects and get information like object moving speed, object length and coordinates etc.? An example would be I have a video of highway traffic, and I want to get the car size, lane number and speed for each car. * * * **Simplified Problem** Here is a simple version of the problem: Say I have several rectangles moving in one direction, and I want to know their length and position. The following code creates 100 frames of moving rectangles:               N0 = 100;     lengthRange = {2, 3, 4, 5};     positionRange = {1, 2, 3, 4, 5};          objectsDimension = RandomChoice[lengthRange, {N0}];(*Different possible length of rectangle*)          objectsPosition = RandomChoice[positionRange, {N0}];(* Track number for the rectangle*)          objectsEndPoins = Transpose /@ Transpose[{Transpose[{objectsPosition - 0.2, objectsPosition + 0.2}], Partition[Prepend[Accumulate[objectsDimension], 0], 2, 1] /. {x_, y_} -> {x + 0.2, y - 0.2}}];     (* coordinates for rectangles*)          timePlot = Graphics[Rectangle @@@ objectsEndPoins, ImageSize -> {200, Automatic}, AspectRatio -> 8];(* the whole time plot*)          frames = Table[Show[timePlot, PlotRange -> {{1 - 0.5, 5 + 0.5}, {n, n + 50}}, AspectRatio -> 1, ImageSize -> {200, Automatic}], {n, 0, 300, 3}];(*show different part of the whole plot, to create video frames*)          frames = Graphics[#[[1]], Sequence @@ Options[#]] & /@ frames;(*workaround of [this][1] problem*)          ListAnimate[frames]      ![enter image description here](http://i.stack.imgur.com/q2iqY.gif) **So can we get the coordinates and the length of the rectangles in the video?** * * * **What I tried** I first use the `FindGeometricTransform` find the speed for the moving objects, then stack each frame together to get a whole time plot, then measure the rectangles.               stepPerFrame = Mean@Table[FindGeometricTransform[frames[[i]], frames[[i + 1]], TransformationClass -> "Translation"][[2, 1, 2, 3]], {i, 1, 20}]       (*calculate the object moving speed per frame. Assume constant speed, average speed for the first 20 frames.*)          blank = Graphics[{}, ImageSize -> ImageDimensions[timePlot]];(*constract a blank plot*)          result = ImagePad[Block[{tmp = blank},         Do[tmp =             ImageCompose[tmp,              frames[[i]], {0, (i - 1)*stepPerFrame}, {0, 0}];, {i, 1,            Length@frames}];         tmp], {{0, 0}, {10, 0}},         White];     (*stack each frame together with a offset of object moving speed.*)          imageData = ImageData[Binarize[ColorNegate[result]]];(*binarize the image*)          lines = Reverse /@         Transpose[         imageData[[All,           Range[20, 180, 40]]]];(*outlines at each lane center*)          position =        Table[lines[[           n]] //. {x__, PatternSequence[0, 1], y__} -> {x, 0, "start",             y} //. {x__, PatternSequence[1, 0], y__} -> {x, "stop", 0,            y}, {n, 1, 5}];(*mark object start and stop in the data *)          objects =        Table[(Transpose@{Flatten[Position[position[[n]], "start"]],            Flatten[Position[position[[n]], "stop"]]}), {n, 1,          5}];(*select the object start and stop position*)          recoveredOjbDim =        Flatten[Differences /@ Sort@Flatten[objects, 1]] /. {5 -> 2, 9 -> 3,          13 -> 4, 17 -> 5};(*calculate the object length*)          recoveredOjbDim == objectsDimension(*compare to the correct answer*)     (*True*)      * * * **Questions:**   1. Could you show your methods, I'm sure I can learn a lot.   2. In the problem, all objects have the same constant speed, what can we do for objects with different speed?


Using ParallelMap to run multiple Game of Life simulations simultaniously

**My Assignment and Code** As an exercise in Parallel computing I've been tasked with implementing Conway's GoL in a way such that at every iteration only a fraction of cells are updated. I'm then to run several simulations starting with the same seed, in order to study effect of non synchronous updating. I've implemented this sequentially as follows: Initial variables:               gridSize = 10;     updateFraction = 0.9;     sampleSize = 8;     seed = RandomInteger[{0, 1}, {gridSize, gridSize}];      Normal GoL rules, and updated rules for randomly updating a fraction of the cells:               rulestest[{neighbours_, cell_}] :=       Module[{},        Piecewise[{{1, neighbours == 3}, {0,           neighbours <= 1 || neighbours > 3}}, cell]]          rulestestrandom[{neighbours_, cell_, randomseed_}] :=       Module[{},        Piecewise[{{cell, randomseed == 0}},         Piecewise[{{1, neighbours == 3}, {0,            neighbours <= 1 || neighbours > 3}}, cell]]]      Applying the rules to the grid:               step[matrix_] :=       Map[{Total@Delete[Flatten[#], 5], #[[2, 2]]} &,         Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /.{p_, q_} -> rulestest[{p, q}]          steprandom[matrix_] :=       Map[Flatten@{Total@Delete[Flatten[#], 5], #[[2, 2]],            RandomChoice[{updateFraction, 1 - updateFraction} -> {1, 0},1]}&,             Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /. {p_, q_, r_} -> rulestestrandom[{p, q, r}]      Doing a bunch of iterations and plotting it:               controlMatrix = seed;     controlAnimateSet = {controlMatrix};      Do[controlMatrixtemp = step[controlMatrix];       AppendTo[controlAnimateSet, controlMatrixtemp];       controlMatrix = controlMatrixtemp;, {100}]          Map[Function[testMatrix[#] = seed], Range[sampleSize]];     Map[Function[testMatrixtemp[#] = {}], Range[sampleSize]];     Map[Function[testMatrixAnimateSet[#] = {testMatrix[#]}],        Range[sampleSize]];     Do[Map[(testMatrixtemp[#] = steprandom[testMatrix[#]];           AppendTo[testMatrixAnimateSet[#], testMatrixtemp[#]];           testMatrix[#] = testMatrixtemp[#];) &, Range[sampleSize]];, {100}]          Manipulate[{Table[        ArrayPlot[testMatrixAnimateSet[m][[n]], Mesh -> True,          ImageSize -> Medium], {m, 1, 8}],        ArrayPlot[controlAnimateSet[[n]], Mesh -> True,         ImageSize -> Medium]}, {n, 1, 100, 1}]      **The problem** The code runs fine just like this, sequentially. However the goal is to make it run in parallel. I figured there are two things that could potentially be parallelized. Firstly updating the grid could be done in parallel:               step[matrix_] :=       ParallelMap[{Total@Delete[Flatten[#], 5], #[[2, 2]]} &,         Partition[ArrayPad[matrix, 1, "Periodic"], {3, 3}, {1, 1}], {2}]          /.{p_, q_} -> rulestest[{p, q}]      Now this works fine, but for grid sizes up to 100x100 (Which I've been instructed to use) this is less efficient when it comes to computing time, resulting in speedups of around 0.8 on my quadcore machine. The second option, which in my mind seems more obvious, is to parallelize the iterations on the group of test matrices. I tried to do it as follows:               Do[ParallelMap[(testMatrixtemp[#] = steprandom[testMatrix[#]];           AppendTo[testMatrixAnimateSet[#], testMatrixtemp[#]];           testMatrix[#] = testMatrixtemp[#];) &, Range[sampleSize]];, {100}]      However this doesn't work, and I don't understand why. The code runs without errors and gives a very nice speedup of around 3.0, however the `testMatrixAnimateSet` never gets appended with future iterations of the grid. Is this an error in my code, or just _Mathematica_ being quirky? Is there a way to work around this?


Defining Tags in Reap

I am trying to use `Sow`/`Reap` to replace `Append` in my code. The problem is that I need to define the tags within my code, but doing so doesn't reap the desired results. A simplified version of my code is               Clear[tag];     Reap[tag = {a,b}; Sow[1, a];Sow[2,b];, tag]      However, if I define my tag outside of Reap, then it works               Clear[tag];     tag = {a,b};     Reap[Sow[1, a];Sow[2,b];, tag]      Any ideas as to how I can define tags within my code?


How to retrieve the remaining cashflows from a FinancialBond object

I would like to get the cash flows and dates for the remaining coupons and principal repayment for a `FinancialBond` object. These must be calculated internally by the `FinancialBond` object for many of its possible return values but I can't see how to get the cashflows explicitly. Thanks


Executing Mathematica script from inside SQL Server

Does anyone have experience in calling _Mathematica_ from inside SQL Server to do calculations? For example, how can I make a Procedure that uses _Mathematica_? Or a job that runs some _Mathematica_ script? I saw this post on MathGroup, but it's a little bit confusing to me. Is there an easy way? Being more specific, I would like to execute (from inside SQL Server) a _Mathematica_ script. The script works using `MathKernel -script myFile.m` but I don't know how to make SQL call it. The Mathematica is installed in another server, in the same local web.


How to manipulate gauge theory in Mathematica?

I want to know if there is a way of typing into Mathematica an expression like the following, $$\epsilon^{\mu \nu \lambda} f^{abc} A^a_\mu A^b_\nu A^c_\lambda + g\epsilon^{\mu \nu \lambda} A^a_\mu \partial_\lambda A^a_\nu + \bar{\psi}(\gamma^\mu(\partial_\mu + gA^a_\mu T^a))\psi$$ (..repeated indices are understood to be summed over..) where $g$ is a number, $A^a_\mu$ can be thought of as matrices with $a,b,c = {1,2,3,..,N}$ for some $N$ and $\mu, \nu, \lambda = \\{ 0,1,2\\}$. So the $\partial_\mu$ are partial derivatives as $\partial_\mu = \frac{\partial}{\partial x^\mu}$. $f^{abc}$ is a set of numbers depending on the values of a,b and c and it is completely cyclic and anti-symmetric in it. $\epsilon^{\mu \nu \lambda}$ evaluates to $0$ if any two or more of its indices are equal and evaluates to 1 or -1 depending on whether the three distinct entries are in cyclic or anti-cyclic order. $\psi$ should also be thought of as a matrix $\psi^a_i$ where $i,j = \\{0,1,2\\}$. $\gamma^\mu$ are a chosen set of $3\times 3$ matrices. Each of $T^a$ is a $N \times N$ matrix. Then the terms involving $\psi$ when expanded out look like, $$\bar{\psi}\gamma^\mu \partial _\mu \psi = (\psi^\dagger)^a_i (\gamma^0\gamma^\mu \partial_\mu )_{ij}\psi_j^a \quad{ \rm and }\quad\bar{\psi}\gamma^\mu A^a_\mu T^a \psi = (\psi^\dagger)^a_i(\gamma^\mu)_{ij}(A^c_\mu T^c)^{ab} \psi^b_j$$   * I would like to be able to input the above expression into Mathematica without having to explicitly specify the numbers $f^{abc}$ and the matrices $T^a$. I would like to be able to manipulate the expression with the matrices $T,A,\psi$ and the numbers $f^{abc}$,$g$ as being variables.  If the above is possible then I would eventually like to do something like write $A^a_\mu = B^a_\mu + C^a_\mu$ and $\psi^a_i = \eta ^a _i + \xi ^a _i$ and expand the expression in terms of B,C,$\eta$ and $\xi$.


Graph vs GraphPlot

What is the difference (in purpose) between `Graph` and `GraphPlot`? Which function is bested suited to which tasks? **Background:** I just spent the last two hours trying to make this graph readable:               trans = Uncompress@        "1:eJyVV01vwjAMRfu47U/sv3RKKc2KGsahxw2YOE0aXPff17RJSZD8/HIBga3Efn5+\     dl4/f/rT32q1ujyNH+35cj09+F8v40d1/j1+XY+\     Ht8P30T2Pf9ihbyvn7Y0T3GbjzZtyM5LbYmcP9Els++FdTWJy7EwrOEYzTjbeRkHyODnvB\     adgnb7d8KHi4e3OgBudmb5sB3xsV1CBOTLpymCdv1sp/\     mBlzhq9tJrfqolRC9aSDNSzGPwxFv5f05GAldDVoJKbrgBWJsnCIuFMB/\     28JVXNMR7IQsfVvZSTCD07V79Z78Clo1VLIS+YVn5/2H67Q3h4M83wZr2B4W/\     oCmhaFDXSWysUWcVpH4sElyUTFYsEGxnPRl7nlRgTFoFBu0xGjuDToRLAs5GeeDWqes22H\     ORPLDl/FENXLXCmuVWQanrkBwmT88uGjhh8JgIyYRI91EW4aBoqtOIbg60RxD+IAGjuZC+\     QRSeXfC2qkhGor6gqD60WfdoZTOy8SGu9iONKFEJeVO7eELQGMvOD0UDYaXHN5a6DT5Zlv\     GuYlu2TmhIyD726bP5gSnswmEttWR9puG1wH6WE1VuSBI2sVNA6cfxlK6JIx7utFDE7vI5\     lyAL+Kv09FopgpA9t+\     cIcCcjZMXgYV4YWrHd86DFyR2xpTh012aCEY8sSoy3sX3A0OHUHTjWYWgR8fv/wd/kB";     Graph[DeleteDuplicates@trans, VertexLabels -> Placed["Name", Center],       VertexShapeFunction -> "Capsule", VertexSize -> 1,       VertexLabelStyle -> Large,       EdgeShapeFunction ->        GraphElementData["ShortUnfilledArrow", "ArrowSize" -> 0.02]]      ![Unreadable](http://i.stack.imgur.com/Cyd6x.png) Then I discovered that `GraphPlot` produces much more readable results:               GraphPlot[      DeleteDuplicates@trans /. (DirectedEdge[a_, b_] -> Rule[a, b]),       VertexLabeling -> True, DirectedEdges -> True]      ![Readable](http://i.stack.imgur.com/PuYrg.png) Which prompted me to wonder what's the point of `Graph`. Of course I noticed this, which while related, asks about the _Combinatorica_ package.


How is OptionsPattern[] defined? Can I replicate this?

I am writing several functions which all take similar input parameters (a complicated nested list structure). Is there some way for me to define a pattern that can be used in multiple places and allows me to extract the individual parameters? (I find `OptionsPattern[]` interesting because its definition isn't really visible but somehow `OptionValues[]` is able to extract information from it.)


Non solutions returned by NSolve. And why does it return both phi and Cos[phi]?

Similarly to this thread NSolve gives additional solutions that don't satisfy the equations! NSolve returns "spurious" solutions, even increasing the working precision               fsys={1 - Cos[(11 \[Pi])/45] - (3 Cos[psi1])/4 - 2/3 Sin[phi + \[Pi]/6] == 0, h + 2/3 Cos[phi + \[Pi]/6] + Sin[(11 \[Pi])/45] - (3 Sin[psi1])/4 == 0, -0.0436952 - (3 Cos[psi2])/4 - 2/3 Sin[phi - \[Pi]/6] == 0,2/5 + h + 2/3 Cos[phi - \[Pi]/6] + Sin[(17 \[Pi])/180] - (3 Sin[psi2])/4 == 0}          NSolve[N[fsys], {phi, h, psi1, psi2}, WorkingPrecision -> 100]      The second solution returned is                   {h -> -1.99515, psi2 -> -1.22627, psi1 -> 1.68803, phi -> 0.0618559,     Sin[psi1] -> -0.993136, Cos[psi1] -> -0.116967,       Sin[psi2] -> -0.941237, Cos[psi2] -> 0.337748, Sin[phi] -> 0.0618165,       Cos[phi] -> 0.998088}, {h -> -1.99515, psi2 -> 1.22627,       psi1 -> -1.68803, phi -> 0.0618559, Sin[psi1] -> -0.993136,       Cos[psi1] -> -0.116967, Sin[psi2] -> -0.941237,       Cos[psi2] -> 0.337748, Sin[phi] -> 0.0618165, Cos[phi] -> 0.998088}      , I do not understand why both psi1 and Cos[psi1] are returned, with Sin[1.68803] actually not equal to 0.993136 (the sign is different)


Document settings for online viewing

I'm trying to figure out how to prepare a notebook for NICE online viewing when it's been converted to PDF form. The students I am working with (sadly!) will not be able to use the CDFPlayer to view existing documents. I'm to use Google Docs and save the notebooks in PDF form. I've been working with settings for margins and page sizes and paper sizes, I'll admit I'm out of my depth completely. Specifically, I'd like two things. FIRST When I save as PDF, I'd like the pages to be like actual slides in terms of size. It would be nice if each page was viewable on screen like a nice "distinct" slide. Below, a 2 second pdf creation, being viewed in Google Docs. ![sample](http://i.stack.imgur.com/U7Dlr.png) B Is there any way to set the stylesheets so I would be able to 'see' in Mathematica what my pages would look like so I can edit, space, page break accordingly. I know, I expect my question is too vague and may get "punted", but I'll need to get going on this ASAP and I simply can't get my mind around it myself. I have tons of content all ready to go in existing notebooks and now find I am faced with a massive reformatting task. I can simply format for nice "regular" pages and students would scroll, but I figured since they were viewing documents on computer, there HAVE to be ways to capitalize on that. Tom


How can I produce a branch cut in a surface plot based made with ListPlot3D?

I need to create some surface plots, based on a function that is computationally expensive (a few minutes per point). The function has some branch cuts. The command `Plot3D` does not work because it just takes too long -- never finishes at any acceptable resolution. I can get enough data points (over a day or three), put them in a matrix, and use `ListPlot3D` to produce a plot. But I don't see how to make _Mathematica_ recognize the branch cut and not connect the two sides at the discontinuity.


Manipulate with variable number of sliders plus variable number of functions

I'm trying to setup a Manipulate where I have a variable number of sliders similar to this one, where every slider controls a function. In my case, there will be an additional slider which sets the number of functions. I've tried with               Manipulate[       Block[{},         Manipulate @@            {Plot[Table[Cos[2\[Pi]Subscript[h, i]x], {i, 1, n}], {x, 0, 1}],             Sequence@@Table[{Subscript[h, i], 0, 1}, {i, n}]}],        {{n, 1, "Waves"}, 1, 4, 1}]      but that does not work. I hope I have been successful in explaining my problem. For instance this is partially working, except I can not add controls on functions, i.e. Subscript[h,i] in a nested manipulate               Manipulate[       Block[{         trange = {t, 0, tmax},         plotrange = {{0, xmax}, {-1, 1}},         aspectratio = 1/xmax,         f = Table[Cos[2 \[Pi] i t], {i, 1, n}]         },         Plot[Evaluate[f], Evaluate[trange], PlotRange -> plotrange,          AspectRatio -> aspectratio]         ],       {tmax, 0.1, 1},       {xmax, 0.1, 1},       {n, 1, 4, 1}     ]


Problem with convert matlab function into mathematica version of euler angle

I've wrote a function that will extract euler angle from matrix according to Matlab's function in AeroSpace toolbox's dcm2angle package file. But not quite right.                threeaxisrot[r11_, r12_, r21_, r31_, r32_, r11a_, r12a_] :=  Module[{r1, r2, r3},  (*        % find angles for rotations about X, Y, and Z axes*)          r1 = ArcTan[ r11/ r12];          r2 = ArcSin[ r21 ];          r3 = ArcTan[ r31/ r32];   If[Abs[r21] >= 1, Print["HA-ha"]; r1 = ArcTan[r11a/r12a];    r2 = ArcSin[r21]; r3 = 0];  {r1, r2, r3}  ]                 Matrix2EulerAngleZXY[matrix0_] :=  Module[{dcm = matrix0},   threeaxisrot[-dcm[[2, 1]], dcm[[2, 2]], dcm[[2, 3]], -dcm[[1, 3]],    dcm[[3, 3]], dcm[[1, 2]], dcm[[1, 1]]]]      * * * Matlab package directory in my computer is               "F:\\Program Files\\MATLAB\\toolbox\\aero\\aero\\dcm2angle.m"      * * *               matrixList =  Table[RotationMatrix[i, {1, 0, 0}], {i, 0, 2 \[Pi], \[Pi]/6}]//N;          Matrix2EulerAngleTrackExpression // Definition          (*         Matrix2EulerAngleTrackExpression[matrix0_,type_:ZXY]:=Module[{matrix=matrix0[[1;;3,1;;3]]}     ,ttt=ToExpression[StringCases[StringReplace[ppp=MATLink`MEvaluate[[yaw, pitch, roll] = dcm     2angle(<>matrix2Matlab[N[Chop[matrix,1/10^5]]]<>,'<>type<>')],x:(NumberString~~e-~~NumberS     tring):>0],NumberString]]]     *)      Result1 * * * This is the Matlab's result(good one).               Matrix2EulerAngleTrackExpression /@ matrixList          (*         {{0,0,0},{0,-0.5236,0},{0,-1.0472,0},{0,-1.5708,0},{-3.1416,-1.0472,-3.1416},{-3.1416,-0.5     236,-3.1416},{-3.1416,0,-3.1416},{-3.1416,0.5236,-3.1416},{-3.1416,1.0472,-3.1416},{0,1.57     08,0},{0,1.0472,0},{0,0.5236,0},{0,0,0}}     *)      * * *               Matrix2EulerAngleZXY /@ matrixList          (*         {{0.,0.,0.},{0.,-0.523599,0.},{0.,-1.0472,0.},{0.,-1.5708,0},{0.,-1.0472,0.},{0.,-0.523599     ,0.},{0.,0.,0.},{0.,0.523599,0.},{0.,1.0472,0.},{0.,1.5708,0},{0.,1.0472,0.},{0.,0.523599,     0.},{0.,0.,0.}}     *)      Where goes wrong? Do you have a robust euler angle function/package?


Projecting image or contour plot on xy-plane of Histogram3D?

I've generated a simple 3D histogram, where the x-y coordinates corresponding to the "location" of an event defined on a simple 160x160 grid, and the z-axis height is simply the count of events that occur at each x-y location. For this particular graph, I have an png image (think of it as a map) on which the 160x160 grid is defined. I'd like to use this image as the x-y floor of my Histogram3D. I'd also like to use a ListContourPlot as the x-y floor, in a companion image. Any suggestions would be most welcome. Thanks. Mark


Can 2D and 3D plots be combined so that the 2D plot is the bottom surface of the 3D plot boundary?

I have a `ListlinePlot` function, that I would like to combine with both a `Graphics3D` plot and a `ListPointPlot3D` plot, in such a way that the `ListLinePlot` is the bottom of the 3D boundary cube for the 3D plots. Can this be done in Mathematica 8.0.4? Obviously the code below fails to combine the plots in `Show`, but is there another way to accomplish this? Thanks!                   Needs["TetGenLink`"]     twodPts = RandomReal[{-1, 1}, {10, 2}];     threedPts = RandomReal[{-1, 1}, {50, 3}];     {pts, surface} = TetGenConvexHull[threedPts];          twoDptsPlot = ListLinePlot[twodPts, ImageSize -> {200, 200}];     threeDPtsPlot = ListPointPlot3D[threedPts, ImageSize -> {200, 200}];     surfacePlot =        Graphics3D[{EdgeForm[], Opacity[0.3],          GraphicsComplex[pts, Polygon[surface]], ImageSize -> {200, 200}}];          {twoDptsPlot,       Show[threeDPtsPlot, surfacePlot, ImageSize -> {200, 200},        BoxRatios -> 1, Axes -> False]}      ![Mathematica graphics](http://i.stack.imgur.com/vzAIF.png)


Problem In using Finding Root for an infinite series involving Hypergeometric function

Tc[κ_] := t /. Chop[       FindRoot[         1 == (4 κ^4 NSum[ 2/3 Hypergeometric1F1[3/2, 5/2, -((2 κ^2 l)/t)], {l, 1, Infinity}]                 + 2 κ^2 t (PolyLog[1, Exp[(-2 κ^2)/t]])                 + 2 t^2 (PolyLog[2, Exp[(-2 κ^2)/t]]                 + (2 κ^2)/t PolyLog[1, Exp[(-2 κ^2)/t]])),       {t, tstart}, AccuracyGoal -> 8, PrecisionGoal -> 8]      ]          tstart = 0.5; ni = 100; κmin = 0; κmax = 1;      dκ := (κmax - κmin)/(ni - 1);     dat = Chop[ Table[{κ = κmax - (i - 1) dκ, Tc[κ]}, {i, ni}] ];      ListLinePlot[dat]      _Mathematica_ keeps on running and doesn't produce the plot for `Tc`


Custom function not returning any output

I'm trying to write a custom function but it isn't returning any output. Here's my code so far:               Options[Alternate] = {AlternationType -> AlternationPlusMinus};          Alternate[Terms_, Exponent_, OptionsPattern[]] := (        tmpSet = {};        If[OptionValue[AlternationType] == AlternationPlusMinus,      Do[If[Mod[counter, 2] != 0,        AppendTo[tmpSet, (counter^Exponent) - 1] AppendTo[         tmpSet, (counter^Exponent) + 1]], {counter, Terms}],      Do[If[Mod[counter, 2] != 0,        AppendTo[tmpSet, (counter^Exponent) + 1] AppendTo[         tmpSet, (counter^Exponent) - 1]], {counter, Terms}]];        Return[Expand[InterpolatingPolynomial[tmpSet, x]]];        );     Alternate[20, 2]      When I execute it, no output block is even generated, let alone any error messages or warnings, is there any way to fix it? Thanks.


Limit for Matrix expression

Let's assume that $Q_0$ is $3\times 3$ matrix with $\det Q_0\neq0 $ and $$ Q_{i+1} = \frac{1}{2}\left[ Q_i+(Q_i^{-1})^T \right] $$ I need to find next limit: $\lim _{i \to +\infty}$$Q_i$. In other words I need to find such $Q_i$ that $\left|Q_{i+1} - Q_i\right| < \epsilon$. Does anybody know, is it possible to find such kind of limits with _Mathematica_?


noninteger indices for tables

Is it bad programming practice to use non-integer values to label data tables? For example, Do[data[dBx, Bz] = Table[{x,f[dBx,Bz]}, {dBx, .1, .5, .05}, {Bz, .4, 1.5, .1}] instead of introducing integer indices for the values of {dBx,Bz}. It works fine most of the time. But sometimes when I plot the data, i.e., ListDensityplot[Table[{dBx,Bz,data[dBx,Bz]},{dBx, .1, .5, .05}, {Bz, .4, 1.5, .1}]] some values are missing because for some reason mathematica adds some tiny numerical values to the indices that get called in the plot, so that 0.1 becomes 0.10000000000002


Automatically including custom stylesheet with notebook

> **Possible Duplicate:**   >  How can I easily eliminate the dependency of a stylesheet on a non-built-in > stylesheet? For some work I am doing, I take my notes in a notebook with a custom stylesheet. For my own convenience, I have separated the styles into their own stylesheet notebook, and reference within the notebook's stylesheet like is done with `Default.nb`: ![enter image description here](http://i.stack.imgur.com/vYJZl.png) Unfortunately, this makes sharing this notebook difficult with out also ensuring that the recipient has the stylesheet already installed. Barring that, what are the alternatives? The simplest would be if the `NotebookDirectory[]` was automatically included in the search for the stylesheets, then the stylesheet can be simply placed in that directory. This works great in the case of a shared network drive, but still requires a two step process for the case of email. Ideally, I would like to automatically embed _all_ of the style definitions up to a certain depth in the referenced stylesheets. How can this be most easily accomplished?


Cases[data,Colon[key,_]] vs. Cases[data,key:_] toward XPath, XQuery

Exploring methods to index and search tree-structured key:value pairs via named-entity index (key paths) as opposed to Position-based indexing.   * Using `Rule` as `key->value` causes difficulties for `Cases`, which is unfortunate since `Rule` could be combined with `ReplaceAll` to yield lightweight path queries.    * Using `List` as `{key,value}` works but too many parentheses are visually confusing especially in data fusion tasks where multiple datasets are imported separately but must be joined and indexed properly for subsequent analysis.   * Using `Equal` prevents the key from being a string, eg `"key1" = value1 --> "Set::setraw : Cannot assign to raw object key1"` Why does `Cases` interpret `Colon` shortcut `(key:value_)` differently than `Colon[key,value_]`? dataR (* for comparison *)                Out[110]= {row1 -> {key1 -> value1, key2 -> value2},       row2 -> {key1 -> value3, key2 -> value4}}           In[69]:= dataC = dataR /. Rule -> Colon           Out[69]= {row1 \[Colon] {key1 \[Colon] value1, key2 \[Colon] value2},       row2 \[Colon] {key1 \[Colon] value3, key2 \[Colon] value4}}      Then, using `Cases`:                In[113]:= Cases[dataC, Colon[row1  , v_] -> v]           Out[113]= {{key1 \[Colon] value1, key2 \[Colon] value2}}           In[114]:= Cases[dataC, (row1 : v_) -> v]           Out[114]= {row1 \[Colon] {key1 \[Colon] value1, key2 \[Colon] value2},       row2 \[Colon] {key1 \[Colon] value3, key2 \[Colon] value4}}      `Levelspec` can be specified to match the inner keys, eg `key2` at `Level 3`. Is there a more convenient syntax or method to rapidly restructure arbitrary tree-shaped data? XPath and XQuery, are W3C standards that could be adapted or improved. In particular, XQuery strikes me as being similar in flexibility as Cases in the ability to match and transform data. I've posed similar questions to Wolfram Tech Support. Has been suggested for implementation.


Morphing a "sheet of paper" into a torus

How can I visualise the standard topological "rubber-sheet" construction of a torus, that is, morphing a square into a torus? How can I start or are there any examples in the _Mathematica_ documentation respectively?


Problem with slot in If statement

I am struggling with slots, In this case I have a function int which gives either true or false. When it gives true, I want               Select[interest, (DateList[#[[1, All]]] === #)&]      to be applied however as you can see this does not work because of the slots. Problem is that I want the slot in function `int[#]` to be the same as the slot behind ===. How can I overcome this problem?                If[int[#], Select[interest, DateList[#[[1, All]]]& === #],          2 {False}] & /@ fasteDatoer]      Simple example Lets say that when first applied it states int[james], which is true. I then want it to `Select[interest, DateList[#[[1, All]]]& === james.`


User-defined Distance Functions with extra parameters

The `Nearest` function accepts a customized distance function. For example, a simple case that works well is               myDist[x_, y_] := Abs[x - y];     data = RandomVariate[UniformDistribution[{0, 1000}], 100];     nf = Nearest[data, DistanceFunction -> myDist]      So for instance, the 5 (random) numbers in `data` that are nearest 100 are               nf[100, 5]      For this particular function, I could have used `DistanceFunction->EuclideanDistance`. But I ultimately need more flexibility, to have a distance function that depends on another parameter. A simple example would be something like               myDist2[x_, y_, t_] := If[Abs[x - y] > t, t, Abs[x - y]];      where the distance is sort of as before, but if it is above the value of `t`, it returns `t` (the actual function is considerably more complicated, but this one already reveals the problem). The goal is to use `myDist2` in some way -- here are some of the statements that don't work               nf = Nearest[data, DistanceFunction -> myDist2[0.5]]     nf = Nearest[data, DistanceFunction -> myDist2[x, y, 0.5]]     nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5] &]     nf = Nearest[data, DistanceFunction -> myDist2[#1, #2, 0.5]] &     nf = Nearest[data, DistanceFunction -> myDist2[#[[1]], #[[2]], 0.5] &]      (I know some of these don't make any syntactic sense, but they show how I was flailing around.) These give a variety of errors, most of which are that the               The user-supplied distance function myDist2 does not give a real numeric distance      Presumably, these are not calling `myDist2` properly. One fix would be to make the third parameter global, but this is probably a bad idea since it is embedded in a pretty complicated setting. So the question is how to add an extra parameter to the user-specified distance function.


How do I project a list of strings from another list to use in ChartLabels?

Say I have the following:               dataList = {{"One", 1}, {"Two", 2}};     PieChart[         #[[2]] & /@ dataList,         ChartLabels -> #[[1]] & /@ dataList,         PlotLabel -> "Test plot"     ]      But while the pie chart is displayed with the correct distribution, the chart labels are not displayed. This is because the output of               #[[2]] & /@ dataList      is               {One, Two}      not               {"One", "Two"}      I have also tried the following:               ChartLabels -> ToString[#[[1]]] & /@ dataList      but the outcome is the same as before. Thanks in advance for your help.