How to insert an expression in a Mathematica program?

I need to insert a very large expression in a _Mathematica_ program. So I first Put[large expression,"file"] and then use               Block[{}, Get["file"];...]      to implement the function. But the variables here is not local variables and may interact with other programs. I have tried to use               Module[{},Get["file"];...],      but it does not work. Do you know a clever way to do this?


(N)Solve does not solve equation

I am trying to calculate where a beam hits a mirror. The mirror is described by this curve (two facing spherical mirrors):               Mirror[x_] := Piecewise[{        {{Sin[-87.5 °] + 0.5, Cos[-87.5 °]}, x < 0},        {{Sin[-x ° - 87.5 °] + 0.5,           Cos[-x ° - 87.5 °]}, x >= 0 && x < 5},        {{Sin[x ° + 82.5 °] - 0.5,           Cos[x ° + 82.5 °]}, x >= 5 && x < 10}        }, {Sin[92.5 °] - 0.5, Cos[92.5 °]}]      Now, I am just trying to get the crossing point with a line:               p = {0, 0};     v = {1, 0};     Solve[Evaluate[       Simplify[Mirror[s].{1, 0}] == (p + v t).{1, 0} &&        Simplify[Mirror[s].{0, 1}] == (p + v t).{0, 1}        ], {s, t}]      The manual projection (.{1, 0}) is done because of the piecewise defined function, as they do not work with the usual Thread - we worked this out here. This code has been working well since then, but it does not for the current Mirror function. I have no idea what the problem could be. Any ideas?


RandomVariate returns values outside the support of a PDF

Let $X$ be a random variable with pdf:               dist = ProbabilityDistribution[1/(Abs[x]*Log[Abs[x]]^2), {x, -E^-2, E^-2}]      Here are some pseudo-random drawings from it:               data = RandomVariate[dist, 500000];      The domain of support for this random variable is:               {x, -E^-2, E^-2} // N     {x, -0.135335, 0.135335}      and all the generated data should lie within this domain of support. But, if I try something like:               Max[data]     0.15312      _Mathematica_ 9 returns a number which lies outside the domain of support. So, the _Mathematica_ random number generator is failing — it is generating values that lie outside the domain of support: i.e. not from this pdf. I reported this under version 8 to WRI, and again under version 9 pre-testing and since it is still here, I am beginning to wonder whether it is just me? Do others get this problem as well? I am running a Mac Pro with OS X 10.6.8


Exporting interpolating functions to excel

I have a question about exporting an InterpolatingFunction to excel. I checked the forum, but I still couldn't completely understand how to solve my problem. Could someone help me with this problem?               a = 10^-2;     eq1 = {hf'[t] == -a*(hf[t] - hs[t]),hs'[t] == a*(hf[t] - hs[t]), hf[0] == 20, hs[0] == 0};     sol1 = NDSolve[eq1, {hf, hs}, {t, 0, 100}]      The I got solution for `hf[t]` & `hs[t]` :               {{hf -> InterpolatingFunction[{{0.,100.}},<>],       hs -> InterpolatingFunction[{{0.,100.}},<>]}}      I'm wondering how I can export `hf[t]` & `hs[t]` values to excel as t ranges from 0 to 100.


How to construct pairs in a list?

I have an expression like this,                   input = x[1] x[2]^3 x[5]^2;      Fist step, we can get a list from the input expression,                   list0={x[1],x[2],x[2],x[2],x[5],x[5]};              list1 = {1, 2, 2, 2, 5, 5};      Second step, I want to get all possible pairs in a new list2. Namely, we divide Length[list1]/2 parts in list1 and combine the possible sublist in a new list. Of course, Length[list1]===Even.                  list2 = {{{1, 2}, {2, 2}, {5, 5}}, {{1, 2}, {2, 5}, {2, 5}} , {{1, 5}, {2, 2}, {2, 5}}};      Last step, we get the output expression,                  output = f[1, 2] f[2, 2] f[5, 5] + f[1, 2] f[2, 5]^2 + f[1, 5] f[2, 2] f[2, 5];      How can I transform the input expression into the output result? Can you show me a simple method that will work for the general problem as well as my example? In addition, we take another example,                   list1 = {1, 1, 2, 4};      the list2 should be                  list2 = {{1, 1}, {2, 4}}, {{1, 2}, {1, 4}};


Force Plot Area size to be equal excluding axes

