Area or NIntegrate curves defined by points?

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?


Plot3D and NMinimize do not work correctly?

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?


Solving an exponential multivariate equation

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.


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

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.


What methods does Solve use?

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


ExampleData menu view

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"]`)


Empty plot - Euler's method

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?


Replacing list elements by other list elements

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!


Possible to scope an anonymous function within Module?

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?


Preparing data for making an ErrorListPlot

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?


Need help coding/creating a recursive list

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_.


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

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) $$


Drawing partition diagrams on spheres

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?


axis label formatting in Plot3D

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?


Collision of axes labels and ticks

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?


complicated Numerical Integration, FEM application

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


Saving Mathematica kernel state?

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)?


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

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`)


Automatically restoring the state of a prior session

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.


Running an initialization cell on Mathematica start up

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?


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

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.


How to automate Mathematica scripts? - I

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.


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

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"]


Beginner: Saving & Reloading but Preserving Input/Output

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.


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

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');


Problem using the DifferentialEvolution method of NMinimize

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}]


Replicating Excel output using Mathematica

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`


Annoying display truncation of numerical results

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.


How to get precision for a small calculation?

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]


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

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)


The difference between 0. and 0

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.)


Frontend displays wrong number digits

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.)


how to round result to 64 bit double precision number?

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.


Mathematica scripting on Microsoft Windows

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).


How to create a combined bar plot with time format?

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)


Replacing Patterns In a List of Varying Length

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.


Using Except with strings

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?


How do you use fourier transforms to perform a deconvolution

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.


How to make DynamicModule work without an extra ENTER

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.


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

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?


Solve never terminates with simultaneous equation set

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


Distance between point and line segments

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?


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

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?


Issues with creating functions

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?


How to assign different colors to list plotted in ParametricPlot?

> **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}]


Changing the plot variable inside Plot

> **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?


Plotting bug? or am I missing something?

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}     ]


Why is ContourPlot not displaying this curve?

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?


plot[] with subsititution rule

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.


Mathematica issue with Plot, D and SetDelayed

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?


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

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)


Plot derivative of integral with changing limits

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?


Defining a function using Series?

