Finding the Centroid of the grid

Im trying to automate the processing of my shooting targets to measure my performance in the range. I was able to process the shots, but I still have to select the center of the target by the use of locator function. Tried using the following questions as a base Detecting Grid Lines               src = ColorSeparate[Import["http://i.imgur.com/BW61u.jpg"], "RGB"][[1]];     p = ImageDimensions[src]/2;     shots = DeleteCases[DeleteCases[Last /@ ComponentMeasurements[MaxDetect@DistanceTransform     @ColorNegate@DeleteSmallComponents@           Binarize[            Closing[ImageAdjust[Blur@Blur@Blur@src, {1, 1}], 2]],        "Centroid"], {0.5, ___}], {___, 0.5}];     pts = Graphics[{Red, PointSize[Large], Point[#]}] & /@ shots;     Show[src, pts, Graphics[Locator[Dynamic[p]]]]      ![Identified Shots](http://i.stack.imgur.com/ptvuO.png) With the locator in place I can now extract the actual shots with respect to the center of the target.               values = (# - p)/100 & /@ shots;     sigImage =       DensityHistogram[values, {0.2}, ColorFunction -> "DarkRainbow",        Method -> {"DistributionAxes" -> True},        ChartBaseStyle -> EdgeForm[Thin],        GridLines -> {{{0, {Red, Dashed, Thick}}}, {{0, {Red, Thick,         Dashed}}}}, PlotRange -> {{-2, 2}, {-2, 2}}]      ![Mathematica graphics](http://i.stack.imgur.com/yrX10.png) I would like for Mathematica to be able to find the center of the target automatically, so then I can create a program to process several targets which I can extract the shots automatically and save in a database, which I can then use to review the Density Histograms of different dates, weapons, distances, stances, etc.


Compiling/calling Mathematica-generated .so from C

I'm trying to call a compiled function from a C program. I am generating the static object               /home/fabio/.Mathematica/SystemFiles/LibraryResources/Linux-x86-64/test.so      through the _Mathematica_ code               << CompiledFunctionTools`     Needs["CCodeGenerator`"]     Needs["CCompilerDriver`"]     compiledfunction = Compile[{x, _Real}, x];     LibraryGenerate[compiledfunction, "test"]      then by using the source `test.c`               #include <stdio.h>          double compiledfunction(double);          int main(){       double a=2e0;       printf("%20.12e\n",compiledfunction(a));       return 0;     }      How I should call the compiler to link with the static object above?


Tricks for solving (lots of) coupled nonlinear equations numerically?

I have a system of 6 non-linear (quadratic) coupled equations with 6 complex unknowns \begin{align*} |x_1|^2 + |x_2|^2 + |x_3|^2 &= a\\\ x_1 x_4^* + x_3 x_5^* &= b + c i\\\ x_1 x_6^* &= d + e i\\\ |x_4|^2 + |x_5|^2 &= f\\\ x_4 x_6^* &= g + h i\\\ |x_6|^2 &= k \end{align*}               {Abs[x1]^2 + Abs[x2]^2 + Abs[x3]^2 == a,      x1 Conjugate[x4] + x3 Conjugate[x5] == b + c I,      x1 Conjugate[x6] == d + e I,      Abs[x4]^2 + Abs[x5]^2 == f,      x4 Conjugate[x6] == g + h I,      Abs[x6]^2 == k}      where $x_1$ etc. are complex variables, $x_1^*$ is `Conjugate[x1]`, $|x|$ is `Abs[x]`, and `a` etc. are real constants. The equations are probably underdetermined - if you break them into real and imaginary parts, there are only 9 equations for 12 real unknowns. Physically (since these equations solves for parameters in a model) I expect some phases in the $x_i$ are not physical (i.e. some $x_i$ are actually real numbers instead of complex), but I don't know a good way to parametrize the phases away. `NSolve[{eqns}, {vars}, Complexes]` has been running for more than 10 minutes (and still running!). I've never encountered numerical equation solving with coupled non-linear equations before, so I don't know what to expect. Is there anything I can do to optimize the process? What other numerical solving functions can I try? Also, probably off-topic here: I am under the impression that numerics is not _Mathematica_ 's strong suit; should I seek out other programs to solve this problem? Recommendations?


How do I link the txt file data sheet to mathematica and extract exact elements that I would like to use in solving for x?

I am trying to solve for a numerical solution for an equation which contains variables that evolves as index i incrreases. The actual equation that I am using to extract solution for x with an ongoing iteration with index i is the following:


How to set the position of the palette when use CreatePalette[]

When using `CreatePalette[]`, the palette created always shows up on the upper left corner. Is there a way to make it show up at the center of the screen, just like what `CreateDialog[]` does?


Graphics3D from Mathematica to SolidWorks (for 3D-printing)

I have an 3D Graphic generated with Mathematica's Graphics3D, and want to use it later in SolidWorks. SolidWorks files are usually *.stp, *.step, *.stl extentions. google search hasn't given me a solution yet, and I didn't find anything on this page either. Are there solutions to that? What is the best way to do this? Or do you know any workarounds? **edit:** Just for info - my 3D Graphics (from here) is:               Graphics3D[{GraphicsComplex[        Join[{Cos[#], Sin[#], 0} & /@ Range[0, Pi, Pi/(25)], {{0, 0, 1}}],         {         {#, Rotate[Rotate[#, 180 °, {0, 0, 1}], 90 °, {0, 1, 0}]} &[              GeometricTransformation[Polygon[{##, 27} & @@@ Partition[Range[26], 2, 1]],                                        {IdentityMatrix[3], ScalingTransform[{1, 1, -1}]}]          ]         }]}]      **edit2:** Thanks to Simon Woods' wonderful answere, I was able to export to Solid Works, and print it with my 3D-printer. Here are real-world results: ![100-sided Sphericon 1](http://i.imgur.com/7WWJLLZ.jpg) ![100-sided Sphericon 2](http://i.imgur.com/9hwv3qV.jpg) Thanks alot again :)


How to flip texture?

I discovered this excellent answer which contains a so beautiful plot. I just copied the whole code and tried to reproduce the result but the contour plot used as texture looks like flipped, that is, when I see the plot from above the result is ![enter image description here](http://i.stack.imgur.com/LKh6r.png) and if I see it from below the result is ![enter image description here](http://i.stack.imgur.com/eQdSC.png) How to fix this? I mean, how to put the white color visible from the top? I'm using _Mathematica_ 9.


Creating a dynamic plot directly from the recurrence relation

I have the following recurrence relation that has no general solution: $$x(t+1) = \frac{x^2 + x(1-x)(1-sh)}{x^2 + 2x(1-x)(1-sh) + (1-x)^2(1-s)}$$ In Mathematica language it gives:               x[t + 1] == (x[t]^2 + x[t] (1 - x[t]) (1 - s h))/(        x[t]^2 + 2 x[t] (1 - x[t]) (1 - s h) + (1 - x[t])^2 (1 - s)  )      * * * I'd like to plot $x$ as a function of $t$ (range{0,100}). How can I do this? Also, that would be awesome if I could directly on my plot, modify the values of $h$ and $s$ in the range {0,1}


Properly Force Mathematica to Simplify Log Expressions/Rules

I want to be able to expand $\log(x^n e^x) = n \log(x) +x$:               FullSimplify[Log[x^n Exp[x]], x > 0 && Element[n, Integers] && n > 1]      yields               Log[E^x x^n]      whereas               -1 +FullSimplify[Log[x^n Exp[x]] + 1,  x > 0 && Element[n, Integers] && n > 1]      yields               x + n Log[x]      what gives? Maybe it recognizes that I want to do arithmetic outside the log, so it then simplifies the expression; if that's the case, how can I force it to do that without hacking it by adding and subtracting 1? thanks!


How to find matrix exponential using RootSum?

From what I've been able to deduce, Mathematica uses a root sum scheme to determine the exponential of a matrix. Can someone please explain to me the theory behind this? I've searched, but have had no luck finding any literature on calculating a matrix exponential using root sums. (Example: Help->RootSum->Applications->'Matrix exponential of any order:'


How can I fill an entire Building with transparent points?

I am posting the same code found at an earlier question, although the concept here is totally different. The following code corresponds to a building-shaped structure.               w = 100;     l = 200;     h = 30;     m = 70;     backwall = {{0, l, 0}, {w, l, 0}, {w, l, h}, {0, l, h}};     side1 = {{0, 0, 0}, {0, 0, h}, {0, l, h}, {0, l, 0}};     side2 = {{w, 0, 0}, {w, 0, h}, {w, l, h}, {w, l, 0}};     floor = {{0, 0, 0}, {w, 0, 0}, {w, l, 0}, {0, l, 0}};     top = {{0, 0, h}, {w, 0, h}, {w, l, h}, {0, l, h}};     front = {{0, 0, 0}, {w, 0, 0}, {w, 0, h}, {0, 0, h}};     leftRoof = {{0, 0, h}, {w/2, 0, m}, {w/2, l, m}, {0, l, h}};     rightRoof = {{w, 0, h}, {w/2, 0, m}, {w/2, l, m}, {w, l, h}};     roofBack = {{w, l, h}, {w/2, l, m}, {0, l, h}};     roofFront = {{w, 0, h}, {w/2, 0, m}, {0, 0, h}};     building = {backwall, side1, side2, floor, front, leftRoof, rightRoof,roofBack, roofFront};     figure =Graphics3D[{Opacity[0.5],Style[Polygon[building,VertexColors -> Map[0.5 + #[[3]]/80 &, building, {2}]],Lighting -> {{"Ambient", White}}]}, Boxed -> False,RotationAction -> "Clip"];     data = RandomReal[60, {100, 3}];     data1 = RandomReal[60, {100, 3}];     redPoints = Graphics3D[{Opacity[0.4], PointSize -> Large,Style[Point[#], Blue]} & /@ data, Boxed -> False,RotationAction -> "Clip"];     bluePoints =Graphics3D[{Opacity[0.4], PointSize -> Large,Style[Point[#], Red]} & /@ data1, Boxed -> False,RotationAction -> "Clip"];     Show[{figure, redPoints, bluePoints}]      and upon evaluation it produces: ![house with transparent points](http://i.stack.imgur.com/MTjV1.png) I have 10000 points that need placing, some with coordinates inside the building while the remaining are outside (like the ones circled above). I have the following two questions:   1. How can I omit the points that are not within the building?   2. How do I fill the entire building with points? Having tried a few things this morning, I still couldn't get it to work as I want so any help is appreciated.


How can I assign a Fit result to a function?

I have this code               ntcrr[t_] := E^(a + b/t + c/t^2 + d/t^3)     kelvin[t_] := t + 273.15     a = -13.40956889; b = 4481.798865; c = -150521.6916; d = 1877102.652;     p1 = {30, ntcrr[kelvin[30]]}; p2 = {35, ntcrr[kelvin[35]]};     line := Fit[{p1, p2}, {1, x}, x]      { 1.67709 - 0.0285019 x } Then I plug in this function in my `Plot`               Plot[ntcrr[kelvin[t]]/(1.67709 - 0.0285019 t), {t, 30, 35}]      and that works, but I'd rather like to assign the `Fit` result to a function, like this:               line[x_] := Fit[{p1, p2}, {1, x}, x]     Plot[ntcrr[kelvin[t]]/line[t], {t, 30, 35}]      but that doesn't work. How can I assign a `Fit` result to a function?


How to get Coefficient List from an expression with various variables

consider following expression:               t = Subscript[α, 0]/2 + Subscript[α, 1]/2 + 2 Subscript[α, 2] + (9 Subscript[α, 3])/2 +      8 Subscript[α, 4] + (25 Subscript[α, 5])/2 + 18 Subscript[α, 6] + (49 Subscript[α, 7])/2 +      32 Subscript[α, 8] + (81 Subscript[α, 9])/2;      one can access variable list of expression above by using:               Variables[t]      but how can I get the corresponding coefficient list of variables? I've tried:               CoefficientList[t, Variables[t]]      it just doesn't work...


Indexed variable with alternatives

I have               a["tree"] := "oak"     a["flower"] := "rose"     a["dog" | "cat"] := "animals"      I want that the last definition of `a` behaves differently like in               b[x_ /; x == "dog" || x == "cat"] := If[x == "dog", "wow", "miau"]      but want to do this with `a` Is there a way to write something like               a["dog" | "cat"] := If[ (* passed parameter *) == "dog", "wow", "miau"]


How to find a recurrence relation for a numerical sequence?

This question was inspired by Vladimir Reshetnikov's question (How to find a recurrence relation for a sequence?): Given a finite sequence of numbers, how can we find in MMA a recurrence relation obeyed by this sequence? To be more specific, assume that the numbers are rationals and the recurrence relation is of a simple type, say linear. This problem is similar to FindFit for the function "behind" the sequence but now we are interested in a recurrence relation of a given form containing some Parameters. Also there is a similarity to DifferenceRootReduce where MMA tries to find the recurrence relation for a given formula for the elements of a sequence. Now the formula is replaced by the numerical sequence. As an Option we would specify a class of recurrence relation, e.g. linear. Let's consider the example of Vladimir, and take this sequnce               seq = Table[{n, -2^-n (2^(1 + n) LerchPhi[2, 2, 1 + n] - PolyLog[2, 2])}, {n, 1, 20}] // Simplify      $\left\\{\\{1,1\\},\left\\{2,\frac{3}{4}\right\\},\left\\{3,\frac{35}{72}\right\\},\left\\{4,\frac{11}{36}\right\\},\left\\{5,\frac{347}{1800}\right\\},\left\\{6,\frac{149}{1200}\right\\},\left\\{7,\frac{9701}{117600}\right\\},\left\\{8,\frac{209}{3675}\right\\},\left\\{9,\frac{8093}{198450}\right\\},\left\\{10,\frac{6031}{198450}\right\\},\left\\{11,\frac{1126651}{48024900}\right\\},\left\\{12,\frac{3587327}{192099600}\right\\},\left\\{13,\frac{990457463}{64929664800}\right\\},\left\\{14,\frac{1653005063}{129859329600}\right\\},\left\\{15,\frac{561462043}{51943731840}\right\\},\left\\{16,\frac{3778408}{405810405}\right\\},\left\\{17,\frac{951790361}{117279207045}\right\\},\left\\{18,\frac{1117157389}{156372276060}\right\\},\left\\{19,\frac{716038369549}{112900783315320}\right\\},\left\\{20,\frac{1600677857657}{282251958288300}\right\\}\right\\}$ Now let make an "educated guess" and assume a recurrence relation of the form $f(n) = a f(n-1) + \frac{b}{n^2}$ How do we determine the two parameters $a$ and $b$? (In this example the solution is well known: $a = \frac{1}{2}$, $b=1$) I tried to first RSolve the recurrence relation and then use FindFit to determine the parameters. It didn't work, too many error message and no result. Can you do better?


How to use Undocumented Functions Prism, Tetrahedron and Hexahedron

Taking a look at this question and this one, I checked to see if _Mathematica_ really does not have a `Prism` primitive. To my surprise the function `Prism` was black but hitting the `F1` key didn't bring up anything useful. I also stumbled upon `Tetrahedron` and `Hexahedron` as being undocumented too. So how can one properly use these functions? If these functions have already been unearthed please forgive me as I could not find any usage of them here.


How to find discretezation error of NDSolve

Is there a way to find out how large the truncation, round-off, and other errors that occur from discretizing a differential equation are while using the default settings in NDSolve? Or would I have to explicitly ask Mathematica to solve the problem using 4th order Runge-Kutta, Adams, etc and find the errors myself. I did find this link: http://reference.wolfram.com/mathematica/howto/CheckTheResultsOfNDSolve.html helpful, but I am wondering what other methods are available.


Calculate mean of values in bins

**Problem description** : I have a list of $\\{x,y\\}$ pairs. I'd like to divide $x$ into equal[*] bins, say $bx_1, bx_2, \ldots$, calculate $\left<y\right>$ for every bin and then plot the bin values versus the means. I.e., plot $bx_i$ versus $\left<y\right>_i$ with `ListPlot[]`. **Question** : I've already done it manually, but I was wondering whether:   1. exists a builtin function in _Mathematica_ that does what I want.   2. exists a builtin function that I could use in my own implementation (e.g., `HistogramList[]`?). [*] Bins with the same interval. Equally spaced intervals. * * * **EDIT** : Largely off-topic, but in `R` it turns out to be very easy with the `fields` package:               library('fields')     df <- read.table('my.dat')    # V1 -> off-axis distance, V2 -> energy     st <- stats.bin(x=df$V1, y=df$V2, N=100)     df2 <- as.data.frame(st$stats["mean",])          # Plot mean energy for every distance bin     names(df2) <- c('mean.energy')     plot(df2$mean.energy, type="s",         xlab="Off-axis distance (mm)", ylab="Mean Energy (MeV)")      ![enter image description here](http://i.stack.imgur.com/bofp5.png)


Binomial sum identities

How do you persuade Mathematica to give simple identities involving binomial sums. For example               Sum[Binomial[a,i]*Binomial[b,i],{i,0,n}]      where n is bigger than both a and b.


Clean webMathematica Kernel

On my webMathematica server, certain input values are being saved between page loads on different computers. I assume this is because the kernel is not clearing the values after it finishes loading a page, which is the behavior that I would like. As per How do I clear all user defined symbols?, it seems there are a few ways to clear the kernel:               ClearAll["Global`*"]      and               Quit[]      and               Utilities`CleanSlate      My worry is this: Does calling one of these functions interfere with all pages that are currently being processed? I'm not sure I understand how the webMathematica kernel pool works, so I have no idea if multiple user accessing the server at the same time would be interfered with by clearing the Kernel. Also, would calling `Quit[]` quit the Kernel until it is restarted through some other process (e.g the Kernel Monitor), and would this interfere with multiple users accessing the page at the same time, or would it slow down the system with constant clearing and reloading? Finally, would it be wise (assuming I'm not counting on packages staying loaded) to just add the lines               <KernelReleaseCode>         Quit[]     </KernelReleaseCode>      to MSPConfiguration.xml? I know there are several questions here, but what I'd really is just a explanation (or a link to one) of how the webMathematica kernel pool and kernels work - I assume the answers to these questions would be trivial once I understand that.


Sorting a list of triplets by first element of each triplet fails

In the last line of code, I´m trying to order the matrix by the first column. I want to store in the Array t2tlistsorted ( 100 x 3 ), but I can´t.               t = {       {{2, 1}, {5, 2}},       {{7, 1}, {9, 4}},       {{9, 2}, {6, 6}},       {{5, 4}, {2, 3}},       {{4, 5}, {7, 9}},       {{8, 5}, {2, 4}},       {{3, 7}, {7, 7}},       {{4, 8}, {1, 10}},       {{3, 10}, {10, 7}},       {{9, 10}, {9, 8}}       }     (* t[[i,j,k]    i\[Rule]tramo Nºi    j\[Rule] \     1=Inicio=Pick-Up  2=Fin=Drop-Off     k\[Rule] 1ª o 2ª componente (es \     decir x ó y) *)          Array[t2t, {10, 10}]     Array[t2tlist, {100, 3}]     Array[t2tlistsorted, {100, 3}]          For[i = 1, i <= 10, i++,      For[j = 1, j <= 10, j++,       If[i != j,        t2t[i, j] =          Sqrt[  (    t[[j, 1, 1]] - t[[i, 2, 1]]      )^2          +    (              t[[j, 1, 2]] - t[[i, 2, 2]]      )^2    ], t2t[i, j] = Infinity        (* Calcualmos los Kilometros para ir del tramo i al tramo j,         para lo que recurrimos a la raiz cuadrada de la suma de los \     cuadrados de la diferencia entre el principio(1) del tramo=        trip j   y el fin (2) del tramo=trip i *)        ]       ]      ]     For[i = 1, i <= 10, i++,      For[j = 1, j <= 10, j++,       t2tlist[10 (i - 1) + j, 1] = t2t[i, j];            t2tlist[10 (i - 1) + j, 2] = i;            t2tlist[10 (i - 1) + j, 3] = j;       ]      ]     t2tlistsorted = SortBy[t2tlist, First]     (*SortBy[t2tlist,First] *)      Can you correct my fault? In this image you can see the output lines


Make a histogram by giving the range and height of each bin one by one

I got the data of each bin by measurements like `{start, end, height}` and I want something like this picture: http://tinypic.com/view.php?pic=2i208hs&s=5 I have no other data for the `Histogram[]`, just what you can see on the linked picture. So any ideas how to do this in _Mathematica_ (version 9)? (The whole thing is for fitting a distibution curve on it.)


Avoiding RandomVariate update with use of Locator

I am preparing an activity that simulates the response from a noisy spectrometer. The function I use to generate the data has the form:               curve[a_, x_] :=        a PDF[NormalDistribution[0, 1], x] +         RandomVariate[NormalDistribution[0, 0.03]];      Which produces something like:               Plot[curve[1, x], {x, -5, 5}, PlotPoints -> 200, MaxRecursion -> 2]      ![enter image description here](http://i.stack.imgur.com/bppS9.png) and I can get the coordinates using a right mouse button click on the plot. The right mouse button works differently in a CDF than it does in a Notebook and I would like to ultimately turn this activity into a CDF-enabled web page. My first attempt is to use a `Locator`               ControllerManipulate[      Plot[curve[1, x], {x, -5, 5}, PlotPoints -> 200, MaxRecursion -> 2,        Epilog -> Inset[p, Scaled[{0.9, 0.9}]]], {p, Locator}]      ![Mathematica graphics](http://i.stack.imgur.com/GR9O0.png) Which does the job except that when I move the locator, the "noise" in my plot changes. How do I modify my `curve` function so that I maintain the ability to generate a "unique" noise pattern each time `curve` is called but it does not continuously update when the end user moves a locator?


Why are we so sure about Map results?

I do abuse it often but when I have faced this feature first time I was really suprised:               i = 0;     (i++; # - i) & /@ Range[5]      > {0, 0, 0, 0, 0} What am I asking about is **how do we know`Map` will do 'mapping' position after position?** Of course it might look logical but it is not stated, and then, since I know nothing about memory allocation etc., I could expect strange results. To be more precise, I could expect them only in cases where mapping funcion is changing during mapping. I have failed to find a word in documentation, only related but **not important** in this case: > Leaves are visited before roots * * * Have I missed something?


Normalization of eigenvectors

I am trying to normalize the following vector in _Mathematica_ with the `Normalize` command. $$(-1+2\cot[x]\csc[x]+2\csc[x]^2,\;2^\frac{1}{2} (1+\cos[x])\csc[x],\; 1)$$ I specified that the argument was real, but keep getting `Abs` in my answer. Is there anyway around this?


Plot image function together maintaining compatibility between their coordinate systems?

Is it possible to plot an image, i.e., draw it's pixels against usual coordinates? My goal is to plot my image and my function in the same coordinates. **Update** I drew an image of size `200x100` and drew a spot at `100,50`. When plotting it should coincide with actual coordinates, but it doesn't. ![enter image description here](http://i.stack.imgur.com/lQate.jpg) i.e. image takes random size and random scale both unrelated with plot size and scale. While I need each pixel be located at it's correct coordinates, not only image corner. **Update 2** Why `Image` is not a `Graphics` primitive or directive?


Axis/Angle from rotation matrix

With `r=RotationMatrix[a,{x,y,z}]` I can compute a 3D rotation matrix from axis/angle representation. Given a 3D rotation matrix `r` how can I compute `a, x, y, z`? Example:               r = {{0.966496, -0.214612, 0.14081}, {0.241415, 0.946393, -0.214612}, {-0.0872034, 0.241415, 0.966496}}      The result should be `a=20. Degree` and `{x,y,z}={2, 1, 2}/3` (or equivalent). **Edit:** I am fine with any answer that gives the same `r` when applied to `RotationMatrix`. PS: Sorry if the tag is wrong, I did not found a matching tag...


What is the correct way to provide Mathematica with a path to Python user scripts?

What is the correct way to provide _Mathematica_ with a path to Python user scripts? Simply executing Python as a shell command, using something like               usefulOutput = Import["!python -c 'import mypkg; mypkg.use()'", "Text"];      fails, because _Mathematica_ — like many IDEs and Python launchers — has no access to (or at least ignores) `PYTHONPATH` or any `sys.path.append` in 'shell_config.py'. I seem to be able to `Run` shell scripts without errors, but that's not what I'm looking fore here. Does _Mathematica_ provide a setting for extending `python.path` or is there a related directory setting in _Mathematica_ that would result in my scripts being found?


Manipulate: size of controls

As you can see in the drawing, I'm making a little Manipulate program. I'd now like to decrease the size of the controls at the left—to have more space for the `Graphics[]`. How is this possible? I've searched in the Documentation, but haven't found anything helpful. Perhaps is it possible to use the grey space in the left part of the screen for displaying purposes (`Print` or `Text`)? For example, print the Cosine of the angle `alpha` somewhere in the left `Pane`? Thanks for all help! ![enter image description here](http://i.stack.imgur.com/yqQro.png)


Missing V9 Menu: File -> New -> FreeCDF

I can run CDFs fine, and can export Notebooks as CDFs. But the `File -> New` menu does not contain a `FreeCDF` option, just the `Package` and `Text File` options. What am I missing? M9.0.1.0 on Mac OS X Mavericks.


How do I display imported images at actual size?

I know that this is an extremely basic question, but I am having a lot of trouble finding the answer in the documentation. When I import an image (for example, `Import[test.png]`), Mathematica often displays it smaller than the _actual_ size of the image. How do I force Mathematica to display the imported image at actual size? I may want to display such images using `Grid`. For example, suppose that `fname` is a list of ***.png** file names. Then I may want to import and display all of those images using a command like:               fname = FileNames["*.png"];     table = Transpose[{fname, Table[Import[fname[[i]]], {i, 1, Length[fname]}]}];     Grid[table]      and I'd like the images displayed at actual size. I know that this is a very basic question, but I really appreciate your time.


Complex valued 2+1D PDE Schroedinger equation, numerical method for `NDSolve`?

Based on the heat equation of the Mathematica Manual tutorial, I wrote the complex counterpart (Schroedinger) equation, for the free particle propagation of an initial wavepacket.               NDSolve[      {       I D[u[t, x, y], t] == -D[u[t, x, y], {x, 2}] -          D[u[t, x, y], {y, 2}], u[0., x, y] == Exp[-(x^2. + y^2.)],        u[t, -5., y] == u[t, 5., y], u[t, x, -5.] == u[t, x, 5.]       }, u, {t, 0., 1.}, {x, -5., 5.}, {y, -5., 5.}      ]      However the solver chokes with serveral warnings, the most serious being that the Maximum number of iterations has been reached that stops the calculation at `t == 0.48`. But the worst is that the solutions (plotted with `Table[Plot3D[ Evaluate[Abs[u[t, x, y] /. First[sol]]^2], {x, -5, 5}, {y, -5, 5}, PlotRange -> All, PlotPoints -> 100, Mesh -> False], {t, 0.0, 0.05, 0.01}]`) looks completely wrong with diverging values. **I know the`NDSolve` is not magic but does anybody know of an option to pass that will make this problem tractable with `NDSolve`?** I couldn't find a coherent explanation of the `NDSolve` options in the manual or anywhere else. Otherwise I would be playing with known methods of propagation, like Crank-Nicolson (for time propagation) and spectral methods (for spatial coordinates). A first nice step would to control the spatial (`x` and `y`) resolution and the time (`t`) resolution independently. **Note 1:** One knows that the time propagation of this problem for that particular initial condition is a simple spreading Gaussian probability, in particular the solution is well defined and smooth. **Note 2:** I tried with and without periodic boundary conditions in both cases the result is numerically wrong (diverging values). **Note 3:** I did some progress for the simpler 1+1D equation, that problem is well undercontrol with most of the defaults/automatics of `NDSolve`, I can propagate for a while:               sol = NDSolve[       {        I D[u[t, x], t] == -D[u[t, x], {x, 2}], u[0., x] == Exp[-(x^2.)],         u[t, 5.] == 0, u[t, -5.] == 0        }, u, {t, 0., 20.}, {x, -5., 5.}, MaxStepSize -> 0.1       ]     Animate[Plot[Evaluate[Abs[u[t, x] /. First[sol]]^2], {x, -5, 5},        PlotRange -> {0, 1}], {t, 0, 17, 0.01}]


Convert Mathematica formula to TeX (MathJax) with color

Case1: formula generated by functions.               Nest[1 + 1/Style[#, Red] &, x, 5]          (*         1+1/(1+1/(1+1/(1+1/(1+1/x))))     *)          TeXForm[%]          (*         \frac{1}{\frac{1}{\frac{1}{\frac{1}{\frac{1}{x}+1}+1}+1}+1}+1     *)      Case2: formula typed by hand(or copy from elsewhere) in inline `InlineFormula` style cell or in `DisplayFormula` style cell. This is an inline formula with coloring ![Mathematica graphics](http://i.stack.imgur.com/CFT7k.png) Some posts or answers at Math.SE you would see are with colored TeXForm output rendered. Here is one sample http://math.stackexchange.com/a/432154/76942 If you are interested that, you may find some more samples, it's helpful by highlighting questionable part of the formulas when asking in Math.SE or Mathematica.SE.                Consider the analytic formulas relating the $\color{#00A000}{\text{vertices}}$      , $\color{#C00000}{\text{midpoints}}$, and $\color{#0000FF}{\text{median}}$:      > $\color{#C00000}{\text{midpoints}}$, and $\color{#0000FF}{\text{median}}$:


Plot a solid generated by a family of surfaces

I'm trying to graph a series of planes as a solid object in _Mathematica_. I first tried to use the `Plot3D` options as well as the fill options to plot a $3D$ volume, but was unable to find a working result. The graphics I'm trying to create will show the deviation between the $z$ axis and the radius from the origin of a $3D$ cuboid. The current equation I'm using is this:               Plot3D[Evaluate[{ Sqrt[(C[1])^2 + x^2 + y^2]} /. C[1] -> Range[6378100, 6379120]],               {x, -1000000, 1000000}, {y, -1000000, 1000000}, AxesLabel -> Automatic]      Where `C1` was the original $z$-value at each plane and the result of this equation is $\; z+(r-z)\;$ for any point on the $(x,y)$-plane. Output for more manageable range looks as follows ![enter image description here](http://i.stack.imgur.com/svwNk.jpg) However this method is incredibly inefficient. Because this will be used to model large objects with an original $z$-values of $>6,000,000$ and heights above $1000$, _Mathematica_ is unable to graph thousands of planes and represent them in a responsive method. Additionally, because the `Range` of `C1` only includes integer values, there is discontinuity between these planes. Is there a way to rewrite this using different _Mathematica_ functionality that will generate a $3D$-plot that is both a reasonable load on my system and is a smooth object? 2nd, What can I do to improve my perforamance? when computing the above input for $>30$min, _Mathematica_ was only utilizing about $30$% _CPU_ and $4$_GB_ of ram with a light load on my graphics card as well. This is only about twice as much as Chrome is using right now on my system. I attempted to enable _CUDALink_ , but it wouldn't enable properly. Would this offer a performance boost for this type of processing? For a reference, my system build is: $16$_GB Ram Intel i7 4770K_ running at stock settings _Nvidia GeForce 760GTX 256 Samsung SSD_ I'm running _Mathematica 9_.


How to discriminate Weatherdata latitude and longitude from a more detailed list

From this list of weather data how can I discriminate only latitude longitude for each station? For example from the following sample I would need only the coordinates:   * "50136","","Aoluguya|Mohe, 15","","CN", **52.13333,122.51667** ,433   * "50246","","Tahe|Ta-He, 23","","CN", **52.33330,124.80000** ,465   * "50349","","Jinsong|Jiu-Hai-Lai, 15","","CN", **51.13330,124.05000** ,610


Specifying an array with a specific number of copies of two elements

To specify an array of length `L` in Mathematica, where each entry is `someElement`, I'm accustomed to writing:               exArray=Array[someElement &, L];      However, let's say that I want to (quickly) generate an array of length `L` where there are `n` copies of `elementOne` and `L- n` copies of `elementTwo`. Maybe `elementOne` is the string character `A` and `elementTwo` is the string character `B`. I'd like to be able to position the two elements in two different ways: (1) where the first `n` elements are all `elementOne` and the remaining elements are all `elementTwo`, and (2) where we have a uniform random sample from the set of all possible arrays where there are `n` copies of `elementOne` and `L - n` copies of `elementTwo`. Are there simple "one-liners" to do (1) + (2)?


Eliminate complex answer to differential equation

I've tried the following:               In[32]:= DSolve[{y'[x] == (x + 2)/(x*(3 - x)), y[4] == 2}, y[x], x]          Out[32]= {{y(x)->1/3 (-5 log(3-x)+2 log(x)+5 I \[Pi]+6-2 log(4))}}          In[57]:= z[x_] := 2/3*Log[x] - 5/3*Log[x - 3] + (2 - 2/3*Log[4])          In[58]:= z[4]          Out[58]= 2          In[59]:= D[z[x], x]          Out[59]= 2/(3 x)-5/(3 (x-3))          In[60]:= Simplify[-(5/(3 (-3 + x))) + 2/(3 x)]          Out[60]= (x+2)/(3 x-x^2)      In[32] produces an answer with a complex number. In[57] is the answer I generated by hand and you can see that it checks. How do I use DSolve to produce the answer In[57]?


How to find intervals in the domain corresponding to intervals in the range?

I want to find the intervals for the argument `m1` of this function corresponding to the value for the function lying in given intervals of the range:               F1==Sqrt[2] Sqrt[Sqrt[1/m1^2 + 20 Sqrt[3118] (1/m1)^(3/2) Sqrt[1/50] +         3118020 Sqrt[3118] Sqrt[1/m1] (1/50)^(3/2) + 24304810001/50^2 +         623602/(m1* 50)] - 10 Sqrt[3118] Sqrt[1/m1] Sqrt[1/50] - 155900/50]      and graph for this function is: ![enter image description here](http://i.stack.imgur.com/LpVWm.jpg) For example I want to find the range of intervals of `m1` when I divide a given range for `F1` into 10 equal intervals. How do I tell the software to divide a range into 10 equal interval and give the corresponding intervals for `m1`?


How to fold output cells by default?

In _Mathematica_ the default behavior of output cells is to pop up after the kernel has processed the input cells and got a result. I know I could add `;` in the end of input cells to disable output cells, which are often too messy in the middle of my calculations and usually I don't really care what they are, from appearing. However sometimes I need to go back and check some stuff, so it is still necessary to keep those intermediate results there. Then my questions is that **is it possible to "fold" output cells?** By "folding" I mean it would look as if I manually double click the cell, so the output cell will be hidden and an arrow appears next to the input cell. I tried to find some related settings described in this post, but nothing useful there. Thanks!


Usage of Assuming for Integration

For some reason, when I enter the following integration in Mathematica               Assuming[{k ∈ Integers}, Integrate[ Exp[ I k t], {t, -π, π}]]      the result turns out to be 0. However, clearly, if $k = 0$, the integral should evaluate to $2\pi$ instead. Can someone explain this behavior?


Inequalities with assumptions and constraints

I'm using Mathematica 8 I've been searching the net without luck for this specific solutions: Suppose I have an inequality f(x;M,m)>0 where I KNOW that M>4m and m>0. How can I let _Mathematica_ know this so that when solving the inequality using `Reduce` I don't get twenty irrelevant solutions, but instead only solutions where 0<4m I've used assumptions and so on but without luck, for instance:               Assuming[m > 0, Reduce[(x + m)*(x - m) < 0]]      Produces;               x \[Element] Reals && (m < -Sqrt[x^2] || m > Sqrt[x^2])      `m<-Sqrt` is unnecessary here, so why does _Mathematica_ write it out? How can we stop it?


Simplification of integrals depending on a parameter

Assuming[Element[n, Integers], Integrate[Sin[x]*Sin[n*x],{x,0,Pi}]]      returns 0, which is obviously wrong for n=1.               Assuming[n==1, Integrate[Sin[x]*Sin[n*x],{x,0,Pi}]]      does return Pi/2 (so in particular not 0). Just evaluating the integral yields               -Sin[n*Pi]/(-1+n^2)      which is indetermined for n=1. Can someone explain to me what Mathematica is doing and how to obtain a correct result?


When and why are Assuming and Assumptions not equivalent?

In this question there's an example of an integral where using `Assuming` and `Assumptions` give different results:               In[1]:= Integrate[Cos[n x], {x, 0, Pi}, Assumptions -> Element[n, Integers]]         Out[1]= Sin[n π]/n          In[2]:= Assuming[Element[n, Integers], Integrate[Cos[n x], {x, 0, Pi}]]     Out[2]= 0          In[3]:= Integrate[Cos[n x], {x, 0, Pi}, Assumptions -> Element[n, Integers]]         Out[3]= Sin[n π]/n      Now let's clear the system cache (or restart the kernel if you like) and try again, but now in a different order:               In[4]:= ClearSystemCache[] (* fresh start! *)          In[5]:= Assuming[Element[n, Integers], Integrate[Cos[n x], {x, 0, Pi}]]     Out[5]= 0          In[6]:= Integrate[Cos[n x], {x, 0, Pi}, Assumptions -> Element[n, Integers]]     Out[6]= 0      To make things even more weird, the results are affected by the order these two versions are evaluated (clearly due to caching). `In[6]` and `In[3]` are the same but they return different results. I always assumed that using `Assuming` or `Assumptions` with built-in functions should be equivalent. It seems this is not true. I can imagine that `Integrate` uses something internally (e.g. `Refine`) that is affected by the global `Assuming`, but not by `Assumptions`. Generally, when are `Assuming` and `Assumptions` not equivalent? Is the result I quoted above a bug? * * * **EDIT:** As Artes and Michael noted in the comments, this is explained by Daniel Lichtblau here. My only remaining worry is that the results are cached and effectively depend on the order of evaluation.


strange result with trigonometric triple integral

I'm defining functions                   e[k_, t_] := Cos[Pi (k - 1) t]         cosIntRaw[k_, l_, m_] := Integrate[e[k, t] e[l, t] e[m, t], {t, 0, 1}]         cosInt[k_, l_, m_] :=             Assuming[Element[{k, l, m}, Integers], Refine[cosIntRaw[k, l, m]]]      The value that Mathematica gives me for `cosInt[k,l,m]` is `0`. But explicitly evaluating `cosInt[1, 1, 1]`, I get `1`. In fact, for any given value of `m`, the number of nonzero elements in the `n`$\times$`n` matrix whose `[k,l]` element is `cosInt[k,l,m]` grows linearly in `n`, said matrix having a nice banded structure. Any idea why Mathematica gives me `0` for `cosInt[k,l,m]`? Thank you!


How do I make a frequency table from a histogram (data set)?

I have a data set.               dataA = {0.37, 0.51, 0.55, 0.78, 0.99, 1.35, 1.49, 1.50, 1.56, 1.61,         1.67, 1.70, 1.89, 1.97, 2.05, 2.16, 2.18, 2.32, 2.41, 2.45, 2.48,         2.49, 2.50, 2.51, 2.52, 2.53, 2.54, 2.65, 2.75, 2.80, 2.85, 2.99,         3.00, 3.15, 3.23, 3.29, 3.44, 3.45, 3.46, 3.47, 3.49, 3.50, 3.51,         3.62, 3.65, 3.66, 3.82, 3.84, 3.99, 4.00, 4.12, 4.23, 4.33, 4.44,         4.45, 4.46, 4.49, 4.52, 4.62, 4.99, 5.20, 5.40, 5.59, 5.99};      I'm able to convert the data to a histogram and analyze the histogram against a binomial distribution. As:               Show[Histogram[dataA, {-0.5, 6.5, 1}, "PDF"],       DiscretePlot[PDF[BinomialDistribution[6, 0.5], x], {x, 0, 7},        PlotStyle -> PointSize[Large]]]      How do I convert my data set (histogram) to a frequency table?


Interactively extract points from a plot (ListPlot or SmoothDensityHistogram)

Is there a way to dynamically define a polygon on a plot (I'm working with `ListPlot` and `SmoothDensityHistogram`) to select a cluster of interest, and give the positions of those points in the original list of data? I'd appreciate any help! Here's just an example set of points:               x = {          {RandomReal[{0, 5}, 20],           RandomReal[{4, 4.5}, 10]},          {RandomReal[1, 20],           RandomReal[{1.5, 2}, 10]}         };          points = Transpose[Join @@@ x] ~RandomSample~ 30;          SmoothDensityHistogram[points, ColorFunction -> "TemperatureMap"]     ListPlot[points, PlotRange -> {{0, 5.5}, {0, 2.5}}]


How to use an arbitrary closed region to extract an image region of interest

I am working on images and I need to be able to extract into a list all the image points that fall within a closed region, such as gotten from using "get coordinates". I can extract the points from the region such as:               contour = ContourPlot[x^2 + y^2 == 1, {x, -1, 1}, {y, -1, 1}]          points = Cases[Normal@contour, Line[x_] :> x, Infinity];          lfp = Length[Flatten[points, 1]];          circlepoints = Table[{Flatten[points, 1][[i, 1]], Flatten[points, 1][[i, 2]], 1},      {i, 1, lfp}];          ListPointPlot3D[circlepoints]      And now I would like to use the points on the circumference and the interior to select only those points in my image that fall on or within the circle and to set the remaining, exterior image points to zero. Here is a test image:               image = Table[{i, j, 2}, {i, 0, 1, .025}, {j, 0, 1, 0.025}];          ListPointPlot3D[image]      I tried to use `winding[points,0]`, as suggested, to test if the center of the circle is within the circle, but I get: > During evaluation of In[133]:= ArcTan::argt: ArcTan called with 318 > arguments; 1 or 2 arguments are expected. >> > > Out[136]= {0, 0} Clearly, I don't understand the input syntax for `winding[]`


how to interactively select points inside certain region in a plot

Very often I encounter a situation that I want to select some points inside certain areas of a plot. For example,               p1 = Graphics[Point[Table[{Random[], Random[]}, {200}]]]      will give a plot. If I use MMA's drawing tool to draw a region in the plot, p2=![enter image description here](http://i.stack.imgur.com/7Y7iB.jpg) how I get the plot dynamically updated so that it shows only the points inside that region? * * * Here is my attempt. I use the function `inPolyQ` by rm -rf at here to test whether the points is inside the region or not.               lines = First[Cases[p2, Line[x_] :> x, \[Infinity]]];     pts = First[Cases[p2, Point[x_] :> x, \[Infinity]]];     inPolyQ[poly_, pt_] := Graphics`Mesh`PointWindingNumber[poly, pt] =!= 0     slctPts = Select[pts, inPolyQ[lines, #] &];     Graphics[{Point[slctPts], Line[lines]}, AbsoluteOptions[p1]]      the out put is ![enter image description here](http://i.stack.imgur.com/Lc7aJ.jpg) I have two problems:   1. How can I change it to a efficient function that can do all this dynamically on a plot(or may density plot), and with the option to output the selected data points?   2. There is a problem that sometimes I actually select more points than I want. Like in the example, there are two points outside the region are also selected. Is there a way to solve that? Thanks.


Complex Values in TSV

I have some data in TSV format and am attempting to import it into Mathematica. Real values import just fine, but complex values keep on getting interpreted as strings. I attempted to figure out what format Mathematica was looking for by exporting some complex values in TSV, but interestingly enough Mathematica fails to import complex TSV values that it exported itself! Is there any way to import complex values through TSV in Mathematica?


How do you check if there are any equal arguments(even sublist) in a list?

I would like to set up a function which has to return True if at least two arguments of a given List are equal. So if I give `{1,4,6,2}` to the function it has to return `False` (since none of his arguments are equal) and the same would happen if I gave `{{1,2,3},{2,3,4}}`, while if I gave `{1,2,3,1,4}` or `{{1,2,3},{2,0,0},{1,2,3},{2,1,2}}` it has to return `True`. I know this is a very simple problem and i think you can easily tell me a convenient way to achieve that.


Setting the context automatically based on section

Suppose I have a task that keeps things organized using contexts, so:               windowLength = 10;     Begin["chocolate`"];     data = RandomReal[NormalDistribution[], 100];     ListPlot[MovingAverage[data, windowLength]]     End[]     Begin["vanilla`"];     data = RandomReal[StudentTDistribution[1], 100];     ListPlot[MovingAverage[data, windowLength]]     End[]      Now, if I want to go back and do something in the `chocolate` context, I have to remember to re-run the line that enters that context or things can get very confusing and mistakes can easily be made. It would be really neat to instead use wiggle-4 to create a Section called "Chocolate" and for everything in that section to run in the `chocolate` context. Is there a way to set the context automatically based on the section of the notebook a cell is in?


Plot least squares curve on Linear Log Plot

I have the following Data:               ExpDataCycles = {23, 69, 39, 25, 6, 43, 431, 328, 130, 614, 5941,         4506, 1876, 7898, 27015, 19154, 11586, 21470,        130885, 431405, 84036, 1003250};     ExpDataMpa = {835.0265363, 823.4175447, 810.7696175, 799.6485919,         794.4425228, 793.0602069, 707.6873459,        704.8236368, 693.9200675, 687.0103167, 609.8345095,        602.6188024, 598.086902, 595.6103517, 591.5466695,        584.7172701, 559.4813142, 556.6416481, 551.1841848,        541.232457, 539.3158579, 385.3438704};      Which I plot using `ListLogLinearPlot`               ListLogLinearPlot[Transpose[{ExpDataCycles, ExpDataMpa}],       PlotRange -> Automatic, AxesLabel -> {"Cycles [N]", "Stress Mpa"},       PlotLabel -> "S-N Cyclic Loading Life at R = -1 "]      ![enter image description here](http://i.stack.imgur.com/TTiiy.jpg) I'm trying to plot a best fit curve using least squares. I plot using:               ExpDataCyclesMpa = Transpose[{ExpDataCycles, ExpDataMpa}];     LeastSqr = Fit[ExpDataCyclesMpa, {1, x, x^2}, x];     Show[ListLogLinearPlot[Transpose[{ExpDataCycles, ExpDataMpa}]],       Plot[LeastSqr, {x, 0, 1100000}]]      ![enter image description here](http://i.stack.imgur.com/4qHTn.jpg) I understand the issue of the straight lines which i thick is because my x-axis is in Log form. How can I Plot a quadratic least squares fit between the LinearLog graph?


relative scale of elements in ImageCompose

My code:               sqrSize = 16/2;     dots = Flatten[Table[{2 i + Mod[j, 2], j Sqrt[3]},                           {i, -sqrSize, sqrSize}, {j, -sqrSize, sqrSize}], 1];     inner = Select[dots, Norm[#] <= 5 &];     zePlot = ListPlot[{dots, inner}, PlotRange -> {{-sqrSize, sqrSize}, {-sqrSize, sqrSize}},          AspectRatio -> 1, Axes -> None, PlotStyle -> {{PointSize[0.02]}},          Epilog -> {Circle[{0, 0}, 5], PlotStyle -> {Blue, Opacity[0.2]}}];     ImageCompose[zePlot, {Graphics[{Blue, Disk[{0, 0}, 5]}], 0.2}]      gives this `Plot` as result: ![enter image description here](http://i.stack.imgur.com/UuyZg.png) Two issues:   1. The disk seems to use another scale than the rest of the image; I'd like to have it the same size as the circle   2. (not in the code yet) Instead of the disk I'd like to have its complement, i.e. the area outside the circle should be blue, inside the circle white. How can I achieve these?


How can I find the source of a memory leak?

I found a really weird issue using NDSolve`ProcessEquations inside module. We start by setting HistoryLength to 0. After this we define a function which takes in an integer and creates a Table of stateData Objects of the desired length and returns a list containing a string and the list of stateData objects. To show how much memory the local objects use I make use of the Print[] function.               $HistoryLength = 0;     Clear[prepareEquations]     prepareEquations[iMax_] :=        Module[{stateDataList, output},         stateDataList =          Table[           First @             NDSolve`ProcessEquations[{y''[t] + y[t] == 0, y[0] == 1, y'[0] == 0}, {y, y'}, t],            {i, 1, iMax}];         Print["ByteCount stateDataList :", ByteCount[stateDataList]];         output = {"hello", stateDataList};         Print["ByteCount output :", ByteCount[output]];         output       ];      First we want to see how much memory we use before calling the functions.               MemoryInUse[]      > >     30105504 >   Alright, so about 30.1 mb. Now we call the function with an input value of 5000. The function will at the same time print how much memory the local objects use.               finalList = prepareEquations[5000];     ByteCount stateDataList :87590968     ByteCount output :87591064      So the output takes about 87.6 mb. So we would assume that the total memory used after calling this function would be about `30.1+87.6=117.7` mb. But instead we have               MemoryInUse[]      > >     164795040 >   Which is about 164.8 mb. Hence there seems to vanish about `164.8-117.7=47.1` mb. If i look into my global context, finalList takes up as much memory as the ByteCount of output. If I change the output to not return the stateDataList by for example `output={"hello",1}`, no memory is leaked. Where does the extra memory go when I return a list of stateData objects? Notice that local variables `y$1235`, `y$125`, ..., and so on is leaked to the global context. I removed them by               Remove /@ Select[Names["Global`*"],StringMatchQ[#1, "y$" ~~ DigitCharacter ..] &];      and the memory used after this was               MemoryInUse[]      > >     164518400 >   so they don't seems to have a major impact. If i look into my global context it looks like this               Reverse@SortBy[Map[{#, ByteCount@ToExpression[#]} &, Names["Global`*"]], Last] //TableForm      > >     {"finalList", 87591064}, >     {"y", 0}, >     {"t", 0}, >     {"stateDataList$", 0}, >         {"stateDataList", 0}, >         {"prepareEquations", 0}, >         {"output$", 0}, >     {"output", 0}, >     {"iMax", 0}, >     {"i", 0} >   So the memory leaked doesn't show up here. Can someone help me figure this out?


Solve Probability of Distribution

Why does this work:               Solve[Probability[x <= t, x \[Distributed] NormalDistribution[]] == 0.95 ,t]      But this doesn't:               Solve[Probability[x <= t,x \[Distributed] StudentTDistribution[2.964, 2.071, 5]] ==0.95,t]      How can I solve this problem?


Module trash collection behaviour

I have asked this question before on the Wolfram community forum (http://community.wolfram.com/groups/-/m/t/83845?p_p_auth=Gxoxe65B) but not with great success. Module creates temporary variables of the form x$NNN which when no longer used are removed. However under certain conditions the temporary variables created by Module are not removed and remain in the global context. If this happens for a Module inside a frequently used function, this leads to memory leak situation where the memory usage of the kernel grows linearly with time. (Which is not good when doing numerical runs of several days). In certain situations, this behaviour is explainable and probably a feature. Generally, speaking it usually involves some side effects which cause something outside the module to reference the temporary variable. # Some examples ## 1.               Module[{x}, x /. NDSolve[x'[t] == 1 && x[0] == 0, x, {t, 0, 1}][[1]]]      Result: x$NNN is not removed. Reason: NDSolve stores some expressions referencing x$NNN in the system cache. Solution: Clear system cache. (Presumably this will happen on its own as the kernel session progresses.) ## 2.               Module[{y, z, a, b}, a = y + z; b = 2*a];      Result: y\$NNN and z\$NNN are not removed from global context. Reason: y\$NNN and z\$NNN appear in the module output and are thus referenced by Out. Solution: Clear Out, or more systematically limit the History Length through $HistoryLength ## 3.               Module[{x}, f = x]      Result: x\$NNN is not removed from global context. Reason: Definition of f is referencing x\$NNN Solution: Clear f. # Behaviour that I do not understand In addition to these well-understood cases, there some cases where I do not understand why mathematica is not removing the temporary variables after use: ## 4. (from a different thread I found when looking for an answer)               a[b_] := Module[{x}, x := 1; x /; b]     a[True]      Result:a x$NNN is permanently placed in the global context every time a[True] is called. Reason: Unknown. This appears to be a bug. Possibly related to how mathematica handles conditionals combined with Module (Clear and ClearSystemCache[] do not remove the x$NNN.) ## 5.               Module[{a, b},     a[i_] := b[i - 1];     b[i_] := a[i - 1]]      Result: a\$NNN and b\$NNN remain in global context. Reason: Unknown. Bug? Related to circular references of temporary variables. Edit: Some experimentation has lead me to simplify this example. It has confirmed to me that this must be related to circular referencing since the temporary variables disappear after clearing their definitions with               Clear["a\$NNN", "b\$NNN"]      It is essential that the variable names are input as a string, to avoid referencing them from the input history. Interestingly enough both temporary variables remain if you clear only one of the definitions using:               Clear["a\$NNN"]      or               Clear["b\$NNN"]      This behaviour seems very buggy to me. At least a cannot think of a reason why this should happen by design. ## Other cases In addition to these cases I have seen this happen for more complicated functions involving Module, which I have not been able to trace to a simple cause. It would be incredibly helpful for me to understand why this is happening (and how to avoid it). And related if it cannot be avoided: What is the best way of dealing with the stray temporary variables?


Is it possible to manipulate a graphics object with 3 rotation transforms simultaneously?

The code that I have written has an unintended consequence that I'm not sure how to get around. I want 3 rotation transforms to be applied simultaneously to 1 graphics object. Instead, I get 3 separate separate copies of the graphics object, one per transformation. The documentation does state that this will be the outcome of using multiple transformations on a graphics object. > GeometricTransformation[g, {t1, t2, ...}]   >  **_represents multiple copies_** of g transformed by a collection of > transformations. My question is: how is it possible to achieve the the outcome that I described instead of getting multiple copies? Here is the code I am executing:               Manipulate[       Graphics3D[{         EdgeForm[None],          GeometricTransformation[Cylinder[],            {RotationTransform[a Pi, {1, 0, 0}],             RotationTransform[b Pi, {0, 1, 0}],             RotationTransform[c Pi, {0, 0, 1}]}]}],        {{a, 0}, -1, 1},        {{b, 0}, -1, 1},        {{c, 0}, -1, 1},        SaveDefinitions -> True]      If anyone could show me a way to accomplish this, I'd appreciate it.


Using Collect with equations

Is it possible to somehow use the expression that Mathematica has collected once the `Collect` command has been used? What I mean is, I have an expression like this (this is imaginary example)               (a[x,y]+b[x,y]+c[x,y]^2) z^5+a[x,y]^3 z^4+(b[x,y]+c[x,y]^4) z^3      That I got after I made `Collect[expression,z,Simplify]`. What I'd like to do is to have command that will, for instance, give me the term that goes along `z^5` (the `(a[x,y]+b[x,y]+c[x,y]^2)`)? I didn't find any examples of it, and `Collect` in help has no such examples. EDIT: Can this be done with the help of `Coefficient` command?


How can I create a fountain effect?

Inspired by this (please use Chrome or Firefox), I tried to simulate it, but I couldn't do it. I'm not familiar with `Dynamic`. Here is my simple code:               Dynamic[      Graphics[{Hue[Random[]], PointSize@Large,         Point[{0, Dynamic[Clock[{0, 5, 0.5}]]}]}, Axes -> 1, PlotRange -> 5]      ]


Making single letters non-italic in Graphics/Text/Style objects

Suppose that I use `Graphics`, `Text`, and `Style` to type one letter in the subscript of a letter and one in the superscript of the same letter. In the Writing Assistant in Mathematica 9, I click the ![button](http://i.stack.imgur.com/P8OSX.png) button to help typeset the string in this command:               Graphics[Text[       Style["\!\(\*SubsuperscriptBox[\(A\), \(B\), \(C\)]\)", 30,         FontFamily -> "Arial"]]]      The graphical output is the following. ![example](http://i.stack.imgur.com/Dic0L.png) Why do the letters A, B, and C appear italic, even though I did not specify them as such? I want the letters to all be regular font. The italicization does not happen if I take out the `Graphics` directive, and just use `Text` and `Style`. But I have to use `Graphics` because I will ultimately include it in a plot.


How to plot a region bounded by three equations?

I'm very new to this website. I am having trouble plotting a 3 dimensional region bounded by these equations:               R = {y == x <= y == - x + 2 <= y == -Sqrt[1 - (x - 1)^2]}      The problem is that I know what command to use to do this, but it gives me a blank plot. If it helps my code is below, and I have _Mathematica_ Version 7.0:               RegionPlot3D[       y == x <= y == - x + 2 <= y == -Sqrt[1 - (x - 1)^2],        {x, -10, 10}, {y, -10, 2}, {z, -10, 10}]      If someone could lead me to the right direction or tell me what is wrong, I would greatly appreciate it.


Help find a bright object on Mars!

In today's news, scientists found a bright object on one of Curiosity's photos (it's near the bottom of the picture below). It's a bit tricky to find - I actually spent quite some time staring at the picture before I saw it. ![Bright object](http://i.stack.imgur.com/z2jmA.jpg) The question, then, is how one can systematically search for such anomalies. It should be harder than famous How do i find Waldo problem, as we do not necessarily know what we are looking for upfront! Unfortunately, I know next to nothing about image processing. Playing with different _Mathematica_ functions, I managed to find a transformation which makes the anomaly more visible at the third image after color separation -- but I knew what I was looking for already, so I played with the numerical parameter for `Binarize` until I found a value (0.55) that separated the bright object from the noise nicely. I'm wondering how can I do such analysis in a more systematic ways.               img = Import["http://www.nasa.gov/images/content/694809main_pia16225-43_946-710.jpg"];     Colorize @ MorphologicalComponents @ Binarize[#, .55] & /@ ColorSeparate[img]      ![enter image description here](http://i.stack.imgur.com/tm6mR.jpg) Any pointers would be much appreciated!


How to select three points $A$, $B$, $C$ from the following list so that the circle passing $A$, $B$, $C$ has centre $(1,2,3)$?

I have the sphere $$(x-1)^2 + (y-2)^2 + (z-3)^2 = 36.$$ From the sphere, I find some points with integral coordinates. And select three points from this list so that the triangles are not right triangle. I tried               ClearAll[a, b, r];     a = 1;     b = 2;     c = 3;     r = 6;     ss = Subsets[{x, y, z} /.          Solve[{(x - a)^2 + (y - b)^2 + (z - c)^2 == r^2, x != a, y != b,            z != c}, {x, y, z}, Integers], {3}];     Pick[ss, (FreeQ[#, \[Pi]/2] &) /@ ({VectorAngle[#2 - #1, #3 - #1],            VectorAngle[#1 - #2, #3 - #2],            VectorAngle[#1 - #3, #2 - #3]} & @@@ ss)]      Now, I want to select three points $A$, $B$, $C$ so that the circle passing through points $A$, $B$, $C$ take the point $(1,2,3)$ as its centre. How can I select them?


Proof: Convergence of an equation and show the first derivative is bounded

We have the following equation \begin{equation} x(k+1)=\arccos\bigg( -\frac{1}{2(Dr^{\frac {|\sin(2x(k)+\theta)|}{M\sin x(k)\sqrt{A+2B\cos(2x(k)+\theta)}}}+1)} \bigg) \nonumber \end{equation} $A,B,D,r,M,\theta$ are constants.               x[k + 1] ==             ArcCos[-1/(Abs[Sin[2 x[k] + θ]]/(             2 (d r^(m Sin[x[k]] Sqrt[a + 2 b Cos[2 x[k] + θ]])) + 1))]      The equation above can be written as $x_{n+1}=f(x_{n})$. How do we show that it converges using _Mathematica_? How do we find the first derivative of the equation given above using _Mathematica_? Also, is that possible to show that the first derivative is bounded?


Hide function arguments (from unknown functions) for simpler output

How can I print my expression with my function's arguments hidden? For example:               exp=A[r,z]+B[s]^2;          HideArgs[exp]      Output:               A+B^2      The expression that could be tested is this one:               r^3*(Br[r, z]^2+Bz[r, z]^2)==E^(6\[Psi][r, z])*(r*D[\[Psi][r, z], z, z]+r*D[\[Psi][r, z],r,r])      Where the unknown functions are:               Br[r,z],Bz[r,z],\[Psi][r, z]


Comparing two symbolic expressions

Does _Mathematica_ provide any way to compare two symbolic expressions and find which is the greatest? For example, I want to find which is the greatest of `(n - 1) + 2(n - 1) Log[2, n]` or `n(n - 1)/2`, where `n` is a variable.


Extract a value from a list of InterpolatingFunction

By running the code               n = 5;     U[t_] := Table[Subscript[u, i][t], {i, 0, n}];     lines = NDSolve[{eqns, initc}, U[t], {t, 0, T}]      I get the output               {{u_0[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t],        u_1[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t],       u_2[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t],        u_3[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t],        u_4[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t],        u_5[t]->InterpolatingFunction[{{0.`,5.`}},"<>"][t]}}      (it's the solution of a system of ODEs that I obtain by discretizing a PDE with the method of lines). Now I would like to extract a particular value for each function, for example `u_2[0.5]` but I'm not managing to do that. Can someone help me? Thank you so much!


TableHeading Lines Do Not Show Up

For a list `list = {{"a", "b", "c"}, {"d", "e"}};` Table heading lines do not show up               TableForm[list, TableHeadings -> Automatic]      ![enter image description here](http://i.stack.imgur.com/tSSKJ.png) But it works if the list `list = {{"a", "b", "c"}, {"d", "e", "f"}};`               TableForm[list, TableHeadings -> Automatic]      ![enter image description here](http://i.stack.imgur.com/wjcq4.png) It seems the lines appear only for rectangular list. Is this a bug or i am missing something? I use v9.0.1 Thank you.


Ubuntu global menu bar integration?

Is there a way to integrate the Mathematica menu bar into the Ubuntu Unity global menu bar at the top of the screen? (I'm not looking to run mini- applications.) Thanks!


Error Trapping Complex Infinity Error due to Divide by Zero in Manipulate

I want to use a `Manipulate` that has two controllers that end up as a difference in the denominator of an expression. It is easy enough to set up the initial conditions such that the two controls are not equal in value, but upon user manipulation the two controls, if set the same give an error. The following code illustrates:                 table = Range[0, 6];       divideByZeroProblem =         Manipulate[         10/(time2 - time1), {{time1, 0}, Most[table],           ControlType -> PopupMenu}, {{time2, time1 + 1},           Drop[table, Position[table, time1][[1, 1]]],           ControlType -> PopupMenu}]      ![Output](http://i.stack.imgur.com/U0I1G.png) But of course if I change `time1` to be 1, then I get the following: ![Bad Output](http://i.stack.imgur.com/pK60P.png) I naively thought that I might be able to utilize `Initialization` to get around the problem by basing the initial value of `time2` on a function, but that doesn't update the initial value set for `time2`. The best lead that I have found in my searching for the answer on Mathematica.SE is Control variable and body variable decoupling in Manipulate, but I didn't succeed in translating that answer into a solution for my problem. It did lead me to try some things though. For example, my initial attempts at writing this question resulted in a simpler code that works as I would like it to.[Note added in later edit: I swear that it worked once this way, but I cannot get it to work again. It has the exact same kind of error. Must have been dreaming.]                   divideByZeroProblem2 =           Manipulate[           10/(time2 - time1), {{time1, 0}, Range[0, 5],             ControlType -> PopupMenu}, {{time2, Dynamic[time1] + 1}, Range[1,6],ControlType->PopupMenu}]      I played around quite a bit with using `Dynamic` and `Setting` in opportune spots to see if I could get it to work, but failed to find an appropriate combination. Any help that folks could provide would be much appreciated.


Undocumented use of Integrate: Integrating over regions

I have come across a few questions asking about integrating over regions. And while the answers are impressive there should be a better more consistent way. So my question is, are there ways, documented or undocumented, that allow one to expressly integrate over regions in an elegant fashion.


Creating a parallelizable DiscretePlot

To my knowledge, `DiscretePlot` cannot be parallelized, although one can simulate the default behavior of `DiscretePlot` and get the benefits of parallelization with a combination of `ListPlot` and `ParallelTable`. For example.               f[x_]:=(Pause[0.5];x^2);     DiscretePlot[f[x], {x, 0, 2, 0.2}] // AbsoluteTiming      ![Mathematica graphics](http://i.stack.imgur.com/lPOfX.png)               ListPlot[ParallelTable[{x, f[x]}, {x, 0, 2, 0.2}],        Filling -> Axis] // AbsoluteTiming      ![Mathematica graphics](http://i.stack.imgur.com/FmRyo.png) The problem with this alternative is that we lose access to several useful `DiscretePlot` options: `ExtentMarkers`, `ExtentSize` and `ExtentElementFunction`. How can we simulate the behavior of these options in `ListPlot` so that we may preserve the benefits of parallelization?


Probablity weighted ReplaceAll

I'm looking for an elegant way of doing a probability weighted replacement rule, something like this               f[x_] :=  x /.  {1,2,3,4} -> {50%{ 4,3,2,1} ,50%{1,3,2,4}}      Using an If statement and generating a RandomReal will be very clumsy as I want different probabilities depending on the pattern I want replaced. Thanks


Efficient replacement of conditional nested Do over elements of a matrix

I have two matrices like these:               m1=Table[Random[],{i,10},{j,10}]          m2=Table[Random[],{i,10},{j,10}]      I want to create a new matrix in which its main diagonal elements are zero and off-diagonals are determined based on               Min(m1[[i,j]],m2[[i,j]])      I came up with this `Do` loop:               newm=ConstantArray[0,{10,10}];     Do[     Do[     If[m1[[i,j]]<m2[[i,j]],newm[[i,j]]=m1[[i,j]],newm[[i,j]]=m2[[i,j]]],     {j,10}],     {i,10}]      What is the better way for doing this and avoiding `Do` loops?Is it possible to use `Map` and `Which`?


Setting CheckboxBar defaults under Manipulate

How is the default for the checkboxes created by `CheckboxBar` in a `Manipulate` set to be checked instead of unchecked? (The number of checkboxes may be variable.)


Listable on first level

I have some function which take `List` as input.               f[l_List]:=someActions[l]      I need apply this function to a list of lists. Now I use this approach               lst = {{1, 2}, {3, 4}};     f /@ lst     (*{someActions[{1, 2}], someActions[{3, 4}]}*)      But as we know `Map` over list is slower than using function with attribute `Listable`. When I set attribute `Listable` to my function I get not expected result:               SetAttributes[f, Listable]     f[lst]     (*{{f[1], f[2]}, {f[3], f[4]}}*)      How can I use attribute `Listable` with function which take a list of lists as input?


Generate Non-Singular Matrix of $n*n$ dimension

I want to create a function that will make an $n*n$ matrix which is non- singular that will always retrieve the same matrix (meaning that the matrix will not be random each time). I tried using the table function with different expressions using $i$ and $j$ but they always ended up singular because they had similar rules. So please don't give me a random matrix, the matrix needs to have a pattern that if two people used the function on different computers with the same $n$ value, they would get the same matrix P.S. Keep the matrix in the Real set of numbers (also Integers) and don't make them too high so that its not too big to work with (I want the values to be ideally under 20)


Map of Swedish regions?

There have been some questions dealing with how to draw individual US states since such data doesn't come with _Mathematica_ through its `CountryData` which offers similar functionality for countries. However, thus far, I haven't seen any questions regarding Swedish counties and municipalities. How would can I get similar functionality for Swedish counties and municipalities as that which exists in `CountryData`?


Taking the derivative of a function with indexed variables

I have a number of functions that depend on a variable `x`. I am using a second, integer variable to index these functions, i.e. something like               f[x_, 1] = a     f[x_, 2] = b x + c      When taking derivatives of these functions with `D`, it works the way I intend, i.e.               D[f[x, 1], x]     D[f[x, 2], x]      returns `0` respectively `b`. Now, however, I have a set of differential equations involving derivatives of these functions. These are expressed by _Mathematica_ as               Derivative[1, 0][f][x, 1]     Derivative[1, 0][f][x, 2]      which remains unevaluated. Is there any way to have `Derivative` ignore the second variable? More specifically, I would like to have a way of doing something along the lines of               Derivative[1][g][x]      and then replacing `g` by `f[x, 1]`. I guess I could just assign specific names to each of the functions `f[x, k]`, but in the end I want to sum them all up               Sum[f[x, k],{k, 1, n}]      for which it would be convienient to have some index variable rather than writing out the sum over different functions. Maybe I am approaching the whole idea of indexing functions in the wrong way?


how to make cursor jump automatically to next input cell after evaluating previous one?

When making separate cells in order to make separate computations to better see the result of each one before going to the next cell to do the next computation (which is a good way of doing things), it will be very useful and more efficient if the cursor would jump to the start of next input cell automatically. This allows one to keep the hand on the `ENTER` key, and just hit `ENTER` again, without having to reach to the `downarrow` key to reposition the cursor to the next cell, and move the hand again to the `ENTER` key. This can get tiring if one has many cells to process one by one. (This is btw how Maple does it, it automatically jumps to start of next command) Here is an example ![enter image description here](http://i.stack.imgur.com/0fZ2I.png) Is it possible to make the notebook do this?


Concatenating strings, unevaluated expressions and evaluated expressions/values

Maybe this is something very simple to some of you. Anyway, I think this can be useful to many others like me. I would like to build an output that involves strings, unevaluated expressions and evaluated expressions/values —something like this: > The value for $C_\mathrm{p}$ is $1.5$ and the value for $\delta^*$ is > $0.123$. where _1.5_ and _0.123_ are the result of evaluating respective expressions. This is what I tried:               Cp = 1.5; deltastar = 0.123;     HoldForm["The value for " HoldForm[Subscript[C, p]] " is " Evaluate[        Cp] " and the value for " HoldForm[        Superscript[\[Delta], "*"]] " is " Evaluate[deltastar] "."]      With this result: ![enter image description here](http://i.stack.imgur.com/2FU3f.png) The outer `HoldForm` is necessary to maintain the order of the _pieces_ , that are actually considered by Mathematica as being multiplied. For instance, this piece of code:               Cp = 1.5; deltastar = 0.123;     "The value for " HoldForm[Subscript[C, p]] " is " Evaluate[        Cp] " and the value for " HoldForm[        Superscript[\[Delta], "*"]] " is " Evaluate[deltastar] "."      yields to this output: ![enter image description here](http://i.stack.imgur.com/npCJV.png) Using `ToString` is not an option when there are superscripts and subscripts, as it is the case (I mean, the raw string output is awful). And because of that, I can't use string concatenation , which would be the most natural approach to me. There should be an easy way to do this in Mathematica, shouldn't there? As I said, I guess there _actually_ is a simple solution for this —that is, **properly building an output text or message that involves strings, unevaluated expressions and evaluated expressions.** Could you help me, please?


Smooth 4D (3D + color) plot from discrete points

I have a file containing isosurface $\\{x,y,z,F\\}$ data (around 9000 points). My goal is to generate a **smooth** (NOT a discrete set of points!) colored surface using `ListContourPlot3D`, i.e., something like this: ![enter image description here](http://i.stack.imgur.com/RWte5.png) More specifically, the surface I am trying to plot is closed. This what I am getting if I plot _x,y,z_ : ![surface](http://i.stack.imgur.com/tri2J.png) Now, I want to add color on top, i.e., I want different regions of the surface to be colored differently depending _F_. I am using `ListContourPlot3D`, because according to the description this what I need: > `ListContourPlot3D` linearly interpolates values to give smooth contours Any hints? So far all my attempts have been unsuccessful. This is what I am getting with `ListContourPlot3D[data]`: ![enter image description here](http://i.stack.imgur.com/dBaUP.png) **EDIT:** attached the file. file I want to plot col. 1(x): col.2(y): col.3(z) col4(color)


Semidefinite Programming

I want to solve a numerical optimization problem using semi-definite programming. Is there a package or add-on that equips mathematica with this functionality?


Dialog inside dialog not DialogReturn-ing properly

How can I prevent the DialogInput from failing (or returning early) as soon as I close the "Close this" dialog?               DialogInput@Button["Click this", CreateDialog["Close this" ]]


Input field that appends to a list

I'd like to make a dynamic, changeable list, which has elements that are supplied by the user in an InputField. I want the program to have an InputField and a "reset" button. Every time the user types an element into the InputField and presses TAB, this element is added to the list. The list is reset to the empty list when clicking on the "reset" button. Is this possible in _Mathematica_? The reset part seems easy, but the first part seems difficult. Perhaps should I use a second button, "add element"?


Creating a Block from a list of rules

How can I create a function which works like `Block` but takes a list of rules as its first argument, rather than a list of assignments? The function needs to be able to work with rules supplied either as an explicit list or via a symbol, and it should work when some of the symbols to be blocked have global values. Test code:               a = 100;     code := a + b;     rules := {a -> 1, b -> 2};          (* using an explicit list of rules *)     ruleBlock[{a -> 1, b -> 2}, code]     (* 3 *)          (* using a symbol *)     ruleBlock[rules, code]     (* 3 *)          (* global values are unaffected *)     {a, b}     (* {100, b} *)      I have a working solution (below) but I have had to write separate functions for `List` and `Symbol` patterns, and I find the code a bit cumbersome. I would like to know if there is a simpler, cleaner way to write `ruleBlock`.               SetAttributes[ruleBlock, HoldAll]          ruleBlock[rules_List, code_] :=       Replace[Apply[Set, Hold[rules], {2}], Hold[x_] :> Block[x, code]]          ruleBlock[rules_Symbol, code_] :=       Replace[Apply[Set, OwnValues[rules] /. HoldPattern[{_ :> r_}] :> Hold[r], {2}],        Hold[x_] :> Block[x, code]]


Using Boost with CreateLibrary

I was looking at the answer of Leonid of Faster alternatives for DayOfWeek and wanted to see how hard it would be to do something similar in C++ using an external library like Boost. I tried to include a Boost header in the example of the CreateLibrary help located here http://reference.wolfram.com/mathematica/CCompilerDriver/ref/CreateLibrary.html specifying also the path for the Boost files to include and Boost compiled libraries, like I would do in VisualStudio that I use, but the example didn't compile. So before trying harder, has anyone already succesfully used Boost with the CreateLibrary function ? (new in Mathematica 8). Thanks


Don't understand why Do-loop index is not evaluated in Play expression

So here is some weird behavior: When I create a list inside a loop whose elements are Play functions, with arguments that depend on the counter, it is as if the counter is being stored symbolically, so all the list elements - not just the last one - change with each iteration. THis only happens with Play. If I do the same thing with Plot, for example, it works as expected. Here is an example, though I have also tried creating the list using Append and AppendTo, I have assigned the outputs, etc. list1 has every part the same, and all equal to the result with the current value of i. list2 has each part equal to what it was when it was first created (so the first with the results evaluated with i=1, the second with i=2, etc.). Why? How do I fix Play?               list1 = {0, 0, 0};     list2 = list1;     Do[      list1[[i]] = Play[Cos[150*i*2*Pi*t], {t, 0, 0.5}];      list2[[i]] = Plot[Cos[i*2*Pi*t], {t, 0, 0.5}];      Print[list1, list2],      {i, 3}      ]     Show[list1]     Show[list2]     list1     list2


Solving a linear system in three unknowns

solve[{2 x + ay - z, bx - 4 y + z, -x + y} == {10, -30, 20}] $$ \begin{array}{lcr} 2x + a\,y - z & = & 10 \\\ b\,x -4y + z & = &-30 \\\ -x + y & = & 20 \end{array} $$ For what values of "a" and "b"   (a) will the system have a unique solution   (b) are the equations consistent?   (c) are the equations inconsistent?


How to insert / merge a list into another list?

Background: I am working on a 2D geometry algorithm where I need to insert a list of 2D points into another list of 2D points. Somewhat to my surprise I found no Mathematica function capable of doing this. My requirement is for a function that when provided for example:                {{1,1},{2,2},{3,3},{4,4},{5,5}}       and                {{100,100}, {200,200}}      returns               {{1,1},{2,2}, {100,100}, {200,200},{3,3},{4,4},{5,5}}       I looked at various Mathematica functions where Insert seemed the candidate to use, now                Insert[{{1,1},{2,2},{3,3},{4,4},{5,5}},{{100,100}, {200,200}},3]       returns                {{1, 1}, {2, 2}, {{100, 100}, {200, 200}}, {3, 3}, {4, 4}, {5, 5}}      note the extra braces around                {100, 100}, {200, 200}      Inspired by this question/answers I created insertM.                insertM[list_, values_, at_] := Module[{i = 0},        Insert[list, "mark", Array[{at} &, Length[values]]] /. "mark" :> (++i; values[[i]])]      which gives                insertM[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}, {{100, 100}, {200, 200}}, 3]      {{1, 1}, {2, 2}, {100, 100}, {200, 200}, {3, 3}, {4, 4}, {5, 5}}      Although insertM does the job, I have this ' there must be a better way ' feeling. Now my question(s): Is there a Mathematica function that performs my requirement? If not, **is there a better function then insertM to do this?** In better I rank beautiful code (short, functional) highest unless it is significantly slower than a less beautiful alternative.


Better way to evaluate integral containing Boolean function

I am trying to compute the integral               $Assumptions = {0 < x[3] < 1, 0 < x[4] < 1, 0 < x[5] < 1};     Integrate[       x[2] Boole[2 (x[2] + x[3]) + x[4] < 1 &&                    2 x[2] + x[3] + x[4] + 2 x[5] > 1 &&                   x[2] + x[5] < x[3] + x[4]],       {x[2], 0, 1}]      but for some reason it takes forever. However, if I manually simplify the integrand               Boole[2 (x[2] + x[3]) + x[4] < 1 &&            2 x[2] + x[3] + x[4] + 2 x[5] > 1 &&            x[2] + x[5] < x[3] + x[4]] ==     Boole[(1 - x[3] - x[4])/2 - x[5] < x[2] <            Min[(1 - x[4])/2 - x[3], x[3] + x[4] - x[5]]] // PiecewiseExpand // Simplify          (* True *)      the integral is easily computed as               Integrate[Boole[a < x[2] < b] x[2], {x[2], 0, 1}] /.       a -> (1 - x[3] - x[4])/2 - x[5] /.        b -> Min[(1 - x[4])/2 - x[3], x[3] + x[4] - x[5]] // PiecewiseExpand // Simplify      I'd appreciate any hints as to how I can compute the integral more quickly without manual intervention.


How to typeset a system of equations with multiple alignment points

I'm aware of how to align a system of equations on the = sign (or other single alignment point), but I'd like to align a system at multiple points so that each variable stays in its own "column" so to speak. This is especially an issue if some variables have a 0 coefficient in some equations. I'd like to extend this idea to typesetting a linear programming problem such as this: ![enter image description here](http://i.stack.imgur.com/bYcQm.png) I use \alignat in LaTeX for this, but am trying to write more in Mathematica and would like to learn how to do it there. Thanks!


Is Mathematica comparable to C++ for creating standalone applications?

At my university, I have a yearly essay. I'm allowed to use any technology for implementing it. I've been coding it in C++ with Qt. I thought of about Wolfram _Mathematica_ because I have some experience in it. I need such functionality:   * Timers — for calling functions by timer    * Threads (or Processes are good too)    * User-friendly GUI (buttons, input forms)   * Be able to catch when user clicked left/right mouse buttons or key on keyboard    * Dynamic graphics (with changing graphics in time)    * Launching applications as a standalone executable file  I'm ready to put more effort into it. But I wonder whether I'm burying myself alive trying to implement things which _Mathematica_ isn't devoted to do. I would appreciate links to topics marked with questions signs. How bad is this idea? What are your opinions? Should I do it in C++? (Doing it in _Mathematica_ would be challenging for me.) ![enter image description here](http://i.stack.imgur.com/nUl5a.png)


arthmetic progression problem series upto 40 terms?

Find the sum of series 5+7+9+10+13+13+17+16+....., upto 40 terms? Please help i am facing problem while solving this question.i have tried my best to solve this but unable to find the common difference.?


Find positions of duplicates that are neighbours

Assuming the following list {1,2,3,3,5,6,3} I would like to get the position of values that are next to each other and are duplicates. That is, the output should be {3,4}. Thank you for any help. Cheers, Vaclav


Reversing every second "row" in a list

I have a list that is obtained by flattening a matrix               list=Flatten[Table[{i, j}, {i, 1, 4}, {j, 2, 6, 2}], 1]      > {{1, 2}, {1, 4}, {1, 6}, {2, 2}, {2, 4}, {2, 6}, {3, 2}, {3, 4}, {3, 6}, {4, > 2}, {4, 4}, {4, 6}} And I am looking for at way to reverse all "rows" with even numbers (the first element). So that my list will look like this               {{1,2}, {1,4}, {1,6}, {2,6}, {2,4}, {2,2}, {3,2}, {3,4}, {3,6}, {4,6}, {4, 4}, {4, 2}}       Note that the first element stays the same, but the last element (for list with even first element) for the whole "row" has reversed. Maybe there is an easy solutions to this, but I have not been able to find it yet.


Converting a date to a calendar quarter

I have a list that includes dates. I need to convert each date to be the last day of the quarter that it's in. So for example I want {2013,7,1,0,0,0} to become {2013,9,30,0,0,0}. Actually I don't need the zero's. I was trying to do this with a rule, but ran into problems. I wanted a rule like: 7,_ -> 9,30. Further I was going to try to insert alternatives into this with something like 7,_ |8,_ |9,_ -> 9,30. Is there a way to write a rule to handle this? Or, for this specific problem is there a better way to convert these dates to quarter end dates? An example of a row of data is: {{2009,5,1,0,0,0},"TYAU145A", 92468., 0.5, 46234.}.


Difference in output from R's mvtnorm and Mathematica/Java

Let a=$\mathcal{N}(6.532056,0.06532056)$,b~$\mathcal{N}(8.390961,0.08390961)$ and c~$\mathcal{N}(8.736566,0.08736566)$. We use $\mathcal{N}(\mu,\sigma^2)$ notation unless specified otherwise. We construct two normal variables x~$a-b$ and y~$a-c$.So, x=$\mathcal{N}(-1.858905,0.14923017)$ and y=$\mathcal{N}(-2.20451,0.15268622)$ Correlation between $x$ and $y$ i.e. $\textrm{cor}(x,y)= \frac{\textrm{var(a)}}{\sigma_x \times \sigma_y}$ by using the basic properties of covariance. Solving, $\textrm{cor}(x,y)=0.4327346392418512 \approx 0.433$ which can be written in matrix (let it be called $ mat $)for as \begin{bmatrix} 1.0 & 0.433 \\\\[0.3em] 0.433 & 1.0 \\\\[0.3em] \end{bmatrix} Now I want to find the $\Pr[-\infty<x<0 \textrm{ and } -\infty<y<0]$. I used the mvtnorm package's pmvnorm method by invoking pr<-pmvnorm(mean=c(-1.858905,-2.20451), corr=mat, lower=rep(-Inf, 2), upper=rep(0,2)) The result was 0.9575448. The same when I want to compute in Mathematica/Java(an implementation of the Genz algorithm found on internet) I am getting the result as 0.9999992445813132. I am including the _Mathematica_ code below. Please note here, the second argument in this case, is standard deviation.               px = NormalDistribution[-1.858905000000001, 0.38630320992712447]          py = NormalDistribution[-2.20451, 0.3907508413298685]          pxy = ProductDistribution[px, py]          Probability[-Infinity < x < 0 && -Infinity < y < 0, {x, y} \[Distributed] pxy]      What is the mistake I am doing? For my application domain (visualization) this difference is turning out to be very costly,especially because I run it over more than 700,000 data points.


Importing from Excel

I'm trying to import a matrix from Excel to Mathematica. My code is:               Import["desktop/stproj.xls", "xls", data, 1]      The output is some weird stuff about population counts and not at all related to what's in the excel file. Can anyone help me with importing this?


Programming a Meijer G related result

I am not that new in Mathematica, but I do not remember I have ever used it for programming (like we may do in Java). I have an important result given here by this integral: $$ \int_0^{+\infty} x^{\alpha-1} G^{st}_{uv} \left[ \sigma x \left| \begin{array}{c} (c_u) \\\ (d_v) \end{array} \right. \right] G^{mn}_{pq} \left[ \omega x^{l/k} \left| \begin{array}{c} (a_p) \\\ (b_q) \end{array} \right. \right] dx = \frac{k^\mu l^{\rho + \alpha(v-u)-1} \sigma^{-\alpha}}{(2\pi)^{b^*(l-1) + c^*(k-1)}} \\\ G^{mn}_{pq} \left[ \frac{\omega^k k^{k(p-q)}}{\sigma^l l^{l(u-v)}} \left| \begin{array}{c} \Delta(k,a_1),\ldots,\Delta(k,a_n),\Delta(k,1-\alpha- d_1),\ldots,\Delta(k,1-\alpha-d_v), \\\ \Delta(k,b_1),\ldots,\Delta(k,b_m),\Delta(k,1-\alpha- c_1),\ldots,\Delta(k,1-\alpha-c_u), \end{array} \right. \right. \\\ \left. \begin{array}{c} \Delta(k,a_{n+1}),\ldots,\Delta(k,a_p) \\\ \Delta(k,b_{m+1}),\ldots,\Delta(k,b_q) \end{array} \right] $$ where $G$ is the Meijer G function, $(s,t,u,v,m,n,p,q)$ are integers, $\alpha$ is real, $\Delta(k,a) = \frac{a}{k},\frac{a+1}{k},\ldots,\frac{a+k-1}{k}$, $b^* = s+t - \frac{v+u}{2}$, $c^* = m+n - \frac{p+q}{2}$, $\mu = \sum_{j=1}^{q} b_j - \sum_{j=1}^{p} a_j + \frac{p-q}{2} + 1$, $\rho = \sum_{j=1}^{v} d_j - \sum_{j=1}^{u} c_j + \frac{u-v}{2} + 1. I tried to create a module that gives me the result in a Traditional Form               \[CapitalDelta][k_, a_] := Range[a/k, (a + k - 1)/k, 1/k]               Res[\[Alpha]_, s_, t_, u_, v_, \[Sigma]_, c_, d_, m_, n_, p_,      q_, \[Omega]_, l_, k_, a_, b_] :=      Module[{a1, b1, arg1, arg2, arg3, arg4, expr},     Print["km+lt = ", k m + l t]      a1 := {Table[\[CapitalDelta][k, a[[i]]], {i, 1, n, 1}],      Table[\[CapitalDelta][l, 1 - \[Alpha] - d[[i]]], {i, 1, v, 1}],      Table[\[CapitalDelta][k, a[[i]]], {i, n + 1, p, 1}]};     Print["a1 = ", a1]     b1 := {Table[\[CapitalDelta][k, b[[i]]], {i, 1, m, 1}],      Table[\[CapitalDelta][l, 1 - \[Alpha] - c[[i]]], {i, 1, u, 1}],      Table[\[CapitalDelta][k, b[[i]]], {i, m + 1, q, 1}]};     Print["b1 = ", b1]     If [Length[a1] > 0, arg1 := Table[a1[[i]], {i, 1, k m + l t}]]     arg2 := Table[a1[[i]], {i, k m + l t + 1, k q + l u}];     If [Length[b1] > 0, arg3 := Table[b1[[j]], {j, 1, k n + l s}]]     arg4 := Table[b1[[j]], {j, k n + l s + 1, k p + l v}];     expr :=      MeijerG[{arg3, arg4}, {arg1, arg2}, (\[Omega]^k k^(     k (p - q)))/(\[Sigma]^l l^(l (u - v)))];     Return[expr];      ] This code returns me a bunch of errors, so your help is much appreciated.


Search function stops working after converting to CDF

My problem is, that when a make a notebook and convert it to CDF using the 'CDF-Export', the search field, which appears on CDF player, does not work. When trying to search for a word, the computer simply makes a sound indicating that the word was not found. But when I use 'CDF-preview' before converting, the search field works just fine. I have tried it with very simple notebooks and the problem is still there. Am I the only one with this problem? Does anyone have an idea for a solution?


How to do System dynamics simulations / diagrams in Mathematica?

System dynamics is an approach to understanding the behaviour of complex systems over time. It deals with internal feedback loops and time delays that affect the behaviour of the entire system. What makes using system dynamics different from other approaches to studying complex systems is the use of feedback loops and stocks and flows. These elements help describe how even seemingly simple systems display **baffling nonlinearity** Here is how a system diagram looks like: ![enter image description here](http://i.stack.imgur.com/6TrpW.gif) Apperently I should be able to this with System Modeler by loading this modelica library but I am also told here that: > The downside, as I understand it, is that **each different use of a System > Dynamics symbol requires its own entry in the library**. For example, a > stock with one inflow and one outflow requires a different Modelica symbol > from one with one inflow and 2 outflows. Also (again, as I understand it), > every separate equation requires its own symbol to be defined and added to > the library before it can be used. ¿Anyone here can confirm or deny this? ¿Is this a limitation inherent in all **Modelica** enviroments? ¿or it is an implementation limitation on this particular library? and, going back to the original aim of this question: Is there a less expensive way (than System Modeler) to do this **in Mathematica, _without_ System Modeler**?


How do I make two styles in a stylesheet inherit the same style

Specifically I want different versions of 'Item1Numbered'. For example one with a frame and another with a background colour. How is that done?


Good ways to organize and document collections of mathematica notebooks?

I've now been using _Mathematica_ for about a year, and am starting to get a somewhat unwieldy collection of notebooks. Sometimes I've figured out how to do a particular task in one of them, and want to use that again, but have to search through what I've done. To tackle this, I've cobbled together a script that generates an html page for all the notebooks that I've checked into my source code repository (I happen to be using github to store my notebooks, latex, and other source code), and can put comments in that generated html file about what I did in each notebook, including any special techniques that I learned to accomplish the task. By way of example, I can list these with something like on this page. From a local copy of my source repository I generate something similar, allowing a click on the various notebooks to view them with the CDF player. I'm able to navigate my collection of notebooks well enough this way, but was curious how other people tackle the same organizational problem?


Finding the characteristic polynomial of a matrix modulus n

Given a square matrix, is it possible to calculate its characteristic polynomial modulo `n`? Unfortunately, this function `CharacteristicPolynomial` doesn't have the `Modulus` option that many other functions have.


MapThread and Compile

After discovering that MapIndexed cannot be used with `compile` (see MapIndexed and Compile) I am now trying do implement similar functionality using a combination of `MapThread` and `Map`. Unfortunately I am running into problems even when only using `MapThread`. Here is a test-scenario: Create Lists first:               A = {{1, 2}, {2, 3}};     B = {{{1, 2, 3}, {2, 3, 4}}, {{2, 3, 4}, {3, 4, 5}}};      The I simply run `MapThread` with function `List[]` to obtain a suitable combination of those lists and put the whole thing inside a `Compile`-statement:               test = Compile[{{B, _Real, 3}, {A, _Real, 2}}, MapThread[List[#1, #2, #3] &, {B, A, A}, 2]];      But when running `test[B,A]` I get the following compile error: > CompiledFunction::cfex: Could not complete external evaluation at > instruction 15; proceeding with uncompiled evaluation. When using `CompilePrint[test]` instruction 15 shows a call to `MainEvaluate`. Unfortunately I currently have no clue how to fix that problem. Any hint is appreciated.


Requesting explanation of FitModel code

I am struggling with understanding the code given in this original post I understand how the tests are conducted, both of them. However, I do not understand this part:               FitModel[data_List, coords_List] :=       With[{lm = LinearModelFit[data, coords, coords]},         dispatch[{           "BreuschPagan" -> BreuschPagan[data, lm, coords],           "WhitesHeteroskedasticity" -> WhitesHeteroskedasticity[lm, coords]}]];     dispatch[list_][field_] := field /. list     dispatch[list_]["Properties"] := list /. Rule[field_, _] :> field     dispatch /: ReplaceAll[fields_, dispatch[list_]] := fields /. list     Format[dispatch[list_], StandardForm] :=        HoldForm[dispatch]["<" <> ToString@Length@list <> ">"]      Could someone explain what this is doing? If you recommend that I do it in a chat, I have created a chat room for such discussion. I find it particularly difficult to understand the code for `dispatch` and how it works.


Partial Differential Equation in Parallel

is there any native way to implement multi-core parallel solving of PDE in Wolfram Mathematica? WM 10 now supports Finite Elements Method, but it is actually useless without parallelization. Usually PDE-systems are heavy and no one solves it using just one core. If there is any sort of domain decomposition or some other way parallelize the calculation?