title: Trouble with using a log10 function in NonlinearModelFit

text: I was wondering why won't mathematica give a result where the function is also `Log10`, instead it gives the ordinary `Log`. Is it because the `Log` fits the problem better than the `Log10` or... ?               Clear[x, a, b, c, d]          Data = {{0, 0}, {1, 6.91}, {2, 9.2}, {3, 11.4}, {4, 13.4}, {24,          39}, {25, 40.5}};          aa = NonlinearModelFit[Data, {a + b*Log10[c*x + d], c > 0, d > 0}, {a, b, c, d}, x];          aa // Normal          Show[Plot[aa[x], {x, 0, 100}, PlotRange -> All], ListPlot[Data, PlotStyle -> Directive[Red, PointSize[0.02]]]]


title: Elements of a List according position in axis

text: ({{a, b}, {c, d}})      a, b, c and d are Lists of 300 length. Their first 4 elements must specify their position in the column (1 column, 2 column, etc) and the following 4 elements the position in the line (1 line, 2 line, etc) but this must be made in binary code and not a 2x2 Table but a 10x10. Also, they must only contain -1, 0 or 1. I was thinking about creating the vector with a smaller length and use `AppendTo` to put the position based on the table index and converting it to binary but couldn't find a final solution.


title: Best way to modify values in a list of rules?

text: Recently I had to solve a problem similar to this: Let's say I have a list of list of rules               Clear[a, b, c, d]     l = {{a -> 2, b -> 1, c -> 3, d -> 2}, {d -> 2, b -> 1, a -> 1, c -> 2},           {c -> 3, a -> 1, b -> 2}};      What is the best way to sort the values of `{a, b, c}` in each sublist without touching the rest of the sublist. So the first sublist should be:               {a -> 1, b -> 2, c -> 3, d -> 2}      and the whole result should be               {{a -> 1, b -> 2, c -> 3, d -> 2}, {d -> 2, b -> 1, a -> 1, c -> 2},       {c -> 3, a -> 1, b -> 2}}      There are no duplicates in the subsists (so `a -> _` appears only once). The order of rules in the sublist does not matter. In an effort to expand my pattern matching skills I would like to know: What's the best way to achieve this? Here "best" means elegant code, but still efficient enough to work ~10^5 subsists.               testdata =        Table[MapThread[         Rule, {RandomSample[{a, b, c, d, e, f, g, h, i, j, k}, 10],           RandomReal[{-1, 1}, 10]}], {ii, 10^5}];      * * * I'm posting my answer below, so that I won't get accused of not showing any effort:)


title: Sales forecast using SARIMAProcess and time-series data