> **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?


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

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`?


Plotting function lists

> **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!


Behavior of expression evaluation in Plot

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?


Failing to get colours in Plot

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)


Why won't ContourPlot accept a variable argument?

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.


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

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?


Reproducing a Plot done with WolframAlpha

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.


Why do I have to put Evaluate[] here

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.".


Colouring of multiple data sets in DiscretePlot

I noticed the following strange behaviour: Let us first define an array of functions                   g[k_] := {Sin[k], 2*Sin[k]}         gg = g[k]      When I plot this array of functions with                   DiscretePlot[{Sin[k], 2 Sin[k]}, {k, 1, 50}]      each of the two sets of points have a different colour. But, both                   DiscretePlot[gg, {k, 1, 50}]      and                   DiscretePlot[g[k], {k, 1, 50}]      show the two sets of points in blue. I am more interested in the second case, because should the array of functions be large, it is more comfortable to use the definitions like `g` and `gg` given above. But I want to preserve the different colours. How do I do that?


When is Evaluate needed within function arguments?

I'm trying to do a simple variable substitution within a ContourPlot, but it's not working. Here's an example:               ContourPlot[x y == 1/2, {x, 0, 1}, {y, 0, 1}]      ContourPlot[x y == 1/2 /. y -> z, {x, 0, 1}, {z, 0, 1}]      The second line, although mathematically identical, produces no contour. Why? How can I do the substitution correctly? **Edit:** It looks like my initial question is solved by simply wrapping the argument in Evaluate. However, why doesn't Plot obey the same rules? The following works without Evaluate:               Plot[x, {x, 0, 1}]     Plot[x /. x -> z, {z, 0, 1}]


How does Plot evaluate its argument?

I have a list of about twenty `InterpolatingFunction`s that I'd like to plot. They are interpolations from experimental data (frequency spectra between 100 and 5000 MHz, since you asked).               In[210]:=  interps     Out[210]:= {InterpolatingFunction[{{100.,5000.}},<>],                 InterpolatingFunction[{{100.,5000.}},<>],                 InterpolatingFunction[{{100.,5000.}},<>] (* ... etc ... *)}      I tried this:               (* Through[interps[f]] threads the argument f through the list *)     Plot[Through[interps[f]], {f, 100, 999}]      ![First attempt: inline expression](http://i.stack.imgur.com/C7w3q.png) This took about thirty seconds, and as you can see the lines are all the same colour. On a whim, I tried replacing it with this:               expr = Through[interps[f]];     Plot[expr, {f, 100, 999}]      ![Second attempt: extracting a variable](http://i.stack.imgur.com/3niGz.png) This only took about two seconds, and the default colours worked this time. This was a major 'WTF' moment for me. Is this a bug? Why aren't the two versions of the code equivalent? I'm using Mathematica 9.0.1.0.


How can I plot the characteristic polynomial?

For example, I have:               CharacteristicPolynomial[m, x]      > >     0.5 + 0.1 x + x^2 >   But               Plot[CharacteristicPolynomial[m,x], {x,-1, 1}]       gives errors.


Why can't D[] be used in place here?

> **Possible Duplicate:**   >  General::ivar is not a valid variable when plotting - what actually causes > this and how to avoid it? Beginner question: Why can't I use `D[]` like that?               Plot[{Sin[x], D[Sin[x], x]}, {x, -2 Pi, 2 Pi}]      If I assign the result of `D[]` to a variable and put that variable in the list it works.


Error plotting delayed expressions

I have defined:               Qq[T_] := Exp[-w/(2 T)]/(1 - Exp[-w/T])       Uq[T_] := T^2 D[Log[Qq[T]], T]      Can someone explain why this expression work:               Plot[Evaluate[Uq[T] /. w -> 1], {T, 0, 2}]        (As result the plot is created) But this does not?:               Plot[Evaluate[Uq[T]] /. w -> 1, {T, 0, 2}]        (As result a General::ivar error is displayed)


How to ContourPlot a Table?

> **Possible Duplicate:**   >  Why is ContourPlot not displaying this curve?   >  Why do I have to put Evaluate[] here I'm trying to plot certain contours of a function $f:\mathbb R^2\to\mathbb R$. What I tried is the following:               ContourPlot[Table[f[x, y] == a, {a, 0, 1, 0.1}], {x, -3, 3}, {y, -3, 3}]      For some reason this doesn't work. If I first evaluate `Table[f[x, y] == a, {a, 0, 1, 0.1}]` and then plug the result into `ContourPlot`, however, it does work. I've noticed that `Table[f[x, y] == a, {a, 0, 1, 0.1}]` is evaluated to `{False, False, ..., False}` somewhere in the process if evaluated inside `ContourPlot`. (Which is not the same result as when evaluated separately.) > Why does this happen? What can I do to make it work? Thanks.


app keeps minimizing when switching in windows 8

so I run mathematica on my surface pro with windows 8 pro, when I opened a notebook in it and switched to my browser and some other apps it's sometimes impossible to go back to my notebook, it doesn't reopen the window. It gives me a windows warning sound but nothing pops up or shows, I just can't switch back is this a certain setting in windows that needs to be changed or a mathematica bug?


When exporting text, how can I set the line separator?

I want to export a string for a bash script. The terminal is naturally very picky when it comes down to the "\n\r" vs "\n", Windows vs. Linux, new line issue. How can I teach _Mathematica_ to use "\n" rather than "\n\r" as the line separator when exporting text (in Windows)? I found a couple of posts regards the same issue, but they were concerned with importing files. For example, here. None of the suggested solutions worked for my case. I played with `CharacterEncoding` and `"LineSeparators"` but nothing worked. EDIT: Great thanks to Mark Adler for giving me the right clue. His suggested solution `WriteString[f, "\n"]` did not work because "\n" is interpreted by _Mathematica_ as string not as end-of-line. However, his suggested `DOSTextFormat -> False` option also works as option for `Export[]`. I got the desired result using `Export[filename,script,"Text",DOSTextFormat -> False]`.


What is wrong with my VectorPlot?

I am trying to make a simple plot of a spherical field falling off with distance from origin:               VectorPlot[{x, y} / EuclideanDistance[{0, 0}, {x, y}]^2, {x, -3, 3}, {y, -3, 3}]      I just get dots. Why do I get this? ![enter image description here](http://i.stack.imgur.com/oFgFY.png)


How can I plot a function that is the sum of another function?

I plotted `m[t]`, but actually what I want to plot is `g[t]`, which is a summation of `m[t]` from 0 to 19 seconds. But when I plot `g[t]`, I get dots. On the picture, what I want is on the right, I don't want the dots, so I guess list plot is not the way to go. How should I plot g to look like the picture I have to the right; ![enter image description here](http://i.stack.imgur.com/j6FkE.png) ### EDIT My code;               period = 1;                                          beta = 0.05;     An = List[{-1 , 1, -1, +1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1}];          sinch[t_] := (Sin[(Pi*t - t*period)/period])/(Pi* t);                                      m[t_] :=        An * sinch[t] * (Cos[(Pi*beta*t - t*period) / period] /          (1 - (4*beta^2 * (t - t*period)^2 )/period^2 ));           Plot[{m[t]}, {t , 0, 19}]                  g = Sum[m[t], {t, 1, 20}];     ListPlot[g]


Fill gap created by Exclusions

A gap appears at the locations of Exclusions at t=1,t=1+t0 when the top slider for t0 is set to Play. How can these gaps be avoided or filled in?                Manipulate[             y[t_, t0_] := 1/(1 - (t - t0));        y0[x_] := y[x, 0];        yT[x_] := y[x, t0];             Plot[{y0[t], yT[t]}, {t, -3, 7},        Exclusions -> {t == 1, t == 1 + t0},        PlotStyle -> {{Thick, Black}},        PlotRange -> {0, 3},        Frame -> True,        Axes -> False,        ImageSize -> 1.2 {500, 330},        BaseStyle -> {FontSize -> 16},        FrameLabel -> {t, x},        RotateLabel -> False,        PlotRangePadding -> {{2, 0}, {.1, .1}},        Epilog -> {PointSize[0.015], Red, Dashed,       Line[{{-4, y0[s]}, {s, y0[s]}}],         Point[{{-4, y0[s]}, {s, y0[s]}, {s + t0, yT[s + t0]}}],        Black, Dashing[{}], Line[{{-4, 0}, {-4, 3}}],        Red, Point[{-4, y1[s]}],        Black, Arrowheads[.03], Arrow[{{-4, 3}, {-4, 3.1}}],        Red, Dashing[{}], Line[{{s, y0[s]}, {s + t0, yT[s + t0]}}]}],             {{t0, 2}, -2, 5, 0.01},        {{s, 0}, -2, 0.67, 0.01}              ]


Why don't * and ^ work as I expected on matrices?

For example, this input...               {{1, 2}, {3, 4}}*{{1, 2}, {3, 4}}      produces this output...               {{1, 4}, {9, 16}}      and this input...               {{1, 2}, {3, 4}}^2      produces the same...               {{1, 4}, {9, 16}}      What I want in both cases is...               {{7, 10}, {15, 22}}      I think I know what's going on here. Mathematica doesn't seem to be discriminating between lists of lists, and matrices, and the `*` and `^` operators are just threading over the lists. I've found `.` and `MatrixPower` which do what I think `*` and `^` should. But the question still remains, is this confusing (to at least me) behavior of `*` and `^` by design, and what benefit does it confer?


Using spherical derivatives with NDSolve

I am trying to plot the path of an object around a centre of mass. Obviously this needs spherical coordinates. The problem I encounter is with the derivatives. The Derivatives in spherical coordinates are for (radial, azimuthal, polar) (r,theta,phi):               dr = r'     dϕ = r ϕ'     dθ = r Sin[ϕ] θ      Where the accelerations in theta and phi remain 0 for now. But I need values for the initial velocity, this means that when I add the sinus to the NDSolve, it can't solve the set of equations; This is the furthest I've come. In truth, I'm not sure if this is the right approach or not, but solving the equations in Cartesian coordinates brings a lot more problems.               b = 20;     ball = First@NDSolve[{r''[t] == -9.81/r[t]^2, r[0] == 5, r'[0] == 0,        WhenEvent[r[t] == 2.25, r'[t] -> -0.9 r'[t]], θ''[t] == 0,       θ[0] == 0,r[0] θ'[0] == π/4, ϕ''[t] == 0,       ϕ[0] == π,r[0] ϕ'[0] == π/4}, {r, θ, ϕ}, {t, 0, b}];      The following doesn't work (third row, added sinus):               ball = First @ NDSolve[{r''[t] == -9.81/r[t]^2, r[0] == 5, r'[0] == 0,       WhenEvent[r[t] == 2.25, r'[t] -> -0.9 r'[t]], θ''[t] == 0,      θ[0] == 0,r[0] Sin[ϕ[0]] θ'[0] == π/4, ϕ''[t] == 0,      ϕ[0] == π,r[0] ϕ'[0] == π/4}, {r, θ, ϕ}, {t, 0, b}];      I then plot with:               Manipulate[       Show[         ParametricPlot3D[{r[t] Sin[θ[t]] Cos[ϕ[t]] /. ball,            r[t] Sin[θ[t]] Sin[ϕ[t]] /. ball,            r[t] Cos[θ[t]] /. ball}, {t, 0, a},            PlotStyle -> {Gray, Dashed, Thick},            PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}],          ParametricPlot3D[{r[t] Sin[θ[t]] Cos[ϕ[t]] /. ball,            r[t] Sin[θ[t]] Sin[ϕ[t]] /. ball,            r[t] Cos[θ[t]] /. ball}, {t, a - 0.001, a},            PlotStyle -> {Black, Thickness[0.05]},            PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}],          Graphics3D[Sphere[{0, 0, 0}, 2]]],       {{a, b/100, "Time"}, b/100, b}]      Trying:               ball = First @ NDSolve[{x''[t]^2 + y''[t]^2 + z''[t]^2 ==      -9.81^2/(x''[t]^2 + y''[t]^2 + z''[t]^2)^2,       x[0] == 3, y[0] == 3, z[0] == 3, x'[0] == 1, y'[0] == 0,       z'[0] == 0,       WhenEvent[x''[t]^2 + y''[t]^2 + z''[t]^2 == 2.25^2,        x''[t]^2 + y''[t]^2 + z''[t]^2 -> -0.9 x''[t]^2 + y''[t]^2 +        z''[t]^2]}, {x, y, z}, {t, 0, b}];      Returns an under-determined error. I get that I have only one second derivative, but going all out (added row 3):               ball = First@NDSolve[{x''[t]^2 + y''[t]^2 +       z''[t]^2 == -9.81^2/(x''[t]^2 + y''[t]^2 + z''[t]^2)^2,       ArcTan[x[t], y[t]] == 0, ArcTan[z[t], Sqrt[x[t]^2 + y[t]^2]] == 0,      x[0] == 3, y[0] == 3, z[0] == 3, x'[0] == 1, y'[0] == 0,       z'[0] == 0,       WhenEvent[x''[t]^2 + y''[t]^2 + z''[t]^2 == 2.25^2,        x''[t]^2 + y''[t]^2 + z''[t]^2 -> -0.9 x''[t]^2 + y''[t]^2 +        z''[t]^2]}, {x, y, z}, {t, 0, b}];      produces the messages: > Warning: the rule (x'')[t]^2+(y'')[t]^2+(z'')[t]^2->-0.9 > (x'')[t]^2+(y'')[t]^2+(z''[t]^2 will not directly set the state because the > left-hand side is not a list of state variables. >> > > Unable to find initial conditions that satisfy the residual function within > specified tolerances. Try giving initial conditions for both values and > derivatives of the functions. >>


Scope within Context

To define some package-wide functions/variables, what approach is recommended? I tried to use contexts with the `Begin` function, but this failed:               Clear[fun];     fun[] := Module[{},        Begin["myContext`"];        x = 1;        End[];        ];     fun[]     myContext`x      I would expect `myContext'x` to be 1, but it seems to be undefined. Why does this fragment fail, what should I do instead?


