How to optimize computing a product?

**Problem description** Write a function to caculate the formula ![formula](http://i.stack.imgur.com/G2EvN.png) **My solutions** Solution 1:                 expBreak[n_Integer] := Which[       n == 1, Sqrt[2],        n >= 2, (Product[                 ((2^(n - 1) + 2 i + 1)^2 - 1)/                  (2^(n - 1) + 2 i + 1)^2, {i, 0, 2^(n - 2) - 1}])^(1/2^n)]       expHalf[n_Integer ] := Product[expBreak[i], {i, 1, n}]          Timing @ (expHalf[20] 2 // N)      > >     {113.896 second, 2.71828} >   Solution 2:                 numeratorList[n_] :=         (Most@Riffle[Table[2 i, {i, 1, 2^(n - 1)}],            Table[2 i, {i, 1, 2^(n - 1)}]])[[2^(n - 1) ;; 2^n - 1]]       denominatorList[n_] :=         (Rest@Riffle[Table[2 i - 1, {i, 1, 2^n}],            Table[2 i - 1, {i, 1, 2^n}]])[[2^(n - 1) ;; 2^n - 1]]       exphalf[n_] :=          Product[(Times @@ numeratorList[i]/Times @@ denominatorList[i])^(1/2^                  i), {i, 1, n}]          Timing @ (exphalf[20] 2 // N)      > >     {95.659 second, 2.71828} >   **So my question is how to revise it and make it more efficient?**


Taylor expansion of function of vectors—simplifying the output

I've got a real-valued function of several vectors $f(u,v,w)$ formed by taking scalar products of linear combinations of the vectors, I want to Taylor expand around small $v$ by writing $$f(u,\delta v, w) = A + B\delta + O(\delta^2)$$ for small real $\delta$. When I do this in _Mathematica_ , the output gives me terms like $v(1.u)$ rather than simplifying this to $v.u$. Note that I have put into my assumptions that $u,v,w$ are all vectors. My _Mathematica_ code is below.               $Assumptions = (p|q|r|P|m|n) ∈ Vectors[4]      > >     (p|q|r|P|m|n) ∈ Vectors[4, Complexes] >                 FullSimplify[       TensorExpand[         Series[((n + q).(n + q)(p + q + δ r).(p + q + δ r))/          (P.P(p + δ r).(p + δ r) -             (p + n + δ r).(p + n + δ r)(p + q + δ r).(p + q + δ r)),          {δ,0,1}]],       {p.p == 0, q.q == 0, r.r == 0, n.n == 0, m.m == 0, δ ∈ Reals}]      > >     -(n.q/n.p) + >       (r n.q (2 (1.n + 1.p + n.1 + p.1) p.q - (1.p + p.1) P.P) δ)/(4 (n.p)^2 > p.q) + O[δ]^2 >


How to make Mathematica graphs in Microsoft Word independent from Mathematica?

When I open a `.docx` file containing _Mathematica_ graphs on a computer without _Mathematica_ software installed, the graphs look corrupted. For example, `PlotMarkers` or `FrameLabel` looks differently. How can I keep these graphs looking as they were originally on a computer without _Mathematica_?


How can I visualize 6 square matrices as a cube?

I have six square matrices of the same dimensions in a list, for example:               n = 4; (*Matrix dimension*)     cubedata = Table[ConstantArray[i, {n, n}], {i, 1, 6}] (*Matrices 1 to 6*)      I would like to make a visualization of the cube that is formed when you put said matrices as its faces. This should be the orientation of the faces. ![This should be the orientation of the faces](http://i.stack.imgur.com/Y6j2A.png) I want to see the numbers and, if possible, the cube colored (like a Rubik's cube). I don't even know where to start. I think I should use `Graphics3D` but I'm not familiar with it, at all. I would greatly appreciate it if you could help me.


DSolve not giving solution expected

I'm trying to solve the ODE $\frac{\partial M}{\partial \tau} = [ 4 c_3 N(\tau) + c_1 ] M(\tau),$ where $N(\tau) = \frac{q}{2 c_3} \frac{ 1 }{c_2 e^{2 q \tau} + 1} - \left ( \frac{ q + c_1}{4 c_3} \right )$ for some parameters $\\{c_1 , c_2 , c_3 , q \\}$ that I would like to evaluate later. I've set up the problem as follows               $Assumptions =      Element[q, Reals] && q > 0 &&     Element[c3, Reals] && c3 > 0 &&     Element[const, Reals] &&     Element[c1, Reals];          Neqn[tau_] := (q/(2*c3))*(1/(const*Exp[2 * q*tau] + 1)) - (c1 + q)/(4*c3);     eqn = {y'[tau] == (4*c3*Neqn[tau] + c1)*y[tau] , y[0] == 0};     sol = DSolve[eqn, y[tau], tau]       which is giving               {{y[tau] -> 0}}


Feynrules -> FeynArts issue

When I try to use model files generated by `FeynRules` in `FeynArts`, I always get errors of this form > Coupling definition in model file for `C[S[5],S[1,{e2x1}],-V[3]]` is \ > incompatible to generic coupling structure. Coupling is not a vector \ of > length 1. (when I use the `InsertField` function, `InsertFields[t11, {S[7], -S[7]} -> {S[2], S[2]}, Model -> "NMSSM"]`, etc.) I have tried using the `SM` and `NMSSM` models included with `FeynRules`, and my own models and I get the same error. When I tried using the `SM` model file that's included with `FeynArts`, there's no problem. So it seems there's a problem with the `FeynArts` model files generated by `FeynRules`? I'm using `FeynRules` 2.0.3 and `FeynArts` 3.9.


Is there a way to track the Simplify process?

Is there any way to track how _Mathematica_ actually performs `Simplify`, so that we can see what those "Automatic" transformation functions it applies are and how it works with assumptions? For example,               ClearSystemCache[];     Simplify[Sin[x]^2 + Cos[x]^2, ComplexityFunction -> ((Print[#]; LeafCount[#]) &)]      will output               Cos[x]^2+Sin[x]^2         Cos[x]^2+Sin[x]^2         Cos[x]^2+Sin[x]^2         Cos[x]^2+Sin[x]^2         Cos[x]^2+Sin[x]^2         1         1         1      Is there a way to see what _Mathematica_ does between these steps?


My Data has negative and positive numbers, can I still use it to get the PDF?

I have data that reflects the arrival time of a flight. {3, -2, 16, 13, -6, 5, 4, -7, 7, 0……..n} _this is for 8:45am and has 150 elements "arrivals"_ The positive values represent the time in minutes past the planned time,{“late”} and the negative, is before planned time {“early”} My question, I would like to find the time of arrival with the highest probability. Can I use this data as is?


Why does Mathematica not simplify the Gudermannian function?

The Gudermannian function is built into Mathematica, but does not reduce to simpler terms in some simple cases. In particular, the Gudermannian is an odd function of real arguments but Mathematica does not seem to know or use this. For example:               FullSimplify[Gudermannian[2x] + Gudermannian[-2x],Assumptions->{x>0}]     Gudermannian[-2 x] + Gudermannian[2 x]      Am I missing some subtlety that invalidates simplifying to 0 or is Mathematica missing something?


Writing a function to mimic Characters

I am working my way through Programming Paradigms via Mathematica (A First Course) and have answered the following question in lesson 25: > Write a function of one argument "s", a String, which writes the string "s" > to some file and then reads the string that file back in as a list of single > characters. This operation thus mimics Characters[]. Pay attention to the > methods Mathematica has for reading in data from a file.               In   Characters["the cow jumped over the moon"]           Out   {t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n}      My function is as follows:               Clear[myCharacters]     myCharacters[s_String] :=       Module[{myStream},        myStream = OpenWrite["file2"];        Write[myStream, s];        Close[myStream];        ReadList["file2", Character]        ];     myCharacters["the cow jumped over the moon"]      which produces an output that includes the leading and trailing quotation marks:               {",t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n,"}      So thinking back to my previous question, where I had a couple of significant mistakes, I am wondering if there is something that I am missing or is my answer basically correct? Also I would appreciate being shown how I could improve my function even if it does give correct output.


Extract function parameters from "unevaluated" FormBox

I want to get the abbreviation for a `Unit` from its full name eg. `"Newtons"` => `"N"`. Using `TraditionalForm` on `Quantity` will show the abbreviation and doing the following will show the code returned by `TraditionalForm`:               Quantity["Newtons"] // TraditionalForm // InputForm     (* =>     FormBox[TemplateBox[{1}, QuantityUnit,         DisplayFunction ->          (TooltipBox[StyleBox[RowBox[{#1,  ,  N}],              ShowStringCharacters -> False], Unit: newtons] & ),         InterpretationFunction ->          (RowBox[{Quantity, [, RowBox[{#1, ,, "Newtons"}], ]}] & ),         SyntaxForm -> Mod], TraditionalForm]     *)      How can I extract the `N` from the above without parsing the string generated by using `ToString` on it?


HoldForm: how does it interact with nested evaluations?

Here's an example to illustrate the issue I'm having.               right = 8 - y;     left = y^2 + 6;          integrand = HoldForm[Evaluate[right]] - HoldForm[Evaluate[left]]      ![enter image description here](http://i.stack.imgur.com/mEEbM.png) (I realize this is a strange form for `integrand` but it is the form I need to work with.) Here, `HoldForm` allows its argument to be evaluated, and then holds the form of the resulting output. This is what I wanted. Then               simpleintegrand = ReleaseHold[integrand]      ![enter image description here](http://i.stack.imgur.com/H6JC4.png) which is fine. However,               HoldForm[Integrate[Evaluate[simpleintegrand], {y, 0, 1}]]      yields ![enter image description here](http://i.stack.imgur.com/7YQfY.png) (removing the `Evaluate` doesn't help) when I was after $$\int_0^1 (2-y-y^2)\,dy.$$ (In another direction, I'd actually prefer to get $$\int_0^1 (-y^2-y+2)\,dy$$ and am happy to hear how, but **the crux of my question is how to use`HoldForm` when its argument involves nested commands like above.**)


Retrieving the text of a message

Is there a simple, built-in way to retrieve the text of a message, given it's identifier (such as `Power::infy`)? The documentation describes how `Message` does this: it looks for different language versions (`Power::infy::langname`), then it looks under the symbol name (`Power::infy`), then it looks under `General` (`General::infy`), then it uses `$NewMessage` ... it's pretty complicated. Is there any built-in, hidden/undocumented way that will let me retrieve the text of a message in a simple way, without issuing the message? I see two possibilities:   1. Reimplement the whole lookup procedure. This is a lot of work.   2. Implement a special stream and do something like `Block[{$Messages = ...}, Message[symb::name]]`. Also a lot of work (implementing the stream methods), and I'm not even sure it would work. Or maybe there is an undocumented way. `?*`*Message*` gives plenty of symbols, but it's not clear which may be interesting and what they do.


Slow NIntegrate over complicated domains (sometimes)

**Overview** I have a very large matrix I need to calculate where each element requires the integration of a product of two functions over some complicated domain. I would like to find a set of options for `NIntegrate` that will work well for all of my integrations. Most of the integrations take only seconds but others take up to 4 hours. Below is a histogram of timing for the integrations. It is clear that there are some very fast one and some very slow ones: ![Histogram of NIntegrate timing](http://i.stack.imgur.com/F5kwQ.png) The following set of plots shows six integrands that took less than 15m along with a visualization of the domain. The plot label shows how long it took to integrate. ![Example functions that takes less than 15m to integrate](http://i.stack.imgur.com/val7s.png) The following set of plots shows six integrands that took more than 15m along with a visualization of the domain. The plot label shows how long it took to integrate. ![Example functions that takes more than 15m to integrate](http://i.stack.imgur.com/tidRg.png) As you can see the two groups do not look much different however all of the ones that take a long time results in integrated values that are very close to zero ($\approx 10^{-16}$). **Details** Here are the functions for the forth plot in each set shown above: A good one (fast):                rg={{-3.35513, 5.30513}, {-1.51554, 7.14471}};           funa=Function[{x, y}, E^(1/2 (-(0.39 + x/5) (100. (0.39 + x/5) -         6.12323*10^-15 (0. + y/5)) - (-6.12323*10^-15 (0.39 + x/5) +         50. (0. + y/5)) (0. + y/5)))]           funb=Function[{x, y}, E^(1/2 (-(-0.195 + x/5) (55.3571 (-0.195 + x/5) +         15.4647 (-0.562917 + y/5)) - (15.4647 (-0.195 + x/5) +         94.6429 (-0.562917 + y/5)) (-0.562917 + y/5)))]           region=Function[{x,y}, ((1/2 (4.54663 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (0.954793 - 1.05 y) >= 0 &&        1/2 (-2.63705 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (-2.63705 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (0.954793 + 1.05 y) >= 0 &&        1/2 (4.54663 - 0.909327 x + 0.525 y) >=         0) || (1/2 (3.45544 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (2.04599 - 1.05 y) >= 0 &&        1/2 (-0.454663 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (-1.54586 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (-0.136399 + 1.05 y) >= 0 &&        1/2 (2.36425 - 0.909327 x + 0.525 y) >=         0) || (1/2 (2.36425 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (-0.136399 - 1.05 y) >= 0 &&        1/2 (-1.54586 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (-0.454663 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (2.04599 + 1.05 y) >= 0 &&        1/2 (3.45544 - 0.909327 x + 0.525 y) >=         0) || (1/2 (2.04599 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (3.45544 - 1.05 y) >= 0 &&        1/2 (2.36425 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (-0.136399 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (-1.54586 + 1.05 y) >= 0 &&        1/2 (-0.454663 - 0.909327 x + 0.525 y) >=         0) || (1/2 (0.954793 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (4.54663 - 1.05 y) >= 0 &&        1/2 (4.54663 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (0.954793 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (-2.63705 + 1.05 y) >= 0 &&        1/2 (-2.63705 - 0.909327 x + 0.525 y) >=         0) || (1/2 (-0.136399 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (2.36425 - 1.05 y) >= 0 &&        1/2 (3.45544 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (2.04599 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (-0.454663 + 1.05 y) >= 0 &&        1/2 (-1.54586 - 0.909327 x + 0.525 y) >=         0) || (1/2 (-0.454663 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (-1.54586 - 1.05 y) >= 0 &&        1/2 (-0.136399 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (2.36425 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (3.45544 + 1.05 y) >= 0 &&        1/2 (2.04599 - 0.909327 x + 0.525 y) >=         0) || (1/2 (-1.54586 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (-0.454663 - 1.05 y) >= 0 &&        1/2 (2.04599 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (3.45544 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (2.36425 + 1.05 y) >= 0 &&        1/2 (-0.136399 - 0.909327 x + 0.525 y) >=         0) || (1/2 (-2.63705 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (-2.63705 - 1.05 y) >= 0 &&        1/2 (0.954793 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (4.54663 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (4.54663 + 1.05 y) >= 0 &&        1/2 (0.954793 - 0.909327 x + 0.525 y) >=         0)) && ! ((-2.75 + x)^2 + (0. + y)^2 <=        0.316406 || (1.375 + x)^2 + (-2.38157 + y)^2 <=        0.316406 || (1.375 + x)^2 + (2.38157 + y)^2 <= 0.316406)]      A Bad one (slow):                rg={{2.9, 5.}, {-1.05, 1.05}};           funa=Function[{x, y}, E^(1/2 (-(0. + 100. (-0.39 + x/5)) (-0.39 + x/5)           - (0. +   50. (0. + y/5)) (0. + y/5)))]           funb=Function[{x, y}, 1.90476 (0. + y)]           region=Function[{x, y},        1/2 (4.54663 - 0.909327 x - 0.525 y) >= 0 &&        1/2 (0.954793 - 1.05 y) >= 0 &&        1/2 (-2.63705 + 0.909327 x - 0.525 y) >= 0 &&        1/2 (-2.63705 + 0.909327 x + 0.525 y) >= 0 &&        1/2 (0.954793 + 1.05 y) >= 0 &&        1/2 (4.54663 - 0.909327 x + 0.525 y) >=        0 && (-2.75 + x)^2 + (0. + y)^2 > 0.316406]      The ugly integral                NIntegrate[         Boole[region[x, y]] funa[x, y] funb[x, y],          {x, rg[[1, 1]], rg[[1, 2]]}, {y, rg[[2, 1]], rg[[2, 2]]},         Method->{"SymbolicPiecewiseSubdivision","ExpandSpecialPiecewise"->False,            Method->"LocalAdaptive"},         MaxRecursion->50,MinRecursion->20,         AccuracyGoal->7,PrecisionGoal->6       ]      I have picked `MinRecursion` to be 20 to make sure that the smaller features of the domain are found. (This is just one example of a domain others are more involved with smaller items.) I have used "LocalAdaptive" because I seam to get fewer complaints about slow convergence than when I use "GlobleAdaptive" and finally I use "ExpandSpecialPiecewise"->`False` because there are a few cases where I get an error that I have exceeded the number of piecewise divisions (This dose not appear to be connected with the number of conditions in the domain but instead the divisions done by `NIntegrate`) I have tried many combinations of options for `NIntegrate` but I have not found one that will work for all gazillion matrix elements. I realize it is not possible with the code give to test for all of my cases but I will give good ideas a run in my code and report back.


"Hard" ODE with three kind of solution: IVP or BVP?

I want to solve numerically the second-order differential equation proposed by Coleman in this paper (equation 8, page 1804): $$ \gamma(\lambda) \lambda_{zz} + \beta(\lambda) \lambda_z^2 + \tau(\lambda) = T_0. $$ In my case, functions $\gamma(\lambda)$, $\beta(\lambda)$, and $\tau(\lambda)$ look analytically different from Coleman's ones, but their result is quite similar. In my case $$ \varphi(\lambda) = a_0 + a_1 \lambda^2 + a_2 \lambda^2 + a_3 \lambda^3 + a_4 \lambda^4, \\\ \tau(\lambda) = \varphi'(\lambda), \\\ \gamma(\lambda) = - \frac{h_0^2}{12} \frac{\tau(\lambda)}{\lambda^5}, \\\ \beta(\lambda)=\frac{1}{2} \gamma'(\lambda). $$ Coleman shows that this ODE have three kind of solution:   1. **Fully developed draw**. In this case, $\lambda_z$ does not vanish at a finite point, but $\lambda(z)$ is bounded, i.e., it is strictly monotone. The solution satisfies these conditions: $$ \lim_{z\to-\infty} \lambda(z) = \lambda_*, \qquad \lim_{z\to+\infty} \lambda(z) = \lambda^*, $$ and $$\int_{\lambda_*}^{\lambda^*} [\tau(\lambda) - T^*]d\lambda = 0, \quad \tau(\lambda_*) = \tau(\lambda^*) = T^*. $$ Moreover, $$ \lim_{z\to \pm\infty} \lambda_z = \lim_{z\to \pm\infty} \lambda_{zz} = 0. $$   1. **Neck or Bulge**. In this case, $\lambda_z$ vanish at a precisely finite point, $z_0$. If $\lambda(z_0)$ is a global maximum we have a neck, if it is a global minimum we have a bulge. In both cases, the solution is symmetric about $z_0$. Conditions: $$ \lim_{z\to \pm\infty} \lambda(z) = \lambda_{(\infty)}, \qquad \lambda_z(z_0) = 0, $$ $$ \int_{\lambda_{(\infty)}}^{\lambda_0} [\tau(\lambda) - T^0]d\lambda = 0, \quad \tau(\lambda_{(\infty)}) = T^0. $$ for each $ \tau(\lambda_{\min}) < T^0 < T^*$ (bulge) or $ T^* < T^0 < \tau(\lambda_{\max})$ (neck).   1. **Equally spaced striae**. In this case, the solution has more than one finite value at which $\lambda_z = 0$, and it is periodic. We call $\lambda_a$ a minimum and $\lambda_b$ its consecutive maximum (and $z_a$ and $z_b$ are the locations of minimum and maximum, respectively). Conditions: $$ \lambda_z(z_a) = \lambda_z(z_b) = 0, \quad \int_{\lambda_a}^{\lambda_b} [\tau(\lambda) - T^0]d\lambda = 0, \quad \tau(\lambda_a) > T_0 > \tau(\lambda_b). $$ ![enter image description here](http://i.stack.imgur.com/R0caM.png) Some parameters:               H0 = 1;     par = {            a0 -> 2.0377638272727268,            a1 ->  -7.105521894545453,            a2 -> 9.234000147272726,            a3 -> -5.302489919999999,            a4 -> 1.136247839999999           };          φ[λ_] := a0 + a1 λ + a2 λ^2 + a3 λ^3 + a4 λ^4 /. par;     τ[λ_] := φ'[λ];     γ[λ_] := -(H0^2/12) τ[λ]/λ^5;     β[λ_] := 1/2 γ'[λ];          SubStar[λ] = 1.0253896074560216`;     SuperStar[λ] = 1.3079437258773567`;     λmax = 1.0851003185010777`;     λmin = 1.2482330148322596`;     λa = 1.0610276111671018`;     λb = 1.194705994040993`;     TM = 0.0059225557575715015`; (* T^* *)     TN = 0.008388970560993414`; (* neck *)      My first approach was considering this ODE as BVP, but I don't know range along $z$: I can assume $z = 0$ where $\lambda_z = 0$ for neck or striae, or a place at which $\lambda_z = \varepsilon$ and $\lambda(0) = (1+\varepsilon_*) \lambda_*$ for fully developed draw (I can't handle an infinity domain), but I know the values of $\lambda$ only at the second place, but I have no idea about where this place is. A second approach was considering the ODE as IVP (see this post), imposing $\lambda(z)$ and $\lambda_z(z)$ at a precisely point (where I assume knowing the function and it's derivative) and seeing its evolution. Unfortunately, this approach leads to a periodic solution only (and when I set some value of the first derivative it approaches infinity at certain point). How can I solve this equation? What is better, IVP or BVP? /Petrus


How do I put a Monitor into CDF?

I would like to keep track of progress of a database request in an Enterprise CDF, but it won't allow `PrintTemporary` or `Monitor[]` to add content. When I use `Dynamic[If[progress<1,Refresh[ProgressIndicator@progress,TrackedSymbols:>{progress},UpdateInterval->.5],Histogram[outputData,<various_options_here>]],TrackedSymbols:>{progress}]`, the ProgressBar doesn't update during VERY heavy operations, like SQLExecute or building a Histogram out of a large set of numbers (2 sets of about 10^6 values). In addition, since the end result of the output has to be without a semicolon, I cannot tag `progress=1;` onto its end. E.g. `progress=0;long_SQL_request;progress=.5;Histogram[huge_data] progress=1;` <\- obviously can't do that last part. And `progress=.5` never gets picked up by the ProgressBar. Please help. Thank you!


help to plot Poincare section for double pendulum

I am reading a book about classical mechanics. In the chapter about chaos, it gives the simplified and scaled equations for double pendulum as $$ \frac{d}{dt}\left[ \begin{matrix} \alpha \\\\[3mm] l_\alpha \\\\[3mm] \beta \\\\[3mm] l_\beta \end{matrix} \right] = \left[ \begin{matrix} 2\frac{l_\alpha - (1+\cos\beta)l_\beta}{3-\cos 2\beta} \\\\[2mm] -2\sin\alpha - \sin(\alpha + \beta) \\\\[2mm] 2\frac{-(1+\cos\beta)l_\alpha + (3+2\cos\beta)l_\beta}{3-\cos2\beta}\\\\[2mm] -\sin(\alpha+\beta) - 2\sin\beta\frac{(l_\alpha-l_\beta)l_\beta}{3-\cos2\beta} + 2\sin2\beta\frac{l_\alpha^2-2(1+\cos\beta)l_\alpha l_\beta + (3+2\cos\beta)l_\beta^2}{(3-\cos2\beta)^2} \end{matrix} \right] $$ I am going to plot the Poincare section, which in this case is the collection of $(\beta, l_\beta)$ when $\alpha=0$ and $d\alpha/dt >0$. I follow the code found in the example of mathematica for Poincare section and write the following code               abc = {a'[t] == 2*(la[t] - (1 + Cos[b[t]])*lb[t])/(3 - Cos[2*b[t]]),             la'[t] == -2*Sin[a[t]] - Sin[a[t] + b[t]],            b'[t] == 2*(-(1 + Cos[b[t]])*la[t] + (3 + 2*Cos[b[t]])*lb[t])/(3 - Cos[2*b[t]]),            lb'[t] == -Sin[a[t] + b[t]] - 2*Sin[b[t]]*((la[t] - lb[t])*lb[t])/(3 - Cos[2*b[t]]) +                        2*Sin[2*b[t]]*(la[t]^2 - 2*(1 + Cos[b[t]])*la[t]*lb[t] +                        (3 + 2*Cos[b[t]])*lb[t]^2)/(3 - Cos[2*b[t]])^2};          psect[{a0_, la0_, b0_ , lb0_}] :=            Reap[NDSolve[{abc, a[0] == a0, la[0] == la0, b[0] == b0, lb[0] == lb0,                         WhenEvent[a[t] == 0 && la'[t]>0, Sow[{b[t], lb[t]}]]}, {},                         {t, 0, 1000},  MaxSteps -> ∞]][[-1, 1]]          abcdata = Map[psect, {{0.01, 0.01, 0.01, 0}, {0.01, 0.01, 0.01, 0.01},                            {0.01, 0.01, 0.01, -0.01}}];          ListPlot[abcdata, ImageSize -> Medium]      Here a is $\alpha$, b is $\beta$, la is $l_\alpha$ and lb is $l_\beta$. I don't know why, they code has two problems. First the condition "la'[t]>0" doesn't work. Secondly, even I remove the condition "&& la'[t]>0", it sill reports that error code like "NDSolve::deqn: Equation or list of equations expected instead of 0.01` in the first argument". I spent quite a long time to figure out the problem but I still cannot find out the reason. Here is plot for the Poincare section from the book I am reading (I redraw with image editor). ![enter image description here](http://i.stack.imgur.com/leEWw.png)


Limiting scope of Front end "Replace All" in Find & Replace

The warning on find and replace isn't explicit and I only found out after an almost harmless global change that I really was replacing **ALL** , not just all instance in my selection (which is where most other applications would automatically limit scope) Is there any way to limit the scope of "Replace All" to selected text only?


Unexpected design of protection against dynamic content

**Introduction/summary** I was surprised by the (from my point of view limited) extent to which the user is defended against "potentially unsafe dynamic content" by default. Two things were unexpected to me: 1) a warning is not always triggered if dynamic content is present , and 2) all dynamic content in a notebook will be evaluated when evaluating any cell in that notebook. The tests I did are first listed below. The question is how we can modify options to let the behaviour correspond to my expectations. Along the way I found an option ("TrustByDefault") that can deal with one of the concerns, so I have provided an answer to my own question. This option was not exactly hidden, as it was mentioned in the docs under tutorial/NotebookSecurity, which is excellent. The main value I see in posting this now is to warn users like me who like to skim pages like tutorial/NotebookSecurity and later draw their own conclusions about options like "Dynamic Updating Enabled". Further I provide some code which may help with "seeing things for yourself". Lastly, I feel a warning about the `Cell`/`Notebook` option `CellEvalaluationFunction` was overdue. **Paraphrasing of relevant parts of /tutorial/NotebookSecurity** Mathematica can warn you about dynamic content, but it does not always do so. If the warning is displayed, dynamic content is also not get evaluated (evaluation can be triggered in an unexpected way though! Details further below). The warning looks like this. ![enter image description here](http://i.stack.imgur.com/Ckdbh.png) Notebooks on a `"TrustedPath"` will never trigger the warning. Notebooks on an `"Untrusted path"` will always trigger the warning. For Notebooks on paths that are neither safe or unsafe in this sense, whether or not the warning will appear will depend on what functions/symbols appear in the Dynamic content. The paths that are not trusted on your system can be found by executing this code               Column[ToFileName /@        CurrentValue[$FrontEnd, {"NotebookSecurityOptions",          "UntrustedPath"}]]      replace `"UntrustedPath"` by `"TrustedPath"` in the above to see which directories are trusted. ## Testing A little way below is a procedure to generate notebooks with dynamic content and then opening them. It requires you to input a path (name of a directory). The result will depend on what path you specify and on the notebook you choose (with or without potentially dangerous functions). As mentioned, for some notebooks/paths the dynamic content will be evaluated right away. I think this does not depend on whether you generated the file yourself or whether it was sent to you. No mention of such a distinction is made in tutorial/NotebookSecurity. For me, if I put a notebook with dynamic content without dangerous functions in my user directory, dynamic content gets evaluated right away. This was unexpected to me, especially because I did not realise that immediate evaluation of dynamic content depended on the functions that appear in it. I now find the design intuitive in a way, but I think there is a serious design flaw here. So much so that I think talking about it here further may do more harm than good. **Code to see how the warning works** As promised, here is the code to generate and open notebooks. Warning: I will not tell you not to trust me, but code containing functions that I use below could be very dangerous. In general I would advise you not to evaluate such code, unless you understand or trust it.               path = (*enter the path where you want to store the notebook here*);     fileName = (*enter example: file.nb*);          Block[{fullFileName = FileNameJoin[{path, fileName}]}      ,      If[       ! FileExistsQ[fullFileName]       ,       Put[        Notebook[         {          Cell[           BoxData@MakeBoxes@             Dynamic[If[! NumberQ[x], x = 0];               StringForm["x is now ``", x++]], "Output"]          ,          Cell[BoxData@MakeBoxes["evaluate this";], "Input",            CellTags -> "eval"]          }         ,         DynamicUpdating -> True         ]        , fullFileName        ];       NotebookOpen@fullFileName;       NotebookLocate["eval"]       ,       Print["file already exists!"]       ]      ]      Even if you put the file on an `"UntrustedPath"`, you still have to be very careful. The unexpected thing to me here is that if you evaluate any regular `Cell` in the notebook, even one that you made yourself, the dynamic content gets evaluated. Even though you did not press the button "Enable Dynamics". You can test this out by simply evaluating the Cell saying `"evaluate this"` that I have included. **CellEvaluationFunction** Now, it is a very bad idea anyway to evaluate a cell in a notebook you do not trust, especially because of the option `CellEvaluationFunction`. `CellEvaluationFunction` is both an option for `Cell` and for `Notebook` and can make cells evaluate in ways you do not expect. Code can not be visible and basically any code can be evaluated against your will this way, provided you evaluate a `Cell` in this notebook. But still the behaviour that evaluating any cell also causes the dynamic content to be evaluated is unexpected to me and therefore I would (have) like(d) to have some protection against it. ## Options for additional protection **Options that do not work** I was looking to see if you could make some additional protection against this unwanted evaluation. In particular the option from the evaluation menu "Dynamic Content Enabled", as well as the front end option `DynamicUpdating`, which is the same as the option `DynamicUpdating` in the option inspector under Cell Options > Evaluation Options, seem to have no effect. The `Notebook` option `DynamicUpdating` only seems to apply to a particular `Notebook`, so that does not help either. I think all the front end option `DynamicUpdating` is, is the default value of the `Notebook` option `DynamicUpdating` for newly created notebooks. This does _not_ include notebooks that already existed and were simply opened. The menu option "Dynamic Content Enabled" from the evaluation menu is not a global setting. It can be different for different notebooks. In particular, when I open the .nb file from an `"UntrustedPath"`, there is a check in front of "Dynamic Updating Enabled", even when there was not one before. **Questions** The question here is: Are there any additional means to protect ourselves against dynamic evaluation?


What is the fastest way to extract a substring from a huge string?

I develop an algorithm to find the most common substrings of a given length **n** up to a certain distance **l** in front of a pattern **p** in a huge sequence **S**. E.g. I want to find the most common hexamers (substring of length 6) that occur in front of the string pattern p="TTAA" at a distance of at most l=1000 characters in front of the pattern "TTAA" in **S**. The steps of the algorithm are:   1. Import the sequence **S**.   2. Detect the first positions i∈{1,...,k} of all occurrences of pattern **p** in **S**.   3. Extract the sites (substrings) **si** in front of each pattern position **i** from **S**.   4. Determine all nmers (substrings of length **n** ) for each site **si**.   5. Select the nmer from all those substrings that is the most common and determine how many sites can be covered with that nmer.    6. Delete the lists that are covered.   7. Repeat 5. and 6. until all lists are covered or stop after a given number of iterations. The result should be a list of the nmers that are the most common ones in decending order of coverage. Consider this string for the variable sequence and the following code. I first determine the positions in **S** where the pattern **p** occurs:               sequence = StringTake[Import["http://ge.tt/api/1/files/9teGemr/1/blob?download"], 200000];         pattern = "TTAA";         positions = StringPosition[sequence, pattern, IgnoreCase -> True];      Now I want to extract all the substrings **si** of length 1000 characters in front of the pattern **p** that appears at position **i** in sequence. In principle, I already have a solution for the problem but it appears to be quite slow if **S** is large and the pattern matches many positions (many **si** have to be extracted):               substrings = Table[         If[          First[i] < 1001,          StringTake[sequence, {1, First[i]-1}],          StringTake[sequence, {First[i] - 1001, First[i] - 1}]          ], {i, positions}     ];      For the runtime I have added some tests here without (left) and with (right) parallelization (ParallelTable instead of Table): ![enter image description here](http://i.stack.imgur.com/xxB4W.png) ![enter image description here](http://i.stack.imgur.com/J9y3a.png) However, as soon as the number of found positions for the pattern and the length of the sequence increases the runtime of this approach explodes. For example if I run the code for the whole sequence of 1 million characters without (left) and with (right) parallelization (ParallelTable instead of Table): ![enter image description here](http://i.stack.imgur.com/yml2t.png) ![enter image description here](http://i.stack.imgur.com/cnGTh.png) Is there a faster way to do this? **Edit 17/03/2014** The code proposed by Öskå is a little bit faster, but still I would need this code to run for much longer sequences (200 million characters) and many more hits (about 3 million). ![enter image description here](http://i.stack.imgur.com/SZcwx.png) **Edit 18/03/2014** The code proposed by Leonid Shifrin seems to be a hell of a fast piece of code :) I tested it for a sequence of 20 million characters and got the following results: ![enter image description here](http://i.stack.imgur.com/IazkL.png) The code proposed by george2079 achieves: ![enter image description here](http://i.stack.imgur.com/JcR6Y.png) @LeonidShifrin comment: > By the way, for 200 million chars and a few million hits, you'll really need > some lazy infrastructure, because just holding all your extracted substrings > in RAM at the same time won't be possible for such large objects. Are you > interested in this kind of solution? Yes indeed, I already thought about this. Later on, each extracted **si** has to be splitted into overlapping substrings of length 6. I currently do this using `Partition` on the list of characters. My idea was to dump save each of those strings _si_ into an `MX` file and then move on file by file:               ParallelTable[      (       cur = FromCharacterCode /@          Partition[ToCharacterCode[sites[[i]]], nSize, 1];       Export[FileNameJoin[{path,           "hexamers-site-" <>            StringJoin[ToString /@ (PadLeft[IntegerDigits[i], 9, 0])] <>            ".mx"}], cur]       ), {i, 1, Length@sites}]


Mathematica 8 and window names for modified files

I do not know if this is particular to Mac OS, but with version 8, the window name of a notebook no longer changes (with an appended *) when it is modified, as it used to do with version 7 (as well as older ones for as long as I remember). I found this feature really useful and wonder if one can re-enable something comparable (by tweaking preferences ?) on version 8.


Curated data sometimes delivered in undefined units

This question may better go to Wolfram, but as it came up on the weekend, I thought I'd try here first. Take a look at the following:               tnx = FinancialData["^TNX", "Open", {All, "Month"}];     DateListPlot[tnx, Joined -> True, PlotRange -> All, ImageSize -> 250]     First@tnx     Last@tnx!      ![enter image description here](http://i.stack.imgur.com/yelpX.png) "^TNX" gives the rates on 10 year U.S. Treasury notes. As presented, by `FinancialData`, this data comes in percentage units (e.g., the `4.06` in the first record really equals `4.06%` or `0.0406`). Apparently the data source (maybe Yahoo Finance) for this doesn't distinguish between the unit of measure. It seems curious to me, that Wolfram's curated data also doesn't. This gets more mysterious and confusing because of the following:               FinancialData["^TNX", "Open", "Units"]     Missing["NotAvailable"]      So, it seems we have no programatic means of identifying key information about the data. I don't know how widely this kind of problem applies, but for me it certainly goes to the usability of curated data. Perhaps, Wolfram only passes along what they get, but the appellation "curated" implies something more.   * Does any other way exist to determine how or in what units curated data comes?   * Does this seem like an oversight in curated data?   * Does this seem like a bug? I don't want to beat up on Wolfram. The curated data provides us with a great resource. I just hope to provide user feedback in the hope of it getting even better.


NIntegrate(with singularities) gives different results, which one should I trust?

I am doing an Numerical integral with sigularities.               tk = Cos[Sqrt[3]/2 kx + 1/2 ky] + Cos[-Sqrt[3]/2 kx + 1/2 ky] + Cos[ky]      + I (Sin[Sqrt[3]/2 kx + 1/2 ky] + Sin[-Sqrt[3]/2 kx + 1/2 ky] - Sin[ky])      The integral I want do is:               int1 = NIntegrate[1/Norm[tk], {kx, 0, 2 Sqrt[3] Pi/3}, {ky, 0, 4 Pi/3}]       Without excluding singularities, I got:               57.6751      This integral has singularities in 3 Places:               {4 Pi/(3 Sqrt[3]), 0}, {2 Pi/(3 Sqrt[3]), 2 Pi/3}, {4 Pi/(3 Sqrt[3]), 2 Pi/3}}      ![Three Singularities](http://i.stack.imgur.com/tyiAb.jpg) So I will Exclude them using:               int1 = NIntegrate[1/Norm[tk], {kx, 0, 2 Sqrt[3] Pi/3}, {ky, 0, 4 Pi/3},            Exclusions ->{{4 Pi/(3 Sqrt[3]), 0}, {2 Pi/(3 Sqrt[3]), 2 Pi/3},             {4 Pi/(3 Sqrt[3]), 2 Pi/3}}]      This result is quite different from which I didn't exclude any singular points. However, it gives me a result:                13.6216 + 0. I      **Q:Why a complex term occurs?** It looks quiet strange to me. However, excluding other points which are not singularities also gives nearly the same answer. For example:               int1 = NIntegrate[1/Norm[tk], {kx, 0, 2 Sqrt[3] Pi/3}, {ky, 0, 4 Pi/3},             Exclusions -> {{1, 1}}]      Gives:               13.6215      Excluding {0,0} gives:               57.6751      This is even stranger for me. What happened? Can you explain to me? This is very untrustworthy for me. **How can I know this numerical integral is right or wrong?** Another integral I want to do is:               int1 = NIntegrate[1/Abs[Norm[tk]-1], {kx, 0, 2 Sqrt[3] Pi/3}, {ky, 0, 4 Pi/3}]      This has singular lines:![enter image description here](http://i.stack.imgur.com/EqQld.jpg) With an without excluding this line, the integral is a finite number. However, I expect this integral to be infinite. **What is wrong?**


Graphing convolutions of user defined functions

I am a statistician who is very new to Mathematica. Ultimately I would like to be able to graph convolutions of arbitrary user defined functions. But I can't as yet obtain values of such convolutions even at single points, unless the convolution can be expressed in terms of builtin functions.               f[x_] := x^0.5 (1 - x)^0.4 UnitBox[x - 0.5]     g[y_] := Convolve[f[x], f[x], x, y]     g[0.2]          (* Out: Convolve[(1 - x)^0.4 x^0.5 UnitBox[-0.5 + x], (1 -          x)^0.4 x^0.5 UnitBox[-0.5 + x], x, 0.2] *)


how to make cells independent with each other in notebook

If we open `DocumentationCenter` and then run code, we will find that the `Cells` are independent from each other. For example: ![enter image description here](http://i.stack.imgur.com/p4Ntp.png)   * `a` or `b` in third `Cell` is independent from the one in the first or second `Cell`. I think maybe it is local cell? If I want to achieve this behaviour in my notebook, how to do this? Thanks.


Selecting every last element of a nested list

I couldn't find a similar question so I decided to ask this one. I have a nested list with many sublists of equal length. To make things easier let's say it's like that:               list={{2,1,7},{3,9,5},{4,8,6}}      I'd like to get a list of last elements from each sublist, in this case: > {7,5,6} I'm not sure whether i should think of a pattern to do this or is there a simpler way?


Create custom shortcut to change font color

Just wondering if I can create a custom shortcut key to change the font color of the notebook text. I've created a custom shortcut (in dkyeventtransactions.tr) to bring up the font color dialog, as so...               Item[KeyEvent["q", Modifiers -> {Control}],            FrontEndExecute[FrontEndToken["FontColorDialog"]]]      but I'm hoping to create different shortcut keys to change the font directly to different colors, without using the font color selection dialog.


Conversion of 3D plot to 2D Contour Plot

Is it possible for Mathematica to convert a 3D plot into a 2D contour plot without having to recompute the values for each point? I realize that looking directly down at the 3D plot will be similar to the contour plot, but I'm wondering if Mathematica is be able to take the 3D plot as input and give the 2D contour plot as output.


How do I use Mathematica as a vector drawing program?

Recently I changed my furniture in my room and I am trying to find the best position of each part. I am sure that Mathematica could help! I read the LocatorPane, selecting multiple Locators for selecting multiple locators. Then I made some shapes like a triangle (3 Locators), a table (4 Locators) etc. and tried to move them(each shape as a whole) in some direction. My questions are:   * How can one group/ungroup some of the shapes (for examples table + chairs)   * Rotate a shape to a particular angle   * Ensure that two sides of the same or different shapes are in parallel,vertical or tangent?


Syntax of transpose etc

This is a simple question: {{0, 1}, {0, 2}, {0, 3}}*Transpose[{{0, 1}, {0, 2}, {0, 3}}] returns an error in Mathematica but works perfectly fine in Wolfram Alpha. Can someone help me? Thanks so much! Hirek


ListPointPlot3d to visualize points close to a manifold

I have a large set of points that are close to manifold which I want to show in a `ListPointPlot3D`. Using part of the data set illustrates this ![plot](http://vollmer.ms/homog3d_0) ![plot](http://vollmer.ms/homog3d_1) there are fewer data points in the middle. But using all the data with               ListPointPlot3D[list[[2 ;; n]]]      results in ![plot](http://vollmer.ms/homog3d_2) Is there a better way to visualize this? Somehow something like 3d contour plot of the density.


How to reduce expressions with complex coefficients in the form of a+0.*I

I'm trying to get an eigenvalue equation in Mathematica, and the result is an expression with coefficients of the form `a + 0. I`. For example, ![Mathematica output](http://i.stack.imgur.com/osLe5.jpg) Is there any clever way to simplify it? I mean the method in which I can take away the `0.*I` in the expression.


Split a number in powers of 2

Ok , I just worked out that every natural number can be expressed as sum of powers of 2, eg: (9 = 2^3 + 2 ^0). I am looking for an algorithm which does the splitting of natural number into powers of 2 efficiently.


HoldFirst and inserting additional options into a Grid of Graphics

This is related to my earlier question, but is specific to an issue I have encountered with the use of the `HoldFirst` First, let's create some fake data for testing purposes.               dateARList =        With[{ar = FoldList[0.9 #1 + #2 &, 0.,            RandomReal[NormalDistribution[0, 1], 100]]},        Transpose[{ Table[DatePlus[{2000, 1, 1}, {n, "Month"}], {n, 0, 100}], ar}] ];      Now define two functions. First, the general one that doesn't assume the size of the matrix in the first argument.               Clear[testHolder, testHolder2]          Attributes[testHolder] = {HoldFirst}          testHolder[m_?MatrixQ, rest : OptionsPattern[{Graphics, Grid}]] :=           Module[{nc, nr, subrules, subargs},       {nr, nc} = Dimensions[m];       subrules = Table[Cases[HoldForm[m[[i, j]]], _Rule], {i, nr}, {j, nc}];       subargs  = Table[Cases[HoldForm[m[[i, j]]], Except[_Rule]], {i, nr}, {j, nc}];       Grid[Table[         Head[m[[i, j]]] @@ Join[subargs[[i, j]], subrules[[i, j]],           {PlotLabel -> {i, j}, Joined -> True} ], {i, nr}, {j, nc}],        FilterRules[{rest}, Grid]]       ]          testHolder[{{DateListPlot[dateARList, PlotStyle -> Red],         DateListPlot[dateARList, PlotStyle -> Blue]}},       Background -> Yellow, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/Gd97p.png) As you can see, the options I tried to insert into the sub-plots (`Joined` and `PlotLabel`) do not get passed to them, nor do the options for the overall `Grid` (`Frame` and `Background`). Now, let's try a more specific case where the dimensions of the matrix in the first argument are known.               Attributes[testHolder2] = {HoldFirst}          testHolder2[{{l_[largs__, lopts___Rule], r_[rargs__, ropts___Rule]}},        rest : OptionsPattern[{Graphics, Grid}]] :=      Grid[{{l @@ Join[{largs}, {lopts}, {PlotLabel -> "Left", Joined -> True}],              r @@ Join[{rargs}, {ropts}, {PlotLabel -> "Right", Joined -> True}]}},        FilterRules[{rest}, Grid] ]      Now we have a better outcome - the options for the specific plots are passed to them, but the options for the `Grid` aren't used.               testHolder2[{{DateListPlot[dateARList, PlotStyle -> Red],         DateListPlot[dateARList, PlotStyle -> Blue]}},       Background -> Yellow, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/93m9n.png) I'm probably missing something, but I don't know what it is. Is `HoldFirst` the right way to ensure that additional options can be inserted into a function before it is evaluated? If not, what do I need to do to the evaluation sequence to get the desired result? Can I get the general (`testHolder`) case to work, or do I have to set things up with explicit pattern matches for the heads and arguments of the elements in the matrix, as in `testHolder2`?


Find Chebyshev center of a region by optimization

Let's consider a region like this: ![Region](http://i.stack.imgur.com/m0zNG.png) The aim is to find the "Chebyshev center" of the region. By using the polygons, one can approximate the perimeter of region by an $n$-gon ($n$ is large enough). Then by saving the coordinates of the perimeter in two vectors, say $x$ and $y$, and using Linear programming, compute the minimal-radius ball enclosing the region. But I want to try another way, an optimization! I have two data sets, produced by MATLAB, (get them from here) and I want to find the Chebyshev center by **optimization** (not linear programming). From here I learnt how to find the **nearest distance** of an interior point from it's boundary:               X = "KP" /. imp // Flatten;     Y = "KI" /. imp // Flatten;     pts = Transpose[{X, Y}];     Nearest[pts, {3, 1.5}]      (* {3,1.5} is a sample interior point *)      If I denote the nearest distance by $d$, the aim is to maximize $d$ (or minimize $-d$) over box inside region. (Like $x \in [1.5 \; 4.5] , y \in [0.5 \; 2]$.) The Chebyshev center will be obtained by maximizing $d$. But I can't define to Mathematica how treat with `FindMinimum` and `Nearest`.


Having difficulty with the Minimize command

I am having trouble getting an answer to this question...Am I missing something that anybody can see.               Simplify[Minimize[{(         x (-a + x))/(-a +           H) + (1 - (-a + x)/(-a + H)) ((y (-b + y))/(-b + H) +             H (1 - (-b + y)/(-b + H))), 0 <= a < 100, 0 <= b < 100,         a < x < 100, b < y <= 100}, {x, y}]]      My problem is: The computer (a small netbook) takes forever and I keep having to abort the evaluation. So I would like to know if it is possible to get an answer maybe on a faster machine or am I doing something wrong


Techniques Modifying Cells M8.0

What techniques are there for modifying/organizing/selecting/deleting cells? I understand Mathematica 9.0 has a Cells function but what techniques exist in Mathematica 8.0? The documentation for effectively using and modifying `Cells` seems quite limited.


Why does iterating Prime in reverse order require much more time?

Say I would like to display the $10$ greatest primes that are less than $10^5$. I could do the following:               AbsoluteTiming[      M = 10^5; m = PrimePi[M];      prms = Prime[#] & /@ Range[1, m];      prms[[#]] & /@ Range[-1, -10, -1]      ]      And the result comes out :               {0.0156250, {99991, 99989, 99971, 99961, 99929, 99923, 99907, 99901, 99881, 99877}}      But if I tried to do in in reverse,               AbsoluteTiming[      M = 10^5; m = PrimePi[M];      prms = Prime[#] & /@ Range[m, 1, -1];      prms[[#]] & /@ Range[1, 10]      ]      the process takes a whole lot longer:               {0.6250000, {99991, 99989, 99971, 99961, 99929, 99923, 99907, 99901,        99881, 99877}}      Using the second method, I can't even increase `M` to $10^6$, as the program takes extremely long to execute. Can anybody offer some insight into this ? $\;$ Am I essentially not doing the same thing in both cases ?


Error When Creating Package

I am trying to make my own package based on the code from this Question. The following is the code from that page:               BeginPackage["SelectData`"];     select::usage = "select[data,where,condition]";     Begin["`Private`"]              ClearAll[select, where];         SetAttributes[where, HoldAll];         select[table : {colNames_List, rows__List}, w : (where[condition_] | None) : None,              cols : (columns[varNames__] | All) : All] :=           With[{namingRules = Dispatch[Thread[colNames -> Thread[Slot[Range[Length[colNames]]]]]]},              With[{cl = {varNames} /. namingRules /. Verbatim[Slot][n_] :> n},               If[cols === All, #, #[[All, cl]]] &@                 If[w === None,                    {rows},                    (* else *)                    With[{selF = Apply[Function, Hold[condition] /. namingRules]},                       Select[{rows}, selF @@ # &]                    ]                 ]             ]           ];           End[]     EndPackage[]      Then, on my notebook, use the following data as input:               table = List[{"ID", "Variable 1", "Variable 2"}, {"Alpha", 1,         0}, {"Beta", 1, 1}, {"Alpha", 0, 0}]      Call the package, Needs["SelectData`"] Evaluating, `select[table, columns["Variable 1"]]` the output is as follows:               select[{{"ID", "Variable 1", "Variable 2"}, {"Alpha", 1, 0}, {"Beta",         1, 1}, {"Alpha", 0, 0}}, columns["Variable 1"]]      I think I have done something wrong when creating my package, but I can't find it. Could anyone give me suggestions?


Converting problem into form involving Probability

I want to solve the following problem symbolically, using `Probability`: > What is the probability of the first random variate of a set to be present > more than once, if the set is constructed of random variates from a specific > discrete probability distribution in a way that its' length is at most N, > and any other duplicates except the first variate are removed? Maybe that's not the most elegant way to describe the problem, but it's better than nothing. What I would want is to reach a symbolic result using `Probability` in a descriptive way that is intuitively reached from the definition of the problem. At the moment, I have only a numeric simulation to solve this problem:               prob[dist_, n_] :=      Block[{weightedResult},            (* Return {probability, weight} for a single trial *)       weightedResult[] :=        Block[{f, test},              (* Append if value is the same as first, or not in rest *)         f[vals_] :=          With[{v = RandomVariate[dist]},           If[vals != {} && v != First@vals && MemberQ[Rest@vals, v],            vals,            Append[vals, v]]];              (* Stop nesting if first and last are the same,          or limiting length of unique values is reached *)         test[{} | {_}] := True;         test[vals_] := First@vals != Last@vals && Length[vals] < n;         Block[{vals = NestWhile[f, {}, test]},          {Boole[First@vals == Last@vals],           PDF[dist][First@vals]}]];            (* Computes weighted mean of 10000 trials *)       WeightedData @@          Transpose[ParallelTable[weightedResult[], {10000}]] // Mean]      It works for plots...               DiscretePlot[      prob[DiscreteUniformDistribution[{1, n}], 10], {n, 10, 50}]      > ![enter image description here](http://i.stack.imgur.com/o2REO.png)               DiscretePlot[prob[GeometricDistribution[1/n], 10], {n, 2, 20}]      > ![enter image description here](http://i.stack.imgur.com/VFh8c.png) Where to start on symbolic solution?


How to perform a symbolic minimization?

Can _Mathematica_ determine the symbolic expression in terms of `τ` that minimizes `f[τ]` ?               u[τ_] := n*E^(-λ*τ)       f1[τ_] := k*τ     f2[τ_] := a*u[τ]     f3[τ_] := m*τ^2     f[τ_] := f1[τ] + f2[τ] + f3[τ]          f[τ]      > >     a E^(-λ τ) n + k τ + m τ^2 >   So far so good. But when I use `Minimize`, it just gives back my input.               Minimize[f[τ], τ, Reals]      > >     Minimize[a E^(-λ τ) n + k τ + m τ^2, τ, Reals] >


specify field width in Print

I would like to format the output. For example, the following code gives               For[n=2,n<=10,n++,       factorization =FactorInteger[n];       length=Length[factorization];       If[length==1,         factorization =(Superscript@@@FactorInteger[n])[[1]],         factorization =CenterDot@@(Superscript@@@FactorInteger[n])       ];            Print["n = ", n, " = ", factorization, ", number of prime factors = ", length];     ]      ![enter image description here](http://i.stack.imgur.com/GF7qH.png) But what I want is something similar to the following (but better alignment) ![enter image description here](http://i.stack.imgur.com/xoJJI.png) I know there is Grid, but I don't know how to use them in this current case. Also, I prefer a simpler solution (if there is), such as one can specify a "field width" like in the C language.


A possible error related to the evaluation of a double integral

According to the Mathematica, the integral below                   NIntegrate[ Log[Log[1/(x y )]]  Log[1/(x y )]^(-0.5 - 1), {x, 0, 1}, {y, 0,1}]      might possibly evaluate to "Overflow, Indeterminate, or Infinity" for $t=-0.5 - 1$, although my calculations show that there should be no problem for all the cases with $t>-2$. More exactly, Mathematica yields this result: **NIntegrate::inumri: "The integrand Log[Log[1/(x y)]]/Log[1/(x y)]^1.5 has evaluated to Overflow, Indeterminate, or Infinity for all sampling points in the region with boundaries {{0.,3.97545*10^-31},{0,1}}"** So, is it a problem with my code or it's just another problem related to the Mathematica?


Since when is a log distributed across a finite sum?

I have this:               $ord = 9;          eq = X^Q - V^P ((V - 1)^Q/(c^(P - Q) (V - c^2)^Q)) /. Q -> 2 /.      P -> 3           VV = Series[Sum[a[i] X^i, {i, 0, $ord}], {X, 0, $ord}]          Solve[((eq /. X -> 0) == 0), V]          VV = VV /. a[0] -> 1          ef = Solve[Series[(eq /. V -> VV), {X, 0, $ord}] == 0,        Table[a[i], {i, 1, $ord}]]          aa = VV /. Flatten[ef] // Simplify          L = Log[Series[aa, {X, 0, $ord - 1}]]/X // Simplify          Expand[Coefficient[L, X]]      which is great in that it gives me what I want and expect. However, I don't understand how the Log[Series[aa,... term distributes a logarithm through a series. Is it just the case that some magnificent simplification occurs? I mean, how does the algorithm in Mathematica even start this? Is the implementation (with the assumption of bounds on the argument):               Log[Z] = Sum[(((z-1)^j)/j)*(-1)^(j+1),j=1..infinity]      I guess I just find it amazing that there are no Log terms left and a polynomial remains. Can someone enlighten me? Thanks!


Mathematica: How to create a function that returns a property similar to how LinearModelFit works?

I'm trying to write a custom function in Mathematica, `myFunc[x]`. I want to be able to define properties of the function so that the user can call `myFunc[x]["Property"]` and have it return the value stored in `Property`. Basically I'm looking for the same functionality as `lmf=LinearModelFit[data,x,x]` where you can use `lmf["RSquared"]` to return the correlation coefficient of the fit, but `lmf[5]` returns the y value for x=5. Here's an example of the function that I'm trying to define:               myFunc[data_]:=Module[        {localProperty, x},        localProperty = "123abc";        Return[data+3x];     ];      And the output should look like:               (* User enters normal data *)     In[1]: foo = myFunc[5]     Out[1]: 5+3x          (* User enters the name of the property *)     In[2]: foo["localProperty"]     Out[2]: "123abc"          (* User wants to enter a value and evaluate *)     In[3]: foo[3]  (* 5+3*3 *)     Out[3]: 14      Is there a way to do this? I believe it's a built-in capability, as witnessed by the symbolic `FittedModel` object, but all my searches have so far yielded nothing of use. I've looked at `Property`, `Option`, `Attributes`, and just using `If` statements to try and catch the cases where the user types in a property name. I'm using Mathematica 8. Thanks, **Edit: Solution Found** Thanks to the guys below, I've found my solution and now have a function that will fit a linear model and plot up the data in one go. I can also extract the model or model parameters by entering different options. Below is the code if anyone is interested.               Clear[ListPlotWithTrendline];     ListPlotWithTrendline[data_, addopts___] := Module[        {lmf, lmfPlot, plot, plots, dr, lmfPlotMinX, lmfPlotMaxX, pos, pr, addopts2, lmfpr, returnValue},        dr = {Min[data[[All, 1]]], Max[data[[All, 1]]]};             (* The workaround to get my 'opts' variable to work with Plot *)        addopts2 = Flatten[{addopts}, 1];        pos = Quiet[Check[Position[Map[StringSplit[ToString[#]][[1]] &, addopts2], "PlotRange"][[1, 1]], 0]];        pr = Quiet[Check[ToExpression[addopts2[[pos, 2]]], dr]];        (* Routine to extract plotrange values for use in the extrapolation *)        lmfpr = If[          pos > 0,          Evaluate[Which[                 (* Both X and Y ranges are given *)            Dimensions[pr] == {2, 2}, {pr[[1, 1]], pr[[1, 2]]},                 (* The X value is All or Automatic, so we use dataRange *)            pr[[1]] === All || pr[[1]] === Automatic || pr[[1]] === Full, dr,                 (* The X range is given and Y is Full, All, or Automatic *)            Length[pr] == 2 && Length[pr[[1]]] == 2, {pr[[1, 1]], pr[[1, 2]]},                 (* Only the Y range is given or there was some error, so use the dataRange *)            True, dr            ]],          dr];        lmf = LinearModelFit[data, x, x];        lmfPlot = Plot[lmf[x], {x, lmfpr[[1]], lmfpr[[2]]}, #] &@addopts2;        plot = ListPlot[data, #] &@addopts2;        plots = Show[plot, lmfPlot];             (* Define the return values, based on what property the user is interested in. *)        returnValue["FittedModel"] = lmf;        returnValue["Plot"] = plots;        returnValue["FitPlot"] = lmfPlot;        returnValue["ScatterPlot"] = plot;        returnValue["RSquared"] = lmf["RSquared"];        returnValue["Slope"] = lmf[[1, 2, 2]];        returnValue["Intercept"] = lmf[[1, 2, 1]];        Return[returnValue];        ];      I'm sure it's not the most efficient or clean code around, but it works so I'm happy. :-) Here's an example: ![Example of ListPlotWithTrendline](http://i.stack.imgur.com/WeyOj.png)


Formatting the output of ComponentMeasurements

I have some code written here which uses ComponentMeasurements to output some data, specifically the one below:               dnaList = ComponentMeasurements[dnaFragsL, "Length"]     Histogram[dnaList]      The first line of code generates the output               {1 -> 177.7, 2 -> 80.4449, 3 -> 338.173, 4 -> 270.588, 5 -> 379.699,       6 -> 93.3377, 7 -> 69.6693, 8 -> 214.073, 9 -> 370.709, 10 -> 81.386,       11 -> 160.486, 12 -> 90.3487, 13 -> 208.946, 14 -> 138.308,       15 -> 86.0753, 16 -> 65.237, 17 -> 65.2137, 18 -> 106.573,       19 -> 141.393, 20 -> 129.238, 21 -> 79.7561, 22 -> 60.7805,       23 -> 73.7609, 24 -> 86.4439, 25 -> 101.005, 26 -> 120.764,       27 -> 229.084, 28 -> 131.506, 29 -> 98.6205, 30 -> 26.1816,       31 -> 387.531, 32 -> 179.419, 33 -> 62.0383, 34 -> 60.3329}      which does not appear to be an array or list and cannot be fed into the Histogram function. What transform has to be carried out in order for it to generate usefully formatted output? The image dnaFragsL is attached below. ![test image](http://i.stack.imgur.com/WPpcz.png)


PlotLabel moves, when i rotate my 3D graphic

How can I stop the label from moving up and down, when rotating using the mouse?               Manipulate[           v = {vx, vy, vz};      start = {sx, sy, sz};           Show[            Graphics3D[{Black,         Table[{Dashing[0.005], Line[{{i, -5, 0}, {i, 5, 0}}],            Line[{{-5, i, 0}, {5, i, 0}}],            Line[{{-.2, 0, i}, {.2, 0, i}}]}, {i, -5, 5}], Thick,          Arrow[{{0, 0, -5}, {0, 0, 5.5}}],          Style[Arrow[{{0, -5, 0}, {0, 5.5, 0}}], Antialiasing -> True],         Arrow[{{-5, 0, 0}, {5.5, 0, 0}}],         Text[Style["x", 16, Italic], {5.8, 0, 0}],          Text[Style["y", 16, Italic], {0, 5.8, 0}],          Text[Style["z", 16, Italic], {0, 0, 5.8}],              Red,         Arrow[Tube[{start, start + v}]],         Purple,         If[stedvektor,          Arrow[{o, v}]],              If[koord && stedvektor, {           PointSize -> 0.008, Point[{vx, vy, 0}], Dashing[{.005, .005}],            Line[{{vx, vy, 0}, v, {0, 0, vz}}],            Line[{{0, vy, 0}, {vx, vy, 0}, {vx, 0, 0}}],           (*Text[Style[vx,16],{vx,0,.5}],Text[Style[vy,16],{0,vy,.5}],           Text[Style[vz,16],{.5,.5,vz}],*)           Text[Style[Row[{"(", nf[vx], ", ", nf[vy], ", ", nf[vz], " )"}],              12], {vx + 1, vy + 1, vz + .3}]}]                        }], PlotRange -> {{-5.5, 5.5}, {-5.5, 5.5}, {-5.5, 5.5}},        AxesLabel -> {Style["x", Italic], Style["y", Italic],          Style["z", Italic]}, Boxed -> False, ImageSize -> {290, 300},       Axes -> False, Boxed -> False,            PlotLabel -> If[koord, Text[Style[Row[{vec["a"], " = ", ( {               {nf[vx]},               {nf[vy]},               {nf[vz]}              } )}], Red, 14]],         Text[Style[Row[{vec["a"], " = ", ( {               {Subscript[a, 1]},               {Subscript[a, 2]},               {Subscript[a, 3]}              } )}], Red, 14]]         ],                 ViewPoint ->         1200 {Cos[-p[[1]]] Sin[p[[2]]], Sin[-p[[1]]] Sin[p[[2]]],           Cos[p[[2]]]},            ViewAngle -> 0.0009,            SphericalRegion -> True],                Row[{        Control[{{dimension, 2, "Antal dimensioner"}, {1, 2, 3}}],         Control[{{koord, True, "Vis koordinater"}, {True, False}}],        Control[{{stedvektor, False, "Vis stedvektor"}, {True, False}}]},        Spacer[20]],                Style[Row[{"Vektor ", vec[a]}], 12, Bold],           {{vx, 3, Subscript[a, 1]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},      {{vy, 1, Subscript[a, 2]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},      {{vz, 3, Subscript[a, 3]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},           Delimiter,                Style["Startpunkt", 12, Bold],           {{sx, 2, Subscript[x, 0]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},      {{sy, -2, Subscript[y, 0]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},      {{sz, 1, Subscript[z, 0]}, -5, 5, ControlType -> Slider,        ImageSize -> Tiny, ControlPlacement -> Left},      {{start, {2, -2, 1}}, ControlType -> None},      {{o, {0, 0, 0}}, ControlType -> None},                     Initialization :> (             p := {2 Pi - Pi/4, Pi/3};        vec[a_] := Style[OverVector[a], Bold];        nf[n_] := NumberForm[n, {2, 1}];        halfway[v_] :=          0.5 Norm[v] {Cos[(ArcTan @@ v - 1.5 ArcTan[Norm[v], .4])],            Sin[(ArcTan @@ v - 1.5 ArcTan[Norm[v], .4])]};         halfway2[v_] :=          0.5 Norm[v] {Cos[(ArcTan @@ v - 2.5 ArcTan[Norm[v], .4])],            Sin[(ArcTan @@ v - 2.5 ArcTan[Norm[v], .4])]}),           TrackedSymbols :> {start, slut, koord, stedvektor, dimension, vx, vy,         vz, sx, sy, sz, p}      ]


Shooting method problem

I am trying to solve the BVP problem: $ u''-u'=-6u^5+(8+4a)u^3-(2+4a)u, u(0.001)=1, u(10)=-1, u'(0.001)=-0.001$               eps=0;     phi6inst = Map[First[      NDSolve[{u''[x] -           u'[x]/x == -6 u[x]^5 + (8 + 4 eps) u[x]^3 - (2 + 4 eps) u[x],         u[0.001] == 1, u[10] == -1}, u, x,        Method -> {"Shooting",          "StartingInitialConditions" -> {u[0.001] == 0,            u'[0.001] == -0.001}}]], {0}];     Plot[Evaluate[x[t] /. phi6inst], {t, 0, 10}]      Yet there is no solution found to this problem...               NDSolve::berr: "There are significant errors {0.,5.91741*10^-7} in the boundary value residuals. Returning the best solution found. "      I do not know where to start...


How do I change the initial state of a discrete Markov process?

I have a simple Markov process defined with               mp = DiscreteMarkovProcess[1, ( {          {1/3, 1/3, 1/3, 0},          {1/2, 1/4, 0, 1/4},          {0, 0, 1, 0},          {0, 0, 0, 1}         } )];      How I change the initial state of this process, without defining an entirely new process. Is there a way to "set" the initial probabilities of `mp` to different values?


A power series expansion

Consider the function, $f(z) = z tanh(\pi z) log (z^2 + a^2)$ for some $a>0$. Now I am considering 3 different situations,   * $z = i(n+0.5) - i\epsilon + \delta - it$ for $n \in \mathbb{Z}$ and we integrate from $t=0$ to $t=1-2\epsilon$.    * $z = i(n-0.5) + i\epsilon - \delta + it$ for $n \in \mathbb{Z}$ and we integrate from $t=0$ to $t=1-2\epsilon$.   * $z = i(n+0.5) - i\epsilon - \delta - it$ for $n \in \mathbb{Z}$ and we integrate from $t=1-2\epsilon$ to $t=0$.  Now in any of these cases I am truncating the Taylor expansion of $f$ (and the integration limits) to zeroth order in $\epsilon$ and $\delta$ and then doing the integration. (...because that is the limit that interests me.) I am using the `Series` function of _Mathematica_ twice (once each for the two infinitesimals) to get this zeroth order term and I get that,   * For the first and third cases this zeroth order term comes out to be, $\frac{1 + 2(n-t) }{2}Cot [\pi (n-t) ]Log [ a^2 - (\frac{1 + 2(n-t) }{2})^2 ] $   * In the second case this zeroth order term comes out to be, $\frac{-1 + 2(n+t) }{2}Cot [\pi (n+t) ]Log [ a^2 - (\frac{-1 + 2(n+t) }{2})^2 ] $ Now the confusion is this - hence symbolically for the first and the third cases the integrations are negative of each other (as I would expect!) but the second case turns out to be distinctly different. But if you think on the z-plane then the second and the third are exactly the same paths on which the integration is being done. Then why this difference? * * * In the comments confusions were raised about how the series was done - so here is the code for the first case,               z = I (n + (1/2) - x - t) + y;           Assuming [        n \[Element] Integers && n < a && a > 0 && x > 0 && y > 0 &&        t > 0   ,        Series [ z Tanh [ \[Pi] z  ] Log [ z^2 + a^2 ]    , {y, 0, 2}]]      Doing the above produced the zeroth order term in "y" ($\delta$) to be,               -(1/2) (1 + 2 n - 2 t - 2 x) Log[          a^2 - 1/4 (1 + 2 n - 2 t - 2 x)^2] Tan[          1/2 (\[Pi] + 2 n \[Pi] - 2 \[Pi] t - 2 \[Pi] x)]      So then I did an "x" ($\epsilon$) series on it,               Assuming [         n \[Element] Integers && n < a && a > 0 && x > 0 && y > 0 &&         t > 0   ,         Series [ -(1/2) (1 + 2 n - 2 t - 2 x) Log[          a^2 - 1/4 (1 + 2 n - 2 t - 2 x)^2] Tan[          1/2 (\[Pi] + 2 n \[Pi] - 2 \[Pi] t - 2 \[Pi] x)]   , {x, 0,          2}]] // FullSimplify       This produced the expression, $\frac{1 + 2(n-t) }{2}Cot [\pi (n-t) ]Log [ a^2 - (\frac{1 + 2(n-t) }{2})^2 ] $ as the zeroth order term. Similarly for the other cases...


How to export .mtl files for 3D textured objects

I would really like to deploy my textured 3D graphics in the web with sketchfab in my blog. Unfortunately, Mathematica only exports the _shape_ of the 3d graphics, i.e. the .obj file, but omits the associated material file (.mtl) which is not generated. Is there any way to accomplish my aim and deploy from Mathematica textured- graphics to sketchfab or any other standard textured material format? Perhaps someone has written a basic .mtl exporter?


Why does Mathematica claim there is no even prime?

I wonder if this is a bug, or if I'm misunderstanding something:               Exists[n, EvenQ[n] && PrimeQ[n]] // Resolve     (*     ==> False     *)      So if I interpret this result correctly, according to Mathematica there does not exist an even prime. However, if given the number directly, it gives the correct result:               EvenQ[2] && PrimeQ[2]     (*     ==> True     *)      So did I find a bug in Mathematica (and if so, is it fixed in the latest version)? Or did I misunderstand `Resolve`?


Future-proofing access to packed array tools

Most of the Mathematica users beyond beginner level will be aware of the phenomenon of _Packed Arrays_. The user-accessible functions related to packed arrays live in the `Developer``context and have been there for quite some time. I wonder what this means for their future use. Is `Developer`` more stable than `Experimental``? Can we expect this functionality to move into the kernel and what calling strategies could we adopt to minimize the effects such a move would have?


Replace rule also matching complex numbers

I'm having the replace rule:               rule = {-g_ x_^4 - 2 g_ x_^2 y_^2 - g_ y_^4 -> -g (x^2 + y^2)^2};      Now,               (2 Re[Hy Conjugate[Hx]] kx^4 vx vy)/(k^2 (kx^2 + ky^2)) + (      4 Re[Hy Conjugate[Hx]] kx^2 ky^2 vx vy)/(k^2 (kx^2 + ky^2)) + (      2 Re[Hy Conjugate[Hx]] ky^4 vx vy)/(k^2 (kx^2 + ky^2)) //. rule      Just spits the same expression back out. The expected output would be               (2 Re[Hy Conjugate[Hx]] (kx^2 + ky^2) vx vy)/k^2      Sure, I could remove the minus signs in the rule, but is it possible to match both `+` and `-`? Furthermore this also fails of one of the coefficients is a complex number, how can I tell Mathematica that this should also work with complex numbers? If there is another way to do this, e.g., using `Solve`, I'd like to hear that.


Why even try the semantic constraints, if expression can't match the pattern structure?

This result is unexpected:               Trace[MatchQ[{7}, {_?NumberQ, __}], NumberQ] (* ->  {{NumberQ[7], True}} *)      Why evaluate `NumberQ` if the pattern can't conceivably match? What kind of side-effect might change the expression arity during pattern-matching? Precisely, due to the unbound side-effects and for performance reasons, I would have thought that the matcher would labor very hard to avoid invoking the evaluator. Note that other cases are not surprising:               Trace[MatchQ[{7}, {_?NumberQ, _}], NumberQ] (* -> {} *)          Trace[MatchQ[{7}, {_?NumberQ, ___}], NumberQ] (* ->  {{NumberQ[7], True}} *)      The combination of a constraint and `BlankSequence` seems to make the pattern- matcher overly suspicious. So, " _a list of two expressions, first one a number_ " bypasses the evaluator; " _a list of two or more expressions, first one a number_ " triggers the evaluation of the restriction. Optimization of pattern-matching is unresolved in general. In the context of expressions in the form **head + n parts** , however, trying to calculate the lower bound of **n** for the class of expressions represented by a pattern strikes me as one of the obvious problems to focus on. Given the experience of these last weeks, though, the struggle between my intuition and Mathematica is always won by the latter. What am I missing, then? **Update** : Mr.Wizard and Leonid Shifrin discussed a few years ago about the uneasy relation between the evaluator and the pattern-matcher.


How to generate random directed acyclic graphs?

How to programmatically build **random** directed acyclic graphs (DAG)? I know about the `AcyclicGraphQ` predicate and the `TopologicalSorting` function, though _Mathematica_ does not offer any algorithm to create such networks. Anyone has some experience in this topic? The following random method does not guarantee that the result will be acyclic:               graph = RandomGraph[{10, 10}, DirectedEdges -> True]      ![Mathematica graphics](http://i.stack.imgur.com/4rZ0M.png)               AcyclicGraphQ@graph          (* ==> True *)


Using variables in function names

I want to make a list of plots and my functions are named `C1`, `C2`... `Cn`. The command I wish to execute is:               Table[Plot[Cn[t], {t, 0, 1}], {n, 1,6}]]      which obviously doesn't work. How is the equivalent of the above done in Mathematica? **EDIT:** Thanks for the answers. Here is what it looks like: ![enter image description here](http://i.stack.imgur.com/Jvj4K.jpg)


Multiple colors in Graphics[] environment

There are other questions on the site that are similar to this one, but the answers provided didn't help me. I want to draw disks of different radii. Each radius is the absolute value of a variable, which takes positive and negative values. I want my disks to be red when the variable is negative, and blue when it is positive. I am wondering how I would do that, since I haven't found pertinent information in Mathematica's documentation. **EDIT** : To be clear, I have a set of eigenvectors, and for each one, I would like to plot a disk for each component of the vector. So, if the $i^{th}$ eigenvector, $\mathbf{\Psi}_i$, has the form $$\mathbf{\Psi}_i = \sum_j c_j \mathbf{e}_j$$ where the $c_j$ are the coefficients and the $\mathbf e_j$ are the unit vectors in my basis, I'd like to plot for each $c_i$ a disk with radius $\vert c_i \vert^2$ and colored by the sign of $\arg c_j$.


How do I plot the images of oriented curves under complex transformation?

I'm working on a complex transformation sketch that I'd like to create via mathematica. I'm working with the mapping $w=z^2$, where its real and imaginary parts are $u=x^2-y^2$ and $v=2xy$, respectively. Now, I want to sketch the image under the given transformation of each branch of the hyperbola $$x^2-y^2=1\tag{1}$$ where the right and left branches (in blue) are oriented upward and downwards, respectively. For example, the blue branches of the hyperbola in (1) appear as such: ![enter image description here](http://i.stack.imgur.com/WFKIM.png) Similarly, for the hyperbola $$2xy=2,\tag{2}$$the left and right branches (in orange) are oriented upwards and downwards, respectively. **How do I sketch the images of these hyperbolas under $w=z^2$, while taking into account the orientation of their respective branches?** I expect the image of the hyperbola in (1), to be the line $u=1$, oriented updwards, and the image of the hyperbola in (2) to be the line $v=2$, oriented rightwards. Here's what I have so far; however, getting the orientation arrows requires that I load the **CurvesGraphics6** package from here. _If anyone could provide a method of providing orientation arrows for these curves via simpler means, that would be great as well._                r1 = ContourPlot[{x^2 - y^2 == 1, x*y == 2}, {x, -4, 4}, {y, -4, 4},       Axes -> True, Frame -> False, PlotRange -> Automatic,       Background -> White, Oriented -> True]      **[UPDATED CODE]** Courtesy of Eldo and Mark McClure, I was able to apply orientation arrows to the Hyperbolas without using the aforementioned package.               r1 = ContourPlot[{x^2 - y^2 == 1, x*y == 2}, {x, -4, 4}, {y, -4, 4},      Axes -> True, Frame -> False, PlotRange -> Automatic,      Background -> White]          Show[r1, r1 /. Line[pts_] :> Arrow[pts, 2]]


NDSolve break condition

I'm solving a differential equation numerically by               NDSolve[{p'[r] == -function[r,p[r]], p[0] == pcenter}, p,{r, 0, rmax}]      with function>0. At some r, p[r] becomes negative. I want NDSolve to stop as soon as this happens and save the value of r. Any ideas how to do this?


NDSolve in exact points - nonlinear equation (Degrees and Radians confusion)

I found solutions of two nonlinear equations, but I have three small questions. First I am in confusion because of initial value. The system is mechanical and unknown ϕ is an angle, which I set to be in position of 90 degrees (Pi/2). Is it correct setting in equation initial position? Second question: I am looking for discrete points of an angle values here                ϕ = 90 Degree (Pi/2 Radians)      ϕ = 80 Degree (1.396 Radians)      ϕ = 70 Degree (1.221 Radians)      ϕ = 30 Degree (0.523 Radians)      ϕ = 20 Degree (0.349 Radians)      ϕ = 10 Degree (0.174 Radians)      ϕ = 0 Degree (0 Radians)      Numerical solutions of these values down and in which time                {z[t], z'[t], ϕ'[t], ϕ''[t], z''[t], t}      I solved the system and obtained solutions, but I don't know how to extract these values from the diagrams. Third question: I am looking for to obtain FindMinimum[zsol[t],t] and FindMaximum[zsol[t],t] but Mathematica gives value which is not extrema because I can see from the diagram that it is not extrema.                c1 = 7.5*10^3;      m = 10;      l = 1;      M = 75;      g = 9.81;           {zsol, ϕsol} =         NDSolveValue[          {z''[t] - (M l)/(m + M) ϕ''[t] Sin[ϕ[t]] - (M l)/(m + M)             (ϕ'[t])^2 Cos[ϕ[t]] + c1/(m + M) z[t] == 0,            ϕ''[t] - 1/l z''[t] Sin[ϕ[t]] + g/l Sin[ϕ[t]] == 0,            z[0] == -((M g)/c1), z'[0] == 0, ϕ[0] == Pi /2, ϕ'[0] == 0},          {ϕ, z}, {t, 0, 15}]           Plot[{zsol[t], ϕsol[t]}, {t, 0, 5}, PlotStyle -> {Red, Blue}]      Plot[{zsol[t]}, {t, 0, 5}, PlotStyle -> {Red}]      Plot[{ϕsol[t]}, {t, 0, 5}, PlotStyle -> {Blue}]      Solutions ![enter image description here](http://i.stack.imgur.com/Cvid2.png)


Hardware required to perform large symbolic calculations

I'm choosing components to set up a pc aimed to run large symbolic computations in Mathematica 9.0 under Windows 7 64 Bit Pro. I have a limited budget therefore I'm considering this system:   * Mother Board Asrock Z97 Extreme 4   * cpu Intel Haswell Core i5-4690K (AVX2, BMI, TSX)   * ram HyperX Fury Memory Black Memorie RAM, 32 GB, 1866 MHz HX318C10FBK2/16 and I have no chance to buy a second machine if the first prove to be badly effective. At present moment, I have no money for a GPU video card. May be in future I can add one. Does Mathematica's standard licence allow the use of all features of this hardware ? Does the hardware lack some major features Mathematica could make use of ? Thanks !!


Custom simplification of symbolic definite integral with regards to bounds

I would like to rewrite symbolic definite integrals such that the bounds are always positive. For example : $\int_{-\infty}^\infty f(x) \mathrm{d} x \rightarrow \int_0^\infty \left[ f(x) + f(-x) \right] \mathrm{d} x$ I know that in mathematica, you can provide a custom complexity function to `Simplify` in order to get a result in a specific form. I was wondering if this could be applied in some way to my problem. Unfortunately, my google search for this kind of problems came up empty. As a first step, it would be really helpful if anyone knew a function that returns the bound of a symbolic integral. Thanks for any help !


Adding another control to Manipulate[MatrixPlot[matrix]] to take specific part of matrix

I got matrix, let's say, 100 rows and I would like to plot only 10-rows window of it. Is it possible to add a slide control to Manipulate[] window so to shift 10-row "window" interactively? I trying Manipulate[MatrixPlot[matrix[[x ;; x + 10]]], {x,0,100}], but that's not working.


Simpler code evaluating Dickman's function?

I've read here that Mathematica 10 can _Obtain symbolic solutions to delay differential equations_. Would that help in numericaly evaluating Dickman's function $\rho(u)$ ? It is a delay differential equation defined for $u\in\mathbb R^+$ by $$\begin{cases} \rho(u)=1 & \text{if }0\le u\le1\\\ u\cdot\rho'(u)+\rho(u-1)=0& \text{if }u>1 \end{cases}$$ * * * Otherwise said, can Mathematica 10 (or something) help improve/simplify this (working) code?               Dickm$pr=40 (*desired ABSOLUTE (rather than relative) accuracy*);          Dickm$ex=Ceiling[Dickm$pr*Log[3,10]]+1 (*order of expansions; empirical*);          Dickm$ma=Ceiling[Dickm$ex/Log[Dickm$ex]] (*domain limit*);          (*Dickm$dv[n] approximates DickmanRho[t+n-1/2] for -1/2\[LessEqual]t\[LessEqual]1/2*)          Dickm$dv[1]=N[1,Dickm$pr+1];          Dickm$dv[n_]:=Dickm$dv[n]=Module[{u=Dickm$dv[n-1],v},v=Integrate[(u+O[\.b2]^Ceiling[Dickm$ex-n])/(\.b2+n-1/2),\.b2];(Normal[u]/.\.b2->1/2)+(Normal[v]/.\.b2->-1/2)-v];          DickmanRho[y_?NumberQ]:=Which[y<=0,1,y>Dickm$ma,N[1,y Log[10.,y]]-1,True,Normal[Dickm$dv[Ceiling[y]]]/.\.b2->y-Ceiling[y]+1/2];          (* Example use *)     DickmanRho[15]


CompiledFunction with multiple outputs of different ranks

Below is a simple compiled function `f` that gives multiple outputs.               f = Compile[{{a, _Real}}, Module[{k1=Table[i, {i, a}], k2=Table[i j, {i, a}, {j, a}]}, {k1, k2}]];      `CompilePrint[f]` shows `MainEvaluate` possibly because the ranks of `k1` and `k2` are diferent. Sample evaluation `f[2]` gives the following warning and proceeds to uncompiled evaluation (probably because of the `MainEvaluate`)               CompiledFunction::cfex: Could not complete external evaluation at instruction 23; proceeding with uncompiled evaluation. >>      Is there an alternate way to get multiple outputs of varying ranks from a compiled function without `MainEvaluate`?


Expectation over a list with nested-mapped expressions

I need expected values of a list where the random variable to take expectations over should be an input into expressions defined earlier. I suspect Set[] and SetDelayed[] tripped me. (Or Map and Table?) I hope the intention is reasonably clear from the code: I am interested in expressions of six numbers in [0,1] where I suspect (model) that they have been measured with error (errors being independent and uniform here, but answers truncated to lie in the meaningful range anyway). I don't get the solution I expect, only an expression substituted into. Input:               AList = {a1,a2,a3,a4,a5,a6}     answers := (Min[1,Max[# ,0]])& /@ (AList+errors)     dlist ={answers[[5]],answers[[6]],answers[[3]]/answers[[1]],answers[[4]]/answers[[2]]}      deltasbetas = Expectation[dlist,errors\[Distributed]Table[UniformDistribution[],{6}]]      (note that errors are defined within Expectation, as I think it should be) Output:               {Min[1,Max[0,0.8 +UniformDistribution[{0,1}]]],Min[1,Max[0,0.7 +UniformDistribution[{0,1}]]],Min[1,Max[0,0.5 +UniformDistribution[{0,1}]]]/Min[1,Max[0,0.8 +UniformDistribution[{0,1}]]],Min[1,Max[0,0.4 +UniformDistribution[{0,1}]]]/Min[1,Max[0,0.7 +UniformDistribution[{0,1}]]]}


Errors when using ParallelTable inside a package

I'm developing a package that contains a function that requires evaluation of an expensive `Table`, so I use `ParallelTable` instead. It works correctly, but always gives an error message, repeatedly, for each kernel, like this: > `Table::iterb: Iterator {mypackage`Private`m,1,mypackage`Private`nsrc$663} > does not have appropriate bounds` How can I avoid this error? Do I need to distribute variables explicitly?


Cannot adjust inset to show at the top of the base graph

I'm trying to put an inset on top of a graph, the inset is also a graph. I'm using `Inset` within `Epilog` and the following command line:               Epilog -> {Inset[coherenceLengthGraph, {12, 0.35}, {Automatic, Top}, 11]}      I've tried many things yet I cannot put the inset above the base graph. * * * I'm using Show to render two lists of different data on the same graph, after that -and within Show- I use Epilog. I looked at GraphicsColumn but I couldn't see how it allows things that one can do using Inset. Here's my code                pwaveGraph = Show[graphlistofKPPhaseBoundaries, graphKPBands,        Frame -> {True},        FrameLabel -> {"2μm/\!\(\*SuperscriptBox[\(\[HBar]\), \     \(2\)]\)", "" }, PlotRange -> {{-2, 18.05}, {-1.05, 1.05}},        FrameTicks -> {Automatic, {-1, 0, 1}},         Epilog -> {Inset[           coherenceLengthGraph, {12, 0.35}, {Automatic, Top}, 11]}];


Setting Up Lightweight Grid On Multiple Clients Programmatically

I have a number of computers which all might need to use the same (client) configuration for the Wolfram Lightweight Grid at some point. I know that there are ways to programmatically set certain front-end options with commands akin to               SetOptions[$FrontEnd, RenderingOptions -> {"HardwareAntialiasingQuality" -> 1}]      as in this question. My question is: are there similar commands which, when I evaluate them on a given computer will set the Local->Lightweight Grid preference pane? That is, I would love to have a notebook that I could distribute to my colleagues that contained code like               SetOptions[Something, LookForKernelsAt->IPAddress(es)OfTheComputer(s)RunningLightweightGrid]      that would configure their computers correctly and through Mathematica restarts (ie. so that they only have to evaluate the code one time). Is this possible? Do such commands exist? I have been trying to understand what is provided in the `LightweightGridClient` and `Parallel``Developer` contexts but nothing seems to fit the bill.


Calculating the distance between the coordinates in a list

I have a list of coordinates               {{A[9, 4, 7], 0.0395174}, {A[1, 5, 0], 0.0163797}, {A[0, 7, 2], 0.0577425},       {A[2, 7, 5], 1.01313}}      I want to find the distance between them using the equation $$r= \sqrt{(x_2-x_1 )^2+ (y_2-y_1)^2+(z_2-z_1)^2 }$$ I will choose the first coordinate and calculate the distance to other coordinates by using the above equation. In the second step I will take the second coordinate and calculate the distance to other coordinates. since the distance between first one and second one is already calculated there is no need to do it again. In this way I have to find the distance between all coordinates. Can anyone help me.


Unexpected result from InverseFunction

Given the following two equivalent inverse functions, why does one simplify (using inverse functions that are acceptable to me) and the other doesn't? Is there an assumption or setting I can give which will force these to use inverse functions and simplify properly?               $Assumptions = A > 0 && k < 1 && k > 0;  (* This seems irrelevant *)     InverseFunction[(#1 A^k (#1)^k) &]     InverseFunction[(#1 (A #1)^k) &]      Is the issue that the #1 isn't given an assumption? Originally came from a problem with Solve which has the same basic behavior, even seems to have consistent behavior:               $Assumptions = A > 0 && k < 1 && k > 0 && m > 0 && z > 0;     Solve[z A^k (z)^k == m, z]      Solve[z (A z)^k == m, z]


How to give axes label to a histogram

I plotted a histogram and I used AxesLabel for labeling X axis and Y axis But it went wrong. How to do it?.               Xarray = A @@@ Tuples[Range[0, 9], 3];          M = RandomSample[Xarray, 7]          Table[energies =  RandomVariate[ExponentialDistribution[1.5], {Length@M}];          Total[energies/7], {i, 1000}];          Histogram[%, AxesLabel \[RightArrow] {"Average energy", "Number of times"}]


Efficient processing of Special Ordered Sets with LinearProgramming

I'm playing with integer linear programming, especially problems involving lots of constraints which would appear to be special ordered sets. Below is a toy example, three last rows of the matrix defining SOS1-like constraints.               LinearProgramming[       (* use SOS dummy variables for weight *)       ConstantArray[-1, 3] ~Join~ ConstantArray[0, 9],            {         (* 3 SOS dummy variables in the beginning *)         (* blocks: {1,0,1}, {2,1} and {1,0,0,1} with all alignments to 5-item array *)         {0,0,0,1,0,0,2,0,0,0,1,0},         {0,0,0,0,1,0,1,2,0,0,0,1},         {0,0,0,1,0,1,0,1,2,0,0,0},         {0,0,0,0,1,0,0,0,1,2,1,0},         {0,0,0,0,0,1,0,0,0,1,0,1},         (* number of alignments per each block present in a solution *)         {0,0,0,1,1,1,0,0,0,0,0,0},         {0,0,0,0,0,0,1,1,1,1,0,0},         {0,0,0,0,0,0,0,0,0,0,1,1},         (* weights for dummy variables: ordered set *)         {-1,0,0,3,2,1,0,0,0,0,0,0},         {0,-1,0,0,0,0,4,3,2,1,0,0},         {0,0,-1,0,0,0,0,0,0,0,2,1}       },            (* limit sum of each position in 5-item array to 2 or less *)       ConstantArray[{2,-1}, 5] ~Join~        (* limit at most one shift per block to be present: SOS1 *)       ConstantArray[{1,-1}, 3] ~Join~        (* constrain SOS dummy variables *)       ConstantArray[{0,0}, 3],            Automatic, Integers]      > {3, 3, 2, 1, 0, 0, 0, 1, 0, 0, 1, 0} Many linear programming solvers provide explicit support for SOS, since their properties allow solvers to find solutions more efficiently. My questions are: does `LinearProgramming` have heuristics for efficient exploitation of SOS, and if it has some that are more efficient than naive presentation in the example above, how to take advantage of them? As often with neatly abstracted interfaces in Mathematica, it's practically impossible to reason about such optimizations in `LinearProgramming`.


Find the smallest positive integer that satisfies a certain condition

I know Mathematica is really powerful when it comes to functional operations like applying a list of tasks to a list of variables. Sometimes I feel like it isn't the most powerful tool when it comes to looking for a number in a large range. But that's what I'd like to use it for regardless. I can always use a `While` loop, but I'm not sure that is the most effective way of doing it. So I'm looking for a more elegant/effective way of doing this. Let me give you an example: Question: Find the smallest positive integer whose sum of its digits squared is greater than 100. My rather sloppy solution:               myInt = 0;     mySum = 0;     SumLimit = 100;     While[mySum < SumLimit,      myDigits = IntegerDigits[myInt];      mySum = Total[#^2 & /@ myDigits];      myInt = myInt + 1;     ]     myInt - 1      And the answer is 59. But as you can clearly see, this method is quite slow. If I said 1000 instead of 100, it would take quite a long time to find. There are obviously better ways to solve this problem than brute force, but I'd basically like to have a more elegant implementation of the brute force method.


Mathematica code for hidden Markov models (HMM)

I am looking for some simple Mathematica code to model an HMM with just a few states and an equal number of observable signals (emissions). I am hoping to generate sample paths and keep track of the posterior probability of the system being in a given state. Any help would be appreciated.


Change the order of magnitude on the y axis Ticks with ListPlot

I have some data plotted with ListPlot. The values on the y axis range from -411230.40068*10^9 to -411230.20005*10^9. Mathematica, when plotting the data, shows me on the y axis only the value -4.1123*10^14 for every tick. Is there any way to make him show the numbers in powers of 10^9, and with 10 digits of precision? I tried with `Ticks` but didn't get so far. Thank you EDITED: A sample on request :) `data2={{1, {-5.54852437936809996398746480994*10^15, \ -1.58405160806420515488174765341*10^15, \ -1.54904996250380274306639604529*10^15, \ -7.24548530142209283870114553464*10^14, \ -7.18837770040996237092450275609*10^14, \ -7.15800320331340464813219293321*10^14, \ -4.11230259670690940795492506374*10^14, \ -4.11230258208178097437386932781*10^14, \ -4.11230256745665254647574651356*10^14, \ -4.11230253333135289454398509564*10^14}},{201, {-5.54852437888387950167782712058*10^15, \ -1.58405160700141010456248575686*10^15, \ -1.54904996124562038459636927190*10^15, \ -7.24548527010296055168304870775*10^14, \ -7.18837765300540306484560667009*10^14, \ -7.15800315786888059026593182124*10^14, \ -4.11230245162563527615111099610*10^14, \ -4.11230245150863424853646162039*10^14, \ -4.11230245139163322092217595244*10^14, \ -4.11230245111863082315635188077*10^14}}}` This is what I use to plot them: `ListPlot[Transpose[Thread[#] & /@ data2], PlotRange -> {-4.112303*10^14, -4.112302*10^14}, Joined -> True, Mesh -> All, PlotStyle -> PointSize[0.002]]`


Expressing large numbers in index form

I have a quick question. Is there anyway of expressing a large number as a power of another number in _Mathematica_? By this, I mean for example, $1237940039285380274899124224 = 512^{10}$. Is there a function that enables me to go from the LHS to the RHS of the above calculation? Given $1237940039285380274899124224$, how can I obtain $512^{10}$? `Divisors` is close but not quite what I need. Thanks for any useful hints.


Double Integral and Assumptions

I'm afraid this is going to be a really stupid question. Evaluating the following definite integral               Integrate[Sqrt[1 - (x^2 + y^2)], {x, -1, 1}, {y, -1, 1}]      gives               (2/3) (Pi - I (-2 + Log[4]))      I don't want the imaginary part. Adding the option               Assumptions -> x^2 + y^2 <= 1      doesn't work. What did I miss?


Simpson's rule with ListConvolve or ListCorrelate

I have a function that's represented as a long list of values that I want to integrate. I can do it procedurally with Simpson's rule. ListConvolve generally runs faster then procedural code, so i would like to use it if I can find the right kernel. My list can be of even or odd length, and for the latter I would like to use a method that is better than the trapezoid method. Is there a higher order method for this case?


Plot discontinuous function with black and white disks marking discontinuities

Let's say I'd like to plot `Sign[x + 0.5]`:               Plot[Sign[x + 0.5], {x, -1, 1}]      _Mathematica_ will give this: ![enter image description here](http://i.stack.imgur.com/BfCAp.jpg) This plot does not show very clearly the value of `Sign[x + 0.5]` at `x = -0.5`: is it 1? is it -1? No, it's 0, but there is no indication of which it is on the plot. This is what I'd like to achieve: ![enter image description here](http://i.stack.imgur.com/raH5t.jpg) (I used Paint to add the markers.) How can I make it _Mathematica_ do it?


Interpolate a curve in 3D

I have a sequence $\\{(x_k, y_k, z_k)\\}_{k=1}^n \subset \mathbb{R}^3$, all points along a path represented by the function $\gamma \colon \mathbb{R} \to \mathbb{R}^3$, which maps the distance along the path to a location in 3D space. Is there any way for _Mathematica_ to output an interpolation parametrized like $\gamma$, and has the sequence as a subset of its range?


Scheduled tasks not preserving order with Dynamic?

In studying the last Basic Example in the documentation for `StartScheduledTask`, namely               fun := With[{t = RandomInteger[{1, 3}]},        Print["Waiting ", t, " seconds."]; Pause[t]]          RunScheduledTask[fun; StartScheduledTask[$ScheduledTask], {1}];          RemoveScheduledTask[ScheduledTasks[]];      I first noted that nothing `Print`s. That doesn't scare me too much; I would just guess that since the task is on another thread, it would have difficulty printing to the Notebook thread, and this might be a regression overlooked in recent versions (it doesn't print when evaluating directly in the documentation, either; MMA 9.0.1.0 on Mac OS X 10.9). I decided to peek inside the task by making it assign something to a `Dynamic` that's on display in the Notebook, so I wrote               $foo = 1;          Dynamic[$foo]               RemoveScheduledTask@ScheduledTasks[];     $foo = -1;         $fun[] :=       With[{t = RandomReal[]},        $foo = ("Waiting " <> ToString@N[t, 2] <> " seconds.");            Pause[t]];         RunScheduledTask[$fun[];      StartScheduledTask[$ScheduledTask], {1}];      When I run this, the value of `$foo` is updated with the random number `t`, but it seems to be _after_ doing the `Pause`. In other words, let's say `t` has the following sequence of values               0.10000     0.90000     0.20000      Now, I can _feel_ the difference between 0.1 seconds and 0.9 seconds and 0.2 seconds, and it feels like 0.1 is Displayed for 0.9 seconds, and the number 0.9 is displayed for 0.2 seconds, and so on. In other words, the display looks like               Waiting 0.10000 seconds   (* this displays for 0.9 seconds *)     Waiting 0.90000 seconds   (* this displays for 0.2 seconds *)     etc.      What's going on here?


Styling of logarithmic tick marks in Mathematica 10

I'm trying to plot a graph wit a logarithmic y-axis. Since I'm exporting the graph to pdf and later printing it, I want to manually set the frame and tick marks to a reasonable thickness. However the logarithmic tick marks do not change their thickness. (Note: I exaggerated the thickness of the tick marks on purpose to illustrate my point.)               LogPlot[x^2, {x, 1, 3}, PlotStyle -> Red, Frame -> True,     FrameStyle -> Directive[Black, AbsoluteThickness[2]],     FrameTicksStyle -> Directive[Black, AbsoluteThickness[2]]     ]      ![Plot with Logarithmic Ticks](http://i.stack.imgur.com/e89fq.png) I'm working with Mathematica 10 on Mac OS X 10.9.4. In Mathematica Version 9 the logarithmic tick marks change their thickness as expected. Can anyone reproduce this behavior? Is this a bug or did the FrameTicksStyle change in Mathematica 10?