text: I would like to ask for help in how to use the new _Mathematica_ 9 time series functions to make some sales forecast. For example, for one of our stores, I have this data set with 35 points, from January 2010 to November 2012 with sales in               salesData = {5.14, 5.32, 6.04, 5.84, 6.09, 6.03, 5.79, 6.26, 5.91, 6.44, 6.54, 7.76, 6.24, 6.19, 6.37, 6.72, 6.72, 6.52, 6.64, 6.96, 6.51, 7.03, 6.79, 8.11, 6.82, 6.96, 7.85, 7.68, 7.80, 7.80, 7.80, 8.22, 8.19, 8.67, 8.29}      If I plot it with DateListPlot as below:               DateListPlot[salesData                 ,{2010,1}                 ,Joined-> True                 ,AspectRatio->0.2                 ,DateTicksFormat->{"MonthShort","/","YearShort"}                 ,PlotLabel->Style["Sales Chart",18,Bold,Blue]                 ,ImageSize->800     ]      I get: ![Sales Graphic](http://i.stack.imgur.com/EunTo.png) My question is: How do I use `SARIMAProcess`, `TemporalData` and `TimeSeriesForecast` to get the forecast and the prediction band with some confidence interval as in this picture? ![Sales Forecast](http://i.stack.imgur.com/VaEW0.png) In this case, the series shows seasonality by year and this is the reason I know that the S in (S)ARIMA is necessary. I'm new to time series, so if possible, I would like to have didactical answer. I am vague on the meaning of the SARIMA coefficients and how to determine them.


title: Tailoring RegionPlot3D with PlotPoints?

text: This seemingly tame solid gives _Mathematica_ (v9) a bit of a workout if you want to generate a good picture:               rinner[y_] = Sqrt[y];     router[y_] = 1;     RegionPlot3D[rinner[y]^2 <= x^2 + z^2 <= router[y]^2,        {x, -1, 1}, {z, -1, 1}, {y, 0, 1}, AxesLabel -> {x, y, z}, PlotPoints -> 100,        PlotStyle -> Opacity[.75], MeshFunctions -> {#3 &}, Mesh -> 5]      ![Mathematica graphics](http://i.stack.imgur.com/srC2C.png) I kept increasing `PlotPoints` from 100 to 200 to 300 and things get pretty slow---without much of an improvement in the rendering of the choppy part of the region at the top. Bumping up `MaxRecursion` and `PerformanceGoal->"Quality"` didn't seem to help. I tried playing with variations like `PlotPoints->{100,100,300}` to get better results faster, and this leads to my two questions.   1. What else should I try? (I experimented with `RevolutionPlot3D`, but I want _solids_.)   2. Is it possible to tailor the placement of `PlotPoints` to a subset of either  (a) an axis (say, 10x more points in the $z$ direction, but pack them into $0.9\le z\le 1$?, or (b) a specific portion of the overall space (say, $x,y,z$ with $0.9^2\le x^2+y^2\le 1^2$ and $0.9\le z\le 1$, etc.)? Thanks for any insight.


title: Part specification error only in LogPlot

text: I've a problem. I defined a simple list and a function like below:               lst := {5, 10, 20}     f[m_] := lst[[Floor[m/10]]];      and drew a plot               Plot[f[x], {x, 10, 38}]      which works fine. But when calling LogPlot               LogPlot[f[x], {x, 10, 38}]      the following error appears before the plot               Part::pspec: "Part specification Floor[x/10] is neither a machine-sized integer nor a list of machine-sized integers"      Can anyone suggest me what's going on and how to deal with this error? Thank you in advance!


title: Alternatives to procedural loops and iterating over lists in Mathematica

text: While there are some cases where a `For` loop might be reasonable, it's a general mantra – one I subscribe to myself – that "if you are using a `For` loop in Mathematica, you are probably doing it wrong". But `For` and `Do` loops are familiar to people who already know other programming languages. It is common for new Mathematica users to rely on loop constructs, only to become frustrated with performance or code complexity. > My question is: **are there some general rules of thumb that would help new > users select the appropriate alternative to a procedural`For` or `Do` loop, > and are there other useful Mathematica constructs, aside from > `RandomVariate`/`Nest`/`Fold`/`Inner`/`Outer`/`Tuples` that they should know > about in order to avoid those loops?** * * * In particular, there are a number of ways of iterating over lists:   1. The `For` loop:               For[i = 1, i <= 10, i++, list[[i]] = func[ list[[i]]]        2. The `Table` function operating over each part of a list in turn:               Table[func[ list[[i]] ], {i, Length[list]}]        3. The `Do` loop operating over each part of a list in turn:               Do[       x = lst[[i]];       t += Mod[x, t],       {i, 1, Length[lst]}     ];     t        4. `Map`ping a function onto each element of a list:               (3 - #)/(7 * #) & /@ list        5. And for nested lists, there are constructs like `MapThread`:               f = Mod[#, #2] Floor[#3/#] &;          a = {{18, 85, 22, 20, 39}, {17, 67, 76, 96, 58}, {40, 97, 56, 60, 53}};          MapThread[f, a]      New users of Mathematica will usually pick options 1 or 3 and use C-style or Matlab approaches that involve the following multistep process:   1. Defining an empty list   2. Setting up a loop    3. Optionally define a variable (usually not localised) to equal the iterator, which is then used in subsequent calculations within the loop   4. Within each loop iteration, use the local variable defined to equal the iterator to _redefine_ each element of that list in turn according to some function   5. If the list is multidimensional, nest another loop inside that. What are some useful guides to help users coming from other languages to Mathematica to improve the conciseness and efficiency of their code by avoiding unnecessary loops?


title: For loop efficiency

text: What is a more efficient way of solving this problem? By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.               sumfib = 0;     For[n = 1, t = Fibonacci[n] ; t < 4*10^6,  n += 1,          If[Mod[t, 2] == 0, sumfib += t]         ]     Print[sumfib]      > >      4613732 >


title: What are some general strategies to avoid using For loops?

text: > **Possible Duplicate:**   >  Iterating over lists in Mathematica While there are some cases where a `For` loop might be reasonable, it's a general mantra – one I subscribe to myself – that "if you are using a `For` loop in Mathematica, you are probably doing it wrong". But `For` and `Do` loops are familiar to people who already know other programming languages. It is common for new Mathematica users to rely on loop constructs, only to become frustrated with performance or code complexity. > My question is: **are there some general rules of thumb that would help new > users select the appropriate alternative to a procedural`For` or `Do` loop, > and are there other useful Mathematica constructs, aside from > `RandomVariate`/`Nest`/`Fold`/`Inner`/`Outer`/`Tuples` that they should know > about in order to avoid those loops?**


title: Seeking faster method than using Table and If together

text: See the example below. Is there any way to make this execute much faster and still get the same output ? I have read Conditionals slower than operators? but it didn't really help me as I can't seem to apply these methods to my problem. I have to execute about 100 of these operations in succession and each one can't take about a second to execute as running the algorithm would take way too long for the end user.               CurrentEquipID = 40          40          AbsoluteTiming[      Table[If[HTimeModelSelection[CurrentEquipID][[i]] ==          0, (1 - HOperatingEfficiency[CurrentEquipID][[i]])*         HUtilizedTime[CurrentEquipID][[i]],         Flatten[ConstantArray[           Select[EquipParams, #[[colEquipID]] == CurrentEquipID &][[;; ,              colOperatingDelayTime]], 20]][[i]]], {i, 1, 20}]]          {1.851185, {744.6512332, 744.6512332, 746.713979, 744.6512332,        744.6512332, 744.6512332, 746.713979, 744.6512332, 744.6512332,        744.6512332, 746.713979, 744.6512332, 744.6512332, 744.6512332,        746.713979, 744.6512332, 744.6512332, 744.6512332, 746.713979,        744.6512332}}


title: Want explanation of when different looping constructs are appropriate

text: For example when would you use a `Do` loop over a `For` loop? For which tasks would you use `Map`, `Table`, `Scan`, et cetera? I'm quite new to _Mathematica_ and I don't really get what the advantages of any of these loops are over the standard `For` loop whose use seems to be so harshly discouraged here on StackExchange.


title: How should I go about writing more functional and list based code?

text: I've heard that Mathematica is usually faster when the code is list-based and/or uses a functional paradigm. I'm still working on getting the hang of this; there are a lot of `If`s and `For`s that I end up using in more complex code that probably shouldn't be there. In general how do I go about writing more functional and list based code?


title: How to make a pattern to change x^(2/y) to (x^2)^(1/y) for any x and y?

text: This might have been asked before. Please let me know if it is. I was looking at an interesting Mathematica question in students forum and trying to solve it, and a chance to learn more about patterns. Having little hard time writing a general pattern to convert an expression `anything^(2/anything)` to `(anything^2)^(1/anything)` For example, given `(-1/3)^(2/3)` , convert this to `((-1/3)^2)^(1/3)` and when given `(-1/3)^(2/z)` convert it to `((-1/3)^2)^(1/z)` which then simplifies to `(1/9)^(1/z)` The problem is that the FullForm changes depending if it is a symbol or a number in the exponent:               FullForm[(-1/3)^(2/6)]      ![Mathematica graphics](http://i.stack.imgur.com/3ecU0.png)               FullForm[(-1/3)^(2/z)]      ![Mathematica graphics](http://i.stack.imgur.com/BZwtV.png) Will there be other general `FullForm(s)` to check for other than these two? For `Rational` (numbers) this is how I do it now:                (-1/3)^(2/3)/.       Power[Rational[-1,x_],Rational[2,y_]]:>Power[Power[Rational[-1,x],2],Rational[1,y]]      ![Mathematica graphics](http://i.stack.imgur.com/2BXzY.png) You might have wondered why I did not write the more direct way:               (-3^(-1))^(2/3) /. (x_)^(2/y_) :> (x^2)^(1/y)      Well, because the above does not work. So, I cheated and looked at the `FullForm` and used that above in the pattern. But the above fails when the denominator is a symbol, for example `2/z` instead of numbers `2/3` ![Mathematica graphics](http://i.stack.imgur.com/wVDGu.png) I need little help figuring how how to check for each case. If I know it is a symbol, then `Times[2, Power[z_, -1]]` can be used. If it is not numeric, then `Rational[2, z_]` can be used. **question is** : How to write a general pattern to convert `x^(2/y)` to `(x^2)^(1/y)` for any `x` and any `y` (excluding edge cases like Infinity, Indeterminate, {}, zero, and such. Just for numerics and symbols. This is practical problem. **Update** I was pointed out in the chat room to an old Mathematica package which was designed to handle such cases. But this package is no longer available. On the right below, is a screen shot of that old package from WRI page, the left is current V9 result ![enter image description here](http://i.stack.imgur.com/QJ7Lp.png) Here is the old package link http://reference.wolfram.com/legacy/v5_2/Add- onsLinks/StandardPackages/Miscellaneous/RealOnly.html (thanks for P.Fonseca for the link) The original question from a student at the WRI forum as asking for the behavior given by this old package (i.e. not the complex root, but show the real root).


title: Is there a way to solve the Apollonius Circle problem in Mathematica?

text: Assuming x, a, and b are complex numbers, is there a way to reduce the equation `Abs[x - a] == k Abs[x - b]` to something like `Abs[x - ...] = ...`? Or if it can't be done by complex number, can it be solved by specified the coordinate explicitely? I've try something like this:               d[x_, y_, xx_, yy_] := (x - xx)^2  + (y - yy)^2     d[x, y, x1, y1] - k d[x, y, x2, y2] == 0 // Expand      and got:               x^2 - k x^2 - 2 x x1 + x1^2 + 2 k x x2 - k x2^2 + y^2 - k y^2 - 2 y y1 + y1^2 + 2 k y y2 - k y2^2 == 0      but how can I transform the above equation to some form like `(x-...)^2 + (y-...)^2 = ...` by mathematica?


title: How to wait until a Listen mode link gets connected to?

text: Suppose we create a link like this:               link = LinkCreate["mylink", LinkMode -> Listen]      How can we wait until this link gets connected to by another process, and time out if there's no incoming connection?


title: Removing elements from a list which appear in another list

text: There are two lists {a, b, c, a, d, a, e} and {a, c, a}. I need to remove those elements from the first list which appears in a second list, to get {b, d, a, e}


title: Go to definition of symbol/variable

text: Is there any easy way of directly jumping to the definition of a Variable like it is implemented in some good IDEs? Currently I have to search manually (ctrl+f) through the whole workbook to find it somewhere.


title: Calculate mean square displacements for different particles from a excel file

text: I have the particle movement data in the following format:               {      {1., 1., 0., 0.},      {1., 2., 0.240727, 0.974106},      {1., 3., 0.0215366, 0.703085},      {1., 4., 0.437541, 1.19085},      {2., 1., 0., 0.},      {2., 2., -2.17808, 0.455328},      {2., 3., -2.97556, -0.668351},      {2., 4., -3.91848, -1.25396},      {3., 1., 0., 0.},      {3., 2., -0.523589, 0.136621},      {3., 3., -1.87956, 0.679403},      {3., 4., -2.36116, 0.749859}     }      The first number is the particle number, second is the frame number in the movie, third is the $x$ position, and the fourth is the $y$-position. So in the above data, the first 4 lists belong to particle 1, the next 4 to particle 2 and the last 4 to particle 3. I need to calculate the mean square displacement (MSD) $(x_2-x_1)^2 + (y_2-y_1)^2$ for each of the particles separately. I can calculate MSD if I don't have to care about the above data having 3 particles, treat all as the same (but that's not what I want). I need to calculate MSD for each of these particles separately. Basically, somehow I have to tell the program where the the data for particle 1 end and where data for particle 2 starts. In MATLAB, I have used the `find` function to return the location index of the number "1" in the second column of the data and run the loop till that index to calculate MSD for each particle. I am new to _Mathematica_ and trying to learn it. It's taking me a while to find a answer to this problem. Can anyone help?


title: Extracting data from a table under conditions

text: I have a very large table with two columns. Let's say the name of first column is E and the name of the second is P. How can I get the E values when P = 0.


title: Distribution of random points in 3D space to simulate the Crab Nebula

text: I'm generating some 3D models of planetary nebulae and supernova remnants for _Celestia_ , a free OpenGL astronomy software. Currently, I know how to do it with random points inside a spherical shell. However, I'm still unable to generate filaments like those in the **Crab nebula** , and I need some help on this. You can see some of the models I've created there : Nebulae models for Celestia. Someone has a suggestion about how to generate random filaments with random points only ? Here's a small part of the code I'm currently using to generate a shell nebula :               X[r_, u_, phi_] := Oblateness r Sqrt[1 - u^2] Cos[phi]     Y[r_, u_, phi_] := Oblateness r Sqrt[1 - u^2] Sin[phi]     Z[r_, u_] :=  r u          Shell[r_, u_, phi_] := {X[r, u, phi], Y[r, u, phi], Z[r, u]}          Coords[n_] := SetPrecision[Flatten[Table[Shell[#1, #2, #3] &[         Random[BetaDistribution[alpha, beta]],         Random[Real, {-1, 1}],         Random[Real, {0, 2Pi}]     ], {n}], 0], CoordinatesPrecision]      This code defines "n" points inside an oblate sphere. If "n" is large, I get an uniform distribution of points, without any internal filaments-like structures. How can I distribute the "n" points so they form "N" filaments inside the sphere, of random lenght and randomly oriented ? There should be some parameters which specify the mean number "p" of points for each filament, so approximately n = p * N. ![A picture of the Crab nebula \(Messier 1\)](http://i.stack.imgur.com/KhZiQ.jpg) **EDIT 1** **Just some precision :** I would like to reproduce _very qualitatively_ the Crab nebula as a 3D object made of points, with definite cartesian coordinates X, Y, Z. The code should be compatible with _Mathematica 7.0_. The features which are desired are the long filaments structures inside the nebula. Ideally, I would like to define a statistical distribution of variables X, Y, Z that could generate some random filaments with voids between them. * * * **EDIT 2** Here's a part of the code I'm now using to generate the models (the rest of the code isn't relevant here). Thanks a lot to all who responded, and thanks to _Simon Woods_ , from whom that code was done ! I still have some issues, however (see below) :               InternalColor := RGBColor[0.2, 0.55, 0.8, 0.6]; (* color at the center of the nebula *)     MiddleColor := RGBColor[0.4, 0.6, 0.4, 1]; (* color of transition to the exterior part *)     ExternalColor := RGBColor[0.9, 0.3, 0.4, 0.4]; (* color of the exterior part *)     MinRadius := 0.00; (* min radius of distribution *)     MaxRadius := 1.00; (* max radius of distribution *)     MinSprite := 0.003; (* min radius of sprites *)     MaxSprite := 0.07; (* max radius of sprites *)     Oblateness := 0.8; (* oblateness of the spherical distribution *)     CoordinatesPrecision := 8;     NumberOfVoids := 1000;     NumberOfPoints := 20000;          SpriteSize[r_] := MinSprite + (MaxSprite - MinSprite)(r - MinRadius)/(MaxRadius - MinRadius);          voidpts = Select[RandomReal[{-1, 1}, {NumberOfVoids, 3}], MinRadius <= Norm[#/{1, 1, Oblateness}] <= MaxRadius &];     pts = Select[RandomReal[{-1, 1}, {NumberOfPoints, 3}], MinRadius <= Norm[#/{1, 1, Oblateness}] <= MaxRadius &];     nf = Nearest[voidpts];     DistributeDefinitions[nf];          pts = ParallelMap[Nest[0.9975 (# + 0.01 (# - First@nf[#])) &, #, 100] &, pts];          SpriteColor = Blend[{InternalColor, MiddleColor, ExternalColor}, #] &;     PlotColor = ColorData["SunsetColors"];          Graphics3D[{PointSize[0.005], {PlotColor[Norm[1.3 #]], Sphere[#, 0.005]} & /@ pts}, Boxed -> False, Background -> Black, Lighting -> "Neutral", SphericalRegion -> True]          Filaments = Join[#, {SpriteSize[Norm[#]]}, List@@SpriteColor[1.3 Norm[#]]] &/@pts;     FilamentsData := SetPrecision[Flatten[Filaments, 0], CoordinatesPrecision]      This code is slow. Is there a way to improve it ? More importantly, I'm having an issue with the number of points generated at the intersection of several filaments : there's too much points accumulated there, and this is a problem for rendering in _Celestia_ (too much sprites at the same location is ugly). Is there a way to reduce or dilute these points ? **Very important :** I need to add a constraint on the shortest distance between two points : it shouldn't be smaller than the local sprite size. How can I add this constraint to the iteration process ?


title: Inconsistent results from equivalent integrals

text: Why is _Mathematica_ returning different values for these two integrals: ![Complex Integral Sine Cosine](http://i.stack.imgur.com/1KIMw.png) I am just being introduced to complex integration, so it's possible that I have a misunderstanding of how this works, but in this case the functions inside the integral are completely equivalent. For some reason the image is not displaying, here is the code:               Integrate[1/(a^2*Cos[t]^2 + b^2*Sin[t]^2), {t, 0, 2*Pi}]          Integrate[1/(a^2*((E^(I*t) + E^((-I)*t))/2)^2 + b^2*((E^(I*t) - E^((-I)*t))/(2*I))^2),       {t, 0, 2*Pi}]


title: Question about using a pattern in ReplacePart

text: I noticed that "ReplacePart" can use pattern. For example:               ReplacePart[{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, {i_, i_} -> x]     {{x, 0, 0}, {0, x, 0}, {0, 0, x}}      So I naively think I can do a little change like               ReplacePart[{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, {i_+1, i_} -> x]      But it gives               {x, x, x}      Why? I anticipated that the result whould be               {{0, 0, 0}, {x,0,0}, {0, x, 0}}      Can anyone help?


title: How to remove some elements in a list based on a rule?

text: I want to deal with the following list.               mylist = Table[cof[i] exp[i], {i, 1, n}]; (*n is very larege *)      `exp[ ]` is a function of `{x1, x2, x3, x4, ...}` and `cof[]` doesn't depend on the variables `{x1, x2, x3, x4, ...}`. `exp[ ]` has a pattern like this, `x_ Exp[_]` (see the following example). I want to deal with this list according to some rule. That is, if `exp[k1]` can be obtained by `exp[k2]` under some permutation of the variables `{x1, x2, x3, x4, ...}`, then I delete the term `cof[k2] exp[k2]` in `mylist` and change `cof[k1]` to `(cof[k1] + cof[k2])`. It seems I should compare all the `exp[]` terms. I cannot find a way to that for this problem. Any help? Here is a simple example,               inputlist = {2 const x1 x2 Exp[2 x1 x1 + 3 x2 x2 + 2 x3 x3 - x1 x2 + x2 + cf1],                   2 x1 x3 Exp[2 x1 x1 + 2 x2 x2 + 4 x3 x3 - x1 x2  ],                  -x1 x3 Exp[2 x1 x1 + 3 x3 x3 + 2 x2 x2 - x1 x3 + x3 ],                  3 Exp[2 x1 x1 + 3 x2 x2 + 4 x3 x3 ],                  -2 Exp[4 x1 x1 + 2 x2 x2 + 3 x3 x3 ]};      The corresponding `exp[]` can be written as,               exp[1] = x1 x2 Exp[2 x1 x1 + 3 x2 x2 + 2 x3 x3 - x1 x2 + x2];     exp[2] = x1 x3 Exp[2 x1 x1 + 2 x2 x2 + 4 x3 x3 - x1 x2  ];     exp[3] = x1 x3 Exp[2 x1 x1 + 3 x3 x3 + 2 x2 x2 - x1 x3 + x3 ];     exp[4] = Exp[2 x1 x1 + 3 x2 x2 + 4 x3 x3 ];     exp[5] = Exp[4 x1 x1 + 2 x2 x2 + 3 x3 x3 ];      Based on the rule, we notice that               exp[1] /. {x1 -> x1, x2 -> x3, x3 -> x2} == exp[3];      exp[4] /. {x1 -> x2, x2 -> x3, x3 -> x1} == exp[5];      so the output list should be               outputlist = {       (2 const Exp[cf1]-1) x1 x2 Exp[2 x1 x1 + 3 x2 x2 + 2 x3 x3-x1 x2 + x2],        2 x1 x3 Exp[2 x1 x1 + 2 x2 x2 + 4 x3 x3 - x1 x2 ],       Exp[2 x1 x1 + 3 x2 x2 + 4 x3 x3]     }


title: Is there a `Real` equivalent to `FromDigits`?

text: One can extract an `Integer`'s digits using `IntegerDigits` and reassemble them into the `Integer` using `FromDigits`. Is there a function that reassembles the output of `RealDigits` into the `Real`?


title: extracting the rows of a matrix satisfying a condition (e.g. all elements negative)

text: I have a matrix with thousands of rows and want the submatrix comprising the rows of the original matrix that have, e.g. a negative element in column 3. How to do that?


title: Need a generalization of RootApproximant to recognize linear combinations over algebraic numbers

text: `RootApproximant` does a very good job when I need to recognize an algebraic number and when enough of its digits are known (or even when an unlimited number of digits can be obtained from a numerical computation given enough time). But often I need to recognize linear combinations of the form $\alpha+\beta\cdot\tau$ where $\alpha$ and $\beta$ are unknown algebraic numbers, and $\tau$ is a known fixed transcendental number (e.g. `Pi`, `E` or `Log[2]`). Some simple cases can be solved using _WolframAlpha_ lookup:               WolframAlpha["2.421441469079183123",         IncludePods -> "PossibleClosedForm",         TimeConstraint -> ∞]      Is there a way to solve this problem in general in _Mathematica_?


title: Mathematica NDSolve and 'Compile'?

text: Since the consensus is usually that `NDSolve` speeds fares badly against compiled code such as c++ ODE solvers using GSL say, is it possible to make up for this lag by using Mathematica's `Compile` functionality? Somehow compiling your ODE to make it execute quicker or some such? If not is there a way to use something like MathLink? And finally, is it really true that c++ ODE solvers outperform Mathematica 8 `NDSolve` in terms of speed?


title: How do you efficiently return all of a List but one element?

text: I have a problem that I am working on that requires that I compare several lists of overlapping data points. As I traverse one of the lists, I'd like to only compare those data to the other lists, and not itself. So, how does one efficiently do this, especially if it must be done potentially hundreds of times? Obviously, if I can control the order in which I make the comparisons, any method would work as I can limit the number of times this has to be done. But, I can't necessarily guarantee the order. Now both `Drop` and `Take` could be used for this, but I'm interested to know if they are the fastest methods to do this, or is there something else?


title: Getting a list of accurate coordinates from a plot

text: I have encountered this problem of getting a list of accurate coordinates from a plot. Upon searching online, the best method of doing so is to right-click on the plot and select "Get Coordinates". After which, I will have to use my mouse to probe and move along the plot as accurately and steadily as I can, but it was rather inaccurate. Hence, I will like to ask if there are any other methods to get the list of accurate coordinates from a plot? Thank you!


I have the following two questions   1. How to visualize the dependence Y versus X with Mathematica using ContourPlot, if it is given by the following system of two equations: Y=f(X,Z) and g(X,Z)=0   2. How to return the points {Xi,Zi} generated by ContourPlot applied to g(X,Z)=0 that visualizes Z=q(X).  Remark 1: The answer on the second question resolves evidently the problem formulated in the first question Remark 2: In fact the problem formulated in the first question may be effectively solved without ContourPlot by differentiating in X both equations, and numerical solving the resulting system of 2 ordinary differential eqs Any help and suggestions are appreciated.


title: How to split a Dataset into training and testing for machine learning?

text: Suppose I have iris data In the Dataset Format. ![enter image description here](http://i.stack.imgur.com/QCRUC.png) How to split the iris data Into training and testing for Machine learning? For example,Transform the data for Classify.


title: Removing calls to MainEvalute when using inlined compiled closures

text: This question is tightly related to the answer Shaving the last 50 ms off NMinimize. There @OleksandR shows how inlined closures can be used to eliminate calls to `MainEvaluate`. This is crucial for my application, since I need every last drop of performance mma can offer. Here is an extremely simplified working example (before you run this code, make sure to evaluate this package, containing the NelderMeadMinimize code):               Needs["CompiledFunctionTools`"]     With[{minimizer =          NelderMeadMinimize`Dump`CompiledNelderMead[          Function[{a, b, c}, (a - d1)^2 + (b - d2)^2 + (c - d3)^2], {a, b, c},             "ReturnValues" -> "OptimizedParameters"],         epsilon = $MachineEpsilon},       orgFitter =         Compile[{{d1, _Real, 0}, {d2, _Real, 0}, {d3, _Real, 0}},          minimizer[RandomReal[{0, 1}, {3 + 1, 3}], epsilon, -1],          CompilationOptions -> {"InlineCompiledFunctions" -> True},          RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False}]];     StringMatchQ[CompilePrint[orgFitter], "*MainEvaluate*"]     (* -> False *)     orgFitter[12, 2, 3]      Now, if I change `(a - d1)^2 + (b - d2)^2 + (c - d3)^2` to calling a compiled function the calls to `MainEvalute` are not eliminated! Please, instead of the simple `myHi2` imagine a monster of a compiled procedure containing several hundred lines.               myHi2 = Compile[{{a, _Real, 0}, {b, _Real, 0}, {c, _Real,           0}, {d1, _Real, 0}, {d2, _Real, 0}, {d3, _Real,           0}}, (a - d1)^2 + (b - d2)^2 + (c - d3)^2];     With[{minimizer =          NelderMeadMinimize`Dump`CompiledNelderMead[          Function[{a, b, c}, myHi2[a, b, c, d1, d2, d3]], {a, b, c},           "ReturnValues" -> "OptimizedParameters"],         epsilon = $MachineEpsilon},       orgFitter =         Compile[{{d1, _Real, 0}, {d2, _Real, 0}, {d3, _Real, 0}},          minimizer[RandomReal[{0, 1}, {3 + 1, 3}], epsilon, -1],          CompilationOptions -> {"InlineCompiledFunctions" -> True,            "InlineExternalDefinitions" -> True},          RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False}]];     StringMatchQ[CompilePrint[orgFitter], "*MainEvaluate*"]     (* -> True *)     orgFitter[12., 2., 3.]      **How can I eliminate this calls to`MainEvaluate`?** Also, could someone help me understand, why this does not compile:               orgFitter = Compile[{{d1, _Real, 0}, {d2, _Real, 0}, {d3, _Real, 0}},        With[{minimizer =            NelderMeadMinimize`Dump`CompiledNelderMead[            Function[{a, b, c}, (a - d1)^2 + (b - d2)^2 + (c - d3)^2], {a,              b, c}, "ReturnValues" -> "OptimizedParameters"],           epsilon = $MachineEpsilon},         minimizer[RandomReal[{0, 1}, {3 + 1, 3}], epsilon, -1]],         CompilationOptions -> {"InlineCompiledFunctions" -> True,           "InlineExternalDefinitions" -> True},         RuntimeOptions -> {"Speed", "EvaluateSymbolically" -> False}];          CompilePrint[orgFitter]


title: Area or NIntegrate curves defined by points?

text: Is there a convenient method to compute the AUC (Area Under the Curve) metric that quantifies a Receiver Operating Characteristic (ROC) like shown here? ![enter image description here](http://i.stack.imgur.com/JYKRr.png) The data used to build the ROC are just pairs of real values in `[0,1]`:               {{1, 1}, {15/64, 30/73}, {5/64, 21/218}, {3/64, 5/109}, {1/64, 3/       109}, {0, 2/109}, {0, 1/109}}      Although this data can be closed to form a polytope, documentation for Area states that polytope edges need to be unit-length, which is not the case in general. Is there a convenient way to pass this data to `NIntegrate`, and if so what integration methods (eg, Trapezoid vs ..) and interpolation are appropriate for the ROC AUC problem?


title: Plot3D and NMinimize do not work correctly?

text: See my code:               ref = Rasterize[Graphics3D[Sphere[]], ImageResolution -> 16,      Background -> LightYellow]     Model[{x_, y_}] :=      Rasterize[Graphics3D[Sphere[], ViewPoint -> {x, y, 1}],      ImageResolution -> 16, Background -> LightYellow]     CostFunction[{x_, y_}] :=      Total[Flatten[ImageData[ImageSubtract[ref, Model[{x, y}]]]]]      Plot3D[CostFunction[{x, y}], {x, -1, 3}, {y, -1, 3}].// My problem is here?????      But When I use               list = ParallelTable[{x, y, CostFunction[{x, y}]}, {x, -10,      10}, {y, -10, 10}];     list = ParallelTable[{x, y, CostFunction[{x, y}]}, {x, -10,      10}, {y, -10, 10}];      I get the function graphics! What is the problem? In the other hand: I want to minimize the cost function using `NMinimize[]`               NMinimize[CostFunction[{x, y}], {x, y}]     {22083.2,{x->0,y->0}}      But When I calculate               CostFunction[{0,0}]       I obtain 8758.65? What is the issue please?


title: Solving an exponential multivariate equation

text: I have the following equation:               p = 1/(1 + E^(-51.179 + 0.849 x1 + 2.3649 x2 + 1.155 x3 + 1.46 x4 + 1.31 x5))      and I want to find the set of values for x1 to x5 such that the fraction be equal to 0.5.In other words, I want x1-x5 values for which `p==0.5`. I tried `NSolve` and `Reduce` but those didn't work. All x1-x5 are between 0 and 10. I searched the list but I couldn't come up with a solution. Any help is appreciated.


title: How to make a depth map from a 3D model?

text: Given a 3D .obj model, for example a rabbit. How can we make a depth map out of it? Any idea or help would be much appreciated.


title: What methods does Solve use?

text: Could you tell me which method that `Solve` applies to solve linear and polynomials equations?


title: ExampleData menu view

text: I'm trying to build an ExampleData browser, so that the "collection"/"type" is selectable in a drop down menu, and the "name" is selectable in another drop down menu. What I have so far:               DynamicModule[ {},      Panel[       Column[{         PopupMenu[Dynamic[q], ExampleData[]],         (PopupMenu[Dynamic[h], Last[##] & /@ ExampleData[#]]) & /@           Dynamic[q],         ExampleData[Dynamic[q], Dynamic[h]]         }]       ]      ]      ...Only produces a nice error message: ![ExampleData is not evaluating!](http://i.stack.imgur.com/w9vKs.png) Why isn't ExampleData evaluating the dynamic value of q & h? (i.e. `ExampleData["TestImage", "Aerial2"]`)


title: Empty plot - Euler's method

text: The answer from this question helped me use Euler's method. It worked for a simple function, but when the function is more complicated, I get an empty plot. This is my function: > $y'=-\frac{3*(3*sin^2(t)-3*(y-1)^{1.5})*y^2}{pi*(1.6)^2}$ And this is the code:               Clear[x];     x = x /. First[         NDSolve[{x'[t] ==          -(3*(3*Sin[t]^2 - 3*((x[t] - 1)^1.5))*(x[t]^2))/(Pi*(1.6)^2), x[0] == 0.8},         x, {t, 0, 10}, StartingStepSize -> 0.5,          Method -> {"FixedStep", Method -> "ExplicitEuler"}]];     grid = Table[{t, x[t]}, {t, 0, 10, 0.5}]     ListLinePlot[grid]      What am I doing wrong?


title: Replacing list elements by other list elements

text: I am a beginner of _Mathematica_ and need some help for the following issue. I have the following two lists:               NamesandIDs = {{"ccc", 05}, {"ggg", 03}, {"zzz", 17}}          data = {{"zzz", 50, 30}, {"zzz", 49, 32}, {"ccc", 49, 21}, {"ccc", 27, 68},             {"ggg", 72, 38}, {"ggg", 77, 59}}      In `NamesandIDs` the first element of each list is a name and the second is ID number corresponding to each name; `data` contains some data for each name. With the two lists, what I wanna do is two things.   * Replacing names in `data` by the corresponding IDs, i.e. I would like to have the following result:              data = {{17, 50, 30}, {17, 49, 32}, {05, 49, 21}, {05, 27, 68}, {03, 72, 38},              {03, 77, 59}}        * Inserting the ID corresponding to each name into the second position of each list in "data," i.e. I would like to have:              data = {{"zzz", 17, 50, 30}, {"zzz", 17, 49, 32}, {"ccc", 05, 49, 21},              {"ccc", 05, 27, 68}, {"ggg", 03, 72, 38}, {"ggg", 03, 77, 59}}      I highly appreciate if someone could let me know how to come up with the two results above. Thank you very much in advance!


title: Possible to scope an anonymous function within Module?

text: This is my first question. I'm fairly new to _Mathematica_ and completely new to SE, so I apologize if this question is trivial. I'm working on a problem that requires a function to be redefined several times and applied to data. My "function generator" (not sure if this is the proper application of this term) looks like this:               makeLine[{m_, b_}] := line = Function[{x, y}, y - m x - b]      The idea being that the program can call line several times and then redefine it and call it again. I was hopeful that I could do something like this:               Module[{line}, makeLine[{1, 0}]]      to avoid defining line as a global function, but it doesn't work.               ?line      > Global`line   >  line = Function[{x\$, y\$}, y\$ - 1 x\$ - 0] So, is it possible to do this? If not, can someone suggest an alternate construct that does essentially the same thing?


title: Preparing data for making an ErrorListPlot

text: I often have the following notebook in _Mathematica_ , which I use to make a dataset and associated errors:               x = {0, 2, 4, 6, 10, 20};     y = {979, 146, 141, 157, 187, 274};     uncY = Sqrt[y];     dataVector = Thread[{x, y}];      I want to make an ErrorListPlot, so I need to add `ErrorBar` with each `uncY`-value as an element in each data pair. So the final dataVector should have the form               {{x_i, y_i}, Errorbar[uncY_i]}      What is an easy way to achieve this, without using a `For`-loop?


title: Need help coding/creating a recursive list

text: I have two lists `A` and `B`, each with 99 real numbers. I want to form a list, `C`, whose elements are functions (`F[]`) of `A` and `B`, and also previous elements of `C` itself.               C ={F[A1/B1], F[A2/(B2-A1/C1)], F[A3/(B3-A1/C1-A2/C2)], ..., F[A99/(B99-A1/C1...-A98/C98.)]}      where the integers after `A`, `B`, and `C`, are element indices. I appreciate any tips on how to code this in _Mathematica_.


title: Replace a specified portion of an array with elements from another smaller array

text: This may be a trivial question, but I have been at it for a couple of hours and I have not made much progress. I have a 10 x 10 array (T) that I have used to generate an 8 x 8 array (Q). I want to replace the interior of array T with array Q. I can think of lots of really cumbersome ways to do this, but I assume that there is a "good" way to do this... I suspect that this can be done using `ReplaceAll` but I cannot get the form correct. Any pointers would be greatly appreciated. The code and arrays are:               Nx = 10;     Ny = 10;     (* Initial Temperature Array *)     T = Table[0, {i, Nx}, {j, Ny}];     T[[1]] = Table[Tbottom, {i, Nx}];     T[[Ny]] = Table[Ttop, {i, Nx}];     T[[All, 1]] = Tleft;     T[[All, Nx]] = Tright;     (* Finite Difference of Array *)     Q = Table[        0.25*(T[[i - 1, j]] + T[[i, j + 1]] + T[[i + 1, j]] +            T[[i, j - 1]]), {i, 2, Nx - 1}, {j, 2, Ny - 1}];     (* Output in Matrix Form *)     T // MatrixForm     Q // MatrixForm      **Array T** $$ \left( \begin{array}{cccccccccc} 50 & 50 & 50 & 50 & 50 & 50 & 50 & 50 & 50 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 50 \\\ 50 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 50 \\\ \end{array} \right) $$ **Array Q** $$ \left( \begin{array}{cccccccc} 25\. & 12.5 & 12.5 & 12.5 & 12.5 & 12.5 & 12.5 & 25\. \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 12.5 & 0\. & 0\. & 0\. & 0\. & 0\. & 0\. & 12.5 \\\ 37.5 & 25\. & 25\. & 25\. & 25\. & 25\. & 25\. & 37.5 \\\ \end{array} \right) $$


title: Drawing partition diagrams on spheres

text: I will be doing a few presentations at an undergraduate research conference later, the topics of which are somewhat tentative at the moment, but one of the things I wanted to go over were some of the introductory bits (say, first 10ish pages) in the paper _On Tutte's Chromatic Invariant_, and with an advisor I found an excellent idea for a visual aid demonstration on how the trace form on the partition algebra can be seen as a monomial in terms of the join operation by using a spherical, baseball-esque covering. These are what the partition diagrams I am interested in should look like (the middle one): ![partition](http://i.stack.imgur.com/SuXhC.png) Notice that in the middle one, there is "vertex-splitting." For non-planar partitions, different shaded regions may overlap, and we have to choose (arbitrarily) which one will go over which. What I want to do, conceptually, is put two partition diagrams over top each other and glue their boundaries, then blow it up so that it is a sphere: one side of the sphere will show one partition diagram, and the other side will show the other partition diagram. The resulting figure will illustrate the "trace form" $\rm tr(p_\pi p_\sigma^{t})$ of the two partitions $\pi$ and $\sigma$ (this is detailed in the linked paper, though somewhat tersely.) Ideally, then, the sphere and the shaded regions will look very pretty and I will be able to rotate it at my whim, and I will be able to animate say a dozen and a half of these figures and put them onto a slide. What sorts of techniques or functions or whatever would Mathematica veterans recommend a newbie look into to accomplish this task?


title: axis label formatting in Plot3D

text: I have the following code:               Plot3D[Cx + p, {Cx, 0, 1}, {p, 0.5, 1},     AxesLabel -> {"Cx", "p", "Val"},     BaseStyle -> {FontWeight -> "Bold", FontSize -> 18}]      which will give me the following plot: ![enter image description here](http://i.stack.imgur.com/iX07P.png) The z-axis label overlaps with the z-axis numbers. How can I prevent the overlap between the label and the numbers on the axis?


title: Collision of axes labels and ticks

text: Is there a way to prevent ugly collision of axes labels and axes number like in the following examples, without the need of adding white space: ### Plot1:               Plot3D[Sin[x] Cos[y], {x, -Pi, Pi}, {y, -Pi, Pi},          AxesLabel -> {"ω", Subscript["E","F"], "Log[σ(ω)]"}, LabelStyle -> Directive[16]]      ![Plot1](http://i.stack.imgur.com/wecGc.jpg) To avoid this distant axes label "Log[$\sigma(\omega)]" one can rotate it, but then: ### Plot2:               Plot3D[Sin[x]Cos[y],{x,-Pi,Pi},{y,-Pi,Pi},         AxesLabel->{"ω",Subscript["E","F"],Rotate["Log[σ(ω)]",90 Degree]},         LabelStyle->Directive[16]     ]      ![Plot2](http://i.stack.imgur.com/p8XS9.jpg) I cannot imagine that using a 2-dimensional column with one element `"Log[σ(ω)]"` and the other a blank square is the only solution to cure Plot2. Is there a nice solution to prevent such an overlay?


title: complicated Numerical Integration, FEM application

text: I am trying to calculate a 2d Integral which has another 2d integral in the integrands. here is the setup:               alpha = 1; sigma1 = 4; sigma2 = 1; phi = 0.5;     a = 0.5*(Cos[phi]/sigma1)^2 + 0.5*(Sin[phi]/sigma2)^2     b = 0.25*Sin[2*phi]*(-1*sigma1^-2 + sigma2^-2)     c = 0.5*(Sin[phi]/sigma1)^2 + 0.5*(Cos[phi]/sigma2)^2     A = alpha/(2*Pi*sigma1*sigma2)          t[x1_, y1_, x_, y_] := A*Exp[-1*(a*(x - x1)^2 + b*(x - x1)*(y - y1) + c*(y - y1)^2)]          B2[x1_, y1_, x_, y_] := HeavisideLambda[x - x1, y - y1]          trans:= NIntegrate[B2[x1, y1, xz, yz]*               NIntegrate[t[xz, yz, xp, yp]*(B2[x2, y2, xz, yz] - B2[x2, y2, xp, yp]),                  {xp, x2 - 10*sigma1, x2 + 10*sigma1},                  {yp, y2 - 10*sigma2, y2 + 10*sigma2}],                          {xz, x1 - 1, x1 + 1}, {yz, y1 - 1, y1 + 1}]     trans[0,0,1,0]     trans[0,0,10,10]     trans[0,0,50,50]      I am trying to get numbers for trans[0,0,x,y] for different x,y, but I couldn't get any results yet. I tried analytic integration too (Integrate instead of NIntegrate) but it didn't help either. I am quite new to Mathematica so I don't know what options in NIntegrate can help me here. I have tried the same integral in Maple, there it works for some values of phi, and doesn't for others (so i'm sure the thing should some how work here too). for example, it works fine for phi=0, but for phi=0.5 it fails. For phi=Pi/4, it works but the results don't go to zero as x,y get far from zero (e.g. trans[0,0,50,50]), which is the expected behavior for this integral. any ideas? Thanks in advance


title: Saving Mathematica kernel state?

text: If I save a notebook, I only save what I see. That is, if I close Mathematica and reopen the notebook later, all previous calculations are lost, except for those things I've output. Now I know that you can save single definitions (and their dependencies) with `Save`, however is there a way to save the whole kernel state (preferably including internally cached data, e.g. from `FullSimplify`) so that when I reload both notebook and kernel state, I can continue to work exactly where I left off? If there's no ready solution for it: From what I understand, the explicit definitions are stored in `UpValues`, `DownValues` and `OwnValues`; also `Options` and `Attributes` affect evaluation, and therefore would have to be saved. However, those all expect an argument specifying a symbol to give information about. Is there any way to get a complete set of them? And would saving those actually suffice, or is there something else needed, too? Also, is there some way to explicitly get at internal cached information (it doesn't need to be in an understandable format, just being able to save and reload it would be sufficient)?


title: How to save all variables in the workspace into a file?

text: I did some time consuming computation and obtained a lot of arrays and variables; however after restart the Mathematica Kernel, all these computational results disappeared. How can I save all these workspace variables into some file, and then re-use them by loading the file next time when I restart Mathematica? (In Matlab all the current workspace can be saved into an `*.mat` file by `save`, and re-used by `load`)


title: Automatically restoring the state of a prior session

text: I have the following problem (I guess a very naive one): I work with some data and make a statistical analysis in _Mathematica_. I do it over several days and each time I open the file, I have to go through all previous lines of calculations, in order that all previously defined variables and data sets are uploaded into _Mathematica_ 's memory. My question is, does there exist a command so that each time I open the file, all defined previously variables are put into the working memory automatically.


title: Running an initialization cell on Mathematica start up

text: I am writing a bash script to run a bunch of Mathematica `.nb` files serially. So I thought I'd convert my Mathematica cells into `initialization cells`. However, I notice that the initialization cell isn't run on start up unless I evaluate it using `Shift` \+ `Enter` or `Command` \+ `Enter`. Is it not an initialization cell that I am looking for? Steps I took to make my cell an initialization cell:   1. Selected the cell with mouse click   2. Cell > Cell properties > Initialization cell ## Edit I just added `InitializationCellEvaluation -> True` as the first line of my file. However, how should I make this evaluatable?


title: Can the value of a variable be made to persist between front end sessions?

text: For example, say I create a notebook with a cell               a = 5 + 2      and then I close _Mathematica_ , reopen the notebook, enter a new cell               b = a*2      and evaluate the new cell with `Shift`+`Enter`. I want the output to be 14 without evaluating to evaluate the first cell. Is this posible? * * * I want this because i'm making a Stylesheet Creator and i have ColorSelectors, inputfield, etc and i want to have dafault values.


title: How to automate Mathematica scripts? - I

text: I would like to use the Windows Task Scheduler, or Visual Cron, to start a _Mathematica_ notebook or .m file to do some system maintenance tasks: copy files from one place to another, etc. How do I set up the notebook/file so it will execute when started without asking any questions? I answered this question myself here.


title: How do I automatically evaluate a cell when a notebook is opened?

text: I'm trying to put together a GUI in _Mathematica_ and need to evaluate one cell to kick that off. Is there a way to automatically evaluate that cell when the notebook is opened? Here is an example of the code I'm using in that cell. Yes I know loading them like:               <<one.nb`..."       etc. is best, but that doesn't seem to work on my system. Thanks!               SetDirectory[NotebookDirectory[]];      nbs = {"one.nb", "two.nb", "three.nb", "four.nb", "five.nb", "six.nb", "seven.nb",             "eight.nb"};     For[i = 1, i <=  Length[nbs], i++,         Block[{nb = NotebookOpen[NotebookDirectory[] <> nbs[[i]]]},               FrontEndTokenExecute[nb, "EvaluateNotebook"]


title: Beginner: Saving & Reloading but Preserving Input/Output

text: This is my first post on this StackExchange. I made a _Mathematica_ Notebook with a simulated data set the other day, just to learn the basics of making different graphs and creating a linear regression, etc. I figured now that I had the Notebook created that I would be able to open the Notebook and completely continue where I left off. (In the previous session I said `model = LinearModelFit[data, {1, x}, x]`.) However while when I type "mo..." it suggests `model`, it doesn't extend this to behaving as it did before when I typed, say, `model["BestFit"]` to get the function form. Instead, once I've reloaded a saved Notebook in which `model` has already been defined it does this: Input:               model["BestFit"]      Output: > `model[BestFit]` Simply without the quotes! All functions that would be processed do this instead. While I'm not complaining if this isn't the case, it seems likely I'm just missing something simple about saving/reloading that would allow me to completely continue where I left off, without first re-processing all my inputs in order again. Anyone know a solution to this problem? * * * Thank you xslittlegrass & Nasser for your clarifications on DumpSave; from what I can tell it performs what I was asking for. A more succinct way to state my question would have been "can I save the kernel state?" as was asked in the following link's question. Copy-pasting the answer from the link xslittlegrass posted: "No, currently you can not save the kernel state; restarting the Kernel from a previous state would need to modify and re-instantiate all sort of things." -ruebenko "While it is true that you can not save a full state of the kernel, in some cases it may be enough for your purposes to save all symbols' definitions in some context(s), such as Global` (or whatever other contexts are of interest to you). This can be done via DumpSave, like DumpSave["state.mx", "Global`"] The .mx file generated by DumpSave will be platform-specific though. By using Get at some later point, you can reconstruct the values stored in symbols in those contexts you saved: Get["state.mx"] As stated already by @ruebenko, this will not generally fully reconstruct the kernel state. But if you manage to correctly account for all symbols (defined by you) which affect your computations, and depending on the circumstances, this may be enough for many practical purposes." -Leonid Shifrin Also, from following Mr. Shifrin's steps, it's important to note that you can name the file "state.mx" whatever you like (I chose 01.mx) and that if you do not specify a location during the DumpSave command, it will default to saving it to your Documents folder in C:\Users\User\Documents\01.mx. Likewise, if you use the Get command after reloading Mathematica and have moved the file from the default Documents folder, if you don't specify where it should look, Mathematica will fail to find it. Thanks for everyone's input.


title: What is Mathematica's equivalent to MATLAB's filter function?

text: The MATLAB code               filter(0.5,[1, -0.5], [1:10])      is equivalent to               Rest@FoldList[(#1 + #2)/2. &, 0, Range[10]]      I don't know how to implement something more general like，`filter([1,2,3],[4,5,6], [1:10])` in _Mathematica_. I'm trying to rewrite a snippet of MATLAB code to _Mathematica_. I'm just interested in the `filter` function and there is no other purpose. What is its equivalent or how can I implement it?               v = [0.0 + 2 j; -sqrt (3) - 1 j; sqrt (3) - 1 j];     n = randi (3, 1, 10000000);     p = filter (0.5, [1 - 0.5], v (n));     plot (p, '.b');


title: Problem using the DifferentialEvolution method of NMinimize

text: I have a function of 20 parameters, which 3 of the parameters are my physical parameters, and the others are pull terms to fix the errors. The goal is finding the global minimum of this function, to find the best fit of those three physical parameters which are minimizing my function. I am using `NMinimize`, with the `DifferentialEvolution` method; however, choosing different options of `DifferentialEvolution` changes my results drastically. I really don't know if I am using those options correctly or not, and I can't be sure if they are really giving my correct minimum. How can I choose these options?: `"CrossProbability"`, `"InitialPoints"`, `"PenaltyFunction"`, `"PostProcess"`, `"RandomSeed"`, `"ScalingFactor"`, `"SearchPoints"`, `"Tolerance"`. My code is long, I can't make it shorter, as I have to make some tables and do some `Interpolation` before defining my final function; however, I put my code here if somebody may need it:               d11 = 667.9; d12 = 451.8; d13 = 304.8; d14 = 336.1; d15 = 513.9; d16= 739.1;     d21 = 1556.5; d22 = 1456.2; d23 = 1395.9; d24 = 1381.3; d25 = 1413.8; d26 = 1490.1;     f11 = 0.0678; f12 = 0.1493; f13 = 0.3419; f14 = 0.2701; f15 = 0.115; f16 = 0.0558;     f21 = 0.1373; f22 = 0.1574; f23 = 0.1809; f24 = 0.1856; f25 = 0.178;f26 = 0.1608;          rhodatar = {{1.70059, 1.38938}, {1.88047, 1.24779}, {2.13609,      1.08850}, {2.39172, 0.93805}, {2.68521, 0.76991}, {2.97870,      0.61947}, {3.42367, 0.45133}, {3.88757, 0.30973}, {4.28521,      0.21239}, {4.68284, 0.14159}, {5.09941, 0.08850}, {5.55385,      0.06195}, {5.88521, 0.03540}, {6.39645, 0.01770}, {6.99290,      0.01770}, {7.68402, 0.01770}, {8.41302, 0.00885}, {9.25562,      0.00885}, {9.89941, 0.00885}, {10.89941, 0.00885}, {12., 0.00885}};          rhor = Interpolation[rhodatar];          rhofinalr[x_] := rhor[x]/NIntegrate[rhor[x], {x, 1.8, 12}];          sterm2ofp11 =NIntegrate[Sin[1.267*2.32*10^-3*d11/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f11sin1 =Table[{w,NIntegrate[Sin[1.267*w*d11/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]},{w,      Table[10^w, {w, -2.634512, -0.5, 0.01}]}];sterm3ofp11 = Interpolation[f11sin1];     f11sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d11/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm4ofp11 = Interpolation[f11sin2];     p11n =.;     p11n[y_, z_, w_] :=f11*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp11 - ((1 + Sqrt[1 y])/2)*z*sterm3ofp11[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp11[w]);               sterm2ofp12 =NIntegrate[Sin[1.267*2.32*10^-3*d12/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f12sin1 = Table[{w,NIntegrate[Sin[1.267*w*d12/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}{w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm3ofp12 = Interpolation[f12sin1];     f12sin2 = Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d12/enu]^2*rhofinalr[enu],{enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm4ofp12 = Interpolation[f12sin2];     p12n =.;     p12n[y_, z_, w_] :=f12*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp12 - ((1 + Sqrt[1 - y])/2)*z*sterm3ofp12[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp12[w]);               sterm2ofp13 =NIntegrate[Sin[1.267*2.32*10^-3*d13/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f13sin1=Table[{w,NIntegrate[Sin[1.267*w*d13/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm3ofp13 = Interpolation[f13sin1];     f13sin2=Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d13/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm4ofp13 = Interpolation[f13sin2];     p13n =.;     p13n[y_, z_, w_] :=f13*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp13 - ((1 + Sqrt[1-y])/2)*z*sterm3ofp13[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp13[w]);               sterm2ofp14=NIntegrate[Sin[1.267*2.32*10^-3*d14/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f14sin1=Table[{w,NIntegrate[Sin[1.267*w*d14/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm3ofp14 = Interpolation[f14sin1];     f14sin2=Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d14/enu]^2*rhofinalr[enu], {enu, 1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm4ofp14 = Interpolation[f14sin2];     p14n =.;     p14n[y_, z_, w_]:=f14*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp14 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp14[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp14[w]);               sterm2ofp15=NIntegrate[Sin[1.267*2.32*10^-3*d15/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f15sin1=Table[{w,NIntegrate[Sin[1.267*w*d15/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm3ofp15 = Interpolation[f15sin1];     f15sin2=Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d15/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp15 = Interpolation[f15sin2];     p15n =.;     p15n[y_, z_, w_] :=f15*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp15 - ((1 + Sqrt[1 - y])/2)*z*sterm3ofp15[w] - ((1 - Sqrt[y])/2)*z*sterm4ofp15[w]);               sterm2ofp16=NIntegrate[Sin[1.267*2.32*10^-3*d16/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f16sin1=Table[{w,NIntegrate[Sin[1.267*w*d16/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}{w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}];     sterm3ofp16 = Interpolation[f16sin1];     f16sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d16/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp16 = Interpolation[f16sin2];     p16n =.;     p16n[y_, z_, w_] :=f16*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp16 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp16[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp16[w]);               sterm2ofp21=NIntegrate[Sin[1.267*2.32*10^-3*d21/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f21sin1=Table[{w,NIntegrate[Sin[1.267*w*d21/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp21 = Interpolation[f21sin1];     f21sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d21/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp21 = Interpolation[f21sin2];     p21n =.;     p21n[y_, z_, w_] :=f21*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp21 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp21[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp21[w]);          sterm2ofp22=NIntegrate[Sin[1.267*2.32*10^-3*d22/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f22sin1=Table[{w,NIntegrate[Sin[1.267*w*d22/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp22 = Interpolation[f22sin1];     f22sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d22/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp22 = Interpolation[f22sin2];     p22n =.;     p22n[y_, z_, w_] :=f22*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp22 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp22[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp22[w]);          sterm2ofp23=NIntegrate[Sin[1.267*2.32*10^-3*d23/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f23sin1=Table[{w,NIntegrate[Sin[1.267*w*d23/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp23 = Interpolation[f23sin1];     f23sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d23/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp23 = Interpolation[f23sin2];     p23n =.;     p23n[y_, z_, w_] :=f23*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp23 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp23[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp23[w]);               sterm2ofp24=NIntegrate[Sin[1.267*2.32*10^-3*d24/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f24sin1=Table[{w,NIntegrate[Sin[1.267*w*d24/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp24 = Interpolation[f24sin1];     f24sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d24/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp24 = Interpolation[f24sin2];     p24n =.;     p24n[y_, z_, w_] :=f24*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp24 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp24[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp24[w]);               sterm2ofp25=NIntegrate[Sin[1.267*2.32*10^-3*d25/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f25sin1=Table[{w,NIntegrate[Sin[1.267*w*d25/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp25 = Interpolation[f21sin1];     f25sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d25/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp25 = Interpolation[f25sin2];     p25n =.;     p25n[y_, z_, w_] :=f25*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp25 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp25[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp25[w]);               sterm2ofp26=NIntegrate[Sin[1.267*2.32*10^-3*d26/enu]^2*rhofinalr[enu], {enu, 1.8, 12}];     f26sin1=Table[{w,NIntegrate[Sin[1.267*w*d26/enu]^2*rhofinalr[enu], {enu, 1.8, 12}]}, {w,Table[10^w, {w, -2.634512, -0.5, 0.01}]}]       sterm3ofp26 = Interpolation[f26sin1];     f26sin2 =Table[{w,NIntegrate[Sin[1.267*(w - 2.32*10^-3)*d26/enu]^2*rhofinalr[enu], {enu,1.8,12}]}, {w, Table[10^w, {w, -2.634512, -0.5, 0.01}]}];      sterm4ofp26 = Interpolation[f26sin2];     p26n =.;     p26n[y_, z_, w_] :=f26*(1 - y*((1 + Sqrt[1 - z])/2)^2*sterm2ofp26 - ((1 + Sqrt[1 -y])/2)*z*sterm3ofp26[w] - ((1 - Sqrt[1 - y])/2)*z*sterm4ofp26[w]);          normfactorfar = 17566.8; normfactornear = 151725.5;          obsnear = 149904.8; obsfar = 16161.5;          chi2reno[y_, z_, w_, a_, xinear_, fnear1_, fnear2_, fnear3_, fnear4_,fnear5_, fnear6_,xifar_, ffar1_, ffar2_, ffar3_, ffar4_, ffar5_, ffar6_, bnear_,bfar_] :=     (obsnear + bnear -normfactornear*(1 + a +xinear)*((1 + fnear1)*(p11n[y, z, w]) +      (1 + fnear2)*(p12n[y, z, w]) + (1 + fnear3)*(p13n[y, z, w]) +      (1 +fnear4)*(p14n[y, z, w]) + (1 + fnear5)*(p15n[y, z,w]) +      (1 + fnear6)*(p16n[y, z, w])))^2/obsnear +      (fnear1^2 + fnear2^2 + fnear3^2 + fnear4^2 +fnear5^2 +fnear6^2)/(0.009)^2 +xinear^2/(0.002)^2 +bnear^2/(1140.93)^2 +      (obsfar + bfar-normfactorfar*(1 + a +xifar)*((1 + ffar1)*(p21n[y, z, w]) +      (1 + ffar2)*(p22n[y,z, w]) +(1 + ffar3)*(p23n[y, z,w]) +      (1 + ffar4)*(p24n[y, z, w]) + (1 + ffar5)*(p25n[y, z, w]) +      (1 +ffar6)*(p26n[y, z, w])))^2/obsfar +      (ffar1^2 + ffar2^2 + ffar3^2 + ffar4^2 + ffar5^2 + ffar6^2)/(0.009)^2 + xifar^2/(0.002)^2 + bfar^2/(166.545)^2;          renovars = {y, z, w, a, xinear, fnear1, fnear2, fnear3, fnear4,fnear5, fnear6, xifar,ffar1, ffar2, ffar3, ffar4, ffar5, ffar6,bnear, bfar};          renobounds = {0. <= y <= 1, 0 <= z <= 1, 0.00232 <= w <= 0.1,bnear >= 0, bfar >= 0};      Changing the values of these options, give me very different results:               Do[Print[NMinimize[{chi2reno[y, z, w, a, xinear, fnear1, fnear2,      fnear3, fnear4, fnear5, fnear6, xifar, ffar1, ffar2, ffar3,      ffar4, ffar5, ffar6, bnear, bfar], renobounds}, renovars,      Method -> {"DifferentialEvolution", "SearchPoints" -> Automatic,      "ScalingFactor" -> 0.9, "CrossProbability" -> 0.1,      "PostProcess" -> {FindMinimum, Method -> "QuasiNewton"},     "RandomSeed" -> i}]], {i, 10}]


title: Replicating Excel output using Mathematica

text: I have 2 columns of data in Excel. One is inputs the other is outputs. I ask Excel to make a graph of that data and to fit the data to a power trendline. Excel does this and it's fine as far as it goes but I'd like to get Mathematica to give me a similar equation for a line. How do I do that? If it helps the ordered pairs are:               {0.473, 1.1}, {0.4825, 1.15}, {0.492833333333333, 1.2}, {0.503666666666667, 1.25},      {0.513666666666667, 1.3}, {0.5245, 1.35}, {0.533, 1.4}, {0.543166666666667, 1.45}      Excel gives it as `y=4.8549x^1.9788`


title: Annoying display truncation of numerical results

text: I have a lot of data to inspect. An example of a number in my program is               123.189094      This gets displayed as               123.189      Unfortunately, most of my information is in the small digits, so, when visually inspecting this data, `123.189094` and `123.189263` are not distinguishable, in other words, a list like               {123.189094, 123.189263}      is displayed like               {123.189, 123.189}      and it looks like I have equal data when I don't. The only fix I have found for this is `FullForm`, but that explodes out all the structure (lists, rules, etc.) and makes the display very annoying. Imagine that my data were actually buried deep in some nested structure of lists and rules (and it is).               {123.189094, 123.189263}//FullForm     (* List[123.189094`,123.189263`] *)      is not what I want. I would have thought `N[#,10]&` or somesuch would work, but it doesn't               {123.189094, 123.189263} // N[#, 10] &     (* {123.189,123.189} AAACH! *)      `StandardForm` doesn't do it, `TraditionalForm` doesn't do it. I'm stuck. As usual, will be grateful for any advice or ideas.


title: How to get precision for a small calculation?

text: For pc1 and pc2 this gives the answer to only four decimal places. How can I get better precision?               c = N[299792458, 100]     hr = N[3600, 100]     da = N[24, 100]     yr = N[365.25, 100]     au = N[149597870700, 100]          a = N[648000/Pi, 200]     pc = N[au*a, 200]     pc1 = N[pc/(c*hr*da*yr), 200]          b = N[au/Tan[1/3600 Degree], 200]     pc2 = N[b/(c*hr*da*yr), 200]


title: How to display the value of a very small number instead of "0."

text: I need to perform an integration. There is one particular value, which may be very small that is showing up as `0.`. Is there any command in _Mathematica_ 9 that will give me the very small value instead of `0.`? ![enter image description here](http://i.stack.imgur.com/km0SH.png)


title: The difference between 0. and 0

text: I have a function for which `0` is a special case:               f[A___, 0, B___] := 0      But since I am doing numerics, sometimes in the course of things `f` gets called with `0.` instead of `0`. Of course I can add the line               f[A___, 0., B___] := 0      But I don't understand why I need to because I don't understand the difference between `0` and `0.`. Can anyone illuminate this for me? (In addition to saving a line of code, or as Jens points out, a couple of characters, I also want to know the difference between them so I don't run into hard-to-debug problems in the future because of something I didn't know about.)


title: Frontend displays wrong number digits

text: How do I change the default precision in Mathematica? Somehow the setting has been changed to 1 digit, so if I type               Timing[...]      I get > {1., ...} which is not very enlightening. Similarly,               N[Pi]      is > 3. Compare Mathematica's documentation for Numerical Precision which says of the above command "In standard output form, Mathematica prints a number like this to six digits." So something isn't right with my setup. I read the guide to numerical precision but it didn't appear to address this issue. Note that I do _not_ want to change `WorkingPrecision` or `PrecisionGoal` on a particular function,but just change the default setting. (Of course I'll have to adjust these in some cases, but I just want to have a sensible starting point.)


title: how to round result to 64 bit double precision number?

text: How do I round to ieee 64 bit floating point with mathematica? I've tried `N[22250738585072014/10000000000000000 10^-308, MachinePrecision]` and I get 2.22507*10^-308 as a result (0x000ffffe2e8159d0 in hex), though it should be 2.2250738585072014e-308 (0x0010000000000000 in hex). Thanks.


title: Mathematica scripting on Microsoft Windows

text: Is it possible to use _Mathematica_ (or the _Mathematica_ kernel) to interact with Microsoft Windows, much like any macro-based scripting language that controls the keyboard/mouse, opens/closes programs remotely, manipulate window sizes, files, and folders, etc? It seems _Mathematica_ is usually used for math related engineering purposes inside the _Mathematica_ notebooks, I'm interested in its symbolic programming style to create standalone applications that interact with windows (to automate repetitive tasks).


title: How to create a combined bar plot with time format?

text: I'm not sure how to add time format to bar plots. I'd like to be able to make one bar plot for one data set and another for another data set and then combine them, but I don't know how to offset each bar from the origin so they can overlap at the right times. See image for an idea: ![concept](http://i.stack.imgur.com/1dlF3.png)


title: Replacing Patterns In a List of Varying Length

text: I am working with an array of data that may look something like this.               data={{0.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,0.,0.,0.,1.,1.,1.,0.,1.,1.},{1.,1.,1.,0.,1.,0.,0.,0.,1.,1.,1.,1.,0.,1.,1.,1.,1.,0.,0.,0.}}      I want to replace any sequence of ones that exceeds two in a row with the same number of zeros in order to maintain the original dimensions of the array. I came up with the following to try to do this.               data /. {x__, PatternSequence[Repeated[1., {2}]], y__} -> {x}~Join~Table[0., {i, 2}]~Join~{y}          {{0.,1.,0.,0.,0.,1.,1.,1.,1.,1.,0.,0.,0.,0.,1.,1.,1.,0.,1.,1.},{1.,0.,0.,0.,1.,0.,0.,0.,1.,1.,1.,1.,0.,1.,1.,1.,1.,0.,0.,0.}}      Unfortunately, it only replaces the first two ones in a sequence with zeros and leaves the rest. That's not exactly what I was aiming for.


title: Using Except with strings

text: Suppose that I have the following sample list, called `list`:               list = {"bBb", "aAa", "aaa"};      Now suppose I want to select the elements that do not contain the string `"A"`. One way to do this is to use `Select` with `StringMatchQ`:               Select[list, ! StringMatchQ[#, ___ ~~ "A" ~~ ___] &]      > {"bBb", "aaa"} (See, for example, this old question.) But, instead of selecting the elements which do _not_ contain `"A"`, is it possible to use `Select` with `StringMatchQ`, but this time selecting all patterns _except_ those that match the pattern `___ ~~ "A" ~~ ___`. My thought is to use `Except`:               Select[list, StringMatchQ[#, Except[___ ~~ "A" ~~ ___]] &]      > {} > > StringExpression::invld: Element `Except[___ ~~ "A" ~~ ___]` is not a valid > string or pattern element in `StringExpression[Except[___ ~~ "A" ~~ ___]]` But I get the error message above. So I looked in the documentation for `StringMatchQ`. It has the following three general syntax forms:               StringMatchQ["string", patt]     StringMatchQ["string", RegularExpression["regex"]]     StringMatchQ[{s1, s2, ...}, p]      Thinking about the first form, `StringMatchQ` takes a pattern as its second argument. I know that `___ ~~ "A" ~~ ___` is a pattern, but is `Except[___ ~~ "A" ~~ ___]` a pattern? According to the documentation for `Except`, it is. The next question is, is `Except[___ ~~ "A" ~~ ___]` a _string_ pattern? According to the error message above, it would seem not. (Also, apparently `StringMatchQ` takes only _string_ patterns as its second argument -- which, of course, is logical.) _**So, my overall question is,_** why does `Select[list, StringMatchQ[#, Except[___ ~~ "A" ~~ ___]] &]` give an error?


title: How do you use fourier transforms to perform a deconvolution

text: I've been trying to teach myself about deconvolution through fourier transforms, but I seem to be missing something simple, as my results are garbage. I start by defining a test function and a window which I will convolve with it               Window[width_, x_] = UnitStep[x + width/2] UnitStep[width/2 - x];     Test[x_] = UnitStep[x] UnitStep[count - x] Sin[0.1 x]^2;      I then sample the convolution across a set of data points               count=100;          MakeData[width_] =        Simplify[Table[         Integrate[Window[width, x - i] Test[x], {x, -Infinity, Infinity},           Assumptions -> {count > width > 0}], {i, 0, count}]];          tempData = MakeData[20];      I make a similar list for my sample window               tempWindow = Table[Window[20, x], {x, -count/2, count/2}];      I use the convolution theorem to deconvolve my window from my data               deconvolved = InverseFourier[Fourier[tempData]/Fourier[tempWindow]];      I was expect that this will return the original function               expected = Table[Test[x], {x, 0, count}];      However, the results are completely different. ![Graph of Results](http://i.stack.imgur.com/MGke1.png) There's obviously something I'm doing wrong in my convolution or deconvolution, but I don't see what it is.


title: How to make DynamicModule work without an extra ENTER

text: I've been trying to learn more about `DynamicModule` (I do not use them, as I used `Manipulate` all the time). After some time struggling with this, and reading everything I can about Dynamics, and lots of trials and errors, I gave up. Any one can figure why this `DynamicModule` will initialize correctly and run ok, ONLY after I hit ENTER on the cell an extra time? This is a problem, since when I saved it to a CDF and opened the CDF, it does not run, since it needs an ENTER to initialize, which is not possible to do in CDF.               DynamicModule[{max = Pi/4, plot = plotClass[Pi/4]},           Row[{        Dynamic[plot@set[max]],        Framed@Grid[{           {Slider[Dynamic[max], {.1, 2 Pi, .1}], Dynamic@max},           {Dynamic[plot@make[]], SpanFromLeft}           }          ]        }       ],      Initialization :> {        plotClass[$max_] := Module[{self, mymax},              self@set[v_] := mymax = v;               self@make[] := Module[{x},                Plot[Sin[x], {x, 0, mymax}, PlotRange -> {{0, 2 Pi}, {-1, 1}},                  ImageSize -> 200]                ];              mymax = $max;          self          ]        }      ]      ![Mathematica graphics](http://i.stack.imgur.com/iqvpA.png) To see the problem, simply do   1. Paste the above into an empty cell (but do not hit ENTER yet)   2. close the kernel `Evalution->Quit kernel`   3. Hit ENTER on the cell. Now you'll see the plot   4. Now move the slider. You'll see that the plot does not update   5. Now hit ENTER one more time into the cell. Now moving the slider will update the plot   6. To reproduce, delete the output cell and go back to step 2. So it needs one more ENTER to work. Another way to see this, is to save the notebook as CDF and open the CDF. You'll see it does not work. I am sure I am doing something silly. But as I said, I just started learning DynamicModule. The problem is with the evaluation with the Module in the Initialization section. It does not get defined without an extra ENTER for some reason. I tried many different way to define this Module, and they are failed. One extra ENTER is needed. Mathematica 9.0.1, on windows 7.


title: How can I select two lists from a list of lists so that I receive the system of equations has only rational solutions?

text: I want to make a sytem of equations has the form $$\begin{cases} a_1x^2+b_1y^2 + c_1xy+d_1x + e_1y+3=0,\\\ a_2x^2+b_2y^2 + c_2xy+d_2x + e_2y+3=0. \end{cases}$$ so that the given system of equations has always two solutions $(1,2)$ and $(3,4)$. I tried               f[x_, y_] := a*x^2 + b*y^2 + c*x*y + d x + e y + 3     l = {a, b, c, d, e} /.      Solve[{f[1, 2] == 0, f[3, 4] == 0, 1 <= a <= 10,      1 <= b <= 10, -10 <= c <= 10, -10 <= d <= 10}, {a, b, c, d, e},      Integers]      Now, I want to select two lists in list `l` and make system of equations. For example               u = l[[77]];     v = l[[75]];     w = {x^2, y^2, x y, x, y};     Reduce[{u.w + 3 == 0, v.w + 3 == 0}, {x, y}, Reals]      > (x == 3/10 && y == 3/5) || (x == 1 && y == 2) || (x == 3 && y == 4) || (x == > 25/4 && y == 4) Another system of equations               u = l[[3]];     v = l[[12]];     w = {x^2, y^2, x y, x, y};     Reduce[{u.w + 3 == 0, v.w + 3 == 0}, {x, y}, Reals]      > (x == -15 && y == -6) || (x == 1 && y == 2) || (x == 3 && y == 4) In the above system of equations, the equation `u.w + 3==0` can be factor               Factor[u.w + 3]      > (3 + x - 2 y) (1 + x - y) Now, I consider system of equations               u = l[[8]];     v = l[[75]];     w = {x^2, y^2, x y, x, y};     Solve[{u.w + 3 == 0, v.w + 3 == 0}, {x, y}, Reals]      > {{x -> 1, y -> 2}, {x -> 3, y -> 4}, {x -> 3/49 (16 - Sqrt[109]), y -> > -(11/4) + 85/98 (16 - Sqrt[109]) - (437 (16 - Sqrt[109])^2)/ 9604 + (3 (16 - > Sqrt[109])^3)/4802}, {x -> 3/49 (16 + Sqrt[109]), y -> -(11/4) + 85/98 (16 + > Sqrt[109]) - (437 (16 + Sqrt[109])^2)/ 9604 + (3 (16 + Sqrt[109])^3)/4802}} How can I select two list from the list `l` so that I receive a system of equations in which all of them can't factor and the system of equations has only rational solutions?


title: Solve never terminates with simultaneous equation set

text: I have the following set of simultaneous equations that I want to solve symbolically. The two unknowns are $a$ and $d$. $a=\frac{c*(d/10)}{1 + (f/130) + (d/50)} - \frac{a}{1 + (a/100) + (d/100) + (f/80)}$ $d=\frac{1*c*(f/130)}{1 + (f/130) + (d/50)}-\frac{c*(d/10)}{1 + (f/130) + (d/50)}+\frac{a}{(1 + (a/100) + (d/100) + (f/80))}-\frac{d}{(1 + (a/100) + (d/100) + (f/80))}$ When I try and solve them with:               Solve[{d == (1*c*(f/130))/(1 + (f/130) + (d/50)) - (c*(d/10))/(         1 + (f/130) + (d/50)) + a/(1 + (a/100) + (d/100) + (f/80)) -          d/(1 + (a/100) + (d/100) + (f/80)),        a == (c*(d/10))/(1 + (f/130) + (d/50)) - a/(         1 + (a/100) + (d/100) + (f/80))}, {a, d}]      The program just says "running" for ages and never terminates. What can I do to solve the system? Thanks


title: Distance between point and line segments

text: How would you determine the shortest distance between a point and one or more segments? For example, what is the shortest distance between the point and the two segments below? Clearly the point is closer to the right line segment. That means the shortest distance between the point and the line segments is equal to the distance between the point and the right segment. ![Example: point and two lines](http://i.stack.imgur.com/Inf9t.png)               point = {{8, 15}}     lines = {{{20, 10}, {11, 27}}, {{11, 27}, {1, 27}}}     Show[Graphics[{Thick, Line@lines}],      Graphics[{PointSize[Large], Pink, Point@point}]]      Can you think of a way that also works with an arbitrary number of segments?


title: Plot draws list of curves in same color when not using Evaluate

text: This example comes from the Mathematica documentation for `Plot` under _Basic Examples_. Can someone please explain why these are each plotted as a different color in this case:               Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis]      ![enter image description here](http://i.stack.imgur.com/r18ux.png) But when `Evaluate[]` is removed, all of them are the same color:               Plot[Table[BesselJ[n, x], {n, 4}], {x, 0, 10}, Filling -> Axis]      ![enter image description here](http://i.stack.imgur.com/FWpFh.png) I know it must have to do with the order of things being evaluated, but I'm really not sure why it is working like this - can someone please point me in the correct direction?


title: Issues with creating functions

text: Sometimes when I try to create a function inside a function, Mathematica gives me a hard time. I usually just have to play around with the syntax until it gets something it "likes" but I really have idea _why_ certain things work and others don't. Here's an example I just ran into recently: **Code version A:**               ans[tf_] :=       NDSolve[{x'[t] == v[t], v'[t] == -x[t] - v[t], x[0] == 1,           v[0] == 1}, {x[t], v[t]}, {t, 0, tf}] // Flatten;     ans[2]     Plot[{x[t], v[t]} /. %, {t, 0, 2}]      So this works beautifully. But for some reason if I try to nest my `ans[2]` inside my function by replacing it with the `%`, Mathematica can't evaluate it! **Code version B:**               ans[tf_] :=       NDSolve[{x'[t] == v[t], v'[t] == -x[t] - v[t], x[0] == 1,           v[0] == 1}, {x[t], v[t]}, {t, 0, tf}] // Flatten;          Plot[{x[t], v[t]} /. ans[2], {t, 0, 2}]      So my question boils down to: Why does _Code Version A_ work and _Code Version B_ doesn't?


title: How to assign different colors to list plotted in ParametricPlot?

text: > **Possible Duplicate:**   >  Difference in Plot when using Evaluate vs when not using Evaluate I am plotting galaxies and I would like to color them according to their redshift values using a temperature map as a metaphor for shifted wavelengths. Here, I will assume that a circle has a redshift value corresponding to its radius. How would one assign a different color to each circle using a temperature map with hue from blue to red corresponding to increasing size?               circle[Theta_, r_] := {r*Cos[Theta], r*Sin[Theta]};     ParametricPlot[Table[circle[Theta, r], {r, 1, 5}], {Theta, 0, 2 Pi}]


title: Changing the plot variable inside Plot

text: > **Possible Duplicate:**   >  Difference in Plot when using Evaluate vs when not using Evaluate Assume one has vector of functions (e.g., `vec={x,x^2}`). The command `Plot[vec, {x, -2, 2}, PlotStyle -> {Blue, Red}]` allows one to plot curves in different colors. ![enter image description here](http://i.stack.imgur.com/6V93x.png) Any use of the replacement operator, however, causes all curves to adopt the final listed color. For example, `Plot[vec /. x -> y, {y, -2, 2}, PlotStyle -> {Blue, Red}]` gives ![enter image description here](http://i.stack.imgur.com/H387A.png) How does one specify different colors for different curves if a replacement (`/.`) is used within the plot command?


title: Plotting bug? or am I missing something?

text: I would like to plot some functions in a family such as the following set of functions:               Table[(n/(1 - 2 x))^2, {n, 1, 29}]      And this works wonderfully:               Plot[Table[(n/(1 - 2 x))^2, {n, 1, 29}], {x, 0, 1}, PlotRange -> {0, 29^2}]      But now When I try to generalize this things go wrong:               Plot[         Table[               (n/(Numerator[1/2] - Denominator[1/2] x))^2,                {n, 1, 29}         ],          {x, 0, 1},          PlotRange -> {0, 29^2}     ]      This plot does is not what I expected. For some reason this gives me what I would expect to see for:               Table[(n/2(Numerator[1/2] - Denominator[1/2] x))^2      So I decided to see if there was a problem with the table:               t1 = Table[               (n/(Numerator[1/2] - Denominator[1/2] x))^2,                {n, 1, 29}         ];     Plot[t1, {x, 0, 1}, PlotRange -> {0, 29^2}]      Well that gives me what I expect. So it seems to me that for some reason using the Numerator and Denominator functions cause a bug the plotting somehow. Over the years I have learned that often 'bugs' are really just a disconnect between my understanding and how things really work. But I am very confused on why the following produces alternating red and blue lines:               Show[         Plot[             Table[(n/(1 - 2 x))^2, {n, 1, 29}],              {x, 0, 1},              PlotStyle -> Blue         ],          Plot[             Table[(n/(Numerator[1/2] - Denominator[1/2] x))^2, {n, 1, 29}],              {x, 0, 1},              PlotStyle -> Red         ],          PlotRange -> {0, 29^2}     ]      They _should be_ the same plot, or am I missing something? Why would this be different?               t1 = Table[(n/(1 - 2 x))^2, {n, 1, 29}];     t2 = Table[(n/(Numerator[1/2] - Denominator[1/2] x))^2, {n, 1, 29}];     Show[         Plot[t1, {x, 0, 1}, PlotStyle -> Blue],          Plot[t2, {x, 0, 1}, PlotStyle -> Red],          PlotRange -> {0, 29^2}     ]


title: Why is ContourPlot not displaying this curve?

text: I am using the general form of a second-degree plane curve: $$Ax^2+2Bxy + Cy^2+2Dx + 2Ey + F = 0$$ I want to randomly generate plane curves of this form, so I am using `RandomReal[{-1,1},6]` to   generate the coefficients. I made the above equation into a function:               SecondDegreeCurve[{a_, b_, c_, d_, e_, f_}, x_, y_] :=         a x^2 + 2 b x y + c y^2 + 2 d x + 2 e y + f == 0      However, when I try to plug the composition               ContourPlot[      SecondDegreeCurve[RandomReal[{5}, 6], x, y],       {x, -2, 2}, {y, -2, 2}]      into `ContourPlot`, the image comes back blank. When I run `SecondDegreeCurve[RandomReal[{5}, 6], x, y]`, I get something like the following output:               1.4557 + 5.20582 x + 1.29609 x^2 + 9.37565 y + 6.73248 x y + 1.84528 y^2 == 0      and when I plug this into `ContourPlot`, the curve is displayed. My question is, what is it about the initial composed expression that doesn't display the curve?


title: plot[] with subsititution rule

text: I encounter this problem in _Mathematica_ 9.0.1, I'm not sure if it ever happens in other version.               Plot[{x, x + 1}, {x, 0, 10}, PlotStyle -> {Red, Green}]      This will show a red curve and a green curve, which is as expected. But               Plot[{a, b} /. {a -> x, b -> x + 1}, {x, 0, 10}, PlotStyle -> {Red, Green}]      will give me two green curves. Since               {a, b} /. {a -> x, b -> x + 1}      will give you               {x, 1 + x}      , I don't understand why there is difference in the results given by the two plot statements.


title: Mathematica issue with Plot, D and SetDelayed

text: I've tried to run the following code:               f[x_] := 2 ArcTan[x] + ArcSin[2 x/(1 + x^2)];     Plot[D[f[x], x], {x, -4, 4}]      Same with `SetDelayed`:               df[x_] := D[f[x], x];     Plot[df[x], {x, -4, 4}]      It starts to complaining:               General::ivar: -3.99984 is not a valid variable. >>     General::ivar: -3.83657 is not a valid variable. >>     General::ivar: -3.67331 is not a valid variable. >>     General::stop: Further output of General::ivar will be suppressed during this calculation. >>      But this code works:               f[x_] := 2 ArcTan[x] + ArcSin[2 x/(1 + x^2)];     df = D[f[x], x];     Plot[df, {x, -4, 4}]      Did I miss something or this is an issue?


title: PlotStyle does not work when plotting a non-evaluated list of functions

text: When a list of functions is passed to `Plot` in an unevaluated form (e.g. with `Through`), the result is a plot with single color.               Plot[Through[{Sin, Cos, Tan}[t]], {t, 0.01, 10.5}, PlotStyle -> {Red, Blue, Green}]      ![Mathematica graphics](http://i.stack.imgur.com/FR11H.png) However, the same list of functions, listed explicitly, gives color as expected.               Plot[{Sin[t], Cos[t], Tan[t]}, {t, 0.01, 10.5}, PlotStyle -> {Red, Blue, Green}]      ![Mathematica graphics](http://i.stack.imgur.com/96IGD.png)


title: Plot derivative of integral with changing limits

text: My code is: `Plot[D[Integrate[E^(t*(-x^2)),{x,t+2,t^2}],t],{t,-2,3}]`. The errors/warnings are: `General::ivar: "-1.9999 is not a valid variable."` `General::ivar: "-1.89786 is not a valid variable."` `General::ivar: "-1.79582 is not a valid variable."` `General::stop: "Further output of \!\(\* StyleBox[ RowBox[{\"General\", \"::\", \"ivar\"}], \"MessageName\"]\) will be suppressed during this calculation. "` The graph turns out empty in the end. What did I do wrong this time?


title: Defining a function using Series?

text: > **Possible Duplicate:**   >  General::ivar is not a valid variable when plotting - what actually causes > this and how to avoid it? I need to define a function using the output of series, i.e.                f[x_,M_]:= Normal[Series[Sin[x],{x,0,M}]];      Now, for reasons explained in Normal[Series[ ]] does not give a normal expression that I can't fully understand (due inexperience and lack of time), the above code does not work as is. I've managed to use `f` within other functions, like                InverseLaplaceTransform[#,s,t] & @ f[s,M]      where `M` is given, but failing when trying to evaluate, i.e.               In[1]:= f[x_,m_]:= Normal[Series[Sin[x],{x,0,m}]];          In[2]:= f[x,3]          Out[2]= x - x^3/6          In[3]:= f[2,3]          General::ivar: 2 is not a valid variable. >>     General::ivar: 2 is not a valid variable. >>          Out[3]= Sin[2]      In a nutshell, is there a way to use `f` like a "normal" function?


title: General::ivar is not a valid variable when plotting - what actually causes this and how to avoid it?

text: I was just evaluating a couple of expressions and started to get errors like this:               General::ivar: -1.49994 is not a valid variable. >>     General::ivar: -1.43871 is not a valid variable. >>     General::ivar: -1.37749 is not a valid variable. >>     General::stop: Further output of General::ivar will be                     suppressed during this calculation. >>      I'm doing nothing complicated - currently, I simply did this:               f[x_]:=x^2 + 2x + 1     Plot[f[x], {x, -4, 4}]     Solve[f[x] == 4]     g[x_]:=D[f[x], x]     Plot[g[x], {x, -2, 2}]     // ^ errors caused by this      Actually, this isn't the _exact_ quadratic I am investigating, but it is a quadratic and I expected this to work. I googled, as you'd expect, and found this Stack Overflow question which suggested:               Plot[Evaluate[g[x]], {x, -2, 2}]      As a workaround. It works - my question is, why doesn't that set of instructions generate that error (I can see it is something to do with replacing, but why is one plot different from the other?) and how can I avoid it? Is there something I should specifically have done in forming `g`?


title: Plotting function lists

text: > **Possible Duplicate:**   >  Difference in Plot when using Evaluate vs when not using Evaluate   >  Why do I have to put Evaluate[] here   >  Why is ContourPlot not displaying this curve? Why is nothing (empty plot, without error) plotted, when using the following code?                tab = Table[x^2 + y^2 == R, {R, 0.2, 1, 0.2}];      ContourPlot[tab, {x, -1, 1}, {y, -1, 1}]      Thank you for your help!


title: Behavior of expression evaluation in Plot

text: I'm confused with Mathematica's way of parsing expressions. I've been struggling with this for a while and never found an exhaustive answer, sometimes things don't parse the way I think they would and I don't really understand why. As an example, with Mathematica 8:               (* A works *)     Manipulate[       Plot[(y/a) /. {y -> (x - b)}, {x, 0, 2}, PlotRange -> {0, 1}],       {a, 1, 2},       {b, 0, 1}]          (* B doesn't work *)     Manipulate[       Plot[(x/a) /. {x -> (x - b)}, {x, 0, 2}, PlotRange -> {0, 1}],       {a, 1, 2},       {b, 0, 1}]          (* C works *)     (x/a) /. {x -> (x - b)}     Manipulate[       Plot[%, {x, 0, 2}, PlotRange -> {0, 1}],       {a, 1, 2},       {b, 0, 1}]          (* D doesn't work *)     test = (x/a) /. {x -> (x - b)}     Manipulate[      Plot[test, {x, 0, 2}, PlotRange -> {0, 1}]     , {a, 1, 2}, {b, 0, 1}]          (* E works *)     test2[x_, a_, b_] = (x/a) /. {x -> (x - b)}     Manipulate[       Plot[test2[x, a, b], {x, 0, 2}, PlotRange -> {0, 1}],       {a, 1, 2},       {b, 0, 1}]      Case A works, so the substitution is performed fine inside Plot and Manipulate. But B doesn't, which I could understand as an issue trying to substitute a variable with an expression containing itself, but then, if you evaluate it beforehand, as in C, everything works again, so it has to be a problem with x being part of Plot, I guess. Then if you assign the result of the substitution to a variable, you can't directly plot it, so it seems that variables are not evaluated if they are not functions (as in E, with pattern matching) inside `Plot`. But % is, so % is "special" as it gets evaluated inside plot while a standard symbol assigned to a value does not. Can someone explain me all this? I guess it's related to the `Hold` attributes a function can have?


title: Failing to get colours in Plot

text: When I plot the functions generated by `NestList`, I do not see differently coloured lines, which I do if I explicitly list them out. I.e. with:               map[ x_, α_] := x^2 - α      the first `Plot` is monochrome (blue), the second one multicolour as expected:               Plot[NestList[map[#, 2] &, x, 5], {x, 0, 1}]      > ![Mathematica graphics](http://i.stack.imgur.com/5aPic.png)               Plot[{x, Nest[map[#, 2] &, x, 1], Nest[map[#, 2] &, x, 2],        Nest[map[#, 2] &, x, 3], Nest[map[#, 2] &, x, 4],        Nest[map[#, 2] &, x, 5]}, {x, 0, 1}]      > ![Mathematica graphics](http://i.stack.imgur.com/d3Q5G.png)


title: Why won't ContourPlot accept a variable argument?

text: I have a list of linear inequalities which describe a (polygonal) region. I can use `RegionPlot` to visualize this region; but I'd also like to overlay this plot with the lines corresponding to each inequality. `ContourPlot` works for drawing the lines, but only if I put my list of equations as it's argument -- if I put a variable holding the list of equations I get nothing out.               constraints = {         x <= 2,         x + 2 y >= 2,         x + 2 y <= 6,         x - 2 y >= -2,         3 x + 6 y <= 18     }     region = And @@ constraints     equations = constraints /. { LessEqual -> Equal, GreaterEqual -> Equal}          p1 = RegionPlot[region, {x, -1, 3}, {y, -1, 3}]      This shows the region nicely shaded in blue. The variable "equations" is set to a list of equations of the lines I'd like to highlight; it's value is               {x == 2, x + 2 y == 2, x + 2y == 6, x - 2y == -2, 3x + 6y == 18}      Now I try to plot these lines:               p2 = ContourPlot[equations, {x, -1, 3}, {y, -1, 3}]      This results in an empty plot! However, if I copy-and-paste the value of "equations" right into the code, it renders a nice plot:               p2 =        ContourPlot[{x == 2, x + 2y == 2, x + 2y == 6, x - 2y == -2, 3x + 6y == 18},         {x, -1, 3}, {y, -1, 3}]      To wrap up, I overlay the two plots:               Show[p1, p2]      Why does `ContourPlot` see a difference between the two invocations? My understanding is that they should be equivalent.


title: Plot[ D[Sin[x]] ] and Evaluate[]

text: Why does               t = 2 Pi;     Plot[D[Sin[x],x], {x,0,t}] (* Plotting the derivative of Sin[x] *)      not work, but               t = 2 Pi;     Plot[Evaluate[D[Sin[x],x], {x,0,t}] (* Plotting the evaluation of the derivative of Sin[x]? *)      do? And why does this work, but neither               t = 2 Pi;     Plot[{D[Sin[x],x]}, {x,0,t}] (* Plotting the one-length array of the derivative of Sin[x] *)      nor               t = 2 Pi;     Plot[{Evaluate[D[Sin[x],x]]}, {x,0,t}] (* Plotting the one-length array of the evaluation of the derivative of Sin[x]? *)      works?


title: Reproducing a Plot done with WolframAlpha

text: I have problem to draw in _Mathematica_ a plot like this:               Plot[{Sum[a^10*(-1)^(x-a), {a, 1, x}]}, {x, 1, 10}]      The problem is that on the plot there is no graph. As it can be calculated, there should be some values plotted. When I try to draw this equation in _Mathematica_ as               plot (sum(a^10*(-1)^(x-a),a=1 to x)), x = 1 to 10       everything works fine, so I think I did something wrong with the first command in Mathematica, but I can't find the mistake.


title: Why do I have to put Evaluate[] here

text: I wanted to draw some contours. I succeeded with this:               W1 = {p, -2, 2, 0.5};     W2 = {p, -10, 10, 1};     P = W1; ContourPlot[       Evaluate[Union[Table[y^2 == 2 p*x, Evaluate[P]],         Table[x^2 == 2 p*y, Evaluate[P]]]], {x, -5, 5}, {y, -5, 5}]     P = W2;     ContourPlot[Evaluate[       Union[Table[y^2 == 2 p*x, Evaluate[ P]],         Table[x^2 == 2 p*y, Evaluate[P]]]], {x, -5, 5}, {y, -5, 5}]      I don't like this solution. I used Evaluate[] a few times and I feel like it is unnecessary although without the function I get errors. Could anyone explain me that. I find the reference unhelpful (maybe that's my lack of language?) "causes expr to be evaluated even if it appears as the argument of a function whose attributes specify that it should be held unevaluated.".