Are there some other ways to solve a second PDE except DSolve?

I have a partial differential equation as follows: $$\frac{\partial p(x,t)}{\partial t}=\text{Dp} \frac{\partial ^2p(x,t)}{\partial x^2}-\frac{p(x,t)-\text{p0}}{\tau }$$ What I try to do was to get its general solution by               DSolve[D[p[x, t], t] == -((p[x, t] - p0)/τ) + Dp D[p[x, t], {x, 2}], p, {x, t}]      However, the output returns what I have inputted, which means **_Mathematica_** cannot solve this PDE. By looking up the help document, I find that `DSolve` can only find the general solution for a restricted type of homogeneous linear second-order PDEs, that is, for such a linear second-order PDE as $b \frac{\partial ^2u}{\partial x\, \partial y}+a \frac{\partial ^2u}{\partial x^2}+c \frac{\partial ^2u}{\partial y^2}+d \frac{\partial u}{\partial x}+e \frac{\partial u}{\partial y}+f u=g$, only when `d=0`,`e=0`,`f=0` and `a`,`b` and `c` are all constants can we get the general solution. I have tried this PED in **Maple** , and get a solution with conditions, but I don't know whether it is correct. The help document tells that the algorithm used by `DSolve` is not applicable in this case. So, I wonder whether there exist some other ways or some packages to solve this PDE. If finding the general solution is impossible, is it possible to get a special solution?


How to change working directory for calculation and save

Hello Mathematica users, I have problem to set working directory, I want to calculate and save my data on D, but down you can see that mathematica shift automatically on old C. How to use D partition for calculating if mathematica is installed on C? If I do calculation as this, file is saved on D but first it is saved on C and on C I don't have enough space.                 In[7]:= ResetDirectory[]                  "C:\\Users\\user\\Documents"            In[8]:= DirectoryStack[]            Out[8]= {}            In[10]:= SetDirectory["D:\\"]            Out[10]= "D:\\"            A:=5;            Export["A.wdx", A];            In[13]:= DirectoryStack[]             {"C:\\Users\\user\\Documents"}


Get rid of external library dependency