Plotting a parametric function with three input variables

I want to plot a 2D parametric function of the form: $$ f_x(\theta_1,\theta_2,\theta_3) = \cos(\theta_1)+\cos(\theta_1+\theta_2)+\cos(\theta_1+\theta_2+\theta_3) $$ $$ f_y(\theta_1,\theta_2,\theta_3) = \sin(\theta_1)+\sin(\theta_1+\theta_2)+\sin(\theta_1+\theta_2+\theta_3) $$ where the ranges for the input variables are: $ \theta_1 \in [-\pi,\pi]$ and $ \theta_2 \in [-\pi,\pi]$ and $ \theta_3 \in [\frac{-\pi }{2},\frac{\pi }{2}]$ I tried to use `ParametricPlot`, but it takes only two input variables. Can any one help me with this?


Using an InputField to define a function to compose with a sequence

I am still trying to figure out Mathematica (started early August). I am trying to write a program that will accept an arbitrary function and an arbitrary sequence that can start at an arbitrary natural number in order to compose the function with the sequence so that my students can investigate the sequential criterion for the limit of a function. I cannot figure out how to get Mathematica to accept a function...below is what I have worked out so far. Any help would be greatly appreciated!               Manipulate[DynamicModule[{ a = 1 /n, b = 1},        Column[{Labeled[InputField[ Dynamic[  f[x_] :> ( x^2 - 4)/( x - 2 ) ]], "function", Left],                Labeled[InputField[Dynamic[a]],"sequence", Left],               Labeled[InputField[Dynamic[b]], "i=" , Left ],                Dynamic[If[ ( t - b ) < 11,                   TableForm[ Transpose[ {Range[b, t], Table[ N[ a, 4 ], {n, b, t} ],                     Table[ N[ f[ a ], 4], {n, b, t}]}], TableHeadings -> {           None, { "n", "\!\(\*SubscriptBox[\(a\), \(n\)]\)",            " f(\!\(\*SubscriptBox[\(a\), \(n\)]\))"}}],                  TableForm[Transpose[ {Range[t - 10, t],                     Table[ N[ a, 4 ], {n, t - 10, t} ],                     Table[N[ f[ a ], 4], {n, t - 10, t}]}], TableHeadings -> {           None, { "n", "\!\(\*SubscriptBox[\(a\), \(n\)]\)",            " f(\!\(\*SubscriptBox[\(a\), \(n\)]\))"}}]]]}]], {{t, 1, "k"}, 1, 1000, 1, Appearance -> "Labeled"}]