I have two plots, both with the exact same formatting (frame, text style, etc.). One of them has 2-digit values for the y axes, the other has scientific notation because the value are large. In addition, they can have a different number of lines for the Axes labels. I set ImageSize->250, and the bounding boxes of the images (plots) are set to 250 pixels. Cool. Normally this is fine. However, when the two plots have different axes or labels, this results in: ![ImageSize->250. Bounding boxes of images are the same](http://i.stack.imgur.com/L60oj.png) What I want is the actual plot area to be the same, without manually adjusting ImageSize for the 2nd image: ![The Plot areas are the same size, but the bounding box for the entire image is different.](http://i.stack.imgur.com/kYDUM.png) Notice how the labels make the bounding box grow outward, but the plot area size is the same (also in width, just not shown). In this particular example, the right image has ImageSize->280. Does anyone know how to set the plot area size rather than the ImageSize? **EDIT 1:** @anononononomous mentioned a function to get the max padding size, and then apply it to each plot. This is getting closer! But it's clipping the FrameLabel: (Also, sorry for adding more data, it doesn't change the question though). ![anononononomous's solution](http://i.stack.imgur.com/jZMNO.png)


Efficient code for solve this equation

We have $a*b*c=-1$, $\frac{a^2}{c}+\frac{b}{c^2}=1$, $a^2 b+a c^2+b^2 c=t$ What's the value of $a^5 c+a b^5+b c^5$? I tried               Eliminate[{a b c == -1, a^2/c + b/c^2 == 1, a^2 b + b^2 c + c^2 a == t,        a b^5 + b c^5 + c a^5 == res}, {a, b, c}]      It's much slower than Maple's eliminate. How do I solve this efficiently?


How to evaluate this indefinite integrate $\csc(4x)\sin(x)$

I tried to integrate the following integral using `Integrate[Sin[x]Csc[4x],x]` and I am getting a strange result. $$\frac{1}{8 \sqrt{2}}\left(-2 i \text{ArcTan}\left[\frac{\text{Cos}\left[\frac{x}{2}\right]-\left(-1+\sqrt{2}\right) \text{Sin}\left[\frac{x}{2}\right]}{\left(1+\sqrt{2}\right) \text{Cos}\left[\frac{x}{2}\right]-\text{Sin}\left[\frac{x}{2}\right]}\right]-2 i \text{ArcTan}\left[\frac{\text{Cos}\left[\frac{x}{2}\right]-\left(1+\sqrt{2}\right) \text{Sin}\left[\frac{x}{2}\right]}{\left(-1+\sqrt{2}\right) \text{Cos}\left[\frac{x}{2}\right]-\text{Sin}\left[\frac{x}{2}\right]}\right]+2 \sqrt{2} \text{Log}\left[\text{Cos}\left[\frac{x}{2}\right]-\text{Sin}\left[\frac{x}{2}\right]\right]-2 \sqrt{2} \text{Log}\left[\text{Cos}\left[\frac{x}{2}\right]+\text{Sin}\left[\frac{x}{2}\right]\right]+2 \text{Log}\left[\sqrt{2}+2 \text{Sin}[x]\right]-\text{Log}\left[2-\sqrt{2} \text{Cos}[x]-\sqrt{2} \text{Sin}[x]\right]-\text{Log}\left[2+\sqrt{2} \text{Cos}[x]-\sqrt{2} \text{Sin}[x]\right]\right) $$ While the answer is `(1/8) Log[Sin[x] - 1] + (1/4) Sqrt[2] ArcTanh[Sin[x] Sqrt[2]] - (1/8) Log[1 + Sin[x]]` $$\frac{\text{ArcTanh}\left[\sqrt{2} \text{Sin}[x]\right]}{2 \sqrt{2}}+\frac{1}{8} \text{Log}[-1+\text{Sin}[x]]-\frac{1}{8} \text{Log}[1+\text{Sin}[x]] $$ Why am I getting this strange result? Are those two answers equivalent? How to avoid such strange results? Sorry if the question is inappropriate!


PDE combined with ODE 1D

I try to solve the following system of PDE coupled with ODE: $$\theta_t - a\theta_{xx} + b\kappa_a(\theta^4-\varphi)=0,$$ $$-\alpha\varphi_{xx} + \kappa_a(\varphi - \theta^4) = 0,$$ $$-a\theta_x + \beta\theta|_{x=0} = 0,\;\;a\theta_x + \beta\theta|_{x=L} = 0$$ $$-\alpha\varphi_x + \gamma\varphi|_{x=0} = 0,\;\;\alpha\varphi_x + \gamma\varphi|_{x=L} = 0$$ $$\theta|_{t=0} = \theta_0, \;\;\varphi_{t=0} = \varphi_0$$ for functions $\theta, \varphi$. I use the following code ($\zeta = \theta - \theta_s$, $\xi = \varphi - \varphi_s$ where $\theta_s, \varphi_s$ is the solution of the stationary problem):               s = NDSolve[{D[zeta[t, x], t] - a*D[zeta[t, x], x, x] +       b*kappaa*(((thetas[x] + zeta[t, x])^4 - thetas[x]^4) -          xi[t, x]) == 0,        -alpha*D[xi[t, x], x, x] +           kappaa*(xi[t, x] - ((thetas[x] + zeta[t, x])^4 - thetas[x]^4)) ==          0,        zeta[0, x] == zeta0[x], xi[0, x] == xi00[x],        -a*Derivative[0, 1][zeta][t, 0] + beta*zeta[t, 0] == 0,         a*Derivative[0, 1][zeta][t, ll] + beta*zeta[t, ll] == 0,        -alpha*Derivative[0, 1][xi][t, 0] + gamma*xi[t, 0] == 0,        alpha*Derivative[0, 1][xi][t, ll] + gamma*xi[t, ll] == 0},       {zeta, xi}, {x, 0, ll}, {t, 0, tt}]      The initial condition for $\theta$ is prescribed, the initial condition for $\varphi$ was computed. Wolfram Mathematica doesn't solve this system. How can I solve it?


Slider resistance and Play-Pausing with Manipulate, TabView, and attempt an granular TrackedSymbols?

Attempting to implement @Nasser's answer for How to avoid an expensive subset of a Manipulate computation when dependent variables have not changed?, using a `Manipulate` that includes a `TabView`, I wrote the following               Manipulate[tick;      TabView[{         "not continuous slider: b" -> Grid[{           {"b",            Manipulator[             Dynamic[b, {activeTab = 1 ; b = #; f = preCalculateStuff[b];                tick = Not[tick]} &], {0, 1, 0.01},             ContinuousAction -> False], Dynamic[b]}}]        , "Plot; continous slider: t" -> Grid[{           {"t",            Manipulator[             Dynamic[t, {activeTab = 2 ; t = #; tick = Not[tick]} &], {0,              1, 0.01}], Dynamic[t]},           {Row[{"f=", f, " b=", b, " t=", t}]},           {Plot[(f t) Sin[t + r], {r, 0, 2 Pi}, ImagePadding -> 30,             ImageSize -> 400, Frame -> True]}           }, Spacings -> {.5, .5}]        }, activeTab, Alignment -> Center]      , {{tick, False}, None}      , {{b, .4}, None}      , {{t, .7}, None}      , {{f, .5*.4}, None}      , {{activeTab, 1}, None}      , TrackedSymbols :> {tick}      , Initialization :> (preCalculateStuff[b_] :=         Module[{},(*heavy computation goes here*)0.5 b])]      This displays fine: ![tab B](http://i.stack.imgur.com/hM5ZF.jpg) ![tab T](http://i.stack.imgur.com/O3Ipl.jpg) I had an issue with `TabView` resetting to the first Tab after any Manipulator change, but solved that by adding the activeTab variable. Without a `TabView` (i.e. just a `Grid`) this works fine, but when I use the `TabView`:   * the slider that does not include `ContinuousAction -> False` will only slide by a small amount at a time.   * either slider automatically goes into "Pause" state if the `Play` arrow of the control is used. Nasser's sample that uses `Grid` handles Play without this pausing issue, so I'm thinking that the trouble is with something like a temporary change of Tab focus happening somewhere under the covers. EDIT: Note that one of my end goals was to have a fairly large set of control variables all in one tab (ones associated with preCalculateStuff), without cluttering up the rest. This is attempt to conform to the size restrictions imposed on wolfram demonstrations submissions. Here's an example of a TabView with the Manipulates distributed between them. This works fine, but doesn't use the Tick method that allows the change of the variables to act as callbacks as in Nasser's code:               Manipulate[      pts1 = p;      pltrng = {{-1, 1}, {-1, 1}};           pnts = LocatorPane[ Dynamic[p, {(pts1 = p; p = #) &, (p = #) &}],        Dynamic@Graphics[Point[p], PlotRange -> pltrng], LocatorAutoCreate -> True ];           slider = Grid[{ { "q", Manipulator[ Dynamic[q, {q = #} &] , {0, 1, 0.01} ], Dynamic[q] },         { "r", Manipulator[ Dynamic[r, {r = #} &] , {0, 1, 0.01} , ContinuousAction -> False ], Dynamic[r] } }] ;           tbl = Dynamic[ Grid[ { { (Table[              With[{i = i}, {i, Dynamic[pts1[[i]]]}], {i, Length@pts1}] // TableForm) , Dynamic[q] } } ]];           ln = Dynamic@Graphics[{Red, Thick, Line[pts1]}, PlotRange -> pltrng];           TabView[{ "table" -> tbl , "locators" -> pnts , "line" -> ln , "slider" -> slider }, Alignment -> Center]      , {{p, {{-.5, -0.5}, {-.25, .5}, {.6, 0.6}}}, None}      , {{q, 0.5}, None}      , {{r, 0.5}, None}      ]      (This is based on: http://mathematica.stackexchange.com/a/5515/10)


Do Mathematica notebooks include personal metadata?

I am about to send a Mathematica notebook to someone and I would like to make sure it does not contain any information that could personally identify me. I would also like to produce pdf files from the notebook and would like them to be metadata-free. Do I need to 'scrub' the file from some intrinsic metadata (as you would need to do, carefully, say, for an MS Word file), or do they generically not include any such information? If they do contain metadata,   * what can it be?   * where is it? and   * how can I scrub it?


Schedule programing problem with integer linear programming

I know how to model this question on paper, but I don't know how doing it in Mathematica. Imagine , there is a university student who want to choose courses for this semester and he got the university program chart that looks like below in excel format : ![University program chart](http://i.stack.imgur.com/uKNWP.png) Lecturers Rating is out of 10 and it means which lecturer is giving a better score in the final exam and teaches better. Course Credit is a restriction, each semester each student should choose courses that total of course credit must be greater than 7 and less than 12: ![](http://i.stack.imgur.com/Vk6QW.png) It is not allowed to pick two courses with the same name. He/She wants to optimize two things :   1. He/She wants to maximize course credits that he/she could use (12)   2. He/She wants to pick up courses with better Lecturers Also He/She wants to get the result like a schedule table like this: ![](http://i.stack.imgur.com/7MJWs.png) Here is excel File form university.


Image fading from one corner to the other

I'm preparing a presentation where I want to place a background image on each slide (for aesthetics). These are extremely color filled images (like photos; lets use "ExampleData/lena.tif" as example), which means that once they are the background, the text becomes hard to read. So, I wanted to have some fading, like white at the top left corner (my background is not white: {253,253,251}, which means that the background color is important to be an option), and then **fading in** in the direction of the bottom right corner. This fading should not change the color in itself (if you understand what I mean: not brighter, but more or less "transparent"). Transparent fading would be the best, since it would cover for whichever slide layout we have; but not sure how to pass it correctly to another program (using MS Powerpoint). It would be great to be able to change each extremity fade value (that is, not from 0 to 1 all the time), and to change direction. To change the fading function is a plus, but I think that not needed at this time (I mean: linear in the chosen direction, or power, or etc.)


Graphics3D: Finding intersection of 3d objects and lines

I found these two nice links 1) intersecting graphics 2) Implementation of Balaban's Line intersection algorithm in Mathematica which works for 2d. However, I need to find whether a ray(line) intersects with a 3d object (it can be the bounding box np) and count how many of the lines intersect with a particular object. **The code so far**               gr1 = Graphics3D[{         Green,          Polygon[{{-10, -15, 0}, {-10, 10, 0}, {10, 10, 0}, {10, -15, 0}}],         }];     gr2 = Graphics3D[{         Yellow, Cylinder[{{4, 0, 3}, {4, 0, 6}}],         Red, Sphere[{6, 5, 2}, 2],         Blue, Cuboid[{-2, -1, 0}, {2, 2, 2}],         Blue, Cuboid[{-6, -2, 0}, {-3, 2, 4}]         }];          grR = Graphics3D[        Line[{{0, -10, 2}, #}] & /@ RandomReal[{-5, 10}, {50, 3}]];     Show[gr1, gr2, grR]      ![the scene](http://i.stack.imgur.com/GCwve.png) **Question** What is an efficient way of finding intersections in 3d and counting based on the objects. **Some useful links for people who might be interested. In computer graphics the subject falls under 'Line clipping'**   * Line clipping   * Liang–Barsky algorithm   * Liang–Barsky algorithm 3d    * Liang–Barsky algorithm java   * Line Box Intersection c


How can I rewrite my code to make it simpler?

Two months ago,I written a function `IRobot` to caculate the $I_{xx},I_{yy},I_{zz}$ and $I_{xy},I_{xz},I_{yz}$,shown as below:                 IRobot[IStyle_String, ρ_, VaribleRange_List] := Module[        {IRobotResult},         IRobotResult =         Which[             IStyle == "xx", Integrate[ρ (y^2 + z^2),               {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},                {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},               {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}],             IStyle == "yy", Integrate[ρ (x^2 + z^2),               {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},                {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},                {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}],             IStyle == "zz", Integrate[ρ (x^2 + y^2),               {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},               {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},               {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}],             IStyle == "xy", Integrate[ρ x y,                {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},                {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},                 {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}],             IStyle == "xz", Integrate[ρ x z,                {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},                 {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},                {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}],            IStyle == "yz", Integrate[ρ y z,                {z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},                 {y,VaribleRange[[2, 1]], VaribleRange[[2, 2]]},                {x,VaribleRange[[3, 1]], VaribleRange[[3, 2]]}]         ]       ]      And I can use it correctly.                IRobot["xx", ρ, {{-h1, 0}, {-r1, r1}, {-L1 - Sqrt[r1^2 - y^2], Sqrt[r1^2 - y^2]}}]      (*===>*)      1/12 h1 r1 (4 h1^2 (2 L1 + \[Pi] r1) + r1^2 (8 L1 + 3 \[Pi] r1)) ρ      However,I would like to simplify my code by `Similarity`,my trail as below:                Flatten /@Thread@List[{z, y, x},        Apply[Part[VaribleRange, ##] &, Table[{i, j}, {i, 1, 3}, {j, 1, 2}], {2}]]     (*==>*)      {{z, VaribleRange[[1, 1]], VaribleRange[[1, 2]]},       {y, VaribleRange[[2, 1]], VaribleRange[[2, 2]]},       {x, VaribleRange[[3, 1]], VaribleRange[[3, 2]]}}      ## Trial 1               IRobot[IStyle_String, ρ_, VaribleRange_List] := Module[        {IRobotResult,intlist},        intlist=         Flatten /@Thread@List[{z, y, x},        Apply[Part[VaribleRange, ##] &, Table[{i, j}, {i, 1, 3}, {j, 1, 2}], {2}]];         IRobotResult =         Which[             IStyle == "xx", Integrate[ρ (y^2 + z^2),intlist],             IStyle == "yy", Integrate[ρ (x^2 + z^2),intlist],             IStyle == "zz", Integrate[ρ (x^2 + y^2),intlist],             IStyle == "xy", Integrate[ρ x y,intlist],             IStyle == "xz", Integrate[ρ x z,intlist],             IStyle == "yz", Integrate[ρ y z,intlist]         ]       ]      Unfortunately,it failed. ## Trail2                IRobot[IStyle_String, ρ_, VaribleRange_List] := Module[        {IRobotResult,intlist},        intlist[z_,y_,x_,range_]:=         Flatten /@Thread@List[{z, y, x},        Apply[Part[range, ##] &, Table[{i, j}, {i, 1, 3}, {j, 1, 2}], {2}]];         IRobotResult =         Which[             IStyle == "xx", Integrate[ρ (y^2 + z^2),intlist[z,y,x,VaribleRange]],             IStyle == "yy", Integrate[ρ (x^2 + z^2),intlist[z,y,x,VaribleRange]],             IStyle == "zz", Integrate[ρ (x^2 + y^2),intlist[z,y,x,VaribleRange]],             IStyle == "xy", Integrate[ρ x y,intlist[z,y,x,VaribleRange]],             IStyle == "xz", Integrate[ρ x z,intlist[z,y,x,VaribleRange]],             IStyle == "yz", Integrate[ρ y z,intlist[z,y,x,VaribleRange]]         ]       ]      Also it ends in failure! ## Or I want to by                Which@@(      Flatten@{IStyle == #1, Integrate[ρ #2, intlist[z,y,x,VaribleRange]]} & @@@      {{"xx", (y^2 + z^2)}, {"yy", (x^2 + z^2)}, {"zz", (x^2 + y^2)},       {"xy", x y}, {"xz", x z}, {"yz", y z}})       (*==>*)      ![enter image description here](http://i.stack.imgur.com/oQTHi.png) to achieve                 Which[             IStyle == "xx", Integrate[ρ (y^2 + z^2),intlist[z,y,x,VaribleRange]],             IStyle == "yy", Integrate[ρ (x^2 + z^2),intlist[z,y,x,VaribleRange]],             IStyle == "zz", Integrate[ρ (x^2 + y^2),intlist[z,y,x,VaribleRange]],             IStyle == "xy", Integrate[ρ x y,intlist[z,y,x,VaribleRange]],             IStyle == "xz", Integrate[ρ x z,intlist[z,y,x,VaribleRange]],             IStyle == "yz", Integrate[ρ y z,intlist[z,y,x,VaribleRange]]         ]      **So my question is why and how to revise it.**


How to convert the following list into a LaTeX table?

How to convert the output of the following code               In[43]:= Func[x_]:=Select[Range[x],Total[IntegerDigits[#]^3]==#&];     Func[1000]      which is > Out[44]= {1,153,370,371,407} to the following form ![enter image description here](http://i.stack.imgur.com/qVtMN.png) such that I can copy it and paste to my LaTeX document without significant hassle. ## Edit I want the output of Mathematica to be consumable for LaTeX engine.               1^3 & 1\\     1^3+5^3+3^3 & 153\\     3^3+7^3+0^3 & 370\\     3^3+7^3+1^3 & 371\\     4^3+0^3+7^3 & 407\\


Having trouble assigning the result of a Solve to a function

Can anyone see what is wrong with my syntax? It looks like I have successfully assigned the result of Solve to a function. I want _Mathematica_ to return me an numeric value of the function `fc1`.               eq1 = (x - Subscript[c, 1])^2 + (Subscript[τ, c] +            Tan[Subscript[ϕ, LIN]] x)^2 == (Subscript[σ, SF] -            Subscript[c, 1])^2 + Subscript[τ, SF]^2;     eq2 = (x - Subscript[c,            1]) + (Subscript[τ, c] +             Tan[Subscript[ϕ, LIN]] x) Tan[Subscript[ϕ, LIN]] == 0;     sols = Solve[eq1 && eq2, {Subscript[c, 1], x}]          fc1[Subscript[τ, c] _, Subscript[ϕ, LIN] _, Subscript[σ, SF] _, Subscript[τ, SF] _] :=        Subscript[c, 1] /. sols[[1]][[1]]          ans = fc1[50, π/6*1.1, 1000, 800]     N[ans, 3]      ![enter image description here](http://i.stack.imgur.com/wVBWu.png)


How can I remove the bottom bar from Mathematica?

There is a bar with a zoom button on it, and it takes too much room. How can I disable it? Appreciate any help! Thank you!


How to make sure Table or Do only runs through specific values?

I often need to generate or run through very large numbers of integers (we're talking `{i, 1, 10^9}` and higher) and want to add certain integers to a list, say `list1`. So far what I've been doing is use the following structure:               list1 = {};     Do[If[PrimeQ[i] && Sort[IntegerDigits[i]] == Range[9], AppendTo[list1, i]], {i, 10^9}];     list1      (This is an example of a function that adds to `list1` only those values that are prime as well as pandigital from 1 to 9) Now I realise that this is probably a horribly inefficient way to generate lists. How can I ensure that my `Do` only runs through those functions which fulfil my criteria, e.g. being prime, or being divisible by 14, and so forth, and skips those which it doesn't need to run through - especially when I am running through 1 billion values for `i`? Is this even possible? Won't my function by definition have to run through every value anyway?


Finding all elements within a certain range in a sorted list

Suppose we have a sorted list of values. Let's use `list = Sort@RandomReal[1, 1000000];` for this example. I need a _fast_ function `window[list, {xmin, xmax}]` which will return all list elements $x$ for which $x_\textrm{min} \le x \le x_\textrm{max}$. How can this be implemented in _Mathematica_? I am looking both for _fast_ and for _elegant_ solutions. The direct solution is implementing binary search, but there are several ways to do this, and perhaps _Mathematica_ already has something built in that I am not aware of. * * * Here's the most naïve implementation:               window[list_, {xmin_, xmax_}] :=       list[[LengthWhile[list, # < xmin &] + 1 ;; LengthWhile[list, # <= xmax &]]]      * * * **Summary:** Here are the timings I get for the different solutions for some random data of a million machine reals which also contains duplicates:   * My original naive solution: 3.85 s   * Leonid, using binary search: 0.01 s (close to the measurable limit, $\log n$ complexity)   * R.M., using `Clip`: 0.59 s (linear time, no sorting required)   * faleichik, using `Nearest`: 1.29 s (strangely, this also runs in linear time, by measurement)   * kguler, using `Map` (which autocompiles) and `Pick`: 0.30 s (also linear time, the fastest simple linear time solution so far, does not require sorting either) For sorted data, the fastest solution is Leonid's, which uses binary search and has logarithmic complexity. For unsorted data, the fastest (and also one of the simplest) is kguler's. A not so obvious trick was using `Boole` on the condition to allow it to be automatically compiled.


How does NIntegrate evaluate a piecewise range of x,y?

Could someone explain to me how Mathematica evaluates the following integration.               NIntegrate[ ψ[x, y] mask[x,y],                  {x, 0, 25, 35, 65, 75, 100}, {y, 0, 25, 35, 65, 75, 100}]      How would this be expressed analytically?   `ψ` is non-zero and `mask` is zero in the `25 - 35` and `65 - 75` square region defined by               mask[x_, y_] := Piecewise[{{1 , y < 25}, {1, y > 75}, {1, x < 25},                                 {1, x > 75}, {1, 35 < y < 65 && 35 < x < 65}}, 0]      How would this be expressed analytically, and is it any different to               NIntegrate[ ψ[x, y] mask[x,y], {x, 0, 100}, {y, 0, 100}]       I don't have access to _Mathematica_ and am having discrepancies trying to port this to _Matlab_.


Computation of Hankel Transform using FFT (Fourier)

To address circular symmetric cases of 2D Fourier Transformations the so called Hankel Transform can be applied (for a detailed derivation of the relation between the 2D Fourier transform and the 1D Hankel transform see Link). For more complex or numerically tabulated radial functions, a numeric implementation of the Hankel transform (similiar to FFT) would come in handy.There has been an interesting proposal by Oppenheim from 1980 (full text is available on the Web), which explains the use of the highly optimized FFT algorithm to do the Hankel transform. Is anybody aware of such an implementation of the Hankel transform in Mathematica?


Opening new notebooks with a non-default window size

I'd like to set Mathematica (8.0.4.0) up so it opens new notebooks with the `"NaturalColor"` stylesheet and with a window size like {800,770}. I tried to change default stylesheet via:               " OptionInspector -> Global Preferences -> Global Options\File Locations\Default Style Definition "      and I get this ugly notebook instead of this one. And when I Change the value of `"WindowSize"` from `"Medium"` to `"{800,770}"` under `"Notebook Options\Window Properties"`, it just does nothing. This is driving me crazy, any ideas ?


How to manipulate web pages on Mathematica?

I wanted to input some data on this page through Mathematica: http://www.fundamentus.com.br/buscaavancada.php Then I would press the "buscar" button also through mathematica coding and get the results on mathematica. The most similar post i've found was this one: Web Browsing Automation with Mathematica I'm trying to import through the Import function:                   Import["http://www.fundamentus.com.br/buscaavancada.php", "Data"]      When i do that, it shows this:               {{{{"Página inicial", "Investimento consciente",      "Entre em contato"}, {"Detalhes", {"Balanço patrimonial",       "Demonstrativos de resultados",       "Indicadores fundamentalistas"}, {"Balanços em Excel",       "Proventos"},      "Histórico de cotações"}}, {{"Preencha apenas os campos que serão \     usados na pesquisa", "Use . (ponto) como separador decimal",      "Utilize o formato decimal para representar porcentagens. Ex: \     Para 15% digite 0.15"}, {{"? P/L (Preço sobre lucro)",       "min max"}, {"? P/VP (Preço sobre Valor Patrimonial)",       "min max"}, {"? PSR (Preço sobre Receita Líquida)",       "min max"} [...]      And from here i'm stuck. Any tips?


How to add big data into a CDF file, without it being loaded into memory

I have 1 GB of data that I would like to add to a CDF file, but I would like to avoid it being loaded into memory when someone opens the file (Free Player). One gigabyte of info takes a lot of computer memory, and the user of the file doesn't need to have it all in memory (specially when the way Mathematica or Player manages the opening of the file originates, for a couple of seconds, a double memory consumption which will go above a 32 bit process limit). So, this would work as something like a DB included in the CDF file. A dynamic structure interface will then allow the user of the CDF file to load only a part of the data into memory (`Set` a variable to a part of the total data).


Different colors for nodes in tree plot

I have some list of numbers which I am plotting using TreePlot. This is the code:               Plotting[S_, u_, d_, n_] :=        Module[{coor = Flatten[Table[Table[{i, j - 1 - i/2}, {j, 1, i + 1}], {i, 0, n}],            1],               steps = Flatten[Table[ Table[              {S*u^k*d^(l - k) -> S*u^k*d^(l - k + 1), S*u^k*d^(l - k) -> S*u^(k + 1)*d^(l - k)},                               {k, 0, l}], {l, 0, n - 1}]]},         TreePlot[steps, DirectedEdges -> True, VertexLabeling -> True,                  VertexCoordinateRules -> coor, PlotLabel -> S]];          Plotting[S, u, d, 4]      And now, i need some of the nodes to be painted in different color. For example dSu, Su^3 and d^4S. Is there a way to do it?


No values in plot

I am trying to plot the following function:               Plot[(0.014901060131333028` ((2 - 0.1` x)^2.5`)^2.5`)/((1 +          0.1` x Sin[Pi])^1.5`)[0.185903200617956`], {x, 0, 10}]      However, when I do I get nothing on graph. But if I plug in specific numbers then it is clear there is a value. Any help would be great


Using only two colors in a ListPlot3D

The data I have given here will plot the data in `ListPlot3D` function and gives the visualization of bars on the plot. I want to customize the color for the bars in the plot. I need to plot them in two colors — one for side of the bar and another for the top surface of the bar. How can I set the color function to achieve this?               finalData = {{14.38, 18.1, 70}, {14.385714285714286`, 54.`,      70}, {42.857142857142854`, 18.1`, 70}, {42.857142857142854`, 54.`,      70}, {14.385714285714286`, 54.1`, 20}, {14.385714285714286`,      90.`, 20}, {42.857142857142854`, 54.1`, 20}, {42.857142857142854`,      90.`, 20}, {14.385714285714286`, 90.1`,      15}, {14.385714285714286`, 126.`, 15}, {42.857142857142854`,      90.1`, 15}, {42.857142857142854`, 126.`,      15}, {14.385714285714286`, 126.1`, 25}, {14.385714285714286`,      162.`, 25}, {42.857142857142854`, 126.1`,      25}, {42.857142857142854`, 162.`, 25}, {14.385714285714286`,      162.1`, 30}, {14.385714285714286`, 180, 30}, {42.857142857142854`,      162.1`, 30}, {42.857142857142854`, 180,      30}, {42.957142857142856`, 18.1`, 14}, {42.957142857142856`, 54.`,      14}, {71.42857142857143`, 18.1`, 14}, {71.42857142857143`, 54.`,      14}, {42.957142857142856`, 54.1`, 60}, {42.957142857142856`, 90.`,      60}, {71.42857142857143`, 54.1`, 60}, {71.42857142857143`, 90.`,      60}, {42.957142857142856`, 90.1`, 14}, {42.957142857142856`,      126.`, 14}, {71.42857142857143`, 90.1`, 14}, {71.42857142857143`,      126.`, 14}, {42.957142857142856`, 126.1`,      24}, {42.957142857142856`, 162.`, 24}, {71.42857142857143`,      126.1`, 24}, {71.42857142857143`, 162.`,      24}, {42.957142857142856`, 162.1`, 34}, {42.957142857142856`, 180,      34}, {71.42857142857143`, 162.1`, 34}, {71.42857142857143`, 180,      34}, {71.52857142857142`, 18.1`, 18}, {71.52857142857142`, 54.`,      18}, {100.`, 18.1`, 18}, {100.`, 54.`, 18}, {71.52857142857142`,      54.1`, 28}, {71.52857142857142`, 90.`, 28}, {100.`, 54.1`,      28}, {100.`, 90.`, 28}, {71.52857142857142`, 90.1`,      23}, {71.52857142857142`, 126.`, 23}, {100.`, 90.1`, 23}, {100.`,      126.`, 23}, {71.52857142857142`, 126.1`, 33}, {71.52857142857142`,      162.`, 33}, {100.`, 126.1`, 33}, {100.`, 162.`,      33}, {71.52857142857142`, 162.1`, 38}, {71.52857142857142`, 180,      38}, {100.`, 162.1`, 38}, {100.`, 180, 38}, {100.1`, 18.1`,      12}, {100.1`, 54.`, 12}, {128.57142857142858`, 18.1`,      12}, {128.57142857142858`, 54.`, 12}, {100.1`, 54.1`,      22}, {100.1`, 90.`, 22}, {128.57142857142858`, 54.1`,      22}, {128.57142857142858`, 90.`, 22}, {100.1`, 90.1`,      17}, {100.1`, 126.`, 17}, {128.57142857142858`, 90.1`,      17}, {128.57142857142858`, 126.`, 17}, {100.1`, 126.1`,      27}, {100.1`, 162.`, 27}, {128.57142857142858`, 126.1`,      27}, {128.57142857142858`, 162.`, 27}, {100.1`, 162.1`,      32}, {100.1`, 180, 32}, {128.57142857142858`, 162.1`,      32}, {128.57142857142858`, 180, 32}, {128.67142857142858`, 18.1`,      16}, {128.67142857142858`, 54.`, 16}, {157.14285714285714`, 18.1`,      16}, {157.14285714285714`, 54.`, 16}, {128.67142857142858`,      54.1`, 26}, {128.67142857142858`, 90.`, 26}, {157.14285714285714`,      54.1`, 26}, {157.14285714285714`, 90.`,      26}, {128.67142857142858`, 90.1`, 21}, {128.67142857142858`,      126.`, 21}, {157.14285714285714`, 90.1`,      21}, {157.14285714285714`, 126.`, 21}, {128.67142857142858`,      126.1`, 31}, {128.67142857142858`, 162.`,      31}, {157.14285714285714`, 126.1`, 31}, {157.14285714285714`,      162.`, 31}, {128.67142857142858`, 162.1`,      36}, {128.67142857142858`, 180, 36}, {157.14285714285714`, 162.1`,      36}, {157.14285714285714`, 180, 36}, {157.24285714285713`, 18.1`,      20}, {157.24285714285713`, 54.`, 20}, {185.71428571428572`,      18.1`, 20}, {185.71428571428572`, 54.`, 20}, {157.24285714285713`,      54.1`, 90}, {157.24285714285713`, 90.`,      90}, {185.71428571428572`, 54.1`, 90}, {185.71428571428572`, 90.`,      90}, {157.24285714285713`, 90.1`, 25}, {157.24285714285713`,      126.`, 25}, {185.71428571428572`, 90.1`,      25}, {185.71428571428572`, 126.`, 25}, {157.24285714285713`,      126.1`, 35}, {157.24285714285713`, 162.`,      35}, {185.71428571428572`, 126.1`, 35}, {185.71428571428572`,      162.`, 35}, {157.24285714285713`, 162.1`,      40}, {157.24285714285713`, 180, 40}, {185.71428571428572`, 162.1`,      40}, {185.71428571428572`, 180, 40}};     ListPlot3D[finalData, Filling -> Bottom, RotationAction -> "Clip",AxesLabel -> {x, y, z}, PlotRange -> {{0, 200}, {0, 200}, {0, 100}}]


Troubleshooting an NDSolve::ndfdmc error message

Τhe following code               Ay[ξ_] := A0*(1 - κ^2)^.5*Exp[-(δ ξ - φ)^2/2] Sin[ξ]     Az[ξ_] := A0*κ*Exp[-(δ ξ - φ)^2/2] Cos[ξ]     Ay1[ξ_] := D[Ay[ξ], ξ]     Az1[ξ_] := D[Az[ξ], ξ]     j1 = DSolve[{y''[ξ] + r^2 y[ξ] == r/Δ (α2 - Az[ξ]) - 1/Δ Ay1[ξ],          z''[ξ] + r^2 z[ξ] == -1/Δ Az1[ξ] - r (α1 - Ay[ξ]), y[0] == yo,          y'[0] == Pyo/Δ, z[0] == zo, z'[0] == Pzo/Δ}, {y, z}, ξ]          Py[ξ_] := D[y[ξ] /. j1, ξ]     Pz[ξ_] := D[z[ξ] /. j1, ξ]     P1[ξ_] := Py[ξ]^2 + Pz[ξ]^2     A0 = 7; δ = 1/15; r = 1; φ = 5; κ = 1/Sqrt[2]; α1 = 0; α2 = 0; Δ = 1;      yo = 0; zo = 0; Pyo = 0; Pzo = 0;     j2 = NDSolve[{x'[ξ] == P1[ξ], x[0] == 0}, x[ξ], {ξ, 0, 1.6*2 π/δ}]      produces the message > NDSolve::ndfdmc: Computed derivatives do not have dimensionality consistent > with the initial conditions. >> How can I fix this so that I can plot `x[ξ]`?               Plot[x[ξ] /. j2, {ξ, 0, 1.6*2*π/δ},       PlotStyle -> Automatic, PlotRange -> All, AxesOrigin -> {0, 0}]


Why does Mathematica evaluate Sin[2.0] but not Sin[2]?

I can't understand why is it that               In[88]:= Sin[2]     Out[88]= Sin[2]      while               In[89]:= Sin[2.0]     Out[89]= 0.909297      I even tried               In[90]:= 2 + Sin[2]     Out[90]= 2 + Sin[2]      thinking that it might force the evaluation, but apparently not... Now, I know that I can just do this               In[91]:= N[Sin[2]]     Out[91]= 0.909297      but I am curious why doesn't just `Sin[2]` work. Even though the _Documentation Center_ page for `Sin[x]` contains _Possible Issues_ examples this behavior is not mentioned. I know from some experience with **Python** and **C** that expressing a integer number, e.g. **2** , as a rational number, i.e. **2.0** , can influence the way an expression is evaluated, e.g.               #Python code         >>> 5 / 2     2     >>> 5 / 2.0     2.5      Even though I personally don't agree with this behavior (I think there should be different operators for _integer division_ and _rational division_ since it will always cause some confusion) if you just see some examples it becomes clear what happens. Here I don't have any idea what **Mathematica** thinks when it sees `Sin[2]` _**Note_** :   * I'm using **Mathematica v7.0**   * I'm basically a beginner.   * I don't plan and have time to go through a tutorial, I just wanted to play around. I expected the simple/common things to behave intuitively enough.   * I also appreciate if you point me to some resources where this behavior is explained.


three-dimensional graphic objects that are not simple cuboids

I am trying to draw some graphics with _Mathematica_. The objects I want to draw are just a little bit more complex than a cuboid -- the difference being that the top and bottom faces are of different depth. Below are two examples of the objects I would like to draw.               p01 = RegionPlot3D[ y <= 1 - 0.5 z, {x, 0, 1}, {y, 0, 1}, {z, 0, 1},        Mesh -> None]          p02 = RegionPlot3D[        y <= 0.5 + 0.5 (z - 1), {x, 0, 1}, {y, 0, 1}, {z, 1, 2},        Mesh -> None]       It would be great if I could make these objects using 3-D graphics primitives found in _Mathematica_. Then I would be able to make 3-D graphics, placing the objects in relation to one another. Below is an example of what I would like to do, basically creating a set of these 6-faced objects and stacking them in relation to one another.               cubeA = Cuboid[{0, 0, 0}, {1, 0.5, 1}];          cubeB =  Cuboid[{0, 0, 1}, {1, 1, 2}];          Graphics3D[{cubeA, cubeB}]      The example above uses the built-in `Cuboid` object. The objects I would like to make are (only so slightly) more complex than this. I can create the geometry I am interested in with RegionPlot3D, but I cannot easily combine these. For example, the following fails:               Graphics3D[{p01, p02}]      I tried to do this with Polygon function, but couldn't quite determine how to extend the examples provided to making a 6-faced objects. Any recommendations or suggestions would be welcome. Thanks.


How can I use assumptions with FindRoot?

I have something like               FindRoot[f[x], {x, a}]      Now I want `FindRoot` to constrain the solutions to 0 < x < 1\. How can I obtain this?


Connected components of a graph

I am trying to find the number of connected components of numerous named graphs within Combinatorica. The obvious answer seems to be:               Length[GraphData[G,"ConnectedComponents"]]        but this fails. What am I doing wrong? Does this property only work when the number of connected components is >= 2?


Use of RegionFunction with Graphics3D?

I'd like to plot in 3D a long list of polygons created with `TetGenConvexHull`, but only in regions specified by a function. Is that possible? As I have it my `RegionFunction` only applies to some points, and not to my `Graphics3D` `Polygon` data:               Show[{ListPointPlot3D[{{-0.57735, 0., 0.8165}, {-0.866025, -0.5, 0.}},         RegionFunction ->          Function[{x, y, z},z <= .6],         BaseStyle -> {Black, PointSize[Large]}, AxesLabel -> {x,y,z},Boxed -> False,        AxesOrigin -> {0,0,0}, BoxRatios -> {1, 1, 1},        PlotRange -> {{-1, .1}, {-.6, .6}, {-.1, 1}}],       Graphics3D[{Opacity[0.34], EdgeForm[], Red,                  Polygon[{{-0.57735, 0., 0.8165}, {0., 0., 0.}, {-0.866025, -0.5, 0.}}]}],        Graphics3D[{Opacity[0.34], EdgeForm[], Blue,                  Polygon[{{-0.57735, 0., 0.8165}, {-0.866025, 0.5, 0.}, {0., 0., 0.}}]}]}]      ![Output from above code](http://i.stack.imgur.com/jV87o.jpg) Notice that `RegionFunction` clips the first datum in `ListPointPlot3D` ({-0.57735, 0., 0.8165}), but not the `Graphics3D` `Polygon` as I would like. I'd like the `Polygon` surfaces to be clipped/truncated wherever they intersect the `RegionFunction` ( _not_ for the surface to be omitted entirely, given a single intersection location/coordinate). Perhaps there is a way to transform `Polygon` data into `ListSurfacePlot3D` data, which can be utilized with `RegionFunction`... Note: I'm actually plotting a lot of complex polygons (not just 2 planes as in the code above), making me want to stick with `Polygon` and `Graphics3D`.


NumberForm and units

NumberForm can be used to print Quantities to a specified precision. For example,               x=Quantity[5.123456789,"Meters"];     5.12346 m     Print[NumberForm[x,{4,2}]]     5.12 m      This does exactly what I want, but it has an undesirable effect for units with exponents. For example,               y=Quantity[5.123456789,"Meters"/"Seconds"^2];     5.12346 m/s^2     Print[NumberForm[y,{4,2}]]     5.12 m/s^2.00      I'd like the precision specification to apply to the quantity, not to the units. Is there a way to do that?


Changing size and color of a Text on version 9

I am running v9 on mac pro and think that I am doing something wrong. When commenting the solution of a particular exercise I add a text cell (command 7) and type the comment which is nothing more than a sentence with some mathematical expressions (control ( - expression- control )). To change the size and color of the whole comment, I simply highlight it and Format - Size or Color - to the desired size and color. The change does not apply to whole comment! Why? (I think that is due to the expressions). For instance, if the comment is as follows > Here is an example, if $P = 1$ then the whole solution depends on the number > of ... the change applies up to $P = 1$. The rest of the sentence is unchanged. Many thanks Ed


Module vs DynamicModule for a dynamic variables in a grid. || Spelling Bee

When my daughter asked me help with her spelling homework, for me the obvious thing to do was to write a _Mathematica_ program for it. The words:               words = {"lightning", "thunder", "cloudy"};      The code:               Grid[      Module[{x = 0, t = 0},         {          #,          Button["Start", t = Hold@AbsoluteTime[] - AbsoluteTime[]],           Button[Style["\[Checkmark]", Darker@Green], t = ReleaseHold[t]; x++],          Button[Style[    "\[Times]",        Red  ], t = ReleaseHold[t]; x--],          Dynamic[x],          Dynamic[Clock[]; ReleaseHold[t]]          }         ] & /@ words]      Which produces this output: ![screenshot](http://i.stack.imgur.com/2cuWe.png) So when I ask her a word, I click "start". Then I click ✔ or × if her answer is right or wrong respectively. I plan to keep track of time to answer, so the timer now shows how much time it took to answer. So my question is: Why do I have to use `Module` instead of `DynamicModule`? For some reason the `Grid` command does not work if I use `DynamicModule`. On the other hand, if I use `Module` (as it is shown), then the syntax highlighter shows my "t" and "x" variables in red as if I am doing something wrong: ![enter image description here](http://i.stack.imgur.com/TFkw6.png) **Update:** I have just realized that using `Module` instead of `DynamicModule` is not a viable option as the scores are lost when you reopen the notebook. **Update 2:** For the record, this is the finished program incorporating the advice from Mr.Wizard and kguler               DynamicModule[{x, t, status, h},      x[_] = 0;      t[_] = 0;      status[_] = False;      h[_] = {};      Column[{Grid[         MapIndexed[{            #,            Button["Start",                    Speak@#; status[#2] = True;                    t[#2] = Hold@AbsoluteTime[] -AbsoluteTime[],                    Enabled -> Dynamic[! status[#2]]],            Button[Style["\[Checkmark]", Darker@Green],                    t[#2] = ReleaseHold[t[#2]]; x[#2]++; AppendTo[h[#2], t[#2]];                    status[#2] = False,                   Enabled -> Dynamic[status[#2]]],            Button[Style["\[Times]", Red],                   t[#2] = ReleaseHold[t[#2]]; x[#2]--; AppendTo[h[#2], -t[#2]];                   status[#2] = False,                    Enabled -> Dynamic[status[#2]]],            Button["spell", Speak@StringJoin[Riffle[Characters[#], ","]]],            Dynamic[x[#2]],            Dynamic[Clock[]; ReleaseHold[NumberForm[t[#2], 2]]],            Dynamic@             If[Length@h[#2] > 0,               Module[{z = Transpose[{Abs[#], Sign[#]} & /@ h[#2]]},                Graphics[                (Rectangle @@@                  (Partition[{Accumulate[First@z],Last@z}\[Transpose],2,1,{2,2},{{0, 0}}] /.                  {{x1_, y1_Integer}, {x2_, y2_Integer}} -> {{x1 + 0.2, 0}, {x2, y2}})) /.                  {Rectangle[{x1_,0}, {x2_, 1}] -> {Darker@Green, Rectangle[{x1, 0}, {x2, 1}]},                    Rectangle[{x1_,0}, {x2_,-1}] -> {Red, Rectangle[{x1,0}, {x2, -1}]}},                ImageSize -> {Automatic, 20},                 PlotRange -> {-1, 1}]],               ""             ]         } &, words],         Alignment -> Left],         Row[{Button[           "reset", (x[{#}] = 0; t[{#}] = 0; h[{#}] = {}) & /@             Range@Length@words], Spacer[10]}]}]]      ![enter image description here](http://i.stack.imgur.com/J6OWs.png)


What's the kernel launch command syntax?

I want to configure a remote kernel, but the box it'll run on doesn't have a fixed hostname or IP address. I can however get its IP address by running a shell script. (For the moment I'm only worrying about unix-oid systems: linux and MacOS -- I'll deal with windows later if I figure this out.) Now, it seems this ought to be easy: all I need to do is use the standard backquote syntax to insert the output of the script into the link command in the appropriate place. But apparently Mathematica is already using backquotes in some other way. This is the generic Launch command it configures: > `java` -jar "`mathssh`" leon@hostname math -mathlink -LinkMode Connect > -LinkProtocol TCPIP -LinkName "`linkname`" -LinkHost `ipaddress` You see it's got java, mathssh, linkname, and ipaddress enclosed in backquotes. But these are not executables (or if they are, they're nowhere I can find). So, either it's using backquotes for some internal variable substitution, or it installs executables with those names somewhere in the path before passing this command to a shell. How can I find out what (if anything) actually gets passed to a shell?


How to mark an image?

How can I place a mark, like a cross-hair (to suggest "X marks the spot") and a text label associated with it, at a particular position on an image (mine in particular is `Colorize`d)?


Why can't I use Sequence to perform a Select like task?

Suppose I wanted to write down a list of $p^2$, for $p$ a prime between $1$ and $20$. I would expect               Table[If[PrimeQ[k], k^2, Sequence[]], {k, 1, 20}]      to work. In fact, this produces,               {Null, 4, 9, Null, 25, Null, 49, Null, Null, Null, 121, Null, 169, Null, Null, Null, 289, Null, 361, Null}      Why does this happen, and is there a variant which does work the way I expect? Of course, I can just do               Map[(#^2) &, Select[Range[20], PrimeQ]]      I don't have a real reason to avoid this, but it feels less readable to me. UPDATE: Given the answers I'm seeing, I should point out that this is meant to be a toy example and the actual code involves boolean functions much messier than `PrimeQ[]`, for which there is no analogue of `Prime[]` available. But Szabolcs answer is exactly what I was looking for, thanks!


ListLogLinearPlot logarithmic axis tickmarks

When using `ListLogLinearPlot` the abscissa labels every other decade. Is there a way to tell Mathematica to label each decade? I need to use this inside `Manipulate` where the axes will scale according to the chosen variable. ![enter image description here](http://i.stack.imgur.com/hVtf4.jpg) Here is some example code of the kind I am using:               s[x_] := (10^-9) x^2; t[x_] := (10^-3) x^2;      Manipulate[ ListLogLinearPlot[{ Table[{a s[T], T}, {T, 0, 1000}],       Table[{a t[T], T}, {T, 0, 1000}] },       GridLines -> None, PlotStyle -> {Thickness[0.005]}, Joined -> True,       PlotRange -> Automatic], {a, 10^-8, 10^8}]


Is there a way to globally set when to treat a very small number as zero?

I understand that I can use `Chop` to force a very small number to be treated as `0` and can use `PossibleZeroQ` to as a way to test whether such a number might effectively be `0`, but applying `Chop` every time a small number is close to zero in order to "make it be" zero is tedious and error prone; while `PossibleZeroQ` seems to have its own ideas about what constitutes `0`. Are there global settings that will let me   * treat every number smaller than some specified value as `0`, effectively applying `Chop` automatically to all results; and   * specify how large a number `PossibleZeroQ` should recognize as `0`?


LinearSolveFunction unusable if stored to disk?

I encounter a problem when saving a `LinearSolveFunction` to disk, where the LinearSolveFunction is obtained with `LinearSolve` for a non-square matrix. If I read the function object from disk, it can no longer be applied to an array. For example:               In[1]:= a = LinearSolve[{{1, 0}, {0, 1}, {1, 0}}];     In[2]:= a >> "tst.m";     In[3]:= b = << "tst.m";      At this point, `a===b` and the displayed `FullForm` of a and b are equal. However:               In[4]:= a[{0, 0, 0}]     Out[4]= {0, 0}          In[5]:= b[{0, 0, 0}]     Out[5]= LinearSolveFunction[{3,2},{2,False,{{{1,0},{0,1},{1,0}}},{0,Automatic,Automatic},0}][{0,0,0}]      I am using Mathematica 8.0.4 (64bit) on Linux. Is this a bug ? Is there a good workaround ? Of course, I could avoid caching the `LinearSolve` result altogether and save only the matrix to be "inverted".


Generating date ranges

How can I, in one line, generate all the dates with a constant day difference from one date to another? For example, if I'm interested in dates in the interval staring from 24.4.2012 till 2015 and a 28 day difference.


Rounding problems inside InputField

Consider the following `InputField`               InputField[Dynamic[h2,       If[# === Null, h2 = h2, h2 = Round[#, 0.001]] &], Number]      The purpose of the second argument of Dynamic is to avoid someone entering a value with more than 3 decimal places (or emptying the field after some value has been assigned). For example, entering 0.4691 immediately reassigns the `InputField` to 0.469. The problem is that entering the number 0.468 renders 0.4680000000000001. I imagine it’s something to do with the representation of 0.468 in binary, etc. How can I avoid this after rounding action? **EDIT:** After some more testings, I see that it is the `Number` part that is causing the problem. This works "badly":               InputField[Dynamic[h2], Number]      This works OK:               InputField[Dynamic[h2]]      ![enter image description here](http://i.stack.imgur.com/OsCUs.gif) If you do `Do[h2 = i; Pause[0.1], {i, 0.04, 0.08, 0.001}]`, you can get a good picture of the problem: ![enter image description here](http://i.stack.imgur.com/Rgx0h.gif) How can I avoid this `Number` side effect?


How can I make hatching filling of plot

How can I make hatching filling of plot Like this: ![hatching filling plot](http://i.stack.imgur.com/dYRYZ.png) I use another one plot with shifting to make filled area above:               plot := ListLinePlot[       Table[{x1[w], x2[w]}, {w, 1.5, 5, .005}],            Filling -> Top,       FillingStyle -> White       ]          fill := ListLinePlot[       Table[{x1[w] - 0.01, x2[w] - 0.02}, {w, 1.5, 5, .005}],       Filling -> Top,       FillingStyle -> LightGray,       PlotStyle -> LightGray       ]          Show[fill, plot]      ![plot](http://i.stack.imgur.com/pkgdl.png) How can I make hatching filling of fill-plot?


Plotting different PDFs of a distribution in the same graph

How would I plot the PDF (probability density function) of `WeibullDistribution[1/5, 50]`, `WeibullDistribution[1/4, 40]`, `WeibullDistribution[1/3, 30]` and `WeibullDistribution[1/2, 20]` in the same graph?


Change locator object appearance inside Manipulate

I have read earlier discussions of changing Locator appearance in Manipulate. I would like to change the rendered size of the locator object based on one of the manipulate variables. I can't get anything to work. Here is an attempt. source is an image, with dimensions {3716,3449}               isize = 240;     dim = ImageDimensions[source]     height = dim[[2]];     Manipulate[(       locator =         Graphics[{Red, FaceForm[Opacity[.1]],           EdgeForm[Directive[Thin, Red]], Rectangle[]},          ImageSize -> (isize size/height)];       sub = ImageTake[source, height - (pt[[2]] - {0, size - 1}),          pt[[1]] + {0, size - 1}];       Row[{Image[source, ImageSize -> isize],          Image[sub, ImageSize -> isize]}])      , {{pt, {820, 1810}}, Locator, Appearance -> locator}      , {{size, 100}, 10, 1000}]


Why is my answer being displayed with "Subscript^(0,1)[a,b]"?

I type in my equations using ctrl+- to make it look nice and my answer outputs in "Subscript^(0,1)[a,b]" form? What is going on? In the answer some bits are displayed with the actual subscripts and some are displayed in the above form, even for the same variable. Edit: more specifics I am taking the partial derivative of a function H wrt to b. H is a function of many variables one of which is a_b. Is it possible that Mathematica is trying to take the derivative of the subscript because there is a b in there?               H=d k2 + c^2 k4 + k5 s^2 + k1 U +       k3 \[Theta] + (g (1 - d - U - \[Theta]) \[Theta] -          U (1 + s Subscript[e, s])) Subscript[\[Lambda],        1] + (-c d + s U Subscript[e, s]) Subscript[\[Lambda], 2] +       U Subscript[\[Lambda], 3]      and               DHds = Simplify[D[H, s]]


Symbolically Expanding One-Variable q-hypergeometric Series

In general, how do I get Mathematica to symbolically expand various infinite series to an arbitrary degree of accuracy? I deal with q-hypergeometric series quite frequently, and specifically want to expand series like the following: $$\sum_{n=0}^{\infty}\frac{(-1)^nq^{6n^2}}{(q^3;q^3)_n(-q;q)_{3n}},$$ where $(a;q)_n$ denotes the standard QPochhammer symbol $\prod_{k=0}^{n-1}(1-aq^k)$. I would like to input a maximal degree, and for Mathematica to output the first few terms of the infinite series up until the specified degree. For example, if I inputted $13$, I would want Mathematica to output (I believe, doing this by hand) $q^6-q^7+q^{10}-q^{11}+q^{12}-q^{13}$. I cannot get the existing series functions to give something as clean as what I want. One preliminary input I tried was               FunctionExpand[Sum[(-1)^n/QPochammer[q^3,q^3,n],{n,0,10}]],      which returned               1 - 1/(1 -        q^3) + 1/((1 - q^3) (1 - q^6)) - 1/((1 - q^3) (1 - q^6) (1 -          q^9)) + 1/((1 - q^3) (1 - q^6) (1 - q^9) (1 - q^12)) - 1/((1 -          q^3) (1 - q^6) (1 - q^9) (1 - q^12) (1 - q^15)) + 1/((1 -          q^3) (1 - q^6) (1 - q^9) (1 - q^12) (1 - q^15) (1 -          q^18)) - 1/((1 - q^3) (1 - q^6) (1 - q^9) (1 - q^12) (1 -          q^15) (1 - q^18) (1 - q^21)) + 1/((1 - q^3) (1 - q^6) (1 -          q^9) (1 - q^12) (1 - q^15) (1 - q^18) (1 - q^21) (1 -          q^24)) - 1/((1 - q^3) (1 - q^6) (1 - q^9) (1 - q^12) (1 -          q^15) (1 - q^18) (1 - q^21) (1 - q^24) (1 - q^27)) + 1/((1 -          q^3) (1 - q^6) (1 - q^9) (1 - q^12) (1 - q^15) (1 - q^18) (1 -          q^21) (1 - q^24) (1 - q^27) (1 - q^30)),      which is not the form of output that I want because the sum is not fully expanded as a polynomial in $q$. Also, if I insert an additional `QPochhammer[-q,q,Infinity]` out front, it leaves the $(-q;q)_{\infty}$ unexpanded because there is no degree specification. (This is why I want to implement the degree specification rather than settling for expanded partial sums.) These are two central issues that I'm not sure how to address.


Need help with C Code Generator

I'm trying to use the _Mathematica_ C Code Generator package to generate code that is to be included in a web application by a developer. I don't know any C, and this seems to be the only way to integrate my model with the web-app. I am having a lot of difficulties getting off the ground. A persistent error seems to be that my iteration indices are not recognised as integers. Here's an example:               Needs["CCodeGenerator`"]     funct = Compile[{{M, _Real, 2}, {l, _Integer}},       Module[{matrix = M, lag = l },        columns = Length[Transpose[matrix]];         Flatten[            Join[ {{{Table[1, {columns - lag + 1}]}},            Table[matrix[[;; , lag - i + 1 ;; columns - i + 1]] , {i, 1, lag}]} ] , 2]         ], {{i, _Integer}}     ]      This produces the following error: > `Compile::cpintlt`: "1;;All at position 2 of > `matrix[[1;;All,lag-i+1;;columns+i+1]]` should be either a nonzero integer > or a vector of nonzero integers; evaluation will use the uncompiled > function." Finally when I export the C code, I get errors like > `CCodeGenerate::wmreq`: "The expression > `Function[{M,l,iCompile$18},Block[{i=iCompile$18},{All,i}]]` requires > _Mathematica_ to be evaluated. The function will be generated but can be > expected to fail with a nonzero error code when executed. " Any help would be greatly appreciated.


Problem with Plot and ParametricNDSolve

This is my first question on this site, I hope it is written in an understandable way. Let's start. My aim is to plot a certain parametric region, with $x$ and $y$ coordinates given by the following formulas. First of all I write down some functions that, once I define a particular potential $U$ of two variables **#1** and **#2** , will calculate some of its derivatives and things like that (since I will need them later for the construction of the plot). Here below are the formulas, the last three are the ones that will be appearing in the following lines of code:               epsilontemp[U_] = D[U[#1,#2],#1])^2/(U[#1,#2])^2/2&;          etatemp[U_] = D[U[#1,#2],{#1,#2}])/U[#1,#2]&;          inttemp[U_] = D[U[#1,#2],#1])/(U[#1,#2])&;          epsilonhelp[U_,a_] = epsilontemp[U][a,1];          etahelp[U_,a_] = etatemp[U][a,1];          inthelp[U_,a_] = inttemp[U][a,1];      Now I write down the potential: it is an infinite series, but Mathematica recognizes it as the sum of two _PolyLog_ functions:               U3=Sum[Cos[n*#1/#2]/n^5,{n,1,Infinity}]&;      in the following equations I will call always **#1** as $a$ and **#2** as $b$. Now: I must find the value of $\frac{a}{b}$ such that epsilontemp[U3][a,b]=1 (this equation can be written more simply in the way I did in the code right below), and I found that this piece of code does the job perfectly (the particular starting point was chosen after I did a "Plot of the equation", in order to find approximately the root):               phiendtemp[b_?NumericQ] := FindRoot[inthelp[U3,x]-Sqrt[2]*b,{x,48/10},MaxIterations->Infinity,Compiled->False][[1,2]];      and in order to work more easily with this quantity, I defined an _InterpolatingFunction_ in the following way:               phiend[b_] = FunctionInterpolation[phiendtemp[btemp],{btemp,3,5}][b];      Now the next step consist in solving numerically a differential equation, with two parameters: one enters simply in the equation while the other enters in the initial condition. The new command of Mathematica _ParametricNDSolve_ was used:               phicmbtemp1 = ParametricNDSolve[y'[eFolds]-b^{-2}*inthelp[U3,y[eFolds]]==0,y[0]==j,y,{eFolds,30,70},{b,j},Compiled->False]          phicmbtemp2[b_,j_,eFolds_] = y[b,j][eFolds]/.phicmbtemp1;      The last step is use the function I defined previously as the initial condition for the differential equation, and I did that in the following way.               phicmb[b_,eFolds_] = phicmbtemp2[b,phiend[b],eFolds];      Up to now the code works perfectly, I also tried to plot phicmb[b,eFolds] for $b=4$ and for $eFolds$ from 30 to 70 (the values I want) and it gives me the results that I expect from the "non numerical" analysis of the equations. Now I turn to the ParametricPlot: the functions that will be the $x$ and $y$ coordinates are the following (the parameters of the region will be $b$ and $eFolds$):               nsplot[U_,b_,eFolds_] = 1 + 2*b^{-2}*etahelp[U,phicmb[b,eFolds]] - 6*b^{-2}*epsilonhelp[U,phicmb[b,eFolds]];     rplot[U_,b_,eFolds_]=16*b^{-2}*epsilonhelp[U,phicmb[b,eFolds]]      After I wrote this, I can at last explain what's my problem. The problem is that if I try to calculate things like (in the actual plots, I will use $c$ for the quantity $b$, and $n$ for the quantity $eFolds$)               nsplot[U3,4,40]      Mathematica returns               0.85485 + 0.i      that (apart the imaginary part, that is a problem on its own) is compatible with what I expect from a "non numerical" analysis of the problem. However if I try to do something like               Table[nsplot[U3,4,n],{n,30,70,10}]      this gives out numbers like               {82.407, 131.036, -43.4576, -309.158, -510.697, -615.093, -660.662, -689.591, -725.895}      which are completely out of any possible result for that quantity (note that in this list appears again the quantity that I evaluated before, for $eFolds = 40$, and it is totally different). I chose to post the issue using _Table_ instead than _ParametricPlot_ , since the problems appear already using _Table_. Anyway, the code I tried to use also was               Plot[nsplot[U3,4,n],{n,30,70}]      that gives, like table, very strange numbers, and               ParametricPlot[{nsplot[U3, c, n],rplot[U3, c, n]}, {c, 3, 5}, {n, 30, 70}]      that gives, too, a very strange plot. To see if something was wrong with the code, I tried with a simpler potential (namely, $1-Cos[\frac{a}{b}]$) that can be solved "with pen and paper" and I tried to do the parametric plot firstly using the "analytical solution", and then using this code: the results are exactly identical. Maybe the problem is in the small imaginary parts? If there's and imaginary part the $Cos$ in the potential will turn into some $exp$ and maybe that messes up the calculations? But then again if I simply calculate something like               nsplot[U3,4,40]      it gives me the correct result. So I don't really know where's the problem. Anyway, I hope you can give me some hint... Thanks, Giovanni P.S.: I used " _Compile->False_ " in NDSolve because I recalled that it was sometimes best to use it when dealing with numerical calculations, I hope that's not the problem...


What is so special about variable s$?

I found a nice bug in _Mathematica_ 9.0.1.0. Could anyone check to reproduce it? Create a file `temp.txt` with one line:               Attributes[s$] = {Temporary}      Load it into _Mathematica_ with `<<`. Now calculate:               Sum[x^(-n)*y^n, {n, 0, Infinity}]      _Mathematica_ stops responding and the only option is to quit the kernel. You can't interrupt or abort. Now change `s` to `a` or `b` in the file and repeat the above. It works! Next put the line               Attributes[s$] = {Temporary}      directly into the notebook and calculate the sum. It works! What is so special about temporary variable `s$` loaded from the file? I used a temporary variable `s$` in one of my functions and then saved the function to the file. _Mathematica_ added the above line to the file. Everything stopped working.


Non-Solvable PDE?

I would like to know whether this PDE is solvable and if yes, for which values of $a$.               2 (y Cos[a] + x Sin[a]) - 4 (y Sin[a] - x Cos[a]) f[x, y]     - 2 (y Cos[a] + x Sin[a]) (f[x, y])^2      + ((x^2) Cos[a] - 2 x y Sin[a] - (y^2) Cos[a]) D[f[x, y], x]     - ((x^2) Sin[a] + 2 x y Cos[a] - (y^2) Sin[a]) D[f[x, y], y] == 0      I have tried to solve it for the case where $a=0$               2 y + 4 x f[x,y] - 2 y f[x,y]^2 -      2 x y Derivative[0,1][f][x,y] + (x^2-y^2) Derivative[1,0][f][x,y] == 0      on _Mathematica_ but after 3 hours it gave me no result. Then I utilized the method of characteristics and expressed the $a=0$ case as a system of three ODEs \begin{eqnarray} \frac{dx}{dt} &=& (x^2 - y^2) \\\ \frac{dy}{dt} &=& (-2xy) \\\ \frac{df}{dt} &=& 2yf^2 - 2y - 4xf \end{eqnarray} but _Mathematica_ still gave me no results. So I suspect that this PDE might not have an analytic solution. Is this PDE solvable, and if not could you please indicate a reference which indicates which cases of PDEs are non solvable? I am only interested in Analytic solutions. Any kind of help will be most appreciated. Thank you in advance.


NIntegrate::ncvbr: How should we interpret and handle this error not mentioned in any documentation?

I have some user-defined module describing my integrand which has to be computed numerically (it's much more complicated than this but bear with me):               foo[x_?NumericQ, y_?NumericQ, z_?NumericQ] := Module[{f}, f = x+y+z; Return[f]];      Then I have a `region` I am defining with a rotated, truncated polyhedron, and using that as my integration domain which is a new V10 feature:               << PolyhedronOperations`     polys = Flatten[Normal[Truncate[PolyhedronData["Octahedron", "Faces"], 1/3]], 1];     p1 = Polygon[{{0, 0, 0}, {0, Sqrt[3/2]/2 - 1/(2 Sqrt[6]), 1/Sqrt[3]}, {-(1/(2 Sqrt[2])), -(1/(2 Sqrt[6])), 1/Sqrt[3]}, {1/(2 Sqrt[2]), -(1/(2 Sqrt[6])), 1/Sqrt[3]}}];     p2 = Polygon[{{0, 0, 0}, {1, 1, 0}/2, {0, 1, 1}/2, {1, 0, 1}/2}];     m = Last@FindGeometricTransform[p1, p2];     rot = Flatten[Table[m[polys[[i, 1]]], {i, 1, 14}], 1];     region = ConvexHullMesh[rot];      Then when I `NIntegrate` over it, I get an error which _doesn't exist yet_ in the Wolfram documentation, or on Google, or anywhere:               NIntegrate[foo[x, y, z], {x, y, z} ∈ region]          NIntegrate::ncvbr: NIntegrate failed to converge to prescribed accuracy after 5 refinements. NIntegrate obtained 0.35562326340448547` and 0.03672493677717351` for the integral and error estimates. >>      (Those numbers will change if you use the simple foo function.) The link in the error (>>) just takes me to the NIntegrate documentation. So my question is: **What precisely does the`ncvbr` error mean?** The error tag which seems related is `ncvb`, for example this is from the `NIntegrate` documentation:               NIntegrate::ncvb: "NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in x near {x} = {9.43625271977563}. NIntegrate obtained 10.3032-6.74255i and 0.3168981771605228` for the integral and error estimates. >>      which is actually informative, and says I need to crank up `MinRecursion` and `MaxRecursion`. However since I am using a `ConvexHullMesh` to specify my domain, could the way Mathematica "tetrahedralizes" my `region` be the problem instead, since `ncvbr` specifically mentions "refinement?" Would playing with `Min/MaxRecursions` even access this new feature, or do I have to manually refine my own mesh to prepare my integration domain? It seems like an unnecessary pain that should be accessible through the `NIntegrate` options.


Implementing a LineStyleFunction for line plots

I have data in the form:               {{0, 3, 4}, {1, 3, -1}, {2, 4, -1}, ...}      and I would like to implement something similar to ColorFunction for the style of a line. Basically I would like to plot a standard line plot using the first two entries of each point `{x, y, ..}`, and then decide on the line style using the 3rd `{.., .., z}`. Specifically I would like to plot dashed lines when the 3rd entry is positive and filled lines when negative, formed as one continuous curve. **EDIT** : to clarify, there will be large regions where the 3rd entry is consistently positive or negative, so its purpose is to set the style for those regions. This method wouldn't really work for situations where the 3rd value oscillates between the two. Many thanks, Hemmer


Eigenvalue / Eigenvector Calculation

I'm currently trying to compute the three smallest eigenvectors for a 34 by 34 matrix. While I was expecting this to take some time, Mathematica has been running for the past 3 hours, which seems maybe slightly disproportional to the task at hand. The matrix is a laplacian matrix, so it is relatively sparse. Here is my input (G is the graph itself):               A1 = AdjacencyMatrix[G];     D1 = DiagonalMatrix[VertexDegree[G]];     NL1 = IdentityMatrix[34] - MatrixPower[D1, -1/2].A1.MatrixPower[D1, -1/2];     EvecsNL1 = Eigenvectors[NL1,-3]      Any help is much appreciated. Edit: Sorry about that:               G = ExampleData[{"NetworkGraph", "ZacharysKarateClub"}]      I'm trying to get accustomed to working with graph laplacians in mathematica, so I'm messing around with some included datasets. Edit 2: Wow, I feel foolish. Thank you for your help.


Fourier transform an expression to obtain a distribution?

I have this expression for the correlation function for a rigid rotating molecule: $G(\tau) = 4 \pi \int \omega ^2 P_2[\cos (\omega \tau)] P(\omega) \, \mathrm{d}\omega \quad [1]$ where $P_2$ is a second order Legendre polynomial, and $P(\omega)$ is some distribution function. and they say "$P(\omega)$ can be solved either by a Fourier transform of Eg. 1 or by choosing an appropriate model for $P(\omega)$" An example of this 'done' in the book is: ![fft](http://i.stack.imgur.com/cTYSC.png) They say "(bottom graph) Angular velocity distribution functional $P(\omega)$ obtained from a Fourier Transform of $G(\tau)$ (the top graph)" I am quite confused how I go about obtaining this distribution via a Fourier transform. I tried a few functions in mathematica but got no where. Any help would be great. Thanks


Forcing efficient numerical arrays

I encounter strange behaviour of _Mathematica_ when evaluating multi- dimensional arrays of double-precision data. _Mathematica_ can express large arrays of machine-precision numbers using a specialized internal data-format, which optimizes memory usage and speeds up operations. However, _Mathematica_ does not always recognize when it can use such optimized arrays. Below are three cases that would ideally yield the same optimized data structure upon evaluation:               arr1 = Table[1.23, {1}, {100000}];     ByteCount[arr1]     (* 800168 *)          ncols = 1000;     arr2 = Table[1.23, {1}, {ncols}];     ByteCount[arr2]     (* 3200088 *)          ncols = 1000;     arr3 = Table[1.23, {1}, Evaluate[{ncols}]];     ByteCount[arr3]     (* 800168 *)      For some reason, the second case gives sub-optimal behaviour. My question is this: If I end up with a case where _Mathematica_ does not use its optimized numeric array data structure (such as `arr2`, above), how can I explicitly force a conversion?


Generate Chaotic Time Series using CellularAutomaton[]

If possible, How could I generate a chaotic Time series using `CellularAutomaton[]`. I am especially interested in Rule 30. A friend told me it was possible but I have yet not found the way to do so.


How to add vertex/edge labels to existing graph

If I have already created a graph using `Graph`. Later, I want to add to the graph some vertex and/or edge labels, how can I do that? Thank you.


How to assign up-values for `Derivative`?

I have defined several custom analytic functions. Here is the simplest example:               ln[x_, a_?NumericQ] := Piecewise[{{Log[x], Re[a] > 0}, {-Log[1/x], True}}]      Now I would like to let Mathematica know how to carry out derivatives on this: I need to make `D` and `Series` work on `ln` as if it were `Log`:               ln /: D[ln[f_, g_], x_] := D[Log[f], x];      Works wonderfully: ![enter image description here](http://i.stack.imgur.com/mafR8.png) But `Series` doesn't work because it is using `Derivative` instead of `D`. ![enter image description here](http://i.stack.imgur.com/pq3VH.png) So, now I try `TagSetDelayed` on `Derivative`: ![enter image description here](http://i.stack.imgur.com/lEy4E.png) But as you can see, it doesn't work because `ln` is too deep. What can I do to make `Series` work?


Arranging connector lines

Heike gave an absolutely wonderful answer to my question about arranging subplots around a main plot and including connector lines. This is the result: ![Mathematica graphics](http://i.stack.imgur.com/esMNn.png) Starting from Heike's answer, what is the best order to arrange the subplots in so the connector lines are as easy to follow / as aesthetically arranged as possible? To have something concrete to test with, let's say we have 12 points in the unit square. These are the starting points of the lines.               start = RandomReal[1, {12, 2}];      The set of endpoints is fixed (due to the subplot positions):               end = With[{dx = 0.1, dy = 0.1},             {{-dx, 1 + dy}, {.25 - dx/4, 1 + dy}, {.75 + dx/4, 1 + dy},              {1 + dx, 1 + dy}, {1 + dx, .75 + dy/4}, {1 + dx, .25 - dx/4},              {1 + dx, -dy}, {.75 + dx/4, -dy}, {.25 - dx/4, -dy},              {-dx, -dy}, {-dx, .25 - dy/4}, {-dx, .75 + dy/4}}];      Then the plot will look similar to this:               Graphics[{       FaceForm[Lighter@Orange], Polygon[{{0, 0}, {1, 0}, {1, 1}, {0, 1}}],       Line@Transpose[{start, end}],       AbsolutePointSize[18], Lighter@Orange, Point[end],        Black, MapThread[Text, {Range[12], end}]},        Frame -> True, FrameTicks -> None, PlotRange -> {{-.2, 1.2}, {-.2, 1.2}}]      ![Mathematica graphics](http://i.stack.imgur.com/bv87S.png) **Given the starting points in the orange square, how can we automatically reorder the labelled endpoints so the lines cross as little as possible (or generally: the figure looks as good as possible)?** Please try to make your answers complete, with a sample output figure using the code above. When it is not possible to avoid that the lines cross, what the "best" arrangement is is admittedly somewhat subjective. * * * **Note:** This is a question that I thought others would be interested in too. It is not a practical problem I am facing (I ordered the subplots manually in my figure), but of course if there are any good solutions, I will use them. I will be working on solutions as well. **Note 2:** Given two lists, `l1` and `l2`, containing the same elements in different orders, the permutation that re-orders `l1` to `l2` is `Part[Ordering[l1], Ordering@Ordering[l2]]`. This may be useful for reordering points.


Euler's method for system of differential equation

I need to program Euler's method to solve a system of two diffferential equations of first order. Fist, I have programmed the Euler's method for just one differential equation:                euler[f_, ini_, int_, h_] :=       Module[{x, y, l}, l = {ini};       y = ini[[2]];       For[x = int[[1]], x <= int[[2]] - h, x = x + h,       y = y + h*f[x, y]; l = AppendTo[l, {x + h, y}]];l]      And it works fine.               f[x_, y_] := 3 (1 - y);     euler[f, {0, 0.01}, {0, 10}, 1]     {{0, 0.01}, {1, 2.98}, {2, -2.96}, {3,8.92}, {4, -14.84}, {5, 32.68}, {6, -62.36}, {7,127.72}, {8, -252.44}, {9, 507.88}, {10, -1012.76}}      Now, changing a little the previous function I want to solve a system of two differential equations of first order. I programmed the following:               euler2[f_, g_, inif_,inig_, int_, h_] :=       Module[{x, y, t, list1, list2}, list1 = {inif}; list2 = {inig}; x = inif[[2]];      y = inig[[2]]; For[t = int[[1]], t <= int[[2]] - h, t = t + h,      x = x + h*f[x, y, t]; y = y + h*g[x, y, t]];      list1 = AppendTo[list1, {t + h, x}];      list2 = AppendTo[list2, {t + h, y}]; {list1, list2}]          But I got an error. What am I doing wrong? For example, I define f anf g in this way: f[x_, y_, t_] := y; g[x_, y_, t_] :=0.5x+0.5y; inif= is a set of the initial value of x (x(0)=1$\to$ inif={0,1}) and inig= is a set of the initial value of y (y(0)=1 $\to$ inig={0,1}) int is the interval where I want to calculate the solution int={0,10} and h the lenght of each step h=1 Thank you for your help.


Locators, lists of variable length, all in Manipulate

I'm trying to implement a complicated Manipulate[] interface. I'm not really interested in working code, but for those interested, I would like the program to   * allow you to drag around a variable number of locators,    * and have it output the motion of an object traveling from one locator to the next in straight line segments at constant velocity (just the function of time; no actual animation needed), and graph of the motion (i.e. connect the locators on the screen via ParametricPlot[]).   * One last thing: the times at which the object passes each of the locators are needed to specify a unique solution. But rather than manipulating the times themselves, I'd like to have input fields for the average velocity in each segment, and have the program infer the times. Here is a schematic that describes how I've tried to accomplish this: ![enter image description here](http://i.stack.imgur.com/ueqYn.png) However, I have been stumped as to how to implement this. Manipulate[] doesn't seem to have enough flexibility, and Dynamic[] seems to come with its own issues. **_All I'd like to know is if this is a dead end, or if not, some rough outline of how I could complete this implementation._** Here is how far I've gotten, with the help of a few answered stack exchange questions: GLOBAL PARAMETERS:               Row[{SetterBar[Dynamic@\[CapitalNu], Range[1, 10, 1]],"     Sets Length of X,Y,V"}]      INTERFACE VARIABLES -> INTERNAL VARIABLES:               Internalize[{V_, {X_, Y_}}, N_] := Module[{T},       T = Table[0, {i, 1, N + 2}];       For[i = 2, i <= N + 2, i++,        T[[i]] =           T[[i - 1]] + Norm[{X[[i - 1]], Y[[i - 1]]} - {X[[i]], Y[[i]]}]/           V[[i]];];       T       ]     X := Table[        ToExpression["x" <> ToString@i], {i, 0, \[CapitalNu] + 1}];     Y := Table[        ToExpression["y" <> ToString@i], {i, 0, \[CapitalNu] + 1}];     V := Table[        ToExpression["v" <> ToString@i], {i, 1, \[CapitalNu] + 1}];     T := Internalize[{V, {X, Y}}, \[CapitalNu]];      MANIPULATE INTERFACE               Procedure[T_,{X_,Y_}]:= Piecewise@      position=Table[{{X[[i]]-(t-T[[i]])/(T[[i+1]]-T[[i]]))(X[[i]]-X[[i-1]]),Y[[i]]-(t-T[[i]])/(T[[i+1]]-T[[i]]))(Y[[i]]-Y[[i-1]])},          T[[i]] <= t <= T[[i + 1]]}, {i, 1, \[CapitalNu]}]          (*The rest would look like this:      Manipulate[ParametricPlot[Procedure[Dynamic@T,{Dynamic@X,Dynamic@Y}][t],  {t,T[[1]],T[[-1]]}],     Table[{X[[i]],Y[[i]]},Locators],Table[Silders[V[[i]]]]],] *)      Does anyone know if Mathematica is capable of something like this? (I must emphasize, the Manipulate interface has to adjust automatically to changes in N; no retyping code permitted). The key issue I haven't been able to figure out is **_how to apply Manipulate[] controls, including locators, to the elements of variable length lists._** While this question may seem unnecessarily long, context really helps.


Using Apply inside Compile

In this great answer a compiled version of the Nelder-Mead algorithm is presented. Since it works on arbitrary dimensions (i.e. arbitrary number of arguments), it has to use apply on the objective function. The problem is that `Apply` is not directly supported inside `Compile`. To overcome this limitation the following code is used:               (* Produces compiled code for the Nelder-Mead algorithm with the objective function inlined *)     ClearAll[apply];     SetAttributes[apply, HoldAll];     apply[f : (_Function | _CompiledFunction), vars : {__Symbol}] :=         With[{applied := f @@ vars},           Function[arglist, Block[vars, vars = arglist; applied]]          ];      This seems to work (inside the package), but I have no idea, how it works. **Could somebody explain the techniques behind this code snippet?** Specifically:   * What does `SetDelayed` do inside `With`?    * Why does `vars` appear twice in the arguments to `Block`?    * Why doesn't this minimal example work? (I believe it mimics what is done in the mentioned answer...)              Clear[a, b, c, x, y, z, objectiveFunction, cfunc];     objectiveFunction = Compile[{a, b, c, x, y, z} ,        (a - x)^2 + 50 (b - y)^2 + (c - z)^2];          cfunc = With[{f = apply[objectiveFunction, {a, b, c, x, y, z}]},       Compile[ {{pts, _Real, 1}}, f@pts]       ]     << CompiledFunctionTools`     CompilePrint[cfunc]      **EDIT:** Here is the working snippet. Note that `"InlineCompiledFunctions"` must be set to `True` to avoid the call to `MainEvaluate`.               ClearAll[a, b, c, x, y, z, apply, objectiveFunction, cfunc];     (* Produces inlinable code for use inside Compile (where Apply is not \     supported directly) *)     SetAttributes[apply, HoldRest];     apply[f : (_Function | _CompiledFunction), vars : {__Symbol}] :=            Function[arglist, Block[vars, vars = arglist; f @@ vars]];          objectiveFunction = Compile[{a, b, c, x, y, z} ,        (a - x)^2 + 50 (b - y)^2 + (c - z)^2];     apply[objectiveFunction, {a, b, c, x, y, z}]     cfunc = With[{f = apply[objectiveFunction, {a, b, c, x, y, z}]},       Compile[ {{pts, _Real, 1}}, f@pts,         CompilationOptions -> {"InlineCompiledFunctions" -> True}]       ]     << CompiledFunctionTools`     CompilePrint[cfunc]


NMinimize memory consumption problem in Mathematica 9 vs. 7 & 8

I am having trouble using `NMinimize` in _Mathematica_ 9 - Memory consumption overflows. The same `NMinimize` command, with the same function to minimize, in _Mathematica_ 7 and 8, gives acceptable results. Is this a bug? Anyone else has had similar issues? Any workarounds ?


Selectively updating individual graphics in a dynamic, multiple-plot Show

Suppose `Show` contains multiple graphics objects that differ markedly in the amount of computation needed for their display. Hence, when dynamically updating only those individual graphics changed by any underlying variable change should be redrawn. For example (and with apologies to Dutch patriots), in the following dynamic `Show`, "pulling the red down" (by dragging the l.h.s locator) should take longer than "pulling the blue up" (by dragging the r.h.s. locator) since it is a more computationally intensive graphic (as simulated here by `Pause@0.1`). Dragging the r.h.s. locator however, is equally sluggish due to the overarching `Dynamic` wrapper causing both graphics to update whenever either locator is dragged. The logical solution would seem to be to wrap each inner `Plot` graphic in a `Dynamic` but `Show` doesn't like this apparently expecting a pure graphic for each of its shown components.               DynamicModule[{top = {.02, 0.15}, bottom = {.08, 0.08}},      Dynamic@       Show[        Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top,FillingStyle -> Red],        Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis,FillingStyle -> Blue],        Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],        Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],       PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/IB3od.jpg) `Overlay`, on the other hand, has no such qualms as indicated by the following graphic being much more responsive to the r.h.s. `VerticalSlider` "pulling the blue up".               DynamicModule[{top = {.02, 0.15},bottom = {.08, 0.08}},      {VerticalSlider[Dynamic[top[[2]]], {0, 0.15}],       Overlay[{        Dynamic@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top,FillingStyle -> Red, Axes -> False,PlotRange -> {0, .2}],        Dynamic@Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis,FillingStyle -> Blue, Axes -> False, PlotRange -> {0, .2}]}],        VerticalSlider[Dynamic[bottom[[2]]], {0, 0.15}]}]      ![enter image description here](http://i.stack.imgur.com/oUyHj.jpg) This is not a permanent solution as `Overlay` doesn't enjoy `Show`'s more natural way of combining plots (more intuitive formatting, locator usage, ability to set common graphics options etc) so the question is; how can `Overlay`'s selective updating be replicated in `Show`? **Answer Update:** The following answer is a hybrid taking from both Jens and Mr Wizard's responses which I think help to nicely illustrate some more general points about dynamic interface design. First, the combined answer:               SetAttributes[{DynamicShow, DynamicPlotRed, DynamicPlotBlue}, HoldAll];          DynamicShow[p_Plot] := Graphics[Dynamic@p[[1]], p[[2]]];          DynamicPlotRed[top_] := DynamicShow@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top, FillingStyle -> Red]          DynamicPlotBlue[bottom_] := DynamicShow@Plot[bottom[[2]], {x, 0, .1}, Filling -> Axis, FillingStyle -> Blue]          DynamicModule[{top = {.02, 0.15},bottom = {.08, 0.08}},      Show[       DynamicPlotRed@top,       DynamicPlotBlue@bottom,       Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],       Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],      PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/8UOn2.jpg) This includes the desired, lower level (indirect) use of `Dynamic` to maintain the usefulness of its automatic, targeting updating as captured in Mr Wizard's answer. This is important as it allows a more general, more numerous adding of interface components (note the relevant `Dynamic` sits in `DynamicShow` to which I'll return). The approach in Jens' answer - having each `Locator` directly update the corresponding plot, while working perfectly for the quoted two-element example, doesn't generalize in the sense that all plot updating now needs to be done "by hand" or via `Dynamic`'s second argument _without_ harnessing `Dynamic`'s automatic updating (in full generality "Plot" can be an arbitrarily complex interface component with multiple, not-immediately-obvious dependencies). There is a potential issue in that this solution relies on a consistent `FullForm` being generated by `Plot` but this can be addressed by adding a helper function. For example, using the `PlotLegend` option changes the `FullForm` structure but this can be handled as follows:               SetAttributes[{DynamicShow, DynamicShowLegend, DynamicPlotRed, DynamicPlotBlue}, HoldAll];          DynamicShow[p_Plot] := Graphics[Dynamic@p[[1]], p[[2]]];          DynamicShowLegend[p_] /; (! FreeQ[Hold@p, PlotLegends]) := Legended[Graphics[Dynamic@p[[1, 1]]], p[[2]]];          DynamicPlotRed[top_] := DynamicShow@Plot[(Pause@.01; top[[2]]), {x, 0, .1}, Filling -> Top, FillingStyle -> Red]          DynamicPlotBlue[bottom_] := DynamicShowLegend@Plot[{x, bottom[[2]]}, {x, 0, .1}, Filling -> {1 ->{Axis, Green}, 2 -> {Axis, Blue}}, PlotLegends -> True]               DynamicModule[{top = {.02, 0.15}, bottom = {.08, 0.08}},      Show[       DynamicPlotRed@top,       DynamicPlotBlue@bottom,       Graphics@Locator[Dynamic[top, (top[[2]] = #[[2]]) &]],       Graphics@Locator[Dynamic[bottom, (bottom[[2]] = #[[2]]) &]],       PlotRange -> {0, .2}, Axes -> False]]      ![enter image description here](http://i.stack.imgur.com/tvUOT.jpg) The functions introduced in Jens' answer also illustrate a fundamental principle for building more complex dynamic interfaces. While introduced here to make `Dynamic`'s second argument more readable, this improved readability assumes much greater proportions as interfaces' complexify (essentially implementing modularization with all its attended advantages, as, for example, enumerated in Tom Wickham-Jones white paper). There is a wrinkle in performing such modularization when it comes to dynamic interfaces however, which can be illustrated by seeing how Mr Wizard's solution modularizes (in fact generalizes). Essentially his insight was that `Show` apparently (mostly) expects `Graphics` heads in its arguments (with exceptions noted as above) so that wrapping one of these in a `Dynamic` upsets this obstinance (which I regard as a design oversight). This can now however, at least be accommodated by giving `Show` its cherished `Graphics` head and instead wrapping `Dynamic` around `Graphic`'s first argument via `Graphics[Plot[...][[1]], AspectRatio->1/GoldenRatio]`. The `AspectRatio` option corresponds to that generated automatically in this plot but in fact any generated option value can be included by defining               DynamicShow[p_Plot]:=Graphics[Dynamic@p[[1]],p[[2]]]      (n.b. The `FullForm` of a `Plot` output is `Graphics[comps, opts]` ) The wrinkle is that in order to apply `DynamicShow` in this way, its argument, `p`, needs to avoid evaluation prior to being wrapped in `Dynamic` to maintain its own "lexical scoping" (a form of code generation/injection). Consequently, this dynamic variable needs to be held right through to its final placement nestled inside a `Dynamic` thereby requiring a chain of `HoldAll` attributions. In a fuller generality, the passed-through variable need not just be a local `DynamicModule` variable holding a pair of numbers like `top` and `bottom` but instead can potentially hold an arbitrary large dataset. This suggests an updated, less-emulative, idiom for answering an earlier question about realizing such modularization in dynamic interfaces; that is, there appears to now be a sufficient level of mutability in the new associations/datasets for expressions like `top[[2]]` to be fruitfully extended to expressions like `interfaceData[[ ...]]`.


Is it possible to pass a "shared" integer in librarylink?

MTensor supports shared pass, where the argument can be modified in the library function and that modification can be seen in Mathematica side. Is it possible to do the same thing to a integer or double type? For example, in the following code, the library function takes an integer and set it to 2.               MMASrc = "#include <WolframLibrary.h>       #include <WolframCompileLibrary.h>            DLLEXPORT mint WolframLibrary_getVersion(){            return WolframLibraryVersion;       }            DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){            return 0;       }       EXTERN_C DLLEXPORT int test(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){            int  a = MArgument_getInteger(Args[0]);       a=2; //library function set a to 2       return LIBRARY_NO_ERROR;       }";               Needs["CCompilerDriver`"];     lib = CreateLibrary[MMASrc, "test", "Debug" -> True,         "TargetDirectory" -> "/tmp"];     testFunc = LibraryFunctionLoad[lib, "test", {Integer}, "Void"];     a = 3;     testFunc[a];     a          (*3*)      However, I get 3 as output. So it is possible to have shared pass so that I Mathematica can reflect the modify of a by the library function, except making it into a MTensor with one element?


Can Tuples help simplify this?

I have a list `{1, 2, 3, 4}` and wish to form                {{{1,2},{3,4}},       {{1,3},{2,4}},       {{1,4},{2,3}}}      I ended up doing it manually like this:               a={1,2,3,4}     {{{a[[1]],a[[2]]}, {a[[3]],a[[4]]}},     {{a[[1]],a[[3]]}, {a[[2]],a[[4]]}},     {{a[[1]],a[[4]]}, {a[[2]],a[[3]]}}}      Is there a way to do this more simply? Of course this is a simplified question from the actual problem which is more complicated. An answer to this can be generalized to my actual problem. Thanks.


Help needed with Simple equations

take a simple formula like Ohm's law u=i*r... is it possible to solve for i without values??, something like Solve[u=i*r, i] and expect an output like i=u/r which gives me: Solve::naqs: i r is not a quantified system of equations and inequalities. >> Solve[i r, i] sol = Solve[u == i*r, i] which gives me {{}} Any help would be greatly appreciated


Using more than one set of Locators in a Manipulate

I need to add locators dynamically to different sets. With one set this works OK:               Manipulate[      Graphics[{Point@pts}, PlotRange -> {{0, 1}, {0, 1}}],      Control[{{pts, {RandomReal[1, 2]}}, ControlType -> Locator}],       Row[{        Button["Add L1", pts = pts~Join~{RandomReal[1, 2]}]}],      Dynamic@pts]      But when I try to use more than one set, it doesn't:               Manipulate[ (*fails*)           Graphics[{Point@pts, Point@ptsNA}, PlotRange -> {{0, 1}, {0, 1}}],      Control[{{pts, {RandomReal[1, 2]}}, ControlType -> Locator}],      Control[{{ptsNA, {RandomReal[1, 2]}}, ControlType -> Locator}],           Row[{        Button["Add L1", pts = pts~Join~{RandomReal[1, 2]}],         Button["Add LNA", ptsNA = ptsNA~Join~{RandomReal[1, 2]}]}],      Dynamic@pts, Dynamic@ptsNA]      I could work out my way by adding all locators to the same set and manually assigning them to one "set" or another, but in my real application I have to add a different number of locators to each set at a time and also be able to delete them, so that complicates the code. **Edit** Thanks to Sjoerd's comment in another question, I found this limitation is covered in the documentation: > Due to internal limitations, it is not possible to combine individual > Locator variables with a variable that is a list of multiple Locator > variables: you can have only one multipoint Locator variable in a > Manipulate. However, in exchange, it is possible to add the option > LocatorAutoCreate->True to that one Locator multivariable specification, and > thereby allow you to create and destroy Locator points interactively > (changing the length of the list of points stored in the variable). So, no hope using `Manipulate[]`, accepting jVincent's answer.


Blurred frontend text in Mathematica 10, Windows, High-DPI Display

So I have recently upgraded to a Windows ultrabook with a high-res display. All my software seems to cope just fine with the high resolution, except for Mathematica 10. Mathematica seems to pretend the screen resolution is lower, and blurs both frontend text and graphics output. How can I configure the interface to display crisp text, as it did on my old MacBook Air? Thanks!


Question about collections of custom GUI controls for Mathematica

Background: I have only recently begun programming GUIs in Mathematica, so I have a continuous need for custom controls. I needed a scrollable list control and with the help of Google I found a beautiful one in this MathGroup post (One of Sjoerd, if I am correct.) The point being: there is a lot of excellent Mathematica code shattered all over. Most matured languages have libraries of custom controls. I am not aware of any existing for Mathematica. **Question(s): What is the best _managed_ collection of (open source) custom GUI controls for Mathematica that you know of? Where do you get your custom GUI controls? Should there be a collection of custom GUI controls for Mathematica?**


How can I use list processing functions on data in a file?

How might I work with the following functions on a list, if the list is a disk based file?               Partition[]     DeleteDuplicates[]     Split[]       SortBy[]      The file is too large to `ReadList[]` or `Import[]` the data in the first place.