I am trying to generate C code for some functions, which I do not post in full because they are a few hundred lines long. The functions do nothing too fancy: a bunch of dot products, powers and roots. Still, when compiling to C code Mathematica sticks in some unwanted dependency on its own libraries, which is not acceptable for the use case in question. The functions I am trying to compile have 5 arguments, 4 of which are 3-dimensional vectors. The compile printout of one of them can be found **here**. As you can see, there are 3 Mathematica functions being pulled in: DotVV, Power and Internal`ReciprocalSqrt. Is there any way I can get rid of these without modifying the code manually? **Edit:** here is the code I am using to compile the function               Compile[{{pos, _Real, 1} , {a, _Real, 1}, {v, _Real, 1}, {ba, _Real,          1} , {V, _Real}} ,        xSol, CompilationTarget -> "C"];


Quick way to use conditioned patterns when defining multi-argument function?

I have a simple function that is supposed to only accept numeric values (i.e. complex/real numbers and constant symbols e.g. Pi, E). $$f(a,b,c)=a+b+c$$ **Edit** : I should have chosen a less simple function for this question as there might be approaches that will work for this simple function but not for functions in general (1-see end of question). Please think of a more complicated function, such as $$f(a,b,c)=a^2 sin(b) log(c)$$ when you're thinking of an answer. I know that one can use _?NumericQ for each parameter such that only numeric values of that parameters are entered into the function (click here for more information on putting constrains on patterns).               Clear[f1]     f1[a_?NumericQ, b_?NumericQ, c_?NumericQ] := a + b + c          f1 @@@ {{1, 2, 3}, {x, y, z}, {1, y, z}, {x, 2, z}, {x, y, 3}}     (* {6, f[x, y, z], f[1, y, z], f[x, 2, z], f[x, y, 3]} *)      However, for functions with more than 1 variables, I'm way too lazy to add NumericQ after each parameter. Using /; at the end of the function definition works, but I feel it's still too long and I have to retype the name of the parameters (a,b,c) at the end.               Clear[f2, f3]     f2[a_, b_, c_] := a + b + c /; And @@ (NumericQ[#] & /@ {a, b, c})     f3[a_, b_, c_] := a + b + c /; VectorQ[{a, b, c}, NumericQ]      Is there any way to express the condition only once, and without having to type the list of parameters one more time? I know that this is a frivolous question borne out of sheer laziness but I'd love to hear your ideas. (1) such as using the double underscore (BlankSequence) to apply NumericQ to any number of arguments passed to Plus (per Kuba's helpful suggestion). This is because these arguments have identical hierarchy in the function--thus having no need for parameters with different names to represent them--and because Plus can take any number of arguments.               Clear[f4]     f[a__?NumericQ] := Plus[a]          f @@@ {{1, 2, 3}, {x, y, z}, {1, y, z}, {x, 2, z}, {x, y, 3}}         (* {6,f[x,y,z],f[1,y,z],f[x,2,z],f[x,y,3]} *)


What does None mean in a control specification for Manipulate?

I am now struggling to understand code that contains the following (simplified) `Manipulate` structure.               Manipulate[         complexparts[E^(I Pi t)],      {{t, 1/4.}, 0., 2},      {{complexparts, {Re[#], Im[#]} &}, None}]      I am having difficulty with the last line: `{{complexparts, {Re[#], Im[#]}&}, None}`. Somehow, this creates a "pure function" with a name "complexparts," which is then used above in the line               complexparts[E^(I Pi t)]      I tried to execute these independently outside the body of code so I could watch them do what they do, but without success. I evaluated:               {{complexparts, {Re[#], Im[#]} &}, None}      and then:               complexparts[x+Iy]      But my output was just:               complexparts(x+I y)      Can I get some help in understanding how `{{complexparts, {Re[#], Im[#]} &}, None}` works? And what does the word `None` do?


Finding Expectation of function of a Log-normal distribution

Say $Y=g(X)$ and $p_X = \frac{e^{-\frac{(\mu -\log (x))^2}{2 \sigma ^2}}}{\sqrt{2 \pi } x \sigma }$ is Log-normal density function: [Wiki] Find E[Y]? Since $E[Y] = \int_0^\infty y f_Y \ dy = \int_0^\infty g(x)f_X(x)dx$. So, I do not need to find $f_Y(y)$.               .         px = Simplify[PDF[LogNormalDistribution[Mu, Sigma], x], x > 0]     Integrate[Log2[1 + x] px, {x, 0, \Infinity}, Assumptions -> {Sigma > 0}]     .      Unfortunately, Mathematica cannot evaluate this integral for a closed form expression and I'm not quite sure how else to solve it. Will appreaciate any help I can get on the evaluation steps. Edit: I've also tried the code below with no results:                Expectation[Log2[1 + x], x \[Distributed] LogNormalDistribution[Mu, Sigma]]


Maximum size of TIF files in Mathematica

I have a question concerning the maximum size of TIFF files Mathematica can handle. According to the TIFF 6.0 specification -revision 6.0 (see: http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf) the maximum size of TIFF files is determined by the 32 Bit offsets used by this format. Thus, the theoretical maximum file size of a TIFF file should be about 4 GB. I am dealing with huge TIFF files that I need to import, process and export with Mathematica. Using Mathematica's Import and Export functions, I cannot import a TIFF file larger than 2 GB nor can I export a TIFF file that exceeds the 2 GB limit. Consider the following example i created:               data = ConstantArray[Image[ConstantArray[0, {1000, 1000}], "Bit16"],         1500];          Export["test.tif", data];      I create 1500 black images with a bit depth of 16. When i export the data, the export stops at about 2 GB. When I open the file with other software, the file only contains 1073 images. My first guess was that somehow one Bit is used to determine the sign, but I cannot figure out how to show that. Does anybody have a solution how to import and export TIFF files larger than 2 GB? Thanks in advance! **System specification**   * OS: Windows 7 Professional, Service Pack 1 (64-bit)    * Processor: Intel Xeon CPU E5630 @ 2.53 GHz (2 Processors)    * Installed memory: 96 GB   * Mathematica 9.0    * Java version 1.7.0_07 **Edit** Since I did not find any other solution, I tried reinstalling Mathematica 8 on my computer. Surprisingly, with Mma 8 it was no problem to export and import the testset. I am wondering why this is not possible with the new version. If you have any ideas, please let me know.


How to convert from and to UTM coordinates in Mathematica?

How to use the UTM coordinate system (northing, easting) in Mathematica using the built-in functions (`GeoPositionENU`, `GeoGridPosition`, etc.). There are UTM Zones implemented in Mathematica, e.g.:               GeoProjectionData["UTMZone33"]      gives               {"TransverseMercator", {"Centering" -> {0, 15},   "CentralScaleFactor" -> 1, "GridOrigin" -> {0, 0},   "ReferenceModel" -> "WGS84"}}      From N45, E15 one should get Easting 500000 and Northing 4982950.4 (zone 33), but I can't reproduce it.               GeoGridPosition[GeoPosition[{45, 15, 0}, "WGS84"], "UTMZone33"]      gives               GeoGridPosition[{0., 4.98494*10^6, 0}, "UTMZone33"]      (Easting offset 500000 is understandable - default, but Northing is way off.) Any help would be appreciated.


Creating a stacked RectangleChart

I would like to make a "Stacked" `BarChart` where the bars have variable widths, like a `RectangleChart`. However, `RectangleChart` does not accept `ChartLayout -> "Stacked"`. Is there a way to do this, or does anyone have a workaround? For example, here is a `RectangleChart` with the bars at different widths: ![enter image description here](http://i.stack.imgur.com/9001Q.png) Here is a "Stacked" `BarChart` with the bars decomposed into two components: ![enter image description here](http://i.stack.imgur.com/VW9C6.png) I would like to make a stacked `RectangleChart` with variable-width bars that can be decomposed into components.


Wait / sleep miliseconds

Is there any way to make _Mathematica_ stop for some miliseconds? I know about the `Pause[]` but it seems it only works with seconds.


Generating figures over remote connection (using terminal)

Recently I've been making movies by having _Mathematica_ create figures and then I combine all of them together using `ffmpeg`. The problem now is that my macbook is not fast enough to generate the figures I want in a short amount of time. I have access to a linux machine and I would like to be able to send a script to that machine so that I can generate my figures. The problem I'm facing is that _Mathematica_ can't open display ":0.0". ![enter image description here](http://i.stack.imgur.com/5FbcP.png) I also found this, but it did not solve my problem. Does anyone know how to generate figures in the terminal? All I want it to do is to write them to a file.


Computing the distance between two curves obtained from image data?

I've got some image data that I've binarized. The image contains two curves, from which I'd like to compute the distance between (eventually computing an average radius for each point in the picture). I've done the computation, but it's done in C programmer style, and fairly ugly               data = ImageData[ b ] ;     {h, w} = Dimensions[data] ;          min = Table[0, {w}] ;     max = Table[0, {w}] ;     averageRadiusList = {} ;     scale = 0.1 / w  ;          For [ column = 1, column < w + 1, column++,      For [ row = 1, row < h/2, row++,        If [         data[[row, column]] != 1,            min[[column]] =  row ; Break         ]        ]       For [ row = h, row > h/2, row--,        If [         data[[row, column]] != 1,           max[[column]] =  row ; Break         ]        ]       If [ min[[column]] !=  0  && max[[column]] != 0,             AppendTo[         averageRadiusList, {column * scale,          scale * (max[[column]] - min[[column]])/2} ]        ]      ]      I was wondering if there's a more natural "Mathematica way" of doing things ... something that is presumably more elegant, efficient, compact, and more general?


How to implement something like NMaximize[ NMinimize [ f(x,y) , {x} ], {y} ]?

Title says it all, really. I want to find some set of values for which a function of those values can't be made larger than a certain number, when some other values (on which that function is also dependent) are unknown.


Subspaces in Mathematica

I'm working on a research project and I need to learn how to use _Mathematica_ to calculate subspaces. Specifically I plan to solve the following operations and I would greatly appreciate if you could give me an example of how to solve it. For example:   1. In the vector space $Ρ^n$, consider the sub space  $$S = \left\langle(1, -2,1,0, ..., 0), (0,1, -2,1,0, ..., 0) ... (0,0, ..., 1, -2,1)\right\rangle$$ Calculate equations defining $S$ for $n = 4, 8, 16, 20$.   2. Find generator subspaces of "magic" matrices of $2\times2$, $3\times3$ and $4\times4$ (a square matrix is called magic if the sums of the elements in each row, each column and in the diagonal are always the same)


How to un-eat memory?

Consider this code:               MemoryInUse[]     T = Table[RandomComplex[], {i, 1, 6000}, {j, 1, 6000}];     MemoryInUse[]     T += T\[ConjugateTranspose];     MemoryInUse[]     {Es, Ys} = Eigensystem[T];     MemoryInUse[]     T = Table[RandomComplex[], {i, 1, 6000}, {j, 1, 6000}];     MemoryInUse[]     T += T\[ConjugateTranspose];     MemoryInUse[]     {Es, Ys} = Eigensystem[T];     MemoryInUse[]     $HistoryLength = 0;     MemoryInUse[]     Clear[T]     MemoryInUse[]     Clear[Es, Ys]     MemoryInUse[]     ClearSystemCache[]     MemoryInUse[]      It gives me the following results: > 15808208 > > 880820520 > > 1456822832 > > 4919500424 > > 5783503032 > > 6359505096 > > 9822181440 > > 9822182648 > > 9822182112 > > 9822181384 > > 9822162952 Clearly, the memory clears negligibly on any of `ClearSystemCache`, `Clear` and zeroing `$HistoryLength`. Repeating its execution leads to swapping, after start of which I hurry up to kill MathKernel before my X or WM or anything else are OOM-killed. So what are the working ways to release the memory?


"Covering up" text in Graphics

Consider the following code:               Show[{Graphics3D[{Opacity[0.2], Sphere[], Opacity[1.0], Blue,      Polygon[{{-.2, -.3, -.3}, {-.2, .3, -.3}, {-.2, .3, .3}, {-.2, \     -.3, .3}}]}],      ParametricPlot3D[{Sin[th] Cos[ph], Sin[th] Sin[ph], Cos[th]}, {th,      0, Pi}, {ph, 0, 2 Pi},      RegionFunction -> Function[{x, y, z}, Abs[x] < .9],      PlotRange -> {-1, 1}, PlotStyle -> Red, Mesh -> None]}]      ![Mathematica graphics](http://i.stack.imgur.com/UDuQQ.png) (Doctored somewhat from another question on this site.) It produces a sphere, with an opaque red surface, except for two "portholes", which allow one to see the blue rectangle inside. Now consider the following minor tweak, replacing the square by some text:               Show[{Graphics3D[{Opacity[0.2], Sphere[], Opacity[1.0], Blue,      Text["Surprise!", {0, 0, 0}]}],      ParametricPlot3D[{Sin[th] Cos[ph], Sin[th] Sin[ph], Cos[th]}, {th,      0, Pi}, {ph, 0, 2 Pi},      RegionFunction -> Function[{x, y, z}, Abs[x] < .9],      PlotRange -> {-1, 1}, PlotStyle -> Red, Mesh -> None]}]      ![Mathematica graphics](http://i.stack.imgur.com/v3Z10.png) The output (which I don't know how to save as a rotating GIF [side question?]) shows the blue text _over_ the red sphere, whether or not I am "looking" through the porthole or not. The reason for this is in the help: > Text is drawn in front of all other objects. Is there way to treat Text like other Graphics primitives, so that indeed it will be a "Surprise!" when you look through the porthole? That is, to get behavior similar to that of the blue rectangle? Perhaps I should clarify I am most interested in being able to change the "z order" of the Text. But the fact that it doesn't rotate with the rest of the Graphics objects (using the mouse) is also kind of annoying. Thanks!


Second-order DSolve overdetermined with only 2 boundary conditions

I was going through some circuit analysis problem and came up with a second- order differential equation, which I decided to solve with _Mathematica_ : $$ L\frac{\mathrm{d}^{2} I}{\mathrm{d}t^{2}} + R\frac{\mathrm{d}I}{\mathrm{d}t} - \frac{I}{C} = 0. $$ I used the following syntax:               DSolve[{L i''[t] + R i'[t] - i[t]/C == 0, i[0] == 0, L i'[t] == 1}, i[t], t]      Yet _Mathematica_ returns the following error:               DSolve::overdet: There are fewer dependent variables than equations, so the system is overdetermined. >>      However, it is a second-order ODE, and so it should not be overdetermined with only two boundary conditions.


How can I create an interactive application that accepts data and and plots it?

I have some code in _Mathematica_ which shows a colored plot, where the coloring depends on data values. I would like to make this into an interactive application that accepts two inputs:   1. data, a list of data points.   2. PocetDat, an integer parameter. I know little about CDF, but i don't see how I can get inputs or table inputs from the users. Further, I want the users of the application to only see the inputs and the final plot -- no code.               data =        {-0.003, 0.002, 0.008, 0.014, -0.026, -0.036, -0.042, -0.010, -0.000,         -0.014, -0.013,  0.048, 0.014, -0.035, -0.023, 0.025, 0.001, -0.002,          0.050, 0.053,  0.031, -0.045, 0.003, 0.052, 0.066, -0.040,  0.016,         -0.054, -0.040, -0.042, -0.018, -0.034, -0.032, -0.021,  0.008, -0.007};     PocetDat = 912;      KorelCiara = 2*Sqrt[1/PocetDat];      PRange = 1.2*Max[{data, KorelCiara}];     Show[       DiscretePlot[data[[i]], {i, 1, Length[data]},          ExtentSize -> Full,          ColorFunction -> Function[x, If[Abs[data[[x]]] > KorelCiara, Red, Blue]],           ColorFunctionScaling -> False],       Plot[{KorelCiara, -KorelCiara}, {x, 0, Length[data]}],        PlotRange -> {-PRange, PRange}]


Multiple plots using dynamics

I am studying Dynamic and DynamicModule, and I have tried to make a simple plot of a family of real functions. The number of functions should be a dynamic variable controlled by a slider. So I have tried something like this               {Slider[Dynamic[z], {1, 4, 1}], Plot[Evaluate[Dynamic[Table[Sin[i*t], {i, 1, z}]]], {t, 0, 2 Pi}]}      In this case variable `t` is highlighted in red and the output is empty. But if you do it outside of `Plot[]`, then you get a correct list of functions               {Slider[Dynamic[z], {1, 4, 1}], Evaluate[Dynamic[Table[Sin[i*t], {i, 1, z}]]]}      So, how one plots this kind of things?


Creating a data1 versus data2 plot?

I have a table of data with multiple rows and columns, and I have to make a versus data table using two of these columns. Essentially, I have to set one column of data (column 3) as the y-axis and another column of data (column 5) as the x-axis. How do I accomplish this?


Efficient Table Generation & NDSolve Error

I'm currently working on solving an SEIR model with data from the CDC. I've created a function to calculate the Square difference for the model and want to create a table of values for the 4 variable combinations, along with their Goodness of fit characteristic from the square difference. I'm getting this alert when running the function:   " _NDSolve has computed initial values that give a zero residual for the differential-algebraic system, but some components are different from those specified. If you need them to be satisfied, giving initial conditions for all dependent variables and their derivatives is recommended._ " It sounds like something I could ignore, but I don't want to mess anything up by doing so. Also... the big question. Is there any recommendations to make creating this table of values more efficient rather than waiting a half hour for this to work itself out?               ClearAll["Global`*"]          CDCdata = {{0, 161}, {1, 197}, {2, 298}, {3, 339}, {4, 409}, {5,      614}, {6, 848}, {7, 1359}, {8, 1985}, {9, 3346}, {10, 4590}, {11,      5938}, {12, 6511}, {13, 6514}, {14, 6952}, {15, 5982}, {16,      5167}, {17, 4077}, {18, 3126}, {19, 2457}, {20, 2136}, {21,      1848}, {22, 1680}, {23, 1497}, {24, 1269}, {25, 1007}, {26,      898}, {27, 644}, {28, 459}, {29, 380}};          ListPlot[CDCdata]          p = Interpolation[CDCdata];     Plot[p[t], {t, 0, 29}]          Population = 20328;     Squarediff[Mu_, Beta_, Alpha_,        Nu_] := (sol =         First@NDSolve[{s'[t] ==             Mu*Population - Mu*s[t] - Beta*(i[t]/Population)*s[t],            e'[t] == Beta*(i[t]/Population)*s[t] - (Mu + Alpha) e[t],            i'[t] == Alpha*(e[t]) - (Nu + Mu)*(i[t]),            r'[t] == Nu*i[t] - Mu*r[t],           i[0] == 161,           s[0] == 20328,           r[0] == 0, e[0] == 0},          {s, e, i, r}, {t, 0, 29}];        Sum[(((CDCdata[[j, 2]] - i[CDCdata[[j, 1]]]) /. sol)^2), {j, 1,          Length[CDCdata]}])          values = Flatten[        Table[{{a, b, c, d}, Squarediff[a, b, c, d]}, {a, 0, 0.0005,           0.00001}, {b, 0, 0.2, 0.01}, {c, 0, 0.1, 0.01}, {d, 0, 0.1,           0.01}], 1];


Why does Mathematica simplify $x/x\to1$?

If I enter `x/x`, I get `1`. Such behavior leads to this:               Simplify[D[Sqrt[x^2], x, x]]      > 0 The same would be even if I use `Together` instead of `Simplify`. One could then think that $\sqrt{x^2}$ is doubly differentiable at least $\forall x\in\mathbb R$, but if we remove `Simplify` call, we would reveal that it's not:               D[Sqrt[x^2], x, x]      > -(x^2/(x^2)^(3/2)) + 1/Sqrt[x^2] Even more ridiculous is this (which I guess is because `x/x` is simplified before feeding to `Assuming`):               Assuming[x == 0, x/x]      > 1 Why does Mathematica assume $x\ne0$? Is there a way to make it not cancel out such terms?


Resources/ best practices for exploratory economic theory work

This is a little general, so I will try to make it as specific as possible. I used Mathematica a fair amount to derive and check analytical solutions to problems in theoretical economics. Lots of derivatives, integrals over probability distributions, root-finding, etc. I also find myself using the Manipulate[Plot] functions a lot to investigate the basic behavior and shape of equations to help conjecture solutions and outcomes. However, I feel like a large amount of what I do is an absurd kluge. My notebooks rapidly become an unreadable mess, and I often find myself accidentally clashing variable definitions or mis-specifying function definitions under Plots. I probably end up restarting the kernel 3-4 times a session just because. Some of this has improved over time simply by learning more about the language and developing my own workflow, but I feel like it's a little inefficient and that I'm probably re-inventing the wheel (octagonal wheels at that) a lot. Are there any online or printed resources for people who use Mathematica for the things I do? Alternatively, does anyone else use Mathematica for this type of exploratory work and have a short list of best practices?


Lists - pairing up

I have two (fairly large) lists of equal length & would like to pair them up. eg - from:               a = {{0, 1}, {0, 2}, {0, 3}};     b = {{1, 2}, {1, 3}, {1, 4}};      I would like to get:               {{{0, 1}, {1, 2}}, {{0, 2}, {1, 3}}, {{0, 3}, {1, 4}}}      I have looked at various thing like Tuple, but can't see a way of doing it efficiently.


Decimal representations of analytic values in an expansion

I have a solution to an ODE (which I call `sol`), which I would like to expand in terms of Log[1+x] around x=-1. I thought that:               Series[y[x] /. sol, {Log[1+x], -1, 6}]      would do the trick, but it doesn't seem to work. That isn't too much of a problem, because if I just do:                Series[y[x] /. sol, {x, -1, 6}]      and I can spot the Log terms myself. It would be very useful though if rather than having an analytic expansion (I get constants in terms of Bessel functions and so on) if I could just get numerical values (i.e. approximate decimal representations) of the terms in the expansion. For concreteness rather than: $\frac{2 (\log (x+1)+\gamma -\log (2))}{\pi }-\frac{(x+1)^2 (\log (x+1)+\gamma -1-\log (2))}{2 \pi }+O\left((x+1)^4\right)$ i'd like something like: 1.234 Log[1+x] + 23.321 (1+x)^2 Log[1+x] etc. Thankyou


Numerical Integration with Variable Parameters

So I want to numerically compute the integral of a long complicated expression over a specified domain (in this case an ellipse). I know how to use a Boole function to sample within the ellipse, but I want to pass a list of points within this ellipse into the function and have the integral be evaluated at each of these specific points. An example would be: $\frac{1}{(x \cos(\theta)+y \sin(\theta))^\frac{5}{2}} $ So I want to integrate over θ from 0 to 2 π and I want to use different points (x, y) within the specified domain when integrating. Can anyone help me with this?


Multiplying two dimensional data by a constant

I have a list of lists of the form:               {{1, 2}, {2, 4}, {2, 8}}      But I want to multiply only the second dimension of that data by a constant. I know I could do this with a loop but that is "dirty". There has to be a better way. For example if I multiply the second dimension by 2 I would get:               {{1, 4}, {2, 8}, {2, 16}}


How to make a notebook not savable?

How to make a particular notebook not savable? Optionally, how to do this by evaluating a command in the notebook?


Import Large Excel File

Currently, I am working on a large time series dataset, which **contains 928,586 rows and 35 time intervals in columns** , in excel format (.xlsx) and using `Import` to read it in. Actually, I cannot use `Import` to handle this file since it gives me the Java heap error message: `Import::nojmem: There was insufficient Java heap space for the operation. Try increasing the Java Virtual Machine heap size.` Here is only a part of my data after using `Import`.               data = {{"BRANCHNO", "Date", "JustDay", "JustDate", "JustMonth", "JustYear",        "DoM.Train", "DoM.Test", "Total TXN", "08:00:00", "08:30:00",        "09:00:00", "09:30:00", "10:00:00", "10:30:00", "11:00:00",        "11:30:00", "12:00:00", "12:30:00", "13:00:00", "13:30:00",        "14:00:00", "14:30:00", "15:00:00", "15:30:00", "16:00:00",        "16:30:00", "17:00:00", "17:30:00", "18:00:00", "18:30:00",        "19:00:00", "19:30:00",        "20:00:00"}, {"B0001", {2011, 1, 4, 0, 0, 0.}, "Tuesday", 4.,        "January", 2011., 4., 4., 1538., 47., 59., 71., 77., 115., 111.,        103., 75., 101., 121., 135., 113., 82., 88., 79., 72., 54., 13.,        21., 1., "", "", "", "", ""}, {"B0001", {2011, 1, 5, 0, 0, 0.},        "Wednesday", 5., "January", 2011., 5., 5., 1589., 20., 51., 33.,        68., 97., 82., 101., 78., 104., 119., 137., 109., 114., 142., 85.,        77., 62., 40., 51., 19., "", "", "", "",        ""}, {"B0001", {2011, 1, 6, 0, 0, 0.}, "Thursday", 6., "January",        2011., 6., 6., 1399., 3., 39., 61., 59., 63., 108., 66., 85., 108.,        119., 114., 121., 94., 80., 62., 88., 56., 46., 16., 9., "", "", 2.,        "", ""}, {"B0001", {2011, 1, 7, 0, 0, 0.}, "Friday", 7., "January",        2011., 7., 7., 1510., 13., 55., 74., 70., 105., 95., 71., 82., 86.,        113., 124., 91., 98., 76., 112., 84., 78., 64., 18., 1., "", "",        "", "", ""}}      I am wondering that:   1. How can I import this file ?   2. What is the best way to handle excel file ?   3. After importing the excel file, can we save the data in other format (like MATLAB can save in .mat file) so that next time we can import it faster ? Thanks for help


Can I customize In[] and Out[] headers?

Can I customize the `In[]` and `Out[]` headers? I'd like to add `$UserName`, `$MachineName` and `DateString[]`, evaluated at cell creation time, into those headers, so it's easy to know by whom and when any particular cell was generated by a glance. This is similar to why/how people customize UNIX terminal prompt.


Problem inserting data into a mysql table with column names having a space

I have a mysql table whose column name has space. I tried inserting the data into this column. I got an error I tried a sample code, which tests accessing the columns with a space and that returns the same error.               Needs["DatabaseLink`"];     conn = OpenSQLConnection["demo"]     SQLCreateTable[conn,      SQLTable["TEST1"], {SQLColumn["COL 1", "DataTypeName" -> "VARCHAR"]}]      I got this error at the last line.               JDBC::error: ""Wrong data type: 1 in statement [CREATE TABLE TEST1 ( COL 1]">>      I tried other combinations to access that column names, such as               "`COL 1`"     "COL\ 1"     "`COL\ 1`"      and they din't work either. What is the proper way to create/access/insert data into columns with a space? (I am on Windows 7, using Mathematica 8)


Complement of multisets

Given lists $a$ and $b$, which represent multisets, how can I compute the complement $a\setminus b$? I'd like to construct a function `xunion` that returns the symmetric difference of multisets. For example, if $a=\{1, 1, 2, 1, 1, 3\}$ and $b=\{1, 5, 5, 1\}$, then their symmetric difference is $\big((a\cup b)\setminus(a\cap b)\big)\setminus(a\cap b)=(a\setminus b)\cup(b\setminus a)=\{1,1,2,3,5,5\}$.


Distinction between 2 NETTypeInfo answers

In a NETLink application I checked all the types offered by `LoadedNETTypes[]` according to the following:               tt1 = NETTypeInfo["Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper1",   "Methods", "DRV_AOVoltageOut"]          tt2 = NETTypeInfo["Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper2",   "Methods", "DRV_AOVoltageOut"]      `tt1` offer `Null` response but `tt2` offer the non-null response below: • Methods (matching string pattern DRV_AOVoltageOut) static short DRV_AOVoltageOut(int DriverHandle, Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper2+PT_AOVoltageOut IntPtr) My question is how to distinct between tt1 and tt2, because I obtain tt1==tt2 although they are obviously different?


Assign the contents of a "Copy" operation programmatically to a variable?

While an earlier question Cut and paste data from a spreadsheet  nominally addresses the issue, a year has past since its OP asked it and I hope that others have come across simpler or more direct ways to do this. I think a new solution might interest the community. I often want to get values (numbers, dates, ...) from a spreadsheet someone has sent me into Mathematica. `Import[...]` works fine, but seems a bit cumbersome, when I just want to grab something like a single column or row of values and work with them immediately. "Copy/Paste" can give one odd results. Set up a short list of numbers in a spreadsheet ... ![enter image description here](http://i.stack.imgur.com/p5Ltl.png) and copy them into Mathematica: ![enter image description here](http://i.stack.imgur.com/o8wWv.png) This seems a bit inconsistent and neither of these gives one a list of the data elements like `Import[...]`. Note: I use Mac OS X if it makes any difference. * * * Mr. Wizard supplies a pretty good solution in the original question, which references code for a palette that Szabolcs posted at see page, see _Pasting tabular data into notebooks_. I've added a title and minor formatting to the palette:               CreatePalette[      Column[{Button["TSV",          Module[{data, strip},           data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];          strip[s_String] :=            StringReplace[s, RegularExpression["^\\s*(.*?)\\s*$"] -> "$1"];          strip[e_] := e;          If[Head[data] === String,            NotebookWrite[InputNotebook[],             ToBoxes@Map[strip, ImportString[data, "TSV"], {2}]]]],          ImageSize -> 85],         Button["CSV",          Module[{data, strip},           data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];          strip[s_String] :=            StringReplace[s, RegularExpression["^\\s*(.*?)\\s*$"] -> "$1"];          strip[e_] := e;          If[Head[data] === String,            NotebookWrite[InputNotebook[],             ToBoxes@Map[strip, ImportString[data, "CSV"], {2}]]]],          ImageSize -> 85],         Button["Table",          Module[{data},           data = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];          If[Head[data] === String,            NotebookWrite[InputNotebook[],             ToBoxes@ImportString[data, "Table"]]]], ImageSize -> 85]},        Alignment -> {Center, Center}], WindowTitle -> "Paste Data",       WindowSize -> {85, Fit}]      One can install this by choosing **Palettes > Install Palette** (from the file menu) then provide the source file, palette name, and installation directory to the Install Mathematica Item dialog, and click **Finish**. * * * This works, but it does not have the immediacy that one gets used to when working with Mathematica, so... Does a simple way exist to assign the contents of a "Copy" operation (from a spread sheet or csv file) programmatically to a variable as a list of elements, which one could immediately press into service? Given that a clipboard appears to hold copies of content in different formats, an elegant solution might involve a right click to select how one wanted it pasted. Maybe a feature request to Wolfram would do it (eventually:-).


Non-regular grid data

I have issue with non-regulary spaced data. I have set of 3 numbers `{x, y, z}` in my list.               data={{-33335.6,15525.1,20722.4},{-33231.7,15509.8,20723.5},<<99852>>,{-32909.4,26425.3,20957.6},{-33021.5,26438.1,20954.4}}      I can plot my data with `ListDensityPlot`. I just want to get those data (interpolated) from the plot for further processing. If one uses               ListInterpolation[data, { {Min[xValues],         Max[xValues]}, {Min[yValues], Max[yValues]}},       InterpolationOrder -> 2]      Interpolation is poor, I suppose because data are not on regular tensor grid. Is there way just to get what _Mathematica_ is doing for `ListDensityPlot` ?


Typesetting help

I have a rather simple question that has me flummoxed. Let's say I have two matrices:               m1 = {{a1, a2}, {b1, b2}};     m2 = {{u1, v1}, {u2, v2}};      I am looking to typeset `m1 ± m2` similar to:               Text@TableForm[m1 + "\[PlusMinus]" m2 ]         * Works for the most part, but I want to remove the + sign from the output   * I also want to control the text sizes for the `m1` and `m2` independently so that the `a1`, `a2` etc appear in a larger text and `u1`, `v1` appear in a smaller text I tried:               Text@TableForm[m1 + "\[PlusMinus]" m2 ] /. "+" -> "x"      But that does not seem to work. Help much appreciated.


Is it the right output for Fourier?

I am learning Fourier Series at university so I wanted to do something with Mathematica to calculate frequency spectrum and harmonics of whatever function I create. This is what I have until now after searching here and found this. This is my code:               Print["Generating function..."]     armonica = 10     frec = 200     period = 1/frec     time = 2;     tinc = 0.001;          (*f=Sin[x*(2 Pi frec)]*)     (*f=SquareWave[x];*)     f = Piecewise[{{1, 0 <= x <= period/2}, {-1,           period/2 <= x <= period}}];     (*f=SawtoothWave[x]*)          Print["Calculating Fourier..."]     (* Armonica *)     series = FourierSeries[f, x,        armonica]; (*FourierParameters->{1,2 Pi}*)     foo = Plot[series, {x, 0, 3*period}, PlotRange -> Full,        PlotLabel -> "Harmonic " <> ToString[armonica]]          (* Fundamental *)     bar = Plot[f, {x, 0, 3*period}, PlotLabel -> "Fundamental",        ExclusionsStyle -> Dashed, PlotStyle -> {Thickness[0.006], Red}]          (* Combinacion *)     Show[foo, bar, PlotLabel -> "Combination"]          (* Coeficientes para el espectro de frecuencia, siendo el numero en \     el eje x las n veces de la frecuencia fundamental *)     FourierCoefficient[f, x, n];     DiscretePlot[Abs[%], {n, 0, armonica}, PlotStyle -> Thickness[0.008]]      I am generating a 200Hz square wave and calculating Fourier Series up to 10th harmonic. But this are the plots I get: ![enter image description here](http://i.stack.imgur.com/VUBCv.jpg) ![enter image description here](http://i.stack.imgur.com/ct7Vg.jpg) The first picture are the summatory of the harmonics from 0 to 10 or at least that's what I think `FourierSeries[]` returns. The second one is the square wave at 200Hz. The third picture is the combination on both and is showing really weird. Finally, the last one is the frequency spectrum which is wrong I think. If I use `frec = 1/(2 Pi)` I get better result but frequency spectrum is still wrong: ![enter image description here](http://i.stack.imgur.com/XFSEb.jpg) I am testing with square but I want to be able to use other wave forms too but I can't even get one working at different frequencies. * * * Also tried using `Fourier[]` which calculates Fourier Series based on a list instead of function but it gives me all complex numbers instead of Fourier in the form of `A[n]*Cos[n*x] + B[n]*Sin[n*x]`


Combination of linear programming with bilevel optimization

I'm not a programmer really (interested in mathematics actually). Excuse me if I can not coding good. I'm also interested in implementation of mathematics results in programming language. That's my hobby! Yesterday I asked the question below but I did not mention my way of coding! For this reason and some other ones, I decided to delete that. First of all, I thanks **rm-rf** for his/her Compassionate advice. * * * I have a combination of two optimization problem, one is bilevel optimization like this: $$\min_{x,y} \max_{\omega} f(x,y,\omega)$$ and the other is linear programming: $$\min \beta $$ $$ s.t. A\alpha \leq b $$ where $$\alpha = \begin{bmatrix} x\\ y\\ \beta \end{bmatrix}$$ My mean of combination two optimization problem is sth like this: $$\min_{x,y} \left [ \theta\max_\omega f(x,y,\omega)+ (1-\theta)\beta\right ]$$ $$s.t. A\alpha \leq b$$ where $\theta \in [0,1]$. How can I do this by mathematica? * * * My try: From the answer of this, I enter the code:               T = 0.01;     f[x_, y_, w_] := (((x + (T/2) y) Exp[I w] + ((T/2) y - x)) (1 -      Exp[-0.3 T]))/((Exp[I w]^100) (Exp[I w] -      Exp[-0.3 T]) (Exp[I w] - 1) + ((x + (T/2) y) Exp[I w] +      ((T/2) y - x)) (1 - Exp[-0.3 T]));     g[x_?NumberQ, y_?NumberQ] :=      NMaximize[{Evaluate[Abs[f[x, y, w]]], 0 <= w <= 1}, {w, 0, 1}][[1]]          NMinimize[{g[x, y], 2 <= x <= 4.5, 0.5 <= y <= 2}, {x, y}]      for bilevel minimization. And use the linear programming command sth like this:               p = LinearProgramming[{1, 2, 0}, A, b, {{-10, 10}, {-10, 10}, {-10, 10}}];      where `A`, `b` are data matrices. My problem is with how to combine two optimization problems in code and I have not any ideas to explain the problem to mathematica! Because one is linear programming (min or max nature!) and another is minimax problem. I think it may be better to convert linear programming to min/max form. I also read documentation of `FindMinimum` & `NMinimum` but it doesn't make any sense to me.


Subtract more than one array using DeleteCases

I need to create an array subtracting two arrays from another array. I know how to subtract one:               am = DeleteCases[amp, Alternatives @@ af]      I can subtract an array each time but there must be a way to subtract more than one array at once. So I want to subtract `af` and `ai` from `amp`. How can I do that at once?


How to get a number, but not a list, of the dimension of your array?

I need to use the dimension of a certain array, to use it as a bounder in a loop afterwards. The problem is that I get a list, when write :               Dimensions[ai]= {2}          aiod = Table[ai[[i]] - 1, {i, 1, Dimensions[ai], 1}]      and it does not work. I need to get "2" instead of {2}.


Least Square Data Fit /Design Matrix

I am trying to learn how to use the `DesignMatrix` function in _Mathematica_ and how to perform a `LeastSquares` fit. I am at end of my rope and seek expert intervention. Say, I have some experimental data and some experimental fit coefficients               size = 20; (*no of points *)      expdata = (Array[#, size] & /@ {x, y, z})~Join~{ConstantArray[1, size]};       coeffs = {{a1, b1, c1, d1}, {e1, f1, g1, h1}, {i1, j1, k1, l1}}; (*can be larger*)       My experimental equations would look like:               lhs = coeffs.expdata; (*Left hand side *)     rhs = Array[#, size] & /@ {u, v, w}; (*Right hand side *)     eqs = Flatten[ Table[ lhs[[#1, i]] == rhs[[#1, i]] & /@ Range[3], {i, 1, size}]];      I know I can solve these equations exactly using the `Solve` function as follows for a small number of data points:               Solve[ eqs, Flatten[coeffs]]       But assuming I have a large number of noisy data points, how do I setup a `LeastSquares` problem. In specific, I’d like to understand how to use the `DesignMatrix` function….


Unable to configure a system of differential equations

My differential equations have been written as               eqns = {Subscript[x, 1]'[t] == \[Alpha]*Subscript[x, 1][t]*Subscript[x, 3][t] -       \[Beta]*Subscript[x, 1][t]*Subscript[x, 2][t],      Subscript[x, 2]'[t] == \[Gamma]*Subscript[x, 2][t] - \[Delta]*Subscript[x, 1][t]*Subscript[x, 2][t],      Subscript[x, 3]'[t] == \[Epsilon]*Subscript[x, 1][t] - \[Lambda]*Subscript[x, 2][t],     Subscript[x, 1][0] == 147100 + 15000,     Subscript[x, 2][0] == 178000,     Subscript[x, 3][0] == 723586 + 554776};          sol = DSolve[eqns, {Subscript[x, 1], Subscript[x, 2], Subscript[x, 3]}, t]


Problem with creating a large list of tuples

This is a follow-up question from Sum of Multinomial Coefficients I have thought about the meaning of the formula I mentioned and, with help, I implemented the following code:               supp[vec_] := Module[{support = {}, i},       Do[If[vec[[i]] != 0, AppendTo[support, i]], {i, 1, Length[vec]}];       support     ];          calctrafo[n_, func_] := Module[{vecs, trafo = 0, i},       vecs = Tuples[Range[0, (n - 1)], n];       vecs = Select[vecs, Total[#] == (n - 1) &];       Do[trafo += (Multinomial @@ vecs[[i]])*func[supp[vecs[[i]]]], {i, 1, Length[vecs]}];       trafo     ];          calctrafo[7, func]      The function `supp` gives me the support of the lists and `func` is a arbitrary function. This code works well for me, but I need the code to work for large `n`, `n >= 100`. The problem lies in the function `Tuples`, which crashes for `n > 6`. Is there a way to make this work for large `n`?


Apply Eigenvalues to a list of matrices

I would like to apply `Eigenvalues[]` to a list of matrices as in the following               foo[x_,y_]=x+y;          ({{foo[#1, #2], foo[#1, #1]},      {foo[#1, #1], foo[#1, #2]}}) & @@@ {{1, 2}, {1, 2}}          --> {{{3, 2}, {2, 3}}, {{3, 2}, {2, 3}}}          Eigenvalues @@@ %      However, I get the error-message "Eigenvalues::matsq: Argument 3 at position 1 is not a non-empty square matrix". What is the problem?


How to add lists with unequal length?

Given lists of unequal lengths, I want to add them together element-wise, treating missing elements as zero. For example, `{1, 2, 3} + {a, b} + {x}` should give `{1 + a + x, 2 + b, 3}`. How do I write a function to do this?


Tensor analysis

Has anybody used tensors in Mathematica? How to properly work with them? I find Mathematica not very friendly in this field, as I am defining my own functions for lowering & raising indices, multiplication and stuff like that. I was wondering if there is some good package or a secret way to use tensors more properly in Mathematica. For example, I need tensor analysis for general relativity kind of calculations.


How do you draw credible regions/intervals on a 2D PDF?

I have some numerical data from which I generate a PDF via:               pdf = HistogramDistribution[data];      Which can then be easily visualised thus:               DensityPlot[PDF[pdf, {x, y}], {x, 1.5, 3.3}, {y, -46, -44}, PlotPoints -> 100]      What I would like to do is be able to quickly draw 90% credible intervals on top of this plot.


Simplifying trig expressions containing Sqrt or Abs

The following Maple code can simplify `abs(sin(x))` into `-sin(x)` given the condition `-3Pi/4 < x < -Pi/2`               simplify(abs(sin(x))) assuming -3*Pi < x, x < -5*Pi/2;      I tried what I thought would be the equivalent _Mathematica_ code:               FullSimplify[Abs[Sin[x]], Assumptions -> -3 Pi/4 < x < -Pi/2]       but _Mathematica_ does not give the answer I expected. Another related example. Starting with `Sqrt[1 + Sin[x]] + Sqrt[1 - Sin[x]]` and the condition `-2Pi < x < -3Pi/2`, I want to get `-2 Cos[x/2]`, Here are some of things I tried:               Sqrt[1 + Sin[x]] + Sqrt[1 - Sin[x]] /. Sqrt[x_] :> Sqrt[TrigFactor[x]]     Refine[%, Assumptions -> -2 Pi < x < -3 Pi/2]     FullSimplify[%, Assumptions -> -2 Pi < x < -3 Pi/2]


How to set the color of plot legend independent of the plot itself

I have written the code below:               ListPlot[das1, PlotMarkers -> {\[FilledCircle], 12},       PlotStyle -> {Black}, Joined -> True, Mesh -> All, MeshStyle -> Red,       PlotLegends ->       Placed[Style[#, FontSize -> 20] & /@ {"6.7 ps"}, {Top, Right}]]      I want a black line to go through my red data points. Then, I want the plot legend to be red. However, by using the above code I get a black plot legend. ![enter image description here](http://i.stack.imgur.com/dPyNu.jpg) How can I set the plot legend color independent of the plot itself? How can I extend the solution to multiple graphs in one plot?


ListContourPlot3D doesn't use all points

**Edited** thanks to @Kuba: In the following example, ListContourPlot3D accepts an array of points spaced at intervals 0.1 apart throughout the volume, but seems to choose an arbitrary number of points for generating a mesh. Setting `MaxPlotPoints` explicitly works to a limited extent. How can I force it to use all points without specifying that number by hand?               gauss = Partition[        Flatten[Table[{i, j, k, Exp[-i^2 - j^2]}, {i, -2, 2, 0.1}, {j, -2,            2, 0.1}, {k, -2, 2, 0.1}]], 4];              GraphicsRow[{       ListContourPlot3D[gauss, Contours -> {0.5},         ContourStyle -> Opacity[0.5], AxesLabel -> {x, y, z}],       ListContourPlot3D[gauss, Contours -> {0.5},         ContourStyle -> Opacity[0.5], AxesLabel -> {x, y, z},         MaxPlotPoints -> 20],       ListContourPlot3D[gauss, Contours -> {0.5},         ContourStyle -> Opacity[0.5], AxesLabel -> {x, y, z},         MaxPlotPoints -> Infinity]       }, ImageSize -> 800]      ![enter image description here](http://i.stack.imgur.com/0GlTY.jpg) **Edit** thanks to @Rahul: For a 3D array (with the right order of indices) we get the right behavior. Does this mean the 4D syntax constructs the mesh in a fundamentally different way?               gauss = Table[Exp[-i^2 - j^2], {k, -2, 2, 0.1}, {j, -2, 2, 0.1}, {i, -2, 2, 0.1}];          ListContourPlot3D[gauss, Contours -> {0.5}, ContourStyle -> Opacity[0.5],      AxesLabel -> {x, y, z}, DataRange -> {{-2, 2}, {-2, 2}, {-2, 2}}]      ![enter image description here](http://i.stack.imgur.com/ZvxWM.jpg) **Edit** thanks to @Szabolcs: Increasing `MaxPlotPoints` constructs the mesh with some strange regularities (and appears to slow it down):               GraphicsGrid[      Partition[       Table[ListContourPlot3D[gauss, Contours -> {0.5},          ContourStyle -> Opacity[0.5], AxesLabel -> {x, y, z},          MaxPlotPoints -> i, ImageSize -> 200,          PlotLabel ->           Style[StringJoin["MaxPlotPoints->", ToString[i]], 16, Bold]], {i,          18, 38, 4}], 3, 3, 1, Null], ImageSize -> 800]      ![enter image description here](http://i.stack.imgur.com/BLvZy.jpg)


Symbolic vs. numeric evaluation is incorrect

In Mathematica 9: I have two functions `f[v]` and `g[v]`. When I do `f[g[0]]`, I get the correct value. However, when I copy the expression for `f[g[v]]`, let's call it `R`, and then do `t[v_]:=R; t[0]` I get an incorrect value. That is, `t[0]==f[g[0]]` returns false. No idea what is going wrong here. In other words, Mathematica seems to incorrectly compute (or output) the symbolic expression for `f[g[v]]`. Here are the two functions: `f[v_]:=Sqrt[(1 - 2 v + 8 v^2 + Sqrt[-3 + 12 v + 4 v^2 - 32 v^3 + 64 v^4])/(-1 + 2 v)]/Sqrt[2]` and `g[v_]:=3/8 + 1/8 Sqrt[25 + 16 v] + Sqrt[ 5 + 8 v - 25/Sqrt[25 + 16 v] - (16 v)/Sqrt[25 + 16 v]]/(4 Sqrt[2])` **EDIT** However, it seems that if I do `f[v_]:=Sqrt[(1 - 2 v + 8 v^2 + Sqrt[-3 + 12 v + 4 v^2 - 32 v^3 + 64 v^4])/(-1 + 2 v)]/Sqrt[2]` followed by `f[3/8 + 1/8 Sqrt[25 + 16 v] + Sqrt[ 5 + 8 v - 25/Sqrt[25 + 16 v] - (16 v)/Sqrt[25 + 16 v]]/(4 Sqrt[2])]` then I get the correct expression.


Can Do-Loops iterate backward?

If I create a `Do` statement,               Do[expr, {i, imin, imax}]      is there a way to make the statement evaluate from `imax` to `imin` instead of `imin` to `imax`?


Function with a sharp resonance which Mathematica fails to integrate. Why?

I'm a new user of _Mathematica_ and I'm trying to use it to calculate the collisional cross-section as a function of energy for a given potential and decay rate. I know that the resulting function should be continuous, but when _Mathematica_ does the integration and plots the function, it gives a discontinuous function. Please help! Here is my code:               rc[k_?NumericQ, b_?NumericQ] := Level[NSolve[3/x^12 - 10/x^6 + (5 k/2) b^2/x^2 == k, x,      Reals], {-1}][[-1]]          i2[k_?NumericQ, b_?NumericQ] := NIntegrate[(1/x^12)/Sqrt[N[k] - (3/(N[x])^12 -      10/(N[x])^6 + (5 N[k]/2) (N[b])^2/(N[x])^2)], {x, rc[N[k], N[b]] + 10^-12,Infinity}]          p2[k_?NumericQ, b_?NumericQ] := 1 - E^(-2 i2[N[k], N[b]])          pb2[k_?NumericQ, b_?NumericQ] := N[b]*N[p2[N[k], N[b]]]          s2[k_?NumericQ] := (N[2 Pi])*NIntegrate[pb2[N[k], N[b ]], {b, 0, Infinity},        MinRecursion -> 3, MaxRecursion -> 20]      The typical probability function for a given energy looks like this:               Plot[p2[5, b], {b, 0, 3}]      ![This the plot of probability vs. impact parameter for k=5](http://i.stack.imgur.com/0u7JW.jpg) Notice that there is a spike somewhere near `b=1`, where the probability jumps up to `1`. However, we know that this function is continuous because the probability for the decay of an orbiting resonance is `1`, and the probability will continuously approach `1` for energies both slightly above and slightly below the resonance. Mathematically, the exponent `-2i2[k,b]` just goes to `-Infinity` and so `1-E^(-2i2[k,b])` goes to `1`. Since all of these functions are continuous in this way, the function `pb2[k,b]` should also be continuous, having a value of `0` for `b=0` (since b approaches `0` and `p2[k,b]` approaches something between `0` and `1`), so we should be able to integrate `pb2[k,b]` with respect to b numerically without any issues, thus obtaining `s2[k]` but when I tried to compute `s2[k]` for various `k's` and plot the results, this is what I got:               Plot[s2[k], {k, 1, 10}]      ![This is the supposed plot of cross-section vs. energy](http://i.stack.imgur.com/2UuXU.jpg) Now everything we know about the mathematics and the physics of the situation suggests that the cross-section should be a continuous function of the energy, so what gives? Why did Mathematica integrate a function which is clearly continuous in both of its variables and give me a /dis/continuous function? I think it must have something to do with that last numerical integration, because I was given the following error message: > >     NIntegrate::slwcon: Numerical integration converging too slowly; suspect >       one of the following: singularity, value of the integration is 0, > highly >       oscillatory integrand, or WorkingPrecision too small. >> >   Like I said, I'm a beginner and don't know how to deal with this stuff. What should I do to get the nice continuous `s2[k]` that I want?


Defining Piecewise Functions in Modules

In short, my question is the same as my previous one except that everything is now wrapped up in a module. The relevant code I'm working with is:               getinter[a_, b_, u0_, k_, m_, hbar_, Nu_, Np_, up_] :=          Module[{ekp, ms, LUs, env, eenv, envpart, f, kppart, g, approx,         approx1, papprox, approx2, hard, ereal, psiparts, real, real1,         realp, real2, er, inter},            ekp = energies[a, b, u0, k, 1, m, hbar, 0.001, 10^-15][[1]];            ms = effmass[a, b, u0, k, 0.2, 1, m, hbar, 0.001, 10^-15];            LUs = BuildLUs[a, b, Nu, Np, u0, up];            env[x_] := Abs[Det[envfunc[ms, hbar, x, up, Nu, Np, a, b]]]^2;            eenv = zeros[env, up + 0.000001, 0.01, 0, 1, 10^-15, 0.02][[1]];            envpart = getpsipieces[LUs[[1]], LUs[[2]], eenv, ms, hbar];            f[x_] := Evaluate@Piecewise[envpart];            Return[f[0.231]];          ]      envpart is a properly formatted object for piecewise and the variable it uses is named x. When I evaluate this, it's returning the structure I put into piecewise but now formatted as a case structure as opposed to an array. What I'd like it to do is to return f[0.231]='some number' like you would expect. Also, f[x_]:= Evaluate@Piecewise[envpart]; works fine if I take it out of the module. Thanks for the help. Also, I get the sense that the solution to this problem, if I fully understand it, will allow me to work out a lot of other problems I encounter, so I'd really appreciate any suggestions on where I can learn about the issues at play. Edited for slightly less awful formatting.


Can someone explain this snippet: (#[#] &)[#[#][#] &]

A friend showed me this snippet of code today:               (#[#] &)[#[#][#] &]      I can sort of see that we're constructing an anonymous function that takes a function as an argument and calls that function passing it itself. Then we're calling that anonymous function, passing another, and I get lost... A cogent explanation of this code would be great. Apologies if this is well known, I tried to google for it, but its nature makes searching for it hard.


How can I define a function which is the sum of other functions?

I have a function which is summation of another function over different i,j iterators.               U[r] = Sum[V[r, i, j], {i, 1, 5}, {j, 6, 10}]      and `V[r, i, j]` function depends on the values of i and j (has different parameters depending on value of i & j)               If[2 <= i <= 5 &&  7 <= j <= 10,        Evaluate[vhh[i_,j_,r_] = -ehh (1 - {1 - Exp[-Ahh (ra[i, j, r] - rshh)]}^2)],        vhh = 0];     If[i == 1 &&  7 <= j <= 10,        Evaluate[vch[i_, j_, r_] = -ech (1 - {1 - Exp[-Ach (ra[i, j, r] - rsch)]}^2)],        vch = 0];     If[2 <= i <= 5 &&  j == 6,        Evaluate[vch[i_, j_, r_] = -ech (1 - {1 - Exp[-Ach (ra[i, j, r] - rsch)]}^2)],        vch = 0];     v[1, 6, r_] := -ecc (1 - {1 - Exp[-Acc (ra[1, 6, k, o] - rscc)]}^2);      And v[i,j,r] is sum of vch, vhh and vcc. so U[r] will be               U[r_]:=Sum[vhh[i_,j_,r_] + vch[i_,j_,r_]+ vcc[i_,j_,r_], {i,1,5},{j,6,10}]      (not defined Vhh or Vcc values are considered 0) The above code isn't intended to work in _Mathematica_ ; it is just pseudo-code for sake of defining my problem. I was thinking of defining three different functions, Vhh[r], Vch[r] and Vcc[r], and summing the three functions into the final function, `U`, but it doesn't work (see below error). Mathematica doesn't allow me to add 2 or more functions to a third one. Do you have any ideas how to define `U` function in _Mathematica_?               U[r_] := Vhh[r] + Vch[r] + Vcc[r]      > SetDelayed::write: Tag C in U[r_] is Protected.


Is it possible to create Evaluatable cell which will be automatically overwritten?

Am trying to generate an `Evaluatable` cell which itself is an output cell which will be overwritten when the original `Input` cell will be evaluated again:               CellPrint[      ExpressionCell[Defer[1 + 1], "Output", Evaluatable -> True,        CellAutoOverwrite -> True, GeneratedCell -> True]]      Without `Evaluatable -> True` everyting works as expected: the generated output cell is automatically overwritten when the input cell is evaluated again. But adding `Evaluatable -> True` breaks this behavior. Is it possible to generate `Evaluatable` cell which will be automatically overwritten?


Finding max, min, and closest root of two dimensional data

I have some data that is two dimensional (traditional (x, y) format) as so:               var = {{x1, y1}, {x2, y2}, {x3, y3}}      I would like to search through that large list and find the maximum and minimum y values and return the ordered pair. Something like:               min[var]->{x2, y2} //read "->" as returns {the minimum ordered pair}     max[var]->{x3, y3} //read "->" as returns {the maximum ordered pair}      Finally I know the data has a "root". A plot of the points cross the x-axis. I would like to find the closest few (maybe 3 or 4) points to zero. Questions similar to this have been posted but I cannot figure out how to adapt those solutions to my needs previous work 1 previous work 2


Convert list of lists to cumulative join

I have this:               list[1]={1,2,3};     list[2]={7,8,9};     list[3]={15,20,22};      I want this:               cumulativeList[1]={1,2,3};     cumulativeList[2]={1,2,3,7,8,9};     cumulativeList[3]={1,2,3,7,8,9,15,20,22};      Sort of like Accumulate, but using Join instead of Sum. I think it might be possible using FoldList but I'm getting confused.


Toolbars in Mathematica

_Mathematica_ seriously lacks some useful toolbars. I wonder why keeping a totally barebone gui is part of WRI's policy? Would such a feature be so platform-specific that it does not worth design it? I really am clueless here. Palettes are fine, but they don't behave like toolbars or dockers. First of all, I have to write them (which is in itself is not trivial to do, see e.g. this post on MathGroup), but then even if I create some, how can I tell them to appear every time I start _Mathematica_ , and that they should appear the same place (e.g. toolbar should be below menubar)? It would be nice to have a toolbar where some of the functionality of the menu **and** custom-wrote functions can be accessed easily. Note that this question is not just about **how to implement it** , but also about **why this was not implemented so far**. If you think that this does not belong here, I am happy to ask it on meta or delete it. For those requiring a specific question for which some coding can be done, here it is: **Question:** How to implement a toolbar with buttons like **Restart kernel** , **Delete all output** , **Show memory in use** , **Turn off syntax colouring** , etc. which always starts with _Mathematica_ and docks just below the menubar in such a way that when windows are maximized, they do not go behind or cover it?


Extracting argument sequences from function expressions

Why is it that               fun[x, y] /. fun[z__] :> z      leads to > >     Sequence[x,y] >   but               Dot[x, y] /. Dot[z__] :> z      gives > >     Dot[x,y] >   I want it to be > >     Sequence[x,y] >   Makes no sense. How do I make it work like I think it should?


Building a new table by repeating elements from another table

I have a small problem that I cannot solve. I have two tables, one with three elements:               a = {0, L/c, 2L/c};      and the other with 9 elements, all 0:               b = {0, 0, 0, 0, 0, 0, 0, 0, 0};      I would like to put the elements from table a into table b, giving so that I get the following table:               {0, L/c, 2L/c, 0, L/c, 2L/c, 0, L/c, 2L/c}      Can someone please give me some advice?


Plots in version 10.0 look washed out compared to previous versions

Recently installed the new version but I can't get the graphics to look the way I want them to. If I run this code               Plot[x^2, {x, -5, 5}, PlotStyle -> Thick]      in version 8.0 I get this: ![enter image description here](http://i.stack.imgur.com/5Wk6q.png) But if I run the same code in version 10.0 I get this: ![enter image description here](http://i.stack.imgur.com/2eKpd.png) (I exported the images using the `Export` command to post them here, but the issue is present in the notebook as well - they look exactly like this when plotted) The blue trace looks better, in my opinion, in the older version. It's more vibrant, less faded or washed out. This also applies to the numbers on the axes, which look gray in the version 10.0 plot but black in the version 8.0 plot. How can I reproduce the old graphics? Why did they make this change? Maybe the newer version is better for the screen, but I am trying to make publication- quality plots and need the old style.


Fitting a spline to data with FindFit?

I am trying to find a function that fits my almost linear data. A high order polynomial model has too much residual. So I was hoping to use Mathematica to **fit splines** to the **curve**. This is what I would like to see in an example.   * `FindFit` with a spline function   * How to get model stats like what `LinearModelFit` provides.   * How to dump the spline terms and control points so I can implement in "C" I can then use the cubic spline on my embedded platform. So can I get a symbolic representation of this function so I can implement it? You can get the sample data here


Graphics[] not working from within For[]

Why is the following code not plotting the set of points from {1,1} to {10,10} ?               For[i = 1, i <= 10, i++, Graphics[Point[{i, i}]]]


Series resulting in "No more memory available."

Is there any way to force Mathematica to come up with the closed form to               Sum[1/(i^18 (i^2 + j^2)), {i, 1, Infinity}, {j, 1, Infinity}]      or               Sum[1/(i^4 (i^2 + j^2)), {i, 1, Infinity}, {j, 1, Infinity}]      ? The former series definitely has a closed form, whereas the 2nd one might have or not.


Why can Format be used on the left side?

I am learning Mathematica in random order by reading its documentation. This approach is what I like most when learning new things. Consider the following 2 cases. Syntax A:               Format[Foo[x_,y_]]:=MatrixForm[{{x},{y}}]     Foo[1,2]      Syntax B:               Foo[x_,y_]:=Format[MatrixForm[{{x},{y}}]]     Foo[1,2]      My confusion is about why can we use `Format` on the left side? It seems to be counter intuitive as in most programming language, definition should be on the right side. Could you explain why?


How to plot empty rectangle?

I know there is a `Rectangle[]` function, but it is always filled with some color. What I need is a rectangle, which is empty inside (only it's boundaries visible). I just need to overlay it on plotted function to indicate some of it's area.


Strange ImageFilter results

I am trying to perform some neighborhood analysis on an image, but ImageFilter seems to be interfering with the results outputted by the provided filtering function. ### Initialization Given the hue channel of an image               image = Import["http://i.imgur.com/IqnvrjC.png"]     hue = ColorSeparate[image, "HSB"][[1]]      We can see that there is some information "hidden" on the dark area               ImageAdjust[hue, {0, 0, 0.2}]      ### Processing My intent is to replace the value of every pixel with the value of the variance of his direct (3x3), neighbors:               huevar = ImageFilter[Composition[Variance, Flatten], hue, 1]      The result is also very dark, as expected, but the dark areas are effectively black. As I haven't clipped the results, it is not what I expected. The filter outputs small values, as I could observe in the following:               Reap[       huevar = ImageFilter[Composition[Sow[#] &, Variance, Flatten], hue, 1],        _,       (reapvar = #2)&     ];          reapvar // Take[#, 5] &     (* {0.000126874, 0.000250331, 0.0000807382, 8.11654*10^-6, 0.0000234952} *)          Flatten@ImageData@huevar // Take[#, 5] &     (* {0., 0., 0., 0., 0.} *)      If I reconstruct the image with data from `reapvar` I get exactly what I want: a dark image that can be re-scaled to show the detail in the dark area.               Image[Partition[reapvar, First@ImageDimensions@image]]     ImageAdjust[%, {0, 0, .1}]      ### Pre or mid-scaling I've also tried pre-scaling the output directly in filtering function, as in               Reap[       scaledhuevar = ImageFilter[Composition[Sow[1000*#] &, Variance, Flatten], hue, 1],        _,       (scaledreapvar = #2)&     ];      The dark areas get brighter this way, but the precise values, even from the bright areas, are different from those obtained by sowing/reaping.               scaledreapvar // Take[#, 5] &     (* {0.126874, 0.250331, 0.0807382, 0.00811654, 0.0234952} *)          Flatten@ImageData@scaledhuevar // Take[#, 5] &     (* {0.12549, 0.25098, 0.0823529, 0.00784314, 0.0235294} *)      What is causing this difference in the results? When/where is the clipping occurring?


Is there a fast method of generating a Standard Deviation image from a frame stack?

Imagine I have a stack of image frames, $(f_1, ..., f_N) \in F$, where each $f_i$ has the same set of $(x,y)$ dimensions. Using these frames, I'd like to create an image where each pixel in the image consists of the standard deviation of the values at the corresponding pixel position in each of the $f_i$. Unfortunately, the following procedure is painfully slow (when applied to a $256 \times 256$ pixel image):               SDImage = ImageData@FrameStack[[1]];       For[a = 1, a <= ImageDimensions[FrameStack[[1]]][[1]], a++,         For[b = 1, b <= ImageDimensions[FrameStack[[1]]][[2]], b++,          SDImage[[a, b]] = StandardDeviation[Table[ImageData[FrameStack[[k]]][[a, b]], {k, 1, Length[FrameStack]}]];          Print[SDImage[[a, b]]];         ];       ];          SDImage = Image[SDImage]        Is there a faster method of doing this, or perhaps a built in tool (like in ImageJ)?


How can I make my output to be added to an existing list?

v = {{0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}}          For[i = 1, i < 6, i++,        For[e = 1, e < 6, e++ 1,          Print[Mod[v[[i]] + v[[e]], 2]]     ]]      I have been trying to make all the output from the loop to be added to another list using `AppendTo`, but it doesn't work. How can I do this task?


Cannot change ImageResolution after applying ImagePad

I want to export high-resolution images of a plot I'm making. The trouble is, the plot has a lot of extra white space around it which I get rid of via `ImagePad` (I could also use `ImageCrop` but I run into the same problem described here). If I put in the following code,               tempimage = Plot[x^2, {x, -10, 10}];          Export["testexport100.png", tempimage, ImageResolution -> 100];     Export["testexport125.png", tempimage, ImageResolution -> 125];     Export["testexport150.png", tempimage, ImageResolution -> 150];      I get three files of different size and quality (10KB, 13KB, and 16KB). But when I first adjust the margins of the image, I no longer have the ability to change the resulting image quality. For example, if I do               tempimage2 = ImagePad[tempimage, {{0, -10}, {0, -10}}];          Export["testexport2_100.png", tempimage2, ImageResolution -> 100];     Export["testexport2_125.png", tempimage2, ImageResolution -> 125];     Export["testexport2_150.png", tempimage2, ImageResolution -> 150];      Then all three resulting files are identical and 7KB.


Minimum spanning Tree from a weighted adjacency graph

**Note:** Cross-posted at http://community.wolfram.com/groups/-/m/t/137658?p_p_auth=8QnKtT9I I have a really big graph, 40x40. Here is my code               `g = WeightedAdjacencyGraph[{{∞, ∞, ∞,          427, 668, 495, 377, 678, ∞,          177, ∞, ∞, 870, ∞, 869, 624, 300,          609, 131, ∞, 251, ∞, ∞, ∞,          856, 221, 514, ∞, 591, 762, 182, 56, ∞, 884,          412, 273, 636, ∞, ∞,          774}, {∞, ∞, 262, ∞, ∞,          508, 472, 799, ∞, 956, 578, 363, 940, 143, ∞,          162, 122, 910, ∞, 729, 802, 941, 922, 573, 531, 539,          667, 607, ∞, 920, ∞, ∞, 315, 649,          937, ∞, 185, 102, 636, 289}, {∞,          262, ∞, ∞, 926, ∞, 958, 158, 647,          47, 621, 264, 81, ∞, 402, 813, 649, 386, 252, 391, 264,          637, 349, ∞, ∞, ∞, 108, ∞,          727, 225, 578, 699, ∞, 898, 294, ∞, 575, 168,          432, 833}, {427, ∞, ∞, ∞,          366, ∞, ∞, 635, ∞, 32, 962, 468,          893, 854, 718, 427, 448, 916, 258, ∞, 760, 909, 529,          311, 404, ∞, ∞, 588, 680, 875, ∞,          615, ∞, 409, 758, 221, ∞, ∞, 76,          257}, {668, ∞, 926,          366, ∞, ∞, ∞, 250, 268, ∞,          503, 944, ∞, 677, ∞, 727, 793, 457, 981,          191, ∞, ∞, ∞, 351, 969, 925, 987,          328, 282, 589, ∞, 873, 477, ∞, ∞,          19, 450, ∞, ∞, ∞}, {495,          508, ∞, ∞, ∞, ∞, \     ∞, 765, 711, 819, 305, 302, 926, ∞, ∞,          582, ∞, 861, ∞, 683,          293, ∞, ∞, 66, ∞,          27, ∞, ∞, 290, ∞, 786, ∞,          554, 817, 33, ∞, 54, 506, 386, 381}, {377, 472,          958, ∞, ∞, ∞, ∞, \     ∞, ∞, 120, 42, ∞, 134, 219, 457, 639,          538, 374, ∞, ∞, ∞,          966, ∞, ∞, ∞, ∞, \     ∞, 449, 120, 797, 358, 232, 550, ∞, 305, 997, 662,          744, 686, 239}, {678, 799, 158, 635, 250,          765, ∞, ∞, ∞, 35, ∞, 106,          385, 652, 160, ∞, 890, 812, 605,          953, ∞, ∞, ∞, 79, ∞, 712,          613, 312, 452, ∞, 978, 900, ∞,          901, ∞, ∞, 225, 533, 770,          722}, {∞, ∞, 647, ∞, 268,          711, ∞, ∞, ∞, 283, ∞,          172, ∞, 663, 236, 36, 403, 286,          986, ∞, ∞, 810, 761, 574, 53,          793, ∞, ∞, 777, 330, 936, 883,          286, ∞, 174, ∞, ∞, ∞, 828,          711}, {177, 956, 47, 32, ∞, 819, 120, 35,          283, ∞, 50, ∞, 565, 36, 767, 684, 344, 489,          565, ∞, ∞, 103, 810, 463, 733, 665, 494, 644,          863, 25, 385, ∞, 342,          470, ∞, ∞, ∞, 730, 582,          468}, {∞, 578, 621, 962, 503, 305,          42, ∞, ∞, 50, ∞, 155,          519, ∞, ∞, 256, 990, 801, 154, 53, 474, 650,          402, ∞, ∞, ∞,          966, ∞, ∞, 406, 989, 772, 932, 7, ∞,          823, 391, ∞, ∞, 933}, {∞, 363, 264,          468, 944, 302, ∞, 106, 172, ∞,          155, ∞, ∞, ∞, 380, 438, ∞,          41, 266, ∞, ∞, 104, 867, 609, ∞,          270, 861, ∞, ∞, 165, ∞, 675, 250,          686, 995, 366, 191, ∞, 433, ∞}, {870, 940, 81,          893, ∞, 926, 134, 385, ∞, 565,          519, ∞, ∞, 313,          851, ∞, ∞, ∞, 248, 220, ∞,          826, 359, 829, ∞, 234, 198, 145, 409, 68,          359, ∞, 814, 218, 186, ∞, ∞, 929,          203, ∞}, {∞, 143, ∞, 854,          677, ∞, 219, 652, 663, 36, ∞, ∞,          313, ∞, 132, ∞, 433,          598, ∞, ∞, 168,          870, ∞, ∞, ∞, 128, 437, ∞,          383, 364, 966, 227, ∞, ∞, 807,          993, ∞, ∞, 526, 17}, {869, ∞, 402,          718, ∞, ∞, 457, 160, 236, 767, ∞,          380, 851, 132, ∞, ∞, 596, 903, 613,          730, ∞, 261, ∞, 142, 379, 885,          89, ∞, 848, 258, 112, ∞,          900, ∞, ∞, 818, 639, 268,          600, ∞}, {624, 162, 813, 427, 727, 582,          639, ∞, 36, 684, 256,          438, ∞, ∞, ∞, ∞, 539, 379,          664, 561, 542, ∞, 999, 585, ∞, ∞,          321, 398, ∞, ∞, 950, 68, 193, ∞,          697, ∞, 390, 588, 848, ∞}, {300, 122, 649,          448, 793, ∞, 538, 890, 403, 344,          990, ∞, ∞, 433, 596,          539, ∞, ∞, 73, ∞,          318, ∞, ∞, 500, ∞, 968, ∞,          291, ∞, ∞, 765, 196, 504, 757, ∞,          542, ∞, 395, 227, 148}, {609, 910, 386, 916, 457, 861,          374, 812, 286, 489, 801, 41, ∞, 598, 903,          379, ∞, ∞, ∞, 946, 136,          399, ∞, 941, 707, 156, 757, 258, 251, ∞,          807, ∞, ∞, ∞, 461,          501, ∞, ∞,          616, ∞}, {131, ∞, 252, 258,          981, ∞, ∞, 605, 986, 565, 154, 266,          248, ∞, 613, 664, 73, ∞, ∞,          686, ∞, ∞, 575, 627, 817, 282, ∞,          698, 398, 222, ∞,          649, ∞, ∞, ∞, ∞, \     ∞, 654, ∞, ∞}, {∞, 729,          391, ∞, 191, 683, ∞,          953, ∞, ∞, 53, ∞, 220, ∞,          730, 561, ∞, 946, 686, ∞, ∞, 389,          729, 553, 304, 703, 455, 857, 260, ∞, 991, 182, 351,          477, 867, ∞, ∞, 889, 217, 853}, {251, 802,          264, 760, ∞,          293, ∞, ∞, ∞, ∞,          474, ∞, ∞, 168, ∞, 542, 318,          136, ∞, ∞, ∞, ∞,          392, ∞, ∞, ∞, 267, 407, 27, 651, 80,          927, ∞, 974, 977, ∞, ∞, 457,          117, ∞}, {∞, 941, 637,          909, ∞, ∞, 966, ∞, 810, 103, 650,          104, 826, 870, 261, ∞, ∞, 399, ∞,          389, ∞, ∞, ∞,          202, ∞, ∞, ∞, ∞, 867, 140,          403, 962, 785, ∞, 511, ∞, 1, ∞,          707, ∞}, {∞, 922, 349,          529, ∞, ∞, ∞, ∞, 761, 810,          402, 867, 359, ∞, ∞,          999, ∞, ∞, 575, 729,          392, ∞, ∞, 388, 939, ∞,          959, ∞, 83, 463, 361, ∞, ∞, 512,          931, ∞, 224, 690, 369, ∞}, {∞,          573, ∞, 311, 351, 66, ∞, 79, 574,          463, ∞, 609, 829, ∞, 142, 585, 500, 941, 627,          553, ∞, 202, 388, ∞, 164, 829, ∞,          620, 523, 639, 936, ∞, ∞, 490, ∞,          695, ∞, 505, 109, ∞}, {856, 531, ∞,          404, 969, ∞, ∞, ∞, 53,          733, ∞, ∞, ∞, ∞,          379, ∞, ∞, 707, 817,          304, ∞, ∞, 939, 164, ∞, ∞,          616, 716, 728, ∞, 889, 349, ∞, 963, 150,          447, ∞, 292, 586, 264}, {221,          539, ∞, ∞, 925, 27, ∞, 712, 793,          665, ∞, 270, 234, 128, 885, ∞, 968, 156, 282,          703, ∞, ∞, ∞,          829, ∞, ∞, ∞,          822, ∞, ∞, ∞, 736, 576, ∞,          697, 946, 443, ∞, 205, 194}, {514, 667,          108, ∞, 987, ∞, ∞, 613, ∞,          494, 966, 861, 198, 437, 89, 321, ∞, 757, ∞,          455, 267, ∞, 959, ∞,          616, ∞, ∞, ∞, 349, 156,          339, ∞, 102, 790, 359, ∞, 439, 938, 809,          260}, {∞, 607, ∞, 588, 328, ∞, 449,          312, ∞, 644, ∞, ∞,          145, ∞, ∞, 398, 291, 258, 698, 857,          407, ∞, ∞, 620, 716,          822, ∞, ∞, 293, 486, 943, ∞,          779, ∞, 6, 880, 116, 775, ∞,          947}, {591, ∞, 727, 680, 282, 290, 120, 452, 777,          863, ∞, ∞, 409, 383,          848, ∞, ∞, 251, 398, 260, 27, 867, 83, 523,          728, ∞, 349, 293, ∞, 212, 684, 505, 341, 384,          9, 992, 507, 48, ∞, ∞}, {762, 920, 225, 875,          589, ∞, 797, ∞, 330, 25, 406, 165, 68, 364,          258, ∞, ∞, ∞, 222, ∞, 651,          140, 463, 639, ∞, ∞, 156, 486,          212, ∞, ∞, 349, 723, ∞, ∞,          186, ∞, 36, 240, 752}, {182, ∞,          578, ∞, ∞, 786, 358, 978, 936, 385,          989, ∞, 359, 966, 112, 950, 765, 807, ∞, 991,          80, 403, 361, 936, 889, ∞, 339, 943,          684, ∞, ∞, 965, 302, 676, 725, ∞,          327, 134, ∞, 147}, {56, ∞, 699, 615,          873, ∞, 232, 900, 883, ∞, 772,          675, ∞, 227, ∞, 68, 196, ∞, 649,          182, 927, 962, ∞, ∞, 349,          736, ∞, ∞, 505, 349, 965, ∞, 474,          178, 833, ∞, ∞, 555,          853, ∞}, {∞, 315, ∞, ∞,          477, 554, 550, ∞, 286, 342, 932, 250, 814, ∞,          900, 193, 504, ∞, ∞, 351, ∞,          785, ∞, ∞, ∞, 576, 102, 779, 341,          723, 302, 474, ∞,          689, ∞, ∞, ∞,          451, ∞, ∞}, {884, 649, 898, 409, ∞,          817, ∞, 901, ∞, 470, 7, 686,          218, ∞, ∞, ∞,          757, ∞, ∞, 477, 974, ∞, 512, 490,          963, ∞, 790, ∞, 384, ∞, 676, 178,          689, ∞, 245, 596, 445, ∞, ∞,          343}, {412, 937, 294, 758, ∞, 33, 305, ∞,          174, ∞, ∞, 995, 186, 807, ∞,          697, ∞, 461, ∞, 867, 977, 511,          931, ∞, 150, 697, 359, 6, 9, ∞, 725,          833, ∞, 245, ∞, 949, ∞,          270, ∞, 112}, {273, ∞, ∞, 221,          19, ∞, 997, ∞, ∞, ∞, 823,          366, ∞, 993, 818, ∞, 542,          501, ∞, ∞, ∞, ∞, \     ∞, 695, 447, 946, ∞, 880, 992,          186, ∞, ∞, ∞, 596, 949, ∞,          91, ∞, 768, 273}, {636, 185, 575, ∞, 450, 54,          662, 225, ∞, ∞, 391,          191, ∞, ∞, 639,          390, ∞, ∞, ∞, ∞, \     ∞, 1, 224, ∞, ∞, 443, 439, 116,          507, ∞, 327, ∞, ∞, 445, ∞,          91, ∞, 248, ∞, 344}, {∞, 102,          168, ∞, ∞, 506, 744, 533, ∞,          730, ∞, ∞, 929, ∞, 268, 588,          395, ∞, 654, 889, 457, ∞, 690, 505,          292, ∞, 938, 775, 48, 36, 134, 555, 451, ∞,          270, ∞, 248, ∞, 371, 680}, {∞, 636,          432, 76, ∞, 386, 686, 770, 828, 582, ∞, 433,          203, 526, 600, 848, 227, 616, ∞, 217, 117, 707, 369,          109, 586, 205, 809, ∞, ∞, 240, ∞,          853, ∞, ∞, ∞, 768, ∞,          371, ∞, 540}, {774, 289, 833, 257, ∞, 381,          239, 722, 711, 468, 933, ∞, ∞,          17, ∞, ∞, 148, ∞, ∞,          853, ∞, ∞, ∞, ∞, 264, 194,          260, 947, ∞, 752, 147, ∞, ∞, 343,          112, 273, 344, 680, 540, ∞}},             VertexLabels -> {1 -> "1", 2 -> "2", 3 -> "3", 4 -> "4", 5 -> "5",          6 -> "6", 7 -> "7", 8 -> "8", 9 -> "9", 10 -> "10", 11 -> "11",          12 -> "12", 13 -> "13", 14 -> "14", 15 -> "15", 16 -> "16",          17 -> "17", 18 -> "18", 19 -> "19", 20 -> "20", 21 -> "21",          22 -> "22", 23 -> "23", 24 -> "24", 25 -> "25", 26 -> "26",          27 -> "27", 28 -> "28", 29 -> "29", 30 -> "30", 31 -> "31",          32 -> "32", 33 -> "33", 34 -> "34", 35 -> "35", 36 -> "36",          37 -> "37", 38 -> "38", 39 -> "39", 40 -> "40"},        VertexStyle -> {RGBColor[1, 0.7, 0]},        VertexShapeFunction -> {"Square"}]`      I want to create MinimumSpanningTree out of this. Im trying:               MinimumSpanningTree[g]      and of course its not working. I know there is something terribly wrong here. But im a begginer with Mathematica and i cant figure it out. Any help?


Dimension of an algebraic variety

I would like to compute, using Groebner bases, the dimension of the variety defined by a set of polynomials in several variables. In the wikipedia page the method is described, and an implementation is possible, but I was hoping there was a predefined function that would do that.


Whats is the real difference between this two examples of using Dynamic with Grid

the question is relatively simple I think. This is the first example of the code which works:               DynamicModule[{tabClicked, buttonClicked},           TabView[{        "First" ->          Dynamic@Grid[{{ Button["xx", tabClicked = 2; buttonClicked = 1],              Button["xx", tabClicked = 2; buttonClicked = 2]}}],        "Second" -> Dynamic[buttonClicked]        }, Dynamic[tabClicked]       ]      ]      while this doesn't:               DynamicModule[{tabClicked, buttonClicked},      buildButton[idx_] :=        Button["xx", tabClicked = 2; buttonClicked = idx];     TabView[{       "First" -> Dynamic@Grid[{{ buildButton[1], buildButton[2]}}],      "Second" -> Dynamic[buttonClicked]      }, Dynamic[tabClicked]      ]     ]      I know I can "fix" it by removing the Dynamic in front of Grid. The problem is that in the real example I need it as the grid context and even it's size are dynamic. I would like to understand why separating construction of button's into a function I get this strange behavior. Looking at the variable names using InputForm[] shows that the presence of Dynamic in front of Grid somehow forces Mathematica to assign temporary names to variables used in the buildButton. Many Thanks, Lukasz


Known restrictions for WolframAlpha in CDF Player and PlayerPro

Are there any known (documented?) restrictions for the use of the WolframAlpha function in CDF-Player and PlayerPro? I only found this answer which mentions upper values for various license version, but it doesn't explicitly mention the two player variants and seem to be outdated (the link in it doesn't point to what it once did, I think). Background: When I try a call to WolframAlpha in PlayerPro it just hangs with no message, even with the TimeConstraint option set to a low value. At least the TimeConstrained wrapper does work as it should. Of course I tested that the exact same code works without problems in Mathematica on the same machine. So I suspect that there are such restrictions but find it hard to find out what these are...


ArcTan expressed as a radian fraction?

This type of answer is what I'm looking for:               In[58]:= ArcTan @ 1     Out[58]=  π/4       This is what mathematica gives me:               In[59]:= ArcTan@2     Out[59]= ArcTan[2]      Is it possible to express `ArcTan` in terms of $\pi$? I understand some fractions would be hairy. I am using `Mathematica 8`.


Faster way to extract partial data from AdjacencyMatrix

I am dealing with a lot of Graph objects. One task is to obtain an `Id` for each of them. So I first used               g = Graph[{1 -> 2, 1 -> 3, 4 -> 2, 3 -> 5, 4 -> 5, 7 -> 2, 4 -> 7, 3 -> 8}];          GraphId[g_] := Module[{}, AdjacencyMatrix@CanonicalGraph@g]     FullForm@GraphId@g      which gives               SparseArray[       Automatic,       List[7,7],       0,       List[         1,         List[           List[0,2,5,5,6,8,8,8],           List[List[5],List[7],List[4],List[6],List[7],List[7],List[3],List[6]]         ],         List[1,1,1,1,1,1,1,1]       ]     ]      I have to reduce this result to save space. The first approach is not to including `List[1,1,1,1,1,1,1,1]` in the result. So I tried               ToData[g_] := (Last@ToExpression@StringReplace[ToString@FullForm@g, "Graph" -> "List"])[[1]]     GraphIdReduced[g_] := Module[{}, ToData@CanonicalGraph@g]     FullForm@GraphIdReduced@g      which gives               SparseArray[       Automatic,       List[7,7],       0,       List[         1,         List[           List[0,2,5,5,6,8,8,8],           List[List[5],List[7],List[4],List[6],List[7],List[7],List[3],List[6]]         ],         Pattern       ]     ]      Of course I can use the same approach to reduce the result much further. But the problem is the above method is very slow.               gT=Table[g,{i,1,10^5}];     AbsoluteTiming[GraphId/@gT][[1]]     AbsoluteTiming[GraphIdReduced/@gT][[1]]      gives               1.185602     14.445625      , and for 10^6 times, the difference is `12.386422 vs 146.539146`. Maybe this is because the string operations are slow, but I don't know how to do without it. `Graph` and `SparseArray` are atomic object and I can't not use `Apply` to change their Head to `List` and then locate the contents I care about. So how to extract some data from the above result more quickly? In fact, the data I need is only ![enter image description here](http://i.stack.imgur.com/gzjFj.jpg)


Help with first order logic equation

So this teacher of mine will give 10 points to the first person who solves the equation $\quad\quad\phi := \forall x \, \forall y \, \exists z \;(x<y \rightarrow x < z \wedge z<y)$ I want an interpretation (structure) $\cal B$ that satisfies $\phi$; i.e., $\quad\quad\cal B \models \phi$ Thanks in advance. I know I can't ask things like this but for once I will.


Multi-column table layout the right way

How do I create book-like multi-column table formatting for a long, narrow tables in a preferably elegant way? Should I be thinking of stylesheets, instead of formatting? I guess this is a solved problem, after all. Row expression below is my own, feeble attempt to solve the problem. Although output is reasonably OK, I detest many details on the implementation; for instance, the magic constant 1.2 needed to make columns evenly tall.               Row[Pane[           Grid[#, Frame -> All, ItemSize -> {Automatic, 1.2},             ItemStyle -> FontFamily -> "Times",             Alignment -> {{Right, Left}, Center}],           ImageMargins -> 2] &         /@ Partition[#1, #2]] &[      {Round[#[[1]]], CityData[#[[2]], "FullName"]} &       /@ ({GeoDistance[$GeoLocation, CityData[#, "Coordinates"]]/             1000, #} &           /@ CityData[]~Select~(CityData[#, "Population"] >= 100000 &))        ~SortBy~First        ~Take~(3*20),      20]      ![OPs code](http://i.stack.imgur.com/41RPB.png)


How can I create CDF applications which adjust their screen dimensions based on the end-user's display configuration?

I am trying to make a CDF application that takes the user's system information (screen information) and adjusts the size of the application to give a seamless experience over different screens with widely varying display properties. Below is the code I tried. It should have worked, but it doesn't. I am very confused. The CDF is intended to be deployed in Player Pro/Mathematica.               CDFDeploy[SystemDialogInput["FileSave"],           CreateDocument[(Column[{Dynamic[CurrentValue["WindowSize"]],               Panel[GraphicsGrid[ConstantArray[1, {48, 78}],                                 ImageSize -> {800, 500},                                 Background -> RGBColor[.745, .886,.1],                                 Alignment -> {Left,Top},                                 ItemAspectRatio -> 1                                ](*GraphicsGrid is Closed*),                     Background -> Gray,                    Alignment ->{Center, Center}                    ](*Panel is Closed*)             }])(*Column is Closed*),              WindowSize ->Dynamic[{Round[N[((780/96)*SystemInformation["Devices","ScreenInformation"][[1, 4, 2]])]],                                        Round[N[((780/96)*SystemInformation["Devices","ScreenInformation"][[1, 4, 2]])]]}]         ](*CreateDocument is Closed*)     ](*CdfDeploy is closed*)


MathLink C API: sending a List[] of so far unknown length

I would like to send a set of Mathematica expressions (i.e. not simple types that are easy to represent and temporarily store in C) in a `List` using the MathLink C API. I do not know how many there will be before I compute all of them, but I need their count to be able to call `MLPutFunction`. How can I conveniently send a `List` without needing to know the number of elements beforehand? * * * One idea I had was to put them on a loopback link while counting them, then transfer the contents of the loopback link at once. But I was hoping for a simpler solution.


ToString in a function

f[x2_] = ToExpression[StringTake[ToString[x2], -1]] x2;     f[a3]     (*Out: 2 a3*)      I expected the output to be `3 a3`, but apparently `x2` isn't evaluated in `ToString`. How would one construct a function that gives the expected result?


Problem with Estimating the parameters value of gamma distribution

can anyone please help me with this problem? I am trying to estimate parameters of gamma distribution (fitted into a set of data). Following are my command and the output produced by mathematica:               In[41]:= EstimatedDistribution[data, GammaDistribution[alpha, beta], ParameterEstimator -> "MethodOfMoments"]      and it gives me:               During evaluation of In[41]:= EstimatedDistribution::ntsprt: One or more data points are not in support of the distribution GammaDistribution[alpha,beta]. >>      I do not understand the message above and what is the cause of it? Is it because of my command or my data? *note: if i am using binomial, NB, poisson and geometric, I can get the results. my data:               data = Join[ConstantArray[0, 96978], ConstantArray [1, 9240], ConstantArray [2, 704], ConstantArray [3, 43], ConstantArray [4, 9]].      Thank you!


What's the analogue of UML in Mathematica land?

What's the analogue of Unified Modeling Language (UML) in Mathematica land? Mathematica has elements of object-orientation, but most Mathematica programs or applications aren't of object-oriented architecture. But, don't people need any representation of the data structure and information architecture, to plan, visualize, and manage the design? Is there an analogue of UML in Mathematica land?


Why doesn't my Manipulate work?

I am new to _Mathematica_ and reading my way through a few books. Playing around with `Manipulate` and I noticed the following does not work:               y[x_]:=x^n;     plot := Plot[y[x],{x,0,10}, AspectRatio->1];     Manipulate[plot,{n,1,5}]      I expected the above to work as I am using `SetDelayed` in my function definition so not sure if I understand why this doesn't work. However the following does work.               Manipulate[      Module[{y,x,plot},       y[x_]:=x^n;       plot := Plot[y[x],{x,0,10}, AspectRatio->1];       Show[plot]       ],      {n,1,5}     ]


How can I create a CDF application while using GUIKit?

I have created a notebook that uses GUIKit to create a user interface. The targeted user does not have Mathematica available so I thought about using the CDF player to convert the file if possible, because it is available for free download. I am done with the current stage of the GUIKit app but how can I make it executable for someone without Mathematica?


What bug fixes can be implemented in init.m?

In comments on this question, Mr. Wizard suggested a community wiki to share the bug fixes/workarounds (or possibly other tricks) people load in their `init.m`. I think this could provide a nice resource.


Convert polynomial to Chebyshev

I want to convert a polynomial in "standard form" to Chebyshev form. Here's one way to do it:                     (* My polynomial *)           pa = Sum[a[i]*t^i,{i,0,5}]           (* "standard form" coefficients of Chebyshev polynomial of same degree *)           pb = CoefficientList[Sum[b[i]*ChebyshevT[i,t],{i,0,5}],t]           (* helper variable *)           bs = Table[b[i], {i,0,5}]           Solve[Table[a[i-1] == pb[[i]], {i,1,6}],bs]       This works, but is there a better (more efficient, more "Mathematica"-ish) way to do it?


Error messages when using NInverseFourierTransform

I have two functions that I need to inverse Fourier transform and I was trying to get Mathematica to help me. I tried simply using the`InverseFourierTransform` function but, since they're complicated 2D functions it just took 7 hours and gave me nothing! I thought `NInverseFourierTransform` would be a good alternative but I keep getting error messages. I think I'm using the function correctly because I ran it with a couple of easier functions first to check and the results came out as expected. The functions look like this:               Uq1[alpha_, oneoverr_, Ge_] := alpha + (1 - alpha)  HeavisideTheta[Dot[Ge, Ge] - oneoverr]);      and               Uq2[alpha_, oneoverr_, Ge_] := (1 + alpha)/2 + ((1 - alpha)/Pi) ArcTan[ Dot[Ge, Ge] - oneoverr];      where alpha and oneoverr are just constants and Ge should be a 2D vector, but I've just been leaving it as 1D to minimise the evaluation time while I'm trying to find a method that works. I tried               Needs["FourierSeries`"]          Plot[NInverseFourierTransform[Uq2[-1, 20, t], t, w], {w, -20, 20}, PlotRange -> All]      and got an error message saying that the integrand evaluated to non numerical values. I'm sorry it's all a bit rubbish but I'm incredibly new to Mathematica and any help would be greatly appreciated!


What calendar is Mathematica using for dates in the distant past?

It appears that _Mathematica_ treats all dates as proleptic Gregorian dates by default, a hypothesis that can be easily tested by using `AbsoluteTime` to compute the Julian Day:               jd[t_] := AbsoluteTime[t]/86400 + 2.4150205*^6      but, while this works for recent dates and for some older ones, it yields results that differ from the correct result for some older dates by exactly a day               jd[{2012, 11, 24, 12}] - 2456256     0     jd[{1100, 11, 24, 12, 0, 0}] - 2123154     0     jd[{-3000, 11, 24, 12, 0, 0}] - 625660     1      notably for the reference date, 12:00 Universal Time on January 1, 4713 BCE in the proleptic Julian calendar (-4713-11-24 in the proleptic Gregorian calendar):               jd[{-4713, 11, 24, 12, 0, 0}]     1      What calendar is _Mathematica_ using for these older dates, if not the proleptic Gregorian calendar? Here, perhaps is another clue:               DateList[{-4713, 11, 24, 12, 0, 0}]     {-4713, 11, 25, 12, 0, 0}     DateList[{-3000, 11, 24, 12, 0, 0}]     {-3000, 11, 25, 12, 0, 0}      I'm no calendar expert, but this "canonicalization" doesn't map to any calendar I'm familiar with. Is this a bug? * * * _Update_ : Version 9, behaves differently:               jd[{2012, 11, 24, 12}] - 2456256     0.     jd[{1100, 11, 24, 12, 0, 0}] - 2123154     0.     jd[{-3000, 11, 24, 12, 0, 0}] - 625660     365.          jd[{-4713, 11, 24, 12, 0, 0}]     366      and               DateList[{-4713, 11, 24, 12, 0, 0}]     {-4713, 11, 24, 12, 0, 0.}     DateList[{-3000, 11, 24, 12, 0, 0}]     {-3000, 11, 24, 12, 0, 0.}


How to extract the edge from a set of points

I have an accumulation of points representing a body as you can see in the image below. From this data I want to generate a list of points or a curve, which is the envelope. ![ListPlot of the data](http://i.stack.imgur.com/h2Ewf.png) The first idea was a convex hull, but the shape of the body is not convex. ![ConvexHull of the datapoints](http://i.stack.imgur.com/F4CpT.png) Is there a way to extract the points at the border? click here for the data


NMaximize stops evaluating my function when run in parallel

I am trying to maximize the results of a Monte Carlo simulation with respect to some input variables.               ClearAll["Global'*"];     gratInit = 100.; rate7520 = 0.022; rateFree = 0.03;     currentstock = 100.; dividendRate = 0.018;      dividendMult = 1. + dividendRate;     AnnuityPayment = 1/2 (gratInit rate7520) (1/((rate7520 + 1)^yr - 1) + 1);     yr = 2; mu = 0.07; sigma = 0.15; iter = 10000;          returns[years_, mean_, sd_] := RandomVariate[NormalDistribution[mean, sd], years];     rwalks = Table[returns[yr, mu, sigma], {iter}];     d1[K_, T_] := (Log[currentstock/K] + T (-dividendRate + rateFree + sigma^2/2))/(sigma Sqrt[T]);     Call[str_, T_] := 1/E^(dividendRate T) currentstock CDF[NormalDistribution[0, 1], d1[str, T]];               spot[k_] := FoldList[#1 (#2 + 1) &, currentstock, rwalks[[k]]]     Spot = Table[spot[i], {i, iter}];               zRisk[T_, r_] := Quantile[LogNormalDistribution[mu T, sigma Sqrt[T]], r];     StrikeRisk[T_, r_] := currentstock zRisk[T, r];     MCRiskRunIter = Function[{D1, D2, r1, r2, n},       dollarsRisk = {D1, D2};       risk = {r1, r2};      strikePricesRisk = Table[StrikeRisk[i, risk[[i]]], {i, yr}];       priceOfCallsRisk = Table[Call[strikePricesRisk[[i]], i], {i, yr}];       numbOfContractsRisk = Table[dollarsRisk[[i]]/priceOfCallsRisk[[i]], {i, yr}];       MrktRisk = gratInit - Total[dollarsRisk];       For[j = 1, j <= yr, j++,        If[Spot[[n]][[j + 1]] >= strikePricesRisk[[j]],         MrktRisk = -AnnuityPayment + MrktRisk (dividendMult + rwalks[[n]][[j]]) +          numbOfContractsRisk[[j]] Spot[[n]][[j + 1]];,         MrktRisk = MrktRisk*(dividendMult + rwalks[[n]][[j]]) - AnnuityPayment;];        If[MrktRisk <= 0, MrktRisk = 0; Break[]];]; MrktRisk];               MCRiskRun[D1_?NumericQ, D2_?NumericQ, r1_?NumericQ, r2_?NumericQ] :=       (output = Mean[ParallelTable[MCRiskRunIter[D1, D2, r1, r2, n], {n, 1, iter}]];        Print[output]; output)               WP = 6;     PG = 2;     MaxIter = 10;          OptimalResults = NMaximize[{MCRiskRun[D1, D2, r1, r2], {D1 >= 0, D2 >= 0,        D1 + D2 <= gratInit, 0 <= r1 <= 1, 0 <= r2 <= 1}}, {D1, D2, r1, r2}, MaxIterations -> MaxIter, WorkingPrecision -> WP, PrecisionGoal -> PG]      When I run with one processor, everything goes great. When I try to use `ParallelTable` in my function (as above), `NMinimize` evaluates my function for a while, but then stops getting number values for my function. Below is the point in the output file where the transition occurs: > >     68.4242   >     69.5474   >     68.1978   >     69.5474   >     Mean[Join[HoldComplete[{45.6694, 60.7975, 92.762, 44.9912, 75.1937, > 75.7598, etc. >   If I limit the Monte Carlo to 500 or so iterations, it still works fine. But I would like the Monte Carlo to go through 10k iterations or so. Is this a memory issue? Am I doing something wrong? I can provide full code if desired.


How to combine two plots with the same y-axis

I have a data file which contains three columns of data. The first and the second column correspond to $x$ coordinates, while the third column to $y$ coordinate. Here is a small sample of the data file:               data = {{0.5, -77.06771909999159, 0.0012271846271586164},             {1.0, 0.9928749927334053, 0.019634954034537862},             {1.5, 78.49520253892854, 0.09940195479984795},             {2.0, 173.19305308215831, 0.3141592645526058},             {2.5, 289.4742561958002, 0.7669903919741358},             {3.0, 428.890904029252, 1.5904312767975672},             {3.5, 592.1255900024181, 2.9464702898078396}}      For the first plot we use               S01 = ListPlot[Flatten[List /@ data[[All, {1, 3}]], 1],       Joined -> False, PlotStyle -> {PointSize[0.01], Black},       Axes -> False, Frame -> True, FrameLabel -> {"x1", "M"},       RotateLabel -> False, ImageSize -> 550]      which gives ![plot1](http://i.stack.imgur.com/yTjw7.jpg) and for the second plot               S02 = ListPlot[Flatten[List /@ data[[All, {2, 3}]], 1],       Joined -> False, PlotStyle -> {PointSize[0.01], Black},       Axes -> False, Frame -> True, FrameLabel -> {"x2", "M"},       RotateLabel -> False, ImageSize -> 550]      ![plot2](http://i.stack.imgur.com/7SilB.jpg) Now, I want to combine these two plots keeping the same $y$ axis as it is, set the first $x$ axis (and of course the corresponding labels and tick marks) at the bottom of the frame and the second $x$ axis at the top of the frame. Is this doable? If so, any suggestions? Many thanks in advance!


Plotting an orbit using first principles

I am fairly new to _Mathematica_ , but I am trying to plot an orbit of the Earth around the sun using the equation: $\quad r(t+dt) = (2 - G*M*dt^2/r^3)*r(t) - r(t-dt)$ I need to break this into components and give Earth an initial velocity. Essentially my goal is to write the code similar to the way I might write it in Fortran but make use of the plotting functions that _Mathematica_ has. This is a homework assignment so unfortunately I do actually need to do it in this basic Fortran style. Can anyone point me in the right direction?


Saving variables from nested function

There has to be a simple solution for my question: I have three functions and each uses the output from the previous function as its input:               x=1;     fx1 = 1 + x;     fx2 = %^2;     fx3 = %-2;      If I want three iterations of the code above               Nest[((1 + #)^2) - 2 &, 1, 3]      works and the result is as expected (62). However, my code is much longer and confusing than this example, so I had to assign names to the functions. If I try to do:               Nest[fx3@fx2@fx1[{x}] &, 1, 3]      it no longer works. I might simply not be using the Nest or other functions properly. Additionally, my first function contains a `RandomVariate` on it that doesn't seem to work either once it is nested. For example, my code could look like:               x=1;     fx1 = RandomVariate[NormalDistribution[]] + x;     fx2 = %^2;     fx3 = %-2;      I would like to generate n loops referencing the functions by their names, where `RandomVariate` produces a new value with each loop, and the value of x at the end is used as the initial value of x for the next loop. Ive tried, but I am much too new at this still. Any help is greatly appreciated!