wrong use of _?NumberQ?

I am having trouble with a numerical exercise. Here's a simplified version of my problem. I define two functions to find the solution to two constrained maximization problems:               g[a_,b_,x_]:=NArgMax[{h2[a,b,x,y], CONSTRAINT[a,b,x,y]},{y}][[1]]     f[a_,b_,y_]:=NArgMax[{h1[a,b,x,y], CONSTRAINT[a,b,x,y]},{x}][[1]]      In the above definitions h1(.) and h2(.) are "well-behaved" objective functions, "a" and "b" are parameters and `CONSTRAINT[a,b,x,y]` is a given inequality involving the parameters and choice variables. With these functions, I would like to find a fixed point, say, `xstar`:               FindRoot[{xstar==f[a, b, g[a,b,xstar] ]}, {xstar, 0}]      When I try to run `FindRoot` with actual numbers for "a" and "b" I get an error saying that the constraint in the maximization problem is not valid. I think the problem is that it attempts to make a symbolic evaluation. I hence tried defining the functions as `g[a_,b_,x_?NumberQ]` and `f[a_,b_,x_?NumberQ]`, but it didn't work. However, when I defined:               G[x_?NumberQ]:=g[a,b,x]     F[y_?NumberQ]:=f[a,b,y]      and then fixed values for the parameters by setting them equal to a given number (e.g. `a=b=0.1`),then it did work. It seems then that I am doing something wrong when I use `?NumberQ` in the original function to avoid symbolic evaluation... Any ideas on why it is wrong and how to solve it? I would like to make a plot for different values of "a" and "b", so running the simulations one by one (as in the solution I mention above that works, by redefining the function only in terms of one variable) is extremely inefficient... and I'm sure there's a smarter way of doing it ! ;) **Here is a complete example using the above notation** :               h1[a_, b_, x_, y_] := PDF[BinormalDistribution[{a, b}, {1, 1}, .5], {x, y}]     h2[a_, b_, x_, y_] := PDF[BinormalDistribution[{a, b}, {.5, .5}, .7], {x, y}]     CONSTRAINT[a_, b_, x_, y_] := CDF[BinormalDistribution[{a, b}, {1, 1}, .5], {x, y}]     g[a_, b_, x_] := NArgMax[{h2[a, b, x, y], CONSTRAINT[a, b, x, y] < .5}, {y}][[1]]     f[a_, b_, y_] := NArgMax[{h1[a, b, x, y], CONSTRAINT[a, b, x, y] < .5}, {x}][[1]]          FindRoot[{xstar == f[1, 1, g[1, 1, xstar]]}, {xstar, 0}]


How does epilog position work in logplots?

I'm trying to use `Epilog` in my plots but the position of the `Epilog` isn't making much sense. As a minimal example consider,               LogPlot[Sin[x], {x, 0, \[Pi]}, Epilog -> {Text["x", {\[Pi], 0.2}]}]      I'd have expected this to put an "x" in the center of the graph but instead it shows up in the corner: ![enter image description here](http://i.stack.imgur.com/z1hTp.jpg) I've also tried `ListLogplot` and other graphics but they all produce similar results. How do I force `Epilog` to use the same positions as the plot? Note: I'm using _Mathematica V10_ on _Linux_.


How to customize the MathematicaClosingDialog.nb?

With _Mathematica_ 10 came the closing dialog notebook, which probably most of you deactivated. (You can bring it back by dechecking "Always exit after closing last window" in Edit->Preferences->Interface.) I just kept it, because my _Mathematica_ installation gets non-responsive (often accompanied by the pop up of the "Progress" window) in several situations including start up. However, the default closing dialog ![defaultClosingDialog](http://i.stack.imgur.com/bUNpL.png)   isn't very functional. Therefore I'd like to customize it to get, e.g. something like: ![customClosingDialog_Explained](http://i.stack.imgur.com/BLc0s.png)   Where the "Quit" button is replaced by a "Quit Kernel" button that just quits the kernel, as there is no advantage to use the default "Quit" instead of the close window X. Furthermore I'd like to extend the closing dialog by adding additional buttons, e.g. a "Evaluate Specified Notebook" button that will evaluate a notebook file, whose path is defined in some .txt file. The only way to read the default _MathematicaClosingDialog.nb_ into Mma I found is               nb = Import[FileNameJoin[{$InstallationDirectory, "SystemFiles", "FrontEnd",                  "TextResources", "MathematicaClosingDialog.nb"}]]      The output of this import looks like a mess, though. In summary:   1. How to replace the "Quit" button with a "Quit Kernel" button?    2. How to add additional buttons, like a "Evaluate Specified Notebook" button?   3. Can the directory for the _MathematicaClosingDialog.nb_ be changed?   (I couldn't find it in the "Option Inspector".)


Expected graph distance in random graph

I am trying to use the functionality of `Expectation` and `Probability` for random graphs, in particular for percolation models. For example, I would like to be able to compute the expected graph distance between two fixed vertices in a complete graph with independent exponential edge weights. The following naive code does not work.               n = 5;     Expectation[     GraphDistance[     CompleteGraph[n,EdgeWeight -> Table[ew[m], {m,1,(n (n-1))/2}]], 1, 2],      Table[ew[m] \[Distributed] ExponentialDistribution[1], {m,1,(n(n-1))/2}]      ]//FullForm      yields               GraphDistance[Graph[List[1,2,3,4,5],List[Null,SparseArray[Automatic,List[5,5],0,List[1,List[List[0,4,8,12,16,20],List[List[2],List[3],List[4],List[5],List[1],List[3],List[4],List[5],List[1],List[2],List[4],List[5],List[1],List[2],List[3],List[5],List[1],List[2],List[3],List[4]]],Pattern]]],List[Rule[EdgeWeight,List[ew[1],ew[2],ew[3],ew[4],ew[5],ew[6],ew[7],ew[8],ew[9],ew[10]]],Rule[GraphLayout,"CircularEmbedding"]]],1,2]      indicating that the random weights are not actually assigned to the edges. A similar example would be the computation of the probability that two fixed vertices in a complete graph are in the same connected component after edges are deleted with probability $1-p$ and retained with probability $p$. Again the following naive code does not work.               n = 5; p = 1/3;     Probability[     GraphDistance[     CompleteGraph[n, EdgeWeight -> Table[ew[m], {m, 1, (n(n-1))/2}]], 1, 2] == 0,      Table[ew[m] \[Distributed] EmpiricalDistribution[{1-p, p} -> {1, 0}], {m,1,(n(n-1))/2}]     ]      Ideally, I would like to be able to compute this probability (a polynomial in $p$) for symbolic $p$. Of course I would also be grateful for other approaches to the problem, but using `Expectation` and `Probability` would feel very intuitive to me. **Update:** The problem can be circumvented by computing the probability of a generic event which is only specified after `Probability` has been applied:               Clear[f, g]     n = 5;     f[ewarray_] :=       GraphDistance[CompleteGraph[n, EdgeWeight -> ewarray], 1, 2]     Probability[     g[Table[ew[m], {m, 1, (n(n-1))/2}]] == 0, Table[ew[m] \[Distributed] BernoulliDistribution[1-p], {m, 1, (n(n-1))/2}]     ] /. g -> f // Simplify      The results are the same as @ubpdqn's MC calculations. I have experimented with `Hold` and `Release` to avoid the use of the extra function `f` but do not know enough those functions to make it work.


Obtain data points from a density plot

I have a density plot, for example               DensityPlot[Sin[x*y],{x,0,2pi},{y,0,2pi}].      Then I would like to collect points from this densityplot into a file so that I can always use ListDensityPlot to draw these points again, or I may draw these points by some other software. I read several posts on how to do that for Plot, but how can I generalize them to `DensityPlot`?


Making an animation which displays a rotating object

I want to rotate the geometry obtained whith the input:                 movil = ExampleData[{"Geometry3D", "SpaceShuttle"}]      But it shows an error message : _Graphics is not a Graphics3D primitive or directive_. I'm trying to represent the attitude of an airplane so if there is another option with similar geometry It can also be usefull. I'm using this code:               frame[α_, β_, γ_, t_] :=        GraphicsRow[         {Graphics3D[            Rotate[              Rotate[                Rotate[movil, α °, {0, 0, 1}],                β °, {0, 1, 0}],              γ °, {1, 0, 0}],             Axes -> True, LabelStyle -> 12,             PlotRange -> {{-0.6, 0.6}, {-0.6, 0.6}, {-0.6, 0.6}},             ViewPoint -> {1, 0, 0.2}],           Show[            ListPlot[{ϕctab, θctab, ψctab}, Joined -> True, LabelStyle -> 12,               AxesLabel -> {"n", "Grados [º]"}],             ListPlot[{{{t, ϕctab[[t]]}}, {{t, θctab[[t]]}}, {{t, ψctab[[t]]}}},               PlotMarkers -> {Automatic, 10}]]},          ImageSize -> 590];          frs = Table[frame[ϕstab[[t]], θstab[[t]], ψstab[[t]], t], {t,1, Length[θstab]}];     ListAnimate[frs]


Incomplete implementation of units?

I've been playing around with the new units capability in MMA9 and I'm becoming a bit frustrated with what I perceive as an incomplete implementation of this capability and I'm wondering if there are other similar examples. For example, `Histogram[]` can take a list of quantities and a `TargetUnits` specification and it will scale the plot appropriately:               data = Quantity[RandomVariate[NormalDistribution[0, 1], 100], "Meters"];     Histogram[data, AxesLabel -> Automatic, TargetUnits -> "Meters"]      ![enter image description here](http://i.stack.imgur.com/a43qZ.png)               Histogram[data, AxesLabel -> Automatic, TargetUnits -> "Centimeters"]      ![enter image description here](http://i.stack.imgur.com/7DER5.png) But the options for `Histogram[]` do not appear to allow units specifications, which seems dangerous to me and can have some (obvious but) strange results if care is not taken. As an example, specifying `bspec = {-3, 3, 0.2}` assuming that the units are in meters results in a figure that looks something like this:               Histogram[data, {-3, 3, 0.2}, AxesLabel -> Automatic, TargetUnits -> "Meters"]      ![enter image description here](http://i.stack.imgur.com/6rzen.png) If we then change the `TargetUnits` to centimeters, here's what happens:               Histogram[data, {-3, 3, 0.2}, AxesLabel -> Automatic, TargetUnits -> "Centimeters"]      ![enter image description here](http://i.stack.imgur.com/wpPSO.png) Needless to say, one could readily draw a completely different conclusion about the nature of the data even though the only thing that's changed is the output units. To me this seems like an incomplete implementation and I'm wondering if anyone else has encountered a similar issue elsewhere? If so, I'm tempted to avoid the new units capability until it's more mature.


Symbolic computations with already assigned variables

For example I have assigned some variables that could defined in terms of each other. Then I for some reason need to derive some formula using this variables. How to show the result of this computation without substituting the values and how then substitute them? It should look something like this:               computeWithOnly[expr_,vars_]:=...     substitute[expr_,vars_]:=...          a:=1;b:=2;c:=d+e;d:=3;e:=4;     computeWithOnly[Expand[(a+b+c)^3]]     (*a^3 + 3 a^2 b + 3 a b^2 + b^3 + 3 a^2 c + 6 a b c + 3 b^2 c +       3 a c^2 + 3 b c^2 + c^3*)     computeWithOnly[Expand[(a+b+c)^3],{c}]     (*a^3 + 3 a^2 b + 3 a b^2 + b^3 + 3 a^2 d + 6 a b d + 3 b^2 d +       3 a d^2 + 3 b d^2 + d^3 + 3 a^2 e + 6 a b e + 3 b^2 e + 6 a d e +       6 b d e + 3 d^2 e + 3 a e^2 + 3 b e^2 + 3 d e^2 + e^3*)     computeWithOnly[Expand[(a+b+c)^3],All]     (*1000*)     substitute[computeWithOnly[Expand[(a+b+c)^3],{c}],{a,b}]     (*27 + 27 d + 9 d^2 + d^3 + 27 e + 18 d e + 3 d^2 e + 9 e^2 +       3 d e^2 + e^3*)


Sound data Import Export

Can't regain the data after Export. Create an array of sampled amplitude values:   2\. Visualize as sound   3\. Save it   4\. Get it back   5\. ???               sound = RandomReal[1, {500}];       ListPlay[sound]       Export["test.txt", sound];       in=Import["test.txt"]       ListPlay[in]      A second example.   Take data from a WAV sound,   Export it,   reImport it,   play it.               tubadat = ExampleData[{"Sound", "Tuba"}, "Data"];       Export["TubaDat.dat", tubadat];       in = Import["TubaDat.dat"];       ListPlay[in]        It is not the original sound.


Precedence of defined functions

When I define functions in _Mathematica_ like:               f[x_] := 3      f[x_Integer] := 6      How is the value of `f[6]` determined?   It seems to be independent of the order they're defined (which would make the most sense). From my initial testing, it picks the most "restricted" definition, but the meaning of this is unclear if I used patterns like `f[x_ /; x > 3]` Can anyone point me to any documentation/specification about this issue ?   I've looked unsuccessfully for a while.


Output of plots from within Do[ ] Command

I am wondering why the following does not plot the way it's written and exactly how does the `Do[]` function operate? I think I could be using it incorrectly.               In[1]:= u[x_, t_] := (1/2) (Exp[-(x + t)^2] + Exp[-(x - t)^2])             Do[                Plot[u[x, k], {x, -5, 5},                 AxesLabel -> {x, u},                 PlotRange -> {0, 1}],                {k, 0, 3}               ]      * * * ## EDIT               In[2]:= Clear["Global`*"]             a=1;             b=1;             \[Phi][\[Xi]_,\[Nu]_,t_]:=\!\(             \*UnderoverscriptBox[\(\[Sum]\), \(i = 1\), \(10\)]\(             \*UnderoverscriptBox[\(\[Sum]\), \(j = 1\), \(10\)]\((             \*FractionBox[\(5\ \((\(-1\) +              \*SuperscriptBox[\((\(-1\))\), \(j\)])\)\ \((\(-1\) +              \*SuperscriptBox[\((\(-1\))\), \(i\)])\)\), \(j\ i\              \*SuperscriptBox[\(\[Pi]\), \(2\)]\)] Cos[             \*FractionBox[\(1\),              SuperscriptBox[\(\[Pi]\), \(4\)]]              \*SqrtBox[\(             \*SuperscriptBox[\(i\), \(4\)]              \*SuperscriptBox[\(\[Pi]\), \(4\)] +              \*SuperscriptBox[\(j\), \(4\)]              \*SuperscriptBox[\(\[Pi]\), \(4\)]\)] t])\) Sin[i\ \[Pi]\ \[Xi]] Sin[j\ \[Pi]\                                \[Nu]]\)\);             Do[Print@                Plot3D[\[Phi][\[Xi],\[Nu],m],{\[Xi],0,a},{\[Nu],0,b},                Mesh:>Automatic,                PlotLabel:>"Surface Plot of Solution at t = "<>ToString[m],                ColorFunction:>{"BlueGreenYellow"}],                {m,0,10,2}               ]


Error in setting matrix elements

> **Possible Duplicate:**   >  How to Set parts of indexed lists? For better organization of my code, sometime I use data objects in the form:               data["A", "1"] = {{1, 2}, {3, 4}}      instead of               dataA1 = {{1, 2}, {3, 4}};      One of the advantages is when working with `Module`, because I can declare `data` just one time, and I can use `data["A","1"]`, `data["A","2"]`, `data["B","1"]` and so on, with limited scope. Everything works fine except for one detail. With `data["A", "1"]` I can't perform operations like:               data["A", "1"] = {{1, 2}, {3, 4}}     data["A", "1"][[All, 2]] = "X"      to change `data["A", "1"]` to `{{1, "X"}, {3, "X"}}` I got the error:               Set::setps: data["A", "1"] in the part assignment is not a symbol      When I try with:               dataA1 = {{1, 2}, {3, 4}};     dataA1[[All, 2]] = "X";     dataA1      I have no problem and get `{{1, "X"}, {3, "X"}}` as expected. There is nome way to perform this kind of operation in `data["A", "1"]` object? **Update** The question indicated as duplicated do not handle the case: `data["A", "1",...]` but just `data["A"]`