Creating Mathematica packages

I'm building a package to help me write packages and their documentation. In this post I explained how to make a package and its documentation. In the answer I provided I describe how to build a very simple package. However, I have been looking around the extra packages that come with _Mathematica_ and in some packages I see many .m files. I see this as a good way of dividing the application. Can someone describe the structure of a package? To do this lets try to make a package out of the next simple functions. Suppose that we have the following in a notebook:               AddTwo::usage = "AddTwo[a, b] returns a+b";     AddThree::usage = "AddTwo[a, b, c] returns a+b+c";     DotTwo::usage = "DotTwo[a, b] returns a*b";     DotThree::usage = "DotTwo[a, b, c] returns a*b*c";     AddTwo[a_, b_] := a + b;     AddThree[a_, b_, c_] := a + b + c;     DotTwo[a_, b_] := a*b;     DotThree[a_, b_, c_] := a*b*c;      I would like to put these functions in a package. They all seem to be very simple arithmetic operations so let us make a package named `SimpleArithmetic`. This package is perfect to be divided into sections. One for additions and one for products, so we can make "subpackages" `Addition` and `Product`. If we follow some of the examples in the _Mathematica_ installation we can create a folder called `SimpleArithmetic` in say `$UserBaseDirectory`. Inside `SimpleArithmetic` we can create two other files `Addition.m` and `Product.m`. The code for the additions would be placed in `Addition.m` and the code for multiplications would be placed in `Product.m`. The question now is, how would these files look like? There is also a folder called `Kernel` which contains `Init.m`. Could someone please just explain the best practices to create packages? I've read over the documentation and the whole "context" and "packages" keywords have already confused me. The code in the files I have described would be very appreciated.


Custom package development: Basic steps

Every once in a while, I write a generic function that I use quite often for months to come. However, package development in Mathematica is not very well documented from what I can tell, and I was not able to find a coherent description online (most of them deal with tiny issues and bits). In the end, I usually give up and copy+paste the function in every new notebook, which isn't really the way to go. Does anyone here develop packages himself and could walk me from "open Mathematica" to "save as something that can be included via `<<Package``" or give me a good reference?


How to get the current index during a Scan iteration?

Is there a special keyword to get the current index in `Scan` ?   For example, let say I have the following code :               Scan[Print[#] &, {2, 5, 7}]      It print the content of the list :               2     5     7      How to modify the code to print the current index also ?               1,2     2,5     3,7


Approximate a function of four variables with a rational polynomial

I have a function that consists of four variables. Currently, I want to view it as function of one variable over the interval (0, 1) with the other three variables as parameters. I will plug values into those three parameters (and those values will not stay fixed). I want to see how the function changes with as the parameters vary. The function is very complicated, so I want to approximate it in a rational form. I have tried using the `MiniMaxApproximation`. However, it is only good for a single variable. Does _Mathematica_ offer any function that is suitable to my needs?


Maintaining postfix convention for directives in notebooks

It seems to be a fairly common convention to write certain 'meta' functions in postfix form like               f[x] // Simplify      to keep the the mathematical content at the front separate from the various directives. However converting expressions to `StandardForm` or `InputForm` converts everything to prefix. Is there a way to get `StandardForm` to use this convention or alternatively is there a form like `StandardForm`, but that uses this convention. I find myself often switching between`StandardForm` and `InputForm` while editing since I prefer to just edit textually using `InputForm` and then convert to `StandardForm` for display, but this makes it impossible to use the above convention. Reading the documentation I came across `Format` which seems one possible way to do this, but the following does not work:               Format[Simplify[x_], StandardForm] := Postfix[Simplify[x_]]      Apparently `Simplify` gets evaluated out before this rule is set up. I tried using `Hold` and `Unevaluated` to fix this without luck. This approach would also have the downside of having to define this rule for every function separately and I also do not yet know how I would set up such rules as a default for all my notebooks. So maybe there is a better way.


How to efficiently mask an image?

I want to extract/cut out a part of an image. Since my mask is not rectangular I want to set pixels that are not masked to zero (black). My current approach is something like this:               img = Import["path/to/image/image.jpg"];     {x, y, temp} = Dimensions@ImageData[img];     center = {100, 100};     radius = 30;     pixels =        Select[Flatten[Table[{i, j}, {i, 0, x}, {j, 0, y}], 1],         (center[[1]] - #[[1]])^2 + (center[[1]] - #[[2]])^2 > radius^2 &];     ReplaceImageValue[img, Map[# -> 0 &, pixels]]      Even though this works, it is extremely slow for large images. Is there any way to speed this up?


Draw grid lines at multiples of k

Here is a beginner's question: when creating plots with mathematica, I want the grid lines to be at multiples of a constant value. E.g. in the following plot, the vertical grid lines are at multiple of 2 $\pi$. ![enter image description here](http://i.stack.imgur.com/Vq3Fu.png) This is the corresponding Mathematica code:               Manipulate[      Plot[Sin[x], {x, 0, n*2*\[Pi]},        GridLines -> {2*\[Pi]*# & /@ Range[n], None},        GridLinesStyle -> Dashed], {n, 1, 50, 1}]      Since equidistant grid lines are very common, I wonder if there is an easier way than to use such complicated expressions like `2*\[Pi]*# & /@ Range[n]` to generate equidistant grid lines. Does Mathematica provide anything simpler?


Returning ancillary computation results from a function

Suppose I want to implement a function to solve a very basic Elliptic problem using Finite Element of some degree (It's just an example). Normally the user of my function is only interested to the numerical solution of the Elliptic problem, i.e. the values of the solution on a proper grid. So, the user call something like               u = EllipticDirichlet[..., range, ...];      Sometimes the caller of my function may be interested to some internal detail of the computation, for example the linear system formulation of the problem, i.e. the stiffness matrix K and the load vector F. Ideally my function should return these ancillary data tagged in some way, so the user of my function can get these data simply and in a roubust. I don't want my fuction return everytime the solution and all ancillary data in a list like in the following pseudocode.               {u, K, F} = EllipticDirichlet[..., range, ...];      What are the way to handle this situation? I can think to the following way.   1. Using Options or Arguments to tell to the function what to return. Not clean in my opinion, not because of the options, but because it would be preferable to keep main result distinct from other ancillary intermediate computation data.   2. Returning an "object" with "properties" like `LinearModelFit` for example. Probably the best idea but make the function result more difficult to use and to understand for a casual reader.   3. Using `Sow`. But I'm not sure if this this a use-case for `Sow`? For example it's legal to `Sow` from a function if no one `Reap`? Documentation say nothing about this.  There are other way to accomplish this task? ### Update I'm anything but a _MATLAB_ fan, but what I'm asking it's a very common scenario under _MATLAB_ , and it's very simple to consume and provide functions that returns differently "shaped" answer with different "levels" of details. For example in _MATLAB_ I can call a function with syntax like this               [x, u] = EllipticSolve[...]      if I'm only interested to the x grid used and solution u on grid vertices; or I can call               [x, u, K] = EllipticSolve[...]      if I'm occasionally also interested to the stiffness matrix K of the linear system used to solve the problem; I can also call               [~, ~, K] = EllipticSolve[...]      if I'm interested only to the stiffness matrix K. I think the function EllipticSolve can also do some optimization of the computation recognizing the output requested. Basically I whish to be able to do something like this.


Extract the generating curves from a Graphics3d returned from RevolutionPlot3D

I have a plot               g = RevolutionPlot3D[{Sin[t], t}, {t, 0, π}, {θ, -π, π + 3 π/4}];      Is it possible to extract the generatrices (generating curves) from `g`? Sometimes, I want to concentrate on plotting the surface in different ways, and what I need is the all the generating curves. Can I obtain these curves from `g`?. * * * For example, this is what I need (the data could be plot by `Line /@ curves` and could be exported elsewhere).               curves = Table[RotationMatrix[θ, {0, 0, 1}]. {Sin[t], 0, t}, {θ, 0, 2π, .3}, {t, 0, π, .3}];      The example result, `curves`, is what I want, but I obtain that by re-think about generating method and `{Sin[t], 0, t}`. Seems defining `g` was a waste of time. But in the plot of `g`, such lines/meshes are really shown by _Mathematica_ , so I would like to extract them.


How can I plot f(x) with respect to 1/x?

How can I plot f(x) on {y axis} with respect to 1/x on {x axis}?


Take[] and other Mathematica functions with live streams

I have a live video feed that I would like to convert into raw numbers that could be used for a variety of different things. I would also like to do simple operations on these numbers live with as little latency as possible. So essentially, I get a Dynamic matrix of numbers that, are in byte form (0 to 255). To make it easier, I greyscaled it, so that there is only one data point per pixel. Assuming the matrix is 360 X 240, whenever I try to `Take[]` from this dynamic matrix, I get an error message. How do I use specified pieces of the matrix to define some output on this data? In other words, lets say I want to cut the video up into 18X12 blocks so that I can operate on just just that section of the live matrix video feed, how can I use `Take[]` to do this? I assume there is some function that is not `Take[]` for this. For my specific project, I need to divide each pixel in this raw matrix data by 2 so that the data fits in the parameters 0 to 127 instead of 0 to 255, what is the most efficient way to calculate this live stream so that there is as little latency as possible? Would I use `TrackSymbols`? Or is there some other way to operate on a dynamic matrix? Any help on solutions to these two problems is greatly appreciated. And a warm smile goes to you for helping out a lone wolf amateur programmer like myself. EDIT: Sample data can be generated from any webcam with the following code, thanks to help from Andy:               img = Dynamic[ColorConvert[CurrentImage[], "Grayscale"]];     rawimg = Dynamic[Flatten[ImageData[img[[1]], "Byte"][[1 ;; 18, 1 ;; 12]]]]      I then want to turn this information into one DYNAMIC digit that is between 0 and 126. by dynamically taking the Mean of all the numbers in the list and dividing this number by two (and using the floor of the answer). So the input is a large matrix and the output is just a single number like "122".


Poor (network) performance of Interpreter["Time"]

I was surprised to see that `Interpreter` requires external WR resources as this is not documented, at least not here. On a 3Ghz iMac, took ~half a minute to process n=68 time strings:               timeData = {"0:12:15", "0:13:00", "0:17:00", "0:00:39", "0:00:25", "0:00:38",      "0:00:48", "0:05:50", "0:03:34", "0:05:50", "0:00:22", "0:04:05",      "0:00:07", "0:00:07", "0:00:46", "0:00:02", "0:00:32", "0:00:11",      "0:00:31", "0:09:55", "0:00:07", "0:00:34", "0:00:36", "0:07:44",      "0:00:11", "0:00:20", "0:02:29", "0:04:30", "0:00:56", "0:01:23",      "0:00:05", "0:00:05", "0:00:18", "0:00:13", "0:00:21", "0:00:21",      "0:00:06", "0:00:13", "0:00:56", "0:00:05", "0:00:15", "0:00:05",      "0:01:38", "0:00:22", "0:01:43", "0:00:14", "0:09:06", "0:01:39",      "0:03:17", "0:03:08", "0:00:45", "0:00:36", "0:00:38", "0:00:06",      "0:00:08", "0:01:07", "0:00:08", "0:01:06", "0:00:11", "0:00:17",      "0:00:08", "0:00:17", "0:00:09", "0:00:34", "0:00:25", "0:00:31",      "0:00:07", "0:01:29"};          AbsoluteTiming [Interpreter["Time"][#] & /@ timeData ] // First          26.633811      Timing is much lower, ~3 seconds, though once I ran it and got: "Interpreter::timeout : "A network operation for Interpreter timed out. Please try again later." Users can define their own interpreters, but curious if it's possible to make at least part of the functionality available locally? I can't imagine a simpler test case than time strings.


Numerical vs Symbolic Integration: Loss of precision

I am trying to integrate the following expression over the time interval $0\leq t \leq \text{period}$.               (Cl - Cn)/Cl*(b Sin[2 Pi/peroid*t] f[t] - 2 (wl/peroid) Pi^2 b^2/wl^2)      where               f[t_] := ((Cl - Cn)^2/Cl 2 Pi^2 b^2/wl - Cn wl) b (wl/peroid)                  Sin[2 Pi (wl/peroid)*t/wl]/((Cl - Cn)^2/Cl*b^2*                 wl*(Sin[2*Pi*(wl/peroid)*t/wl]^2) + (Cn - Cl) wl b^2/2*                 Cos[4 Pi (wl/peroid) t/wl] - Cl b^2 wl/2 - Cn wl^3/12)      $Cl, Cn, b, period, wl$ are all parameters and $t$ is the only variable. I tried to perform the integration symbolically and _Mathematica_ gave me the following result: > >     -(((Cl - Cn) (2 b^2 (Cl - Cn) \[Pi]^2 + Cn wl^2))/((2 Cl^2 - 3 Cl Cn + > Cn^2) wl)) >   To further verify that this symbolical expression is correct, I performed the above integration again but numerically with both _Mathematica_ and _Matlab_ with the following parameter values:               Cn = 0.001903418147340     Cl = 8.265172296997836/10000     b = 10/1000000     wl = 1000/1000000     peroid = 0.5      and I also evaluated the symbolic expression with the above set of values. The numerical integration performed by _Mathematica_ and _Matlab_ agrees with each other. However, both numerical integration performed by _Mathematica_ and _Matlab_ are 4 orders of magnitude different from the result obtained by evaluating the symbolic expression with the same set of parameter values. There's something going on, but I don't know what. Any suggestions ? So far, I have checked that the function that I want to evaluate is smooth. Any suggestions are greatly appreciated.


Importing .txt or .csv financial data

I am trying to import some financial data exported from Excel. You can find the relevant file here : Text File or CSV File This is what the data looks like in Excel : ![enter image description here](http://i.stack.imgur.com/W1prV.png) Using the following code to import :               BankShadowFed =        Import[FileNameJoin[{NotebookDirectory[], "BankShadowFed.txt"}],         "Table"];      I have the following problem: ![enter image description here](http://i.stack.imgur.com/YKwoW.png) While I can Change to expression each element, ![enter image description here](http://i.stack.imgur.com/1uGUb.png) I can't get it all right including the dates... What is the right way to `Import[]` those files ? Or `Export[]` them in the first place?


Exporting a plot inside Manipulate - Update first, then Export

I want Mathematica to excute the first action inside the `Button` fully before executing the second action. In particular, look at the following plot which I want to `Export` to a pdf.               Manipulate[myFigure=Show[Plot[x^2+a,{x,-1,1},PlotRange->{-1,4}]],{{a,2,"a"},-1,3},Button["Export a=0",{a=0,Export["Figure1.pdf",myFigure];}],Button["Export a=1",{a=1,Export["Figure2.pdf",myFigure];}]]      If I click `Export`, Mathematica seems to `Export` the plot before `Updating` the `Manipulate` to the new value for 'a'. However, I obviously want it to change to the new 'a' first, showing the new plot, and then `Export` this plot to a pdf. Any thoughts on how to make `Manipulate` `Dynamically Update` itself before the `Export`? Or other solutions?


Plotting columns of two separate data lists

I have two data lists with names data1 and data2. data1 has 8 columns and data2 has two columns. How can I plot 3rd column of data1 verses 1st column of data2?


ListLinePlot problem

OK, so here I got the solution of a numerically-solved PDE. I wish to plot in a graph, for a given time, the point x where the solution reaches 1/2. So here's the relevant string of code:               eps=5/9;     phi6m = NDSolveValue[{         D[u[t, x], t, t] - D[u[t, x], x, x] ==                 -6 u[t, x]^5 + (8 + 4 eps) u[t, x]^3 - (2 + 4 eps) u[t, x],         u[0, x] == Tanh[x],          Derivative[1, 0][u][0, x] == 0,          u[t, -7] == -1, u[t, 7] == 1                          }, u, {t, 0, 6}, {x, -7, 7}];     Do[         phi62 = phi6m[k/10, x];         phi6plus[[k]] = FindRoot[phi62 == 1/2, {x, k/10}],      {k, 1, 55}]     ListLinePlot[phi6plus, PlotRange -> All]      But when I run that code, I get all the values of x where the solution is worth 1/2 for the sampled time points instead of a plot. It also says that ListLinePlot is called with no argument. How am I to make a graph with the values of phi6plus for the given values of k? If possible, I'd also like to interpolate the data contained in the phi6plus array.


Plotting a time delay in mathematica?

I'm having some difficulty plotting a phase space of a function `f` that exhibits time delay. i.e.               s = NDSolve[{x'[t] == f[x[t - \[Tau]]], x[0] == 1 }, {x}, {t, 100}];     ParametricPlot[{x[t] /. s, x[t-\[Tau]] /. s}, PlotRange -> All]      i.e. how do I plot `x(t-\[Tau])` vs `x(t)` ?


Overlay two images

I have a series of endoscopic images taken by two cameras at the same time. A color image: ![enter image description here](http://i.stack.imgur.com/n74Fl.jpg) and a fluorescent image indicating cancerous cells ![enter image description here](http://i.stack.imgur.com/porNw.jpg) I now want to overlay the two images to indicate the cancer in the color image.               ImageCompose[img1, {img2, 0.35}]      ![enter image description here](http://i.stack.imgur.com/KKuzq.jpg) you can see that it does not match exactly. I need a way to match both images. Another problem is, sometimes the color camera zoomed a little in while the fluorescent image does not. In the fluorescent image everything but the bright area should be omitted. The color image is the basis and the fluoro image should be fitted to it, preferably in some false coloring. Here are two corresponding images: pair 1               im1col=Import["http://i.imgur.com/shzDETI.jpg"]     im1fluo=Import["http://i.imgur.com/Yh9iAXH.jpg"]      pair2               im2col=Import["http://i.imgur.com/ZnUJFrv.jpg"]     im2fluo=Import["http://imgur.com/VHlrpNj.jpg"]


Approximately Fit Data Without FindFit

I have some noisy data, and I'd like to analyze the derivative of the function the data approximately matches. `Interpolation` is normally great, but doesn't work very well at all here.               data = Table[{x, Sin[x] + RandomReal[{-.15, .15}]}, {x, 0, 2 \[Pi], .05}];      ![Almost sin\(x\)](http://i.stack.imgur.com/WR6Um.png)               xi = Interpolation[data];     Plot[xi'[t], {t, 0, 6.25}];      ![Not cos\(x\)](http://i.stack.imgur.com/MaOVG.png) As you can see, the derivative (as expected when you think of how interpolation works) is not at all `Cos[x]`. In this case, because it is so obvious that the curve is of the `Sin[x]` family, it would be trivial to fit it and take the derivative of the fit. In the data I actually collected, I do not know the function, and assuming some high-order polynomial, while it may fit well, is almost certainly an incorrect assumption. Is there a way to plot the derivative cleanly without requiring other knowledge about the function? Is it possible to tell `Interpolation` that it doesn't need to hit every point exactly?


How can I change the CDF which imports the data and uses it, without execution of code

I am making an application which first imports the data from the Excel file and then uses it in the deployment of a CDF. But is it possible to change the data of the Excel file and see its corresponding CDF without executing the code in the notebook? I have imported y1 and y2 from an excel file. Here is the code.               CDFDeploy[     ToFileName["C:\\Users\\murali\\Desktop","demo2thomson.cdf"],     {DynamicModule[{y =      Import["C:\\Users\\murali\\Desktop\\demo.xlsx"], y1 = y[[1, 1]],   y2 = y[[1, 2]], q1, q2},      Panel@Column[{Spacer[70] Text[         Style["iPhone and iPad quarterly sales- units, million", Bold,           18]], Column[{Spacer[70],          Text[Style["Click on/off:", Bold, 14]], q1 = True; q2 = True;          Row[{Labeled[            Button["     ", q1 = ! q1, Background -> Blue,              Appearance -> "Frameless"], "iPhone", {Right}],            Spacer[19],            Labeled[Button["     ", q2 = ! q2, Background -> Orange,              Appearance -> "Frameless"], "iPad", {Right}]}],          Column[{Dynamic@            BarChart[             Table[{If[q1, y1[[i]], 0], If[q2, y2[[i]], 0]}, {i, 1, 22,                1}], BarSpacing -> 0.8, ChartStyle -> {Blue, Orange},              ImageSize -> {600, 280},              GridLines -> {None, Automatic}]}]}]}]]}]      I am importing these values just as default and want that the end user can change these values. i.e. I don't want the end user to go to the code and execute again and again if he wants to change some of the values of y1 and y2. Is it possible that he can change value and see the difference in the CDF itself?


How to deal with complicated gaussian integrals in Mathematica?

As we know, for most Gaussian integrals, we can get the analytical result. Now I have many Gaussian integrals to treat, which have the following general form,               Integrate[        x1^n1 x2^n2 x3^n3 ... xd^          nd Exp[-{x1, x2, x3 ... xd}.matrix.{x1, x2, x3 ... xd} + c1 x1 +              c2 x2 ... cd xd], {x1, -Infinity, Infinity},          {x2, -Infinity, Infinity} ... {xd, -Infinity, Infinity}].       The matrix is a symmetrical positive definite matrix. We can get the analytical integral result for this general form. However, it is a difficult task for Mathematica to deal with the similiar expressions, which takes so much time. I have written a package for treating this problem. But, it is still not sufficient because I need to deal with lots of these kinds of integral expressions. So the computation time is important. So have you ever seen the package for doing this kind of Gaussian integral? Or can you give me some suggestions about this problem? Thank you very much! Thanks all of you. For the concept MultinormalDistribution, it is very helpful for me. By the way, How can I transform the following integral expression to the standard form of MultinormalDistribution in a simple way?               vec1 := {r1x, r1y, r1z};     vec2 := {r2x, r2y, r2z};     vect := {r1x, r1y, r1z, r2x, r2y, r2z};     vcof := {c1, c2, c3, c4, c5, c6};     Integrate[Exp[-vect.mat.vect + vcof.vect] (vec1.vec2)^n (vec1.vec1)^     l (vec2.vec2)^m, {r1x, -Infinity, Infinity}, {r1y, -Infinity,      Infinity}, {r1z, -Infinity, Infinity}, {r2x, -Infinity,      Infinity}, {r2y, -Infinity, Infinity}, {r2z, -Infinity, Infinity}];      The mat is a symmetrical positive definite sparse matrix. And n, l, m are integers.   Thanks!


Awkward output of TeXForm

When I try to format a number that has a big exponent with TeXForm the following happens:               In[1]:= TeXForm[1.543*10^-10 ]          Out[1]//TeXForm=         \text{1.543$\grave{ }$*${}^{\wedge}$-10}      But I would like to get something like `1.543 \cdot 10^{-10}`. Is there any workaround for this?


PDE with Stefan Conditions, a.k.a variable boundary

I want to solve the one-dimensional one-phase Stefan problem, but I don't know how to make Mathematica understand the conditions. If you are not familiar with what I'm asking please refer to this wikipedia article: http://en.wikipedia.org/wiki/Stefan_problem#Mathematical_formulation This is what I have so far. Clearly, it doesn't work.               NDSolve[      {D[u[x, t], t] == D[u[x, t], {x, 2}],       (-D[u[x, t], x] /. x -> 0) == 1,       u[s[t], t] == 0,       D[s[t]] == (-D[u[x, t], x] /. x -> s[t]),       u[x, 0] == 0,       s[0] == 0       },     {u, s}, {x, 0, s[t]}, {t, 0, 10}]      I hope there is someone out there with a magical code I'm using Mathematica 10. Thanks!


Symbolic derivatives are being calculated numerically

Just found the following while debugging a problem. _Mathematica_ is calculating the derivative of `IntegerPart[x]` in some odd way:               Plot[{IntegerPart@u, D[IntegerPart[x], x] /.x -> u}, {u, 0, 3},PlotRange -> Full]      ![enter image description here](http://i.stack.imgur.com/SJRtd.png) Do you know what is the violet curve in the plot above, and why _Mathematica_ thinks it is the derivative of `IntegerPart[x]`? **Edit** Or consider for example the following:               f[x_] := Sin[x] + IntegerPart[x];     Plot[{f[x], Derivative[1][f][x]}, {x, 0, Pi/2}]      ![enter image description here](http://i.stack.imgur.com/BB7zW.png) Or similarly               Plot[{FractionalPart[x], Derivative[1][FractionalPart][x]}, {x, 0, 3}]      ![enter image description here](http://i.stack.imgur.com/Jb8Ws.png) What is happening here?


Sum equation with equation and get an equation

I am trying to get an equation from summing other equations but it doesn't result in a correct answer. Is there another way of doing this?               n = 4; xList = {1, 2, 3, 4, 5}; yList = {4, 5, 6, 8, 7};     equation[x_] = a*(x^4) + b*(x^3) + c*(x^2) + d*(x^1) + e*(x^0);     eqSummer = 0;          Do[       eqSummer = eqSummer +  equation[xList[[i]]];       , {i, 1, Length[xList]}     ];          eqSum     36768/25 + (512 c)/5 + 10 e


Unexpected Setter Bar Behavior when Manipulate Nested in Dynamic Module

Consider this code:               DynamicModule[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {fcn, {x -> "Square", y -> "Cubic"}}]]      ![SetterBar not working properly](http://i.stack.imgur.com/zQemy.png) Why does the SetterBar created by Manipulate not highlight properly when either option is selected? The same problem exists for other user interface elements, like a RadioButtonBar:               DynamicModule[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}, RadioButtonBar}]]      ![enter image description here](http://i.stack.imgur.com/IZSfz.png) However, if you remove the DynamicModule, everything works as expected:               x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}}]      ![enter image description here](http://i.stack.imgur.com/pZUlD.png) Also if you were to replace DynamicModule with Block or Module, everything works as expected:               Module[{x, y},     x[t_] := t^2 + 5;     y[t_] := t^3 + 5;          Manipulate[Plot[fcn[t], {t, -5, 5}],     {{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}}]]      Can anyone explain why this is, and how to fix it?


How to set the slider width inside Manipulate

I use the code below to visualise the connection between a sine curve and the unit circle, but would like to make the slider wider, so it has at least almost the same with as the image. I have tried to replace ControlType->Slider[] with ControlType -> Slider[ImageSize->800], but this seems to have no effect at all och the resulting graphics. The question is thus how to set the width of the slider inside Manipulate?               Manipulate[      With[{ar = 1/(2*Pi), o = v - Cos[v]},        Show[Plot[Sin[x], {x, -6*Pi, 6*Pi},          PlotRange -> {{-2*Pi, 2*Pi}, {-1, 1}}, PlotStyle -> {Black},          AxesLabel -> {"v", Sin["v"]}, AspectRatio -> ar],        ListLinePlot[{{o + Cos[v], 0}, {o + Cos[v], Sin[v]}},          PlotStyle -> {Thick, Black}, AspectRatio -> ar],        ListLinePlot[{{o + Cos[v], Sin[v]}, {o, 0}},          PlotStyle -> {Dashed, Black}, AspectRatio -> ar],        Graphics[{AbsolutePointSize[8], Point[{o, 0}]}, AspectRatio -> ar],        Plot[{-Sqrt[1 - (x - o)^2], Sqrt[1 - (x - o)^2]}, {x, o - 1,           o + 1}, PlotRange -> {{-2*Pi, 2*Pi}, {-1, 1}},          PlotStyle -> {{Thick, Orange}, {Thick, Orange}},          AspectRatio -> ar], ImageSize -> 800]], {v, -3/2*Pi, 3/2*Pi},       ControlType -> Slider[]]      ![The resulting graphics](http://i.stack.imgur.com/zTgCy.png)


Finding the time at which an Ito process satisfies a constraint

I want to run an Ito stochastic process. I have the following parameters               b1b = 0.9;     b3b = .8;     a1b = 0.1;     a3b = 0.2;     eps = 0.1;     G = (1/eps^2)*b1b ; a1 = (1/eps^2)*a1b; a3 = (1/eps^2)*a3b;     xc = Sqrt[a1/a3];     Uc = a1*xc^2/2 - a3*xc^4/4      I want to stop the process when `U[x[t]]=U[xc]` and `y[t]=0` (or at least very close for each of these parameters: say in the vicinity of `10^-4*U[xc]` for `U[x[t]]` and `10^-8` for `y[t]`). Please note `U[x]` is the integral of `U'[x]`. I am trying to write code that simulates `dz[t]` for many realisations (say 100) and calculates the average of times at which the aforementioned constraint is satisfied (i.e., average of 100 times). However, I have no idea how to incorporate the constraints and extract the time at which the constraints are satisfied. I tried to use the `ItoProcess[]` function, but had no fruitful outcome. Any help would be much appreciated.


Log-scale histogram bug

Not really a question, more a solution to what I call a bug in mathematica v8(.0.0.4). I already sent a bug report to Wolfram. ### Problem The documentation for the _Histogram_ -function explains the following option.               {"Log",bspec}       apply binning bspec on log-transformed data.      When specifying the bins in the format `{xMin, xMax, dx}`, these values are not processed corretly which leads to insatisfying results. In detail, the lower and upper bounds are transformed to the logarithmic scale using the natural logarithm. From there on, the bin widths are determined using `dx` and these bin coordinates are transformed back using the common logarithm. One would expect that the routine uses either the natural or the common logarithm for both operations, but not a mixture of the two. ### Example Imagine, that `data` is a list of real values.               (* binning settings *)     binMin = 0.01;     binMax = 100;     binWidthLog = 1;     Histogram[data, {"Log", {binMin, binMax, binWidthLog}}]      ![Standard histogram](http://i.stack.imgur.com/PE32X.png) The minimum and maximum `x` values clearly don't follow the wanted behaviour. Using custom bin limits, this result can be reproduced as follows with a mixture of common and natural logarithms.               bins = {10^Range[Log[E, binMin], Log[E, binMax], binWidthLog]};     Histogram[data, {"Log", bins}]      ![Reproduced standard histogram](http://i.stack.imgur.com/JzVDp.png)


How do I plot cities on a Map?

Right now, I have the 20 cities with the most population in the world, given by the lines of code               numberofpeople = Map[{#, CityData[#, "Population"]} &, CityData[All]];     datapoints =       Reverse[SortBy[DeleteCases[numberofpeople, {_, _Missing}],          Last]][[1 ;; 20]]      Now, I am going to plot these cities on a World Map, so that there is a point for each city in the dataset. However, I am stuck on what to do from there. As of now, I have the line of code               Graphics[{EdgeForm[Black], , CountryData[#, "SchematicPolygon"]} & /@        CountryData[]]      I am unsure on what goes between the commas. The other two arguments give a black border for each country's border and then displays the world as a SchematicPolygon. Any help is much appreciated.


Derivative of a spline approximation

To approximate an experimental data function $f(t)$ with $t \in (t_{min},t_{max})$ I used a cubic spline $s(p)=(t(p),f(p))$ with the parameter $p \in (0,1)$ and $p = t/(t_{max}-t_{min})$ by using the command BSplineFunction. To take the time derivative I use the chain rule $s'=ds/dt = ds/dp \cdot dp/dt = s'(p)/(t_{max}-t_{min})$. When I try plotting the derivative $df/dt = s'[[2]]$ by               Show[ParametricPlot[{93*p, 1/93 s'[p][[2]]}, {p, 0, 1}], AspectRatio -> 1]      it shows me the error warning > Part::partw: Part 2 of BSplineFunction[{{0.,1.}},<>][t] does not exist. >> but still shows the correct graph. What went wrong?               data = {{3.107, 0.997}, {6.851, 1.008}, {10.594, 1.011}, {14.338,      1.007}, {18.081, 0.977}, {21.825, 0.967}, {25.568, 0.917}, {29.311,       0.852}, {33.055, 0.736}, {36.798, 0.533}, {40.542, 0.336}, {44.285,      0.205}, {48.029, 0.111}, {51.772, 0.074}, {55.516, 0.044}, {59.259,      0.032}, {63.003, 0.034}, {66.746, 0.01}, {70.49, 0.026}, {74.233,      0.01}, {77.977, 0.016}, {81.72, 0.002}, {85.464, -0.002}, {89.207,      0.01}, {92.951, 0.01}}     s = BSplineFunction[data, SplineDegree -> 3];      There is a caveat to the method. When fitting a spline to data p is not necessarily proportional to the independent variable. In my case the relationship between $p$ and $t(p)$ deviates substantially from linearity outside the range $p \in (0.025, 0.975)$. Is there a better way to get the derivative?


Why does the PlotStyle not apply globaly when I plot multiple data files

I have several data files which contain columns of data. All my files follow the same format data001.out, data002.out, ... , data00n.out. I want to import and plot all of them simultaneously. In particular, I use only the first two columns of the data files for my plot. I wrote this simple Mathematica code:               SetDirectory["..."];          dataAll = {};          Do[        data = ReadList["data00" <> ToString[NumberForm[i, 2, NumberPadding         -> {"0", ""}]] <> ".out", Number,         RecordLists -> True];        pdata = Table[{data[[j, 1]], data[[j, 2]]}, {j, 1, Length[data]}];        AppendTo[dataAll, Flatten[pdata]];       , {i, 1, 50}     ]             S0 = ListPlot[dataAll, Frame -> True, FrameLabel -> {"x", "y"},      RotateLabel -> False, PlotStyle -> {Black, PointSize[0.01]},      PlotRange -> All, ImageSize -> 500]      I am wondering, if there is a simpler or even more correct way to perform this task. Perhaps, the `Do` loop needs improvement. I noticed that the `PlotStyle` in `ListPlot` does not apply to all points of the dataAll list. Even if I determine the color (black) and the size, the output contains several colors ans sizes. Where is the mistake? Many thanks in advance!


What algorithm does Plot use to determine abscissas?

(I'm hoping this question is not hopelessly naive...) My understanding is that `Plot`'s strategy is to generate a list of abscissas, evaluate the argument expression at those abscissas, and from that point on behave pretty much like ListPlot with the list of abscissa-ordinate pairs as input. (More or less.) Assuming that the sketch above is not fantastically off-base, what algorithm does `Plot` use to compute the list of abscissas to use?


Getting InputStream errors when including a call to ElementData within an Import definition

So I am writing an `ImportExport` converter for a common chemistry file format, and I've run up against a problem that seems to be about shared streams and whatnot. I followed the directions on this page. To work the example, create a random text file whose contents do not matter.               Export["testfile.txt", "hello"];      The definition for the `Import` converter is as follows               ImportExport`RegisterImport["TestFormat", TestFormat`TestFormatImport];     TestFormat`TestFormatImport[filename_String, options___] :=       Module[{temp},       (*Do some stuff, all works just fine*)       temp = ElementData["C", "AtomicNumber"];       {"Test" -> temp}];      All this does is call for the atomic number associated with the symbol C. If you test it out it seems to work just fine:               In[3]:= Import["testfile.txt",{"TestFormat","Test"}]     Out[3]= 6      But any subsequent call to `ElementData` gives a stream error:               In[4]:= ElementData["F","AtomicNumber"]     During evaluation of In[4]:= General::openx: InputStream[C:\Users\myusername\AppData\Roaming\Mathematica\Paclets\Repository\ElementData-7.0.28\Data\ElementData.wdx,122] is not open. >>     During evaluation of In[4]:= BinaryRead::openx: InputStream[C:\Users\myusername\AppData\Roaming\Mathematica\Paclets\Repository\ElementData-7.0.28\Data\ElementData.wdx,122] is not open. >>     Out[4]= $Failed      But, if I make a call to `ElementData` _before_ I make the `Import` command, then the errors go away.               In[1]:= ImportExport`RegisterImport["TestFormat",                  TestFormat`TestFormatImport];             TestFormat`TestFormatImport[filename_String, options___] :=                  Module[{temp},                (*Do some stuff, all works just fine*)                temp = ElementData["C", "AtomicNumber"];                {"Test" -> temp}];             ElementData["H", "AtomicNumber"]             Import["testfile.txt", {"TestFormat", "Test"}]             ElementData["F", "AtomicNumber"]          Out[3]= 1          Out[4]= 6          Out[5]= 9      This is all well and good, but I don't want to have to randomly make a call to `ElementData` before I do an `Import` command every time. What is going on here and how can I fix it? Thanks


How to translate interactive graphics from Mathematica to standard HTML+SVG?

I have a simple interactive plot in _Mathematica_ , with controls for various parameters. The point the plot is simply that, by manipulating these controls users can explore how the plot changes as the parameters change. IOW, this is `Dynamic`-101 stuff (which is my level at the moment). I would like to convert this to (non-proprietary) HTML + SVG (+ CSS, JavaScript, etc., as needed). Is there a straightforward path for doing this? I know that one can export _Mathematica_ graphics to SVG, but I'm not sure how one would export the dynamic behavior described above. (BTW, I've looked for ways to do this starting from JavaScript to begin with, but I have found that JavaScript support for plotting is rather primitive. JavaScript graphics seem to be mostly about Illustrator-type stuff, and more recently, "data visualization". In comparison there's almost nothing in the JavaScript graphics universe for plotting functions, the way `Plot` et al. do.)


integral, explicit form

I want to estimate the ratio of integrals: $$ \frac{\int \frac{4 a T^3}{\frac{4 a T^4}{3}+\Lambda_1 \left(\frac{4}{T^3}+1\right)}}{\int \frac{4 a T^3}{\frac{4 a T^4}{3}+\Lambda_0 \left(\frac{4}{T^3}+1\right)}} $$ where $\Lambda_1$=$\Lambda$ (constant) and $\Lambda_1$=0 for some temperature $T_0$ (arbitrary constants are set to zero). When I try to integrate the function:               f[T_] := (4 a T^3)/(4/3 a T^4 + Λ (1 + 4/T^3))     Integrate[ f[T], T]       I get the result like this (with `#` and `&`) :               12a RootSum[ 12 Λ + 3 Λ #1^3 + 4 a #1^7 &, (Log[T - #1] #1^4)/(9 Λ + 28 a #1^4) &]      What am I doing wrong? How do I get an explicit expression for the integral? How do I solve this problem ?


Plotting multivariable integration

If I have a multivariable integration like               NIntegrate[x^2 + y^2, {x, 1, 5}, {y, 6, 10}]      But I need to plot its result in terms of `x` . Then how to do it ?


difficulty abstracting the OptionValue pattern

I am building lots of functions that use `Options` and `OptionValue` and wanted to reduce the redundancy in the expressions that define the functions. I will show a tiny example, here, but please imagine that instead of a couple of options with names like `a` and `b`, my real examples have dozens of options with names like               blancmangeWithRaisinsAndPartiallyHydrogenatedChocolateSauce      and you will easily understand why I want to do what I want to do. What do I want to do? My functions fit the following pattern: The following defines the acceptable optional parameters for `foo`: they are `a` and `b`, and they have default values 1 and 2, respectively. The acceptable options are defined separately from the body of the function. A caller may supply values for `a` or `b` or both or neither, using option syntax below.               ClearAll[foo];     Options[foo] = {"a" -> 1, "b" -> 2};      The following defines the body of the function. This function produces an association object with attributes corresponding to the values of the optional parameters.               foo[OptionsPattern[]] :=       <|"a" -> OptionValue["a"],        "b" -> OptionValue["b"]|>;      The following is a call that supplies only the optional value for a.               foo["a" -> 42]      > >     <|"a" -> 42, "b" -> 2|> >   The following is a call that supplies both a and b; notice that the order does not matter.               foo["b" -> 43, "a" -> 42]      > >     <|"a" -> 42, "b" -> 43|> >   The following is a call that supplies neither a nor b.               foo[]      > >     <|"a" -> 1, "b" -> 2|> >   I want to reduce the redundancy in the definition expression for `foo`. I define a helper:               ClearAll[opt];     opt[nym_] := Rule[nym, OptionValue[nym]];      Hoping for a new style of definition for `foo`:               foo[OptionsPattern[]] = <|opt["a"], opt["b"]|>      Notice that I used `Set` and not `SetDelayed` because I wanted the right-hand side to be evaluated at definition time, not at call time. But still no dice: `foo` doesn't work any more               foo[]      > >     <|"a" -> OptionValue["a"], "b" -> OptionValue["b"]|> >   Its options are still in-force               Options[foo]      > >     {a -> 1, b -> 2} >   Why doesn't my little trick work? Why doesn't `opt` rewrite in the context of the definiing expression for `foo`?


Remove redundant dependencies from a directed acyclic graph

Given a directed acyclic graph, I want to remove all the edges $v_i \rightarrow v_j$ if $v_j$ is reachable from $v_i$ by some other path. Given the rich set of graph algorithms in _Mathematica_ , what is the best way to achive this? The background of the problem is this. I have a list of jobs and their dependencies, e.g., $a \rightarrow b$ means job $b$ can start only when job $a$ finishes. A list $\\{a \rightarrow b, b \rightarrow c, a \rightarrow c\\}$ is redundant because $a \rightarrow c$ is implied. I want to reduce the dependencies to a bare minimum.


Possible to include additional styles in context menu?

I am using Mathematica 9 on Windows 8, and I regularly want to use cell styles such as _Section_ , _SubSection_ and so on. If I click the `+` button before creating a new cell, a context menu with a number of style options is displayed: ![enter image description here](http://i.stack.imgur.com/2W4HX.png) Is there a way to configure this menu to contain some of the styles that I regularly use?


What is Mathematica's equivalent to MATLAB's Simulink?

MATLAB has Simulink and Simscape, Maple has MapleSim and Scilab has Xcos. What is the equivalent product for _Mathematica_?


Time differences between code using user-defined probability distribution and code using built-in distribution

Why is the reponse time of of kernel significantly different when I use the first code rather than the second? Shouldn it not be the same? Is there any way that the response time can be made smaller without having to use probability distributions built into _Mathematica_? Code 1:               triangular = TriangularDistribution[{0, 12}, 6];     Manipulate[       Plot[{         PDF[triangular, x]*If[x <= Quantile[triangular, p], 1, 0],          CDF[triangular, x],          PDF[triangular, x]},          {x, 0, 12},         PlotRange -> All, Filling -> {1 -> Axis}, ImageSize -> Large, AxesLabel -> {x, ""}],        {p, .6, "Percentil"}, 0, 1, .001, Appearance -> "Labeled"}]      Code 2:               D = ProbabilityDistribution[       Piecewise[{{         x/36, 0 <= x <= 6},         {(12 - x)/36, 6 < x <= 12}}],        {x, 0,12}];      Manipulate[       Plot[{         PDF[D, x]*If[x <= Quantile[D, p], 1, 0],         CDF[D, x],          PDF[D, x]},          {x, 0, 12},         PlotRange -> All, Filling -> {1 -> Axis}, ImageSize -> Large, AxesLabel -> {x, ""}],        {p, .6, "Percentil"}, 0, 1, .001, Appearance -> "Labeled"}]


Generating function for Newton series?

The function GeneratingFunction gives generating function for Taylor series. Is there a similar function for Newton's series? $$f(x) = \sum_{k=0}^\infty \binom{x}k \Delta^k [f]\left (0\right)$$


How do you properly create Buttons to change dynamic variables using Table

In this example, I want a series of four buttons to change the value of a variable that is used dynamically to drive a plot. I am trying to figure out why using Table around the buttons causes a problem. This works:               {Button["1", freq = 1], Button["2", freq = 2], Button["3", freq = 3],       Button["4", freq = 4]}      Dynamic[Plot[Sin[freq * x], {x, 0, 2 \[Pi]}]]      Why doesn't this work:               Table[Button[ToString[i], freq2 = i], {i, 4}]     Dynamic[Plot[Sin[freq2 * x], {x, 0, 2 \[Pi]}]]


Scope of expression in a user-defined function

I have the following code:               fbasic = A + R + Z*Z *Z*Z;     f[A_, Z_, R_] := fbasic + R;     f[0, 2, 3]      The answer I am getting is > >     3 + A + R + Z^4 >   Which is not what I want because the `fbasic` is not replaced by the expression. How can I do that?


What kinds of uses of SymbolicC (introduced in Mathematica 8) do you foresee? Are there any neat examples already?

Mathematica 8 introduced SymbolicC, a set of Mathematica functions that capture C language constructions in the familiar Mathematica tree-like fashion. Additionally, there are functions to write SymbolicC trees as straight C code to a file. The tutorial clearly explains the functions, but -as far as I know- it doesn't provide any examples of useful applications of this capability. It sounds like it should be tremendously useful, but I have a hard time coming up with some creative uses of my own. A couple of years ago, I used Mathematica to 'flatten out' a recursive algorithm I had written in C to gain some speed. Mathematica wrote the whole program for me pasting C phrases together I had prepared in strings. SymbolicC would have been much neater, though not really necessary. Yesterday, Leonid Shifrin came up with a very nice application of symbolicC to make an alternative of CForm that doesn't make calls to the auxiliary function Power(). That's a good start. I'd like to ask the creative minds on StackOverflow to come up with more _ideas_ and/or actual _uses_ of SymbolicC. I'll accept the most upvoted answer. **EDIT** Mar 30 The response to the question is a bit scant so far. So, we have this mma extension with more than 60 functions added and virtually nobody has an idea of how to use them? Come on guys, show that you're creative!


Parametric 3D plot with parameters satisfying an implicit equation

I am trying to plot a function $ {\bf x}(t) = r(t)\hat{v} + {\bf b}(t) $, with unit vector $ \hat{v} $ and vector $ {\bf b}(t) $ given in spherical coordinates. For simplicity, assume that $ \hat{v} = (\sin\theta\cos\phi, \sin\theta\sin\phi, \cos\theta) $, and $ {\bf b}(t) = [t, \sin(a+t), \cos(b + at^2)] $, where $ a $ and $ b $ are constants. This is easy to plot, however, I want the angles $ \theta $ and $ \phi $ to satisfy an implicit equation, say, $ \cos\theta + a(\phi + b t)^2 + c = 0 $.


How to draw timing diagram from a 0 and 1 string list (2)

I like ubpdqn's last edition & Mr Wizard's refactoring to my last question very much. I inserted two `Reverse` just to make the diagrams and the strings match in order.               fun[str : {__String}] :=       Module[{fs, n, timd},        fs = Riffle[#, #]~Append~Last[#] & /@ ToExpression@Characters@str;       n = Length@First@fs;       timd = Reverse@fs~Append~PadLeft[{0}, n, {0, 1}];            ListLinePlot[MapIndexed[#1 + 2 First@#2 - 2 &, timd],         InterpolationOrder -> 0, Frame -> True,         FrameTicks -> {Thread[{Range[1.5, n - 1.5, 2], Range[n/2]}],           Thread[{Range[0.5, 2 Length@timd, 2],             Join[Reverse@str, {"clock"}]}], None, None},         PlotRange -> {{0, n + 1}, Automatic}]]      ![enter image description here](http://i.stack.imgur.com/Yh3Ud.gif) And here, I managed to make the input strings rotate dynamically with the following code, the problem is I failed to make the timing display rotates with the strings as well. Pls help.               str2 = {"11000011", "00000011", "11100111"};     Dynamic[      Refresh[str2 = {StringJoin[RotateRight[Characters[str2[[1]] ]]],          StringJoin[RotateRight[Characters[str2[[2]] ]]],         StringJoin[RotateRight[Characters[str2[[3]] ]]]         };       Column[{str2[[1]], str2[[2]], str2[[3]]}], UpdateInterval -> 1       ],      TrackedSymbols -> {}      ]


how to find the vector intersection in a collection of triangulated 3D points?

I'm trying to calculate the 3D point coordinates for the intersection of a vector with a plane. I have been using the following code to do this:               PointPlaneIntersection[{{x1_, y1_, z1_}, {x2_, y2_, z2_}, {x3_, y3_,      z3_}}, {{x4_, y4_, z4_}, {x5_, y5_, z5_}}] :=  Module[{t = -Det[{{1, 1, 1, 1}, {x1, x2, x3, x4}, {y1, y2, y3,           y4}, {z1, z2, z3, z4}}]/      Det[{{1, 1, 1, 0}, {x1, x2, x3, x5 - x4}, {y1, y2, y3,          y5 - y4}, {z1, z2, z3, z5 - z4}}]},  {x4 + t (x5 - x4), y4 + t (y5 - y4), z4 + t (z5 - z4)}]      which I found at: http://mathworld.wolfram.com/Line-PlaneIntersection.html I have the vector and a point of origin for this vector:               vec={1.11593, 0.0607521, 0.125472};pt={-45.0446, 0.0900457, -1.42599}      However, rather than having a know plane defined by 3 points, as the PointPlaneIntersection code needs, I have a group of planes/triangles defined by 3D points:               triangles={{{-46.4755, -0.0930855, -2.55178}, {-46.6708, -1.22548, -2.25304},{-46.9169, -0.664019, -0.916458}}, {{-46.4736,  0.544871, -1.66483}, {-46.4755, 0.0930855, -2.55178}, {-46.9169,-0.664019, -0.916458}}, {{-46.0117, 0.605676, -3.13173}, {-46.4755, -0.0930855, -2.55178}, {-46.4736, 0.544871, -1.66483}}, {{-45.6652, 1.74667, -1.92923}, {-46.0117, 0.605676, -3.13173}, {-46.4736, 0.544871, -1.66483}}, {{-45.2907, 1.39215, -3.80111}, {-46.0117, 0.605676, -3.13173}, {-45.6652, 1.74667, -1.92923}}, {{-46.4736, 0.544871, -1.66483}, {-46.9169, -0.664019, -0.916458}, {-46.8575, -0.142585, 0.141953}}, {{-46.2786, 1.32328, -0.512178}, {-46.4736, 0.544871, -1.66483}, {-46.8575, -0.142585, 0.141953}}, {{-45.6652, 1.74667, -1.92923}, {-46.4736, 0.544871, -1.66483}, {-46.2786, 1.32328, -0.512178}}};      This can be visualised:               Show[Graphics3D[{Yellow, Specularity[White, 20], Directive[Opacity[0.75]], EdgeForm[{Gray, Thin}], Polygon[triangles], Red, AbsolutePointSize[8], Point[pt], Blue, Thick, Arrowheads[0.02], Arrow[{pt, (pt + (vec))}]}], PlotRange -> All, Lighting -> "Neutral", Boxed -> False, Axes -> False, Ticks -> None, AxesLabel -> {"X", "Y", "Z"}, AxesStyle -> Gray, BoxRatios -> Automatic, AspectRatio -> Automatic, ImageSize -> 650, ViewPoint -> vec*10]      ![enter image description here](http://i.stack.imgur.com/SxjsL.png) Also, note that in the graphic produced the vector direction is away from the collection of triangles. I'm looking for a solution where it doesn't matter whether the vector is towards or away from the triangles...ie the code will effectively flip the vector round. Can anyone suggest a solution for selecting which triangle/plane the vector passes through? Or alternatively, could anyone suggest a good way to fit a surface (eg a bezier surface) to the points, then find the intersection of the vector with the surface? thank you for reading my problem, Dime


Cannot compile OpenGL code in Mathematica (vc2010-windows 8.1)

# LinkError of OpenGL * * * My enviroment is windows 8.1 x64, _Mathematica_ 9.0.1, opengl 1.1               targetDirectory = "E:\\Users\\Hyper\\Documents\\OpenGL";     sourceDirectory = "E:\\Users\\Hyper\\Documents\\OpenGL\\SourceFile";     includeDirectory = {"E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include",         "E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\\GL"};     libraryDirectory = {"E:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\lib"};     LinkerOptions = {"opengl32.lib", "glaux.lib", "glu.lib", "glu32.lib",    "glut.lib", "glut32.lib", "opengl.lib"};          mainFile = Import[sourceDirectory <> "\\opengl-test1.txt"]          (*         #include <windows.h>           //#include <gl/glaux.h>        //#include <gl/gl.h>        //#include <gl/glu.h>       //#include <gl/glut.h>       #include <glaux.h>       #include <gl.h>       #include <glu.h>       #include <glut.h>       #pragma comment(lib, "opengl32.lib")       #pragma comment(lib, "glaux.lib")#pragma comment(lib, "glu.lib")       #pragma comment(lib, "glu32.lib")       #pragma comment(lib, "glut.lib")       #pragma comment(lib, "glut32.lib")       #pragma comment(lib, "opengl.lib")       int main(int argc, char* * argv)     {auxInitDisplayMode(AUX_SINGLE|AUX_RGBA);     auxInitPosition(0,0,500,500);     auxInitWindow(argv[0]);     glClearColor(0.0,0.0,0.0,0.0);     glClear(GL_COLOR_BUFFER_BIT);     glColor3f(1.0,1.0,1.0);     glMatrixMode(GL_PROJECTION);     glLoadIdentity();     glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0);     glBegin(GL_POLYGON); glVertex2f(-0.5,-0.5);     glVertex2f(-0.5,0.5);     glVertex2f(0.5,0.5);     glVertex2f(0.5,-0.5);     glEnd();     glFlush();     }     *)          exe = CreateExecutable[mainFile, "opengl-test1-x64",   "IncludeDirectories" -> includeDirectory, "Language" -> "C++",   "LibraryDirectories" -> libraryDirectory,   "TargetDirectory" -> targetDirectory, "Debug" -> True,   "LinkerOptions" -> LinkerOptions]      ![enter image description here](http://i.stack.imgur.com/jmJcg.png) * * * I can build and run this little example, in VC2010-IDE enviroment, so I'm not sure where goes wrong.


Nonrectangular region for NDSolve

I have a PDE with mixed boundaries (Neumann and Dirichlet on some sides) in the region $(t,x,y) \in \left( 0, T\right) \times\left\\{ -L \leq x \leq L, 0 \leq y \leq h(x) \right\\}$ where $h(x)$ is something like $\exp\left\\{ -(x-x^*)^2\right\\}$, doesn't matter. And I have Neumann boundary condition on the curve $\left(x, h(x)\right)$. How can I provide such region to NDSolve?


Integral over squared Hermite polynomial

I would like to calculate the uncertainty of the nth Eigenstate of a 1-dim harmonic oscillator. To obtain the result I have to solve the integral $$\int_{-\infty}^{\infty} \psi^* x^2 \psi \:dx$$ with $$\psi(n,x)=\frac{e^{-\frac{x^2}{2}} H_n(x)}{\pi^{\frac{1}{4}}\sqrt{2^n n!}}$$, where $H_n(x)$ is the Hermite polynomial (degree n) in the physicist version (as implemented in Mathematica). In Mathematica this equals to the Integral over               (2^-n E^-x^2 x^2 HermiteH[n, x]^2)/(Sqrt[π] n!)      Doing this manually gives $1/2+n$, but i can't get Mathematica to solve this integral without specifying $n$. I used `               Assuptions=n ∈ Integers && n >= 0      Is there anyway to solve similar integrals with Mathematica? Edit: Thanks for you answer, but I should have mentioned, that I'm looking for a way to let Mathematica solve such problems analytical.


Mystery with ValueQ

Consider the following               ClearAll[jd];     ValueQ[jd]      We expect `False` and get it. Now consider               ClearAll[jd];     ValueQ[jd /. {foo -> Unique[]}]      which yields `True`. But               jd /. {foo -> Unique[]}      is just `jd` and has no value defined. What's going on here?


Add lines to 3D Plot

How can I add lines that demarcate the different regions of the following 3D plot:               Plot3D[1/(1 + E^(-a - c)), {a, -8, 8}, {c, -8, 8}]      To give you an idea of what I have in mind I have added the lines and descriptions in the 3D plot in paint; now I want to know how to do it directly in _Mathematica_. ![enter image description here](http://i.stack.imgur.com/HKHLP.gif)


What is the equation to plot a vertical line?

Please help. Trying to find area between three curves, `e^-x, x = 2, y = 1`. Can't find out how to plot `x = 2`. Don't want to use `Epilogue` unless it can shade the area enclosed by the three curves.


How to get an Excel-like surface plot with ListContourPlot3D

I'm trying to create an Excel like surface plot from an import of data from an Excel workbook. I get the data without issue. It is a set of percentages in bin ranges over a series of dates. I'd like to plot this as a surface. After some searching it appears that I need to use _ListContorPlot3D_. It seems that I need to transform the data into a list of 3d vectors. I want the dates to show in the plot so I use the _DateObject_ to let the plot know what it is. However, it wont plot. It complains that I have not provided a list of points of dimension 3. But it is a list of points of dimension 3; {Date, Bin, Value}. I thought this would be an easy thing to do with the import. What have I done wrong? Am I using the correct plot for this? A sample of the data, the transformation command, and the plot command is below. Many thanks for your help. Edmund               testData = {{{2014, 4, 30, 0, 0, 0.`}, 0.5037593984962406`,      0.2631578947368421`, 0.11278195488721804`, 0.045112781954887216`,      0.03007518796992481`, 0.007518796992481203`,      0.022556390977443608`, 0.007518796992481203`, 0.`, 0.`,      0.007518796992481203`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2014, 3, 31, 0, 0, 0.`}, 0.5072463768115942`,      0.2536231884057971`, 0.12318840579710146`, 0.050724637681159424`,      0.028985507246376812`, 0.007246376811594203`,      0.014492753623188406`, 0.014492753623188406`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`, 0.`}, {{2013, 12, 31, 0, 0, 0.`},      0.49295774647887325`, 0.29577464788732394`, 0.09859154929577464`,      0.04225352112676056`, 0.035211267605633804`,      0.007042253521126761`, 0.014084507042253521`,      0.007042253521126761`, 0.007042253521126761`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`}, {{2013, 9, 30, 0, 0, 0.`}, 0.4765625`, 0.25`,      0.125`, 0.0703125`, 0.046875`, 0.0078125`, 0.`, 0.015625`, 0.`,      0.0078125`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2013, 6, 28, 0, 0, 0.`}, 0.3761467889908257`,      0.3211009174311927`, 0.14678899082568808`, 0.05504587155963303`,      0.05504587155963303`, 0.`, 0.009174311926605505`,      0.009174311926605505`, 0.`, 0.01834862385321101`,      0.009174311926605505`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2013, 3, 29, 0, 0, 0.`}, 0.42857142857142855`,      0.24761904761904763`, 0.14285714285714285`, 0.06666666666666667`,      0.01904761904761905`, 0.0380952380952381`, 0.01904761904761905`,      0.009523809523809525`, 0.009523809523809525`,      0.009523809523809525`, 0.`, 0.009523809523809525`, 0.`, 0.`, 0.`,      0.`}, {{2012, 12, 31, 0, 0, 0.`}, 0.39`, 0.23`, 0.22`, 0.03`,      0.01`, 0.06`, 0.01`, 0.04`, 0.01`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2012, 9, 28, 0, 0, 0.`}, 0.3473684210526316`, 0.2`,      0.25263157894736843`, 0.07368421052631578`, 0.042105263157894736`,      0.042105263157894736`, 0.010526315789473684`, 0.`,      0.021052631578947368`, 0.010526315789473684`, 0.`, 0.`, 0.`, 0.`,      0.`, 0.`}, {{2012, 6, 29, 0, 0, 0.`}, 0.28888888888888886`,      0.25555555555555554`, 0.2222222222222222`, 0.06666666666666667`,      0.1`, 0.022222222222222223`, 0.011111111111111112`,      0.011111111111111112`, 0.011111111111111112`,      0.011111111111111112`, 0.`, 0.`, 0.`, 0.`, 0.`,      0.`}, {{2012, 3, 30, 0, 0, 0.`}, 0.27906976744186046`,      0.19767441860465115`, 0.3023255813953488`, 0.05813953488372093`,      0.08139534883720931`, 0.03488372093023256`, 0.011627906976744186`,      0.`, 0.023255813953488372`, 0.011627906976744186`, 0.`, 0.`, 0.`,      0.`, 0.`, 0.`}};          plotData = Flatten[Table[{DateObject[testData[[x, 1]],       DateFormat -> {"Year", "Month", "Day"}], y - 1,       testData[[x, y]]}, {x, Dimensions[testData, 1][[1]]}, {y, 2,       Dimensions[testData, 2][[2]]}], 1];          ListContourPlot3D[plotData, Contours -> 1,       AxesOrigin -> {DateObject[{2014, 4, 30, 0, 0, 0.`}], 0, 0},       AxesLabel -> {"Date", "Bins", "%"}]


parameter optimization

Does anybody know of any tutorial material that explains how to use Mathematica to fit parameter values used in a set of ordinary differential equations to experimental values stored in a comma separated variable (CSV) file, and assumes very basic Mathematica programming experience? The ordinary differential equations are required to provide a time course simulation of the variables that is fitted to experimental data, in order to use the parameter values to predict hypothesis on the behavior of the system. Thanks for any assistance.


How to draw a graph about the FourierTransform of a 2D Function?

Here is a 2D function, and it cannot be calculated by the `FourierTransfrom`               n = 2; δ = 0.2;     p[x_, y_] = Cosh[n*Sqrt[2 Pi]*δ*Sqrt[x^2 + y^2]]*Exp[-((δ^2*(x^2 + y^2) + 2 n^2*Pi)/2)];          p[x,y] ContourPlot      ![enter image description here](http://i.stack.imgur.com/9xkKS.jpg) and my problem is how to draw a graph about its `FourierTransform` Function? Here is an example: if I have a function that can be calculated by `FourierTransform` like below:               n = 2; δ = 0.2;     p[x_, y_] = Cosh[n*Sqrt[2 Pi]*δ*x]*Cosh[n*Sqrt[2 Pi]*δ*y]*Exp[-((δ^2*x^2+ 2 n^2*Pi)/2)]*Exp[-((δ^2*y^2+ 2 n^2*Pi)/2)];     uu1[tx_, ty_] = FourierTransform[p[x, y], {x, y}, {tx, ty}];     ContourPlot[p[x, y], {x, -40, 40}, {y, -40, 40}]     ContourPlot[uu[tx, ty]^2, {tx, -0.5, 0.5}, {ty, -0.5, 0.5}]      we will get the answer below: ![enter image description here](http://i.stack.imgur.com/wg64K.jpg) And here, I suppose the function p[x,y] can not use `FourierTransform` ,I can use the function `Fourier`               data = Table[p[x, y], {x, -40, 40, 0.4}, {y, -40, 40, 0.4}];     ListDensityPlot[Re[Fourier[data]]]      ![enter image description here](http://i.stack.imgur.com/8VsWK.jpg) but the answer is not I wanted! I don't know why? and I hope I can get help from you!


How do I solve coupled ordinary differential equations?

I have four coupled ODE's. I am not sure how to plot and solve them using Mathematica. I won't give the exact problem, but the following is something analogous: The equations               a= x'[t]     a'=-c1*x[t]/c2+c1*(y[t]-x[t])/c2     b=y'[t]     b'=-c1*(y[t]-x[t])/c2      Can be written as               x'[t]= -c1*x[t]/c2 + c1*(y[t]-x[t])/c2     y'[t]= -c1*(y[t]-x[t])/c2      The question is, now how do I use these in NDSolve to give solution and later a plot as well? I have initial conditions to plug in, but I am hung up on how to solve these coupled equations... Thank you in advance. _Edit_ I do not know how to input this into NDSolve.


Retrieving other information on CountryData

The following input will produce some answers, however how do we find out other details, such as the specific year the result corresponds to, as well as the source from which the data is obtained?               CountryData["France", "MaleElderlyPopulation"]          CountryData["Australia", "MaleElderlyPopulation"]


Avoiding MainEvaluate in a CompiledFunction to fetch global variables

I'm trying to write a simulation using Mathematica 8.0. Since I will most likely be doing the same operation over and over again, I'm trying to `Compile` whatever I can. However, I've been having problems avoiding `MainEvaluate` calls when I define `CompiledFunction` objects which refer to global variables. A simplified sample of what I'm trying to use is:               g = 4.49*^3;     m = 1.;     s = 1.;     ϵ = 2.;     sAcceleration = Compile[{{sPosition, _Real, 1}},        (-g (m + s))/(sPosition.sPosition + ϵ*ϵ)^(3/2) sPosition];      I have also tried wrapping the whole thing inside a `Module`, to no avail:               sAcceleration2 =  Compile[{{sPosition, _Real, 1}},       Module[{gg = g, mm = m,  ss = s, ϵϵ = ϵ^2},         (-gg (mm + ss))/(sPosition.sPosition + ϵϵ)^(3/2) sPosition]];      They seem to run just fine. However, when I take a look at what the `CompiledFunction` is trying to do internally using `CompilePrint`               << CompiledFunctionTools`     CompilePrint[sAcceleration]     CompilePrint[sAcceleration2]      I get, respectively > 1 R1 = MainEvaluate[ Function[{sPosition}, g][ T(R1)0]] > > ... > > 3 R1 = MainEvaluate[ Function[{sPosition}, m][ T(R1)0]] > > 4 R4 = MainEvaluate[ Function[{sPosition}, s][ T(R1)0]] > > ... > > 7 R6 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > 8 R7 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > ... and > 1 R1 = MainEvaluate[ Function[{sPosition}, g][ T(R1)0]] > > 2 R3 = MainEvaluate[ Function[{sPosition}, m][ T(R1)0]] > > 3 R4 = MainEvaluate[ Function[{sPosition}, s][ T(R1)0]] > > 4 R6 = MainEvaluate[ Function[{sPosition}, ϵ][ T(R1)0]] > > ... Since I will most likely be toying with different values for these variables in different simulation runs, but they will be held constant within a given run, can I avoid both `MainEvaluate` and feeding these variables to my function as additional arguments? Thanks in advance.


Text as plot axes values

I have some chemical data that I am plotting using `ListLogPlot`.               data={{2776.37,2016.64,1483.51,1027.35,500.878,94.1385,310.402,282.548,            257.886,224.359,218.688,209.312,215.776,198.78},            {40.5063,24.633,12.069,8.3151,6.35135,15.0977,8.74372,15.5125,9.34959,            9.70696,11.125,12.1457,10.8075,9.7561},           {113.08,124.633,75.9698,59.5186,55.9459,7.81528,57.4372,69.5291,80.4878,            88.2784,105.563,127.935,148.571,148.78}};          ListLogPlot[data, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/MCO17.png) I want to replace the x-axis tick values with the associated elements. e.g. replace 1,2,3,...,14 with               xaxis= {"La","Ce","Pr","Nd","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu"};      Any suggestions on how to achieve this? Is there another plot function that I should be using?


Odd colourization for FourierParameters. UI bug?

The Mathematica UI colourizes the FourierParameters in the following               Clear[x, y]     g[x_, y_] = x^2 y ;     f[x_, y_] =      FourierSeries[x^2 y, {x, y}, {4, 4}, FourierParameters -> {1, 2 Pi}]      as in the following ![colorized input](http://i.stack.imgur.com/F7FOh.png) "Why color" on right click says it is excess arguments, but the resulting series computation matches nicely, and returns without error, so this seems like a UI colorizing bug to me.


Timing Total crashes kernel

Here is a simple test function               test[n_] :=       Module[{i = 0}, Total[Nest[{++i, #}&, {0}, n], -1]]      On my system V9.0.1 running OS X 10.6.8 and with a clean kernel, the following works               Timing[test[26198]]      > >     {0.106564, 343180701} >   but then immediately evaluating               Timing[test[26199]]      fails. I get a beep and Help > Why the Beep?... shows ![alert.png](http://i.stack.imgur.com/o0elR.png) Can anybody verify this on another system different from mine? Can you cast any light on why it happens? I will submit a bug report to WRI if this is not just peculiar to my system.


How to update package?

when I use `<< PhysicalConstants`` I get the message like :General::obspkg: PhysicalConstants is outdated... see the Compatibility Guide for more infomation... The question is how to update it? My version is MA9.0.


Plotting surfaces described by redundant variables - Alternatives to use of Eliminate + ContourPlot3D

Suppose I want to plot a surface defined by equations involving redundant variables. Consider, for example, plotting the surface defined by the equations: $$ \left\\{ \begin{array}{l} \cos x + \sin y = z^2+\cos w \\\ \sin w=0 \end{array} \right.$$ for $-2 \pi \leq x \leq +2\pi$, $-2 \pi \leq x \leq +2\pi$, $-2 \leq z \leq +2$. I have used the following code for this:               eqs = Flatten[ Quiet @ Eliminate[{Cos[x] + Sin[y] == z^2 + Cos[w], Sin[w] == 0},                                       {w}]];     ContourPlot3D[ Evaluate[eqs], {x, -2 π, 2 π}, {y, -2 π, 2 π}, {z, -2, 2}]      It works quite well for simple examples like this, but it is not a good alternative for similar problems involving more complex equations (or more redundant variables).   Is there a more efficient algorithm for plotting surfaces defined this way?


Problem with manipulation and plot

I want to make my function trace the hypotrochoid through one period of its motion and trying to change the color of the trace, color of the radius, and change the color of the dot on it so I can view it easier I have came up with this following function                hypotrochoid[a_, b_, h_,t_] := {(a - b) Cos[t] + h Cos[(a - b)/b t], (a - b) Sin[t] -      h Sin[(a - b)/b t]};           myfigure[a_, b_, h_]:=Manipulate[ParametricPlot[hypotrochoid[a, b, h, t], {t, 0, c*2 \[Pi]},PlotRange -> {{-(a + b + h + 1/4), a + b + h + 1/4}, {-(a + b + h + 1/4), a + b + h + 1/4}}], {c, -1, 1}]      Though when I test it on               myfigure[5, 1, 1/2]      Nothing shows up on this testing. I know I do not have the coloring but not certain of the syntax require.


How to define a list that contains all primes less than x?

how can I define my own list in which I have all primes less than x?


CUDAFunctionload error

I am trying to get `CUDAFunctionLoad` to work with _Mathematica 9.0_. I installed the latest clang and the _Nvidia Tools 6.0_. but I keep getting the error message: > >     CUDAFunctionLoad::cmperr: "-- Message text not found -- >                                  "clang: error: unsupported option > -dumpspecs" " >   I note that others have the same problem. i asked _NVIDIA_ and _Wolfram Reaserch_ for help and they have not come up with any solution so far, although they suspect the problem is that clang in latest version is not compatible with _Mathematica 9.0_. Any help, insights or leads would be very much appreciated.


Matrix multipication

Is this matrix multiplication is possible? Microsoft mathematics gives me a answer for it? How it could be a correct? If we need multiple two matrix, number of rows and columns should be equal. So how it is possible? ![Is that possible?](http://i.stack.imgur.com/EI76V.png)


Can `Array` work as `Loop`?

I got Mathematica code from my friend:               n = 100     l = 0     gw = GaussianQuadratureWeights[n, 0, 2]     (*the result of gw maybe like this {{0.000286273, 0.000734634}, {0.00150805, 0.00170939}, {0.00370487, 0.00268393},...}}*)     J = Array[SphericalBesselJ[l, gw[[#, 1]]] &, n]      The first, I'm not sure with syntax because i'm not a Mathematica user. But in my understand this code just try to create Spherical Bessel array by using 2 parameters such as               l just a constant. its value is 1           qw this is two dimensional array       On Mathematica code up there for `gw[[#, 1]]` i think they just tried to call {{0.000286273, 0.00150805, 0.00370487, ...}} and put them one by one to second parameters of SphericalBesselJ . And finally, we will get a one dimensional `J` array If write it as pseudo code from my understanding it might be like this:               l = 1     n = 100     gw = gaussiannode(100) //generate 100 gaussian nodes     for (i==1, i<=n, i++):         J[i] = SphericalBesselJ(l, gw[1][i])      My question is "Is it the Mathematica code up there equivalent to my pseudo code?" My point is just want to know `Array` can work as `Loop` or not? if not please correct Mathematica code up there to the right way by using loop.


Details about Symbolize

When I'm using Symbolize function, there are some details that I'm not sure. For example:               << Notation`     Symbolize[Subscript[q, 1],Subscript[q, 2]];(*I want to declare two symbols with subscript*)        1. Can I type the name "Symbolize[...]" instead of using the Notation Palette？It seems there is a little distinction, Notation Palette has a colored region: ![enter image description here](http://i.stack.imgur.com/pX5Yj.jpg)   2. Does "Symbolize" support multiple inputs, such as the above example? What if i want to declare as many as 100 variables with subscript? I want to do differentiation on q1.               Subscript[q, 1] /:D[Subscript[q, 1], t, NonConstants -> {Subscript[q, 1]}] :=      Subscript[dq, 1];     D[Subscript[q, 1]^2, t]      I expect to get 2*q1*dq1, but Mathematica gives 0. Why is that?


Under OS X, is there a way to view graphics output when running in the command line?

Being a long time unix shell person, I prefer Mathematica's command line interface, over the notebook. (command history, etc...) It just learned that on OS X, the cli is available as MathKernel. What I'm wondering now is, is it possible to open graphics (and/or animations, sounds, etc) result, from within the command line?               In[16]:= Plot[Sin[x], {x, -Pi, Pi}]          Out[16]= -Graphics-      I would like to be able to view output #16.


Simplifying expression with patterns (Replace)

**Q1** : I need to simplify some algebraic expression, according to particular pattern, namely: \begin{equation*} x^m = \left\\{ \begin{array}{ll} 1 & \text{if } m \text{ is even} \\\ x & \text{if } m \text{ is odd} \end{array}\right. \end{equation*} for example: $$ a x^3 + b x y-c x^7 y^2 $$ should be simplified to $$ ax + bxy - cxy^2 $$ I need something like:               a x^3 + b x y - c x^7 y^2 /.{x^_ -> ... }      but, that will recognize the parity of the each power in the expression. **Q2** : How one can get only one term in the sum? For example, in the example there are three terms $$ a x^3, \ b x y, \ -c x^7 y^2 $$ is there any possibility to decompose the full expression to               A = {a x^3, b x y, - c x^7 y^2}


Buttons Which Change Color, Each Time Pressed

I need to have 100 buttons, which their color is defined by the parity of number of times they are pressed: If they're pressed an even number of times their color is blue, and otherwise red. I don't know how to use 'Button' and 'Dynamic' to do so. Thanks in advance.


Rounding values

In _Mathematica_ 8 when I enter `1 - 0.99 - 0.01` I get `8.67362*10^-18` instead of zero. How do I fix this problem? I am getting imaginary solutions because of this error in my program.


Moving maximum function?

How can I construct a moving maximum function? For example, if I have a list of 12 values: `{ 5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7 }` and I want to maximize over 3 values then the expected result would be: `{ 6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7 }`.


Quick way to invert a fraction

Over the years of using Mathematica, I find myself doing something along the lines of rewriting this: $\frac{[A^-_F]}{[A^-_U] + \frac{[H^+][A^-_U]}{\kappa_1}}$ as this: $\frac{[A^-_U] + \frac{[H^+][A^-_U]}{\kappa_1}}{[A^-_F]}$ on a constant basis. In other words, just switching the numerator and the denominator of a fraction. Copying and pasting is kind of a drag, especially when you have to do it many times, and Mathematica can be kind of persnickety when it comes to highlighting things. Is there a built in keyboard shortcut that can invert fractions automatically? If not, is there a way for me to build a custom keyboard shortcut in order to do so?


Pattern matching

This is a very simple question I hope you can help me with. I am experimenting with pattern matching. I want to write a pattern for a difference between two symbols, `a-b`, that recognises cases like `{a-2,a-2b,f[x]-g[x]}` as special cases while rejecting cases like `{a,a+b,a+2b,f[x]+g[x]}`. So I started experimenting Now when I write               MatchQ[a + 2b, a_ + b_]      It returns `True` When I write               MatchQ[a - 2b, a_ - b_]      It returns `False`, which surprises me given the first code snippet returns `True`. I imagined my question could be solved by:               mypattern = a_ - _Integer. b_.       But that doesn't seem to work. Any pointers greatly appreciated.


Sorting a list with secondary criterion

Is there an easy way to sort a list on multiple levels of criteria? By this I mean, first the list should be sorted according by criteria A (the same as using the usual sort function, `Sort[list, A[#1] < A[#2] & ]`. I am a big fan of using the pure ordering function in Sort.). However, then I want to have elements with the same value for criterion A to be sorted within their class by criterion B. In general, I would like to do this to an arbitrary depth of criteria. An example would be, given a set of colored blocks, first sort the blocks alphabetically by shape, then (maintaining that all the squares come before all the triangles) sort each cluster of shapes alphabetically by their colors. (Blue square, Purple square, Red square, black triangle, orange triangle, yellow triangle, etc.)


plotting a {{Latitude,Longitude}} list on top of a GIS shapefile

I have a dataset composed of points specified in {Latitude,Longitude} format. Call it `latlong` for the purposes of this question. It displays properly with               Graphics[{Point /@         Map[GeoGridPosition[GeoPosition[#],             "Mercator"][[1]] &, {latlong}, {2}]}]      I also have a shape file that contains the boundaries of the counties in which the `latlong` points reside. If I query `Import[demo.shp", "CoordinateSystemInformation"]`, I get               "GEOGCS" -> {"GCS_North_American_1983",        "DATUM" -> {"North_American_Datum_1983",          "SPHEROID" -> {"GRS_1980", 6.37814*10^6, 298.257}},        "PRIMEM" -> {"Greenwich", 0.}, "UNIT" -> {"Degree", 0.0174533}}      and if I just `Import` the shape file, it displays correctly on screen. I would like to display the points from `latlong` within the county borders from `demo.shp`. I have not been able to figure out how. I appreciate that this is as much a GIS question as it is a Mathematica question, but I hope somebody here can help.


Threading over a list of lists of lists and a list of atomic expressions

Although I solved the following problem using `MapThread`, I'm curious about why `Thread` does not work as I expect it to here. Given two lists of length n, where the first list is a list of lists of lists and the second is a list of atomic expressions, such as:               list1 = {{{1, 2}, {3, 4, 5}}, {{1, 3, 5}, {9, 8}}};     list2 = {"a", "b"};      and where `list1[[n]]` can contain 1 or more lists of atomic expressions. I would like to create a single list that places the nth element of the second list at the end of every sublist of `list1[[n]]`, producing:               {{{1, 2, "a"}, {3, 4, 5, "a"}}, {{1, 3, 5, "b"}, {9, 8, "b"}}}      I first tried the following               appendTo[ll_, item_] := Map[Append[#, item] &, ll];     Thread[appendTo[list1, list2]]      But this returns:               {{{1, 2}, {1, 3, 5}}, {{3, 4, 5}, {9, 8}}, {{"a", "b"}, {"a", "b"}}}      even though threading an undefined function seems to produce the right expressions:               Thread[f[a, b]]     {f[{{1, 2}, {3, 4, 5}}, "a"], f[{{1, 3, 5}, {9, 8}}, "b"]}      `MapThread` works fine:               MapThread[appendTo, {list1, list2}]     {{{1, 2, "a"}, {3, 4, 5, "a"}}, {{1, 3, 5, "b"}, {9, 8, "b"}}}      So why is `Thread` producing the behavior shown above instead of giving the same result as `MapThread`? Threading `Rule` on the same lists also produces what I expect:               Thread[Rule[list1, list2]]     {{{1, 2}, {3, 4, 5}} -> "a", {{1, 3, 5}, {9, 8}} -> "b"}


Mathematica vs. $\LaTeX$? Replacement for Legacy "Authoring Tools" package?

I'd rather write in Mathematica than in $\LaTeX$, but it's not really practical, especially for big works (> 100 pages) without good tooling. I'm just starting to look into what's available for big works, but I haven't found any guidelines later than 2005 (e.g. this). The specific things I need are numbering for all kinds of cells with cross- referencing, intelligent DIFFing (text diffing of notebooks doesn't work because every cell has gobs of timestamp info that is always different even if the contents of the cell aren't different), Bibliography, tables of contents, etc. I.e., $\LaTeX$-level tooling. I've been scrounging around my grooveyard of forgotten favorites, that is, my big hoard of legacy books & notebooks & CD-ROMs, and there are many references to an old package called "Authoring Tools". For instance, a book by Heiki Ruskeepaa called "Mathematica Navigator" was written using Authoring tools. The book was written around Mathematica Version 5, and we're now at version 8.0.4. Then there is Michael Trott's Eulerian 4-volume opus "The Mathematica Guidebook," which appears to have been written entirely in MMA with Authoring tools. Would anyone happen to know if Authoring Tools has been replaced by something similar but of another name? Superceded by built-in functionality? Ditched forever? Is there some other guidelines, conventions, recommendations, or other zeitgeist for writing big works in MMA?


How to find out the (current) free memory on the system?

Is there any way in Mathematica to find out the currently free memory on the system Mathematica runs on (like the utility `free` shows on the command line)? I've found out functions to show the memory occupied by Mathematica itself, but of course there are also other programs running on the system, taking their share of memory, so that number is not sufficient to estimate the free memory. The background is that currently if I do something which might fill up my memory (and I don't forget to do it), I call `free` by hand, subtract a safety margin, and then use `MemoryConstrained` in order to prevent the memory to get completely filled up (with quite unpleasant consequences). I'd like to automate that. While I certainly could call `free` from Mathematica and parse its output for the number, I'd like to avoid that if I can (who knows if the next system update makes subtle changes to `free` and then the parsing fails to give the correct number).


Bug with SparseArray selector in Pick

I have created a notebook with two cells. This is the content of the first:               g = Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 1 \[UndirectedEdge] 3, 1 \[UndirectedEdge] 4, 4 \[UndirectedEdge] 5, 4 \[UndirectedEdge] 6}]      And this is the content of the second:               g     listDegree = VertexDegree[g]     vl = VertexList[g]     nodeMaxDegree = Pick[vl, listDegree, Max[VertexDegree[g]]][[1]]     aM = AdjacencyMatrix[g];     vLM = aM[[VertexIndex[g, nodeMaxDegree]]];     nN = Pick[vl, vLM, 0]      If I evaluate the second cell (after processing the first) for a **second** time:   1. the first time no problem, the results are correct;    2. **the second time the vertex list of`g` is inexplicably wrong but the graph remain correct!!** I don't understand the cause because the graph `g` is never touched. Thanks in advance


Numbering of cases implied by a subset of Boolean vectors

In the course of a programming problem I stumbled upon the following sub- problem. Given an arbitrary, but fixed, number of Boolean variables, I would like to be able to pick a subset of the variables and combine them in such a way that I get a numbering of the unique cases that the subset possesses. To give an example, let $A, B, C$ be three Boolean variables. The truth table has the form $$\begin{array} {|c|} \hline A & B & C \\\ \hline 1 & 1 & 1 \\\ \hline 0 & 1 & 1 \\\ \hline 1 & 0 & 1 \\\ \hline 0 & 0 & 1 \\\ \hline 1 & 1 & 0 \\\ \hline 0 & 1 & 0 \\\ \hline 1 & 0 & 0 \\\ \hline 0 & 0 & 0 \\\ \hline \end{array}$$ Take the subset of variables to be $\\{A,C\\}$. It would be great to get a numbering of the different cases implied by $A$ and $C$ in the following way, $$\begin{array} {|c|} \hline A & C & Numbering \\\ \hline 1 & 1 & 1 \\\ \hline 0 & 1 & 2 \\\ \hline 1 & 1 & 1 \\\ \hline 0 & 1 & 2 \\\ \hline 1 & 0 & 3 \\\ \hline 0 & 0 & 4 \\\ \hline 1 & 0 & 3 \\\ \hline 0 & 0 & 4 \\\ \hline \end{array}$$ What would be the most efficient way to getting the vector containing the numbering of the different cases? I thought of generating the truth table, combining the truth values of the chosen variables into a unique symbol, i.e. the string consisting of the respective truth values, 1 1 -> "11", eliminating the redundant symbols in that vector and mapping back the indices of the symbols in that smaller vector to the symbols in the vector containing the redundant symbols. However, that seems to be horribly inefficient. Is there a Mathematica- specific way to optimize this, possibly one which would allow it to be extended to multi-valued variables? **Edit** : It seems to be inefficient because the choice of the subset and the total number of variables uniquely determine the numbering vector.


how to apply a function to a list of tables

I have several files, and I want to extract for each of them a table, and then select just numbers, and keep only rows with five elements. My code works fine during import               data = Import[#, "Table"] & /@     FileNames["*.txt",     NotebookDirectory[]] ; (*This line import only tables of numerical     values from txt files*)      but if I want to apply selection of numbers to my list of tables, simply doesn't work,               Select[#, NumberQ[#] & ] & /@ data      and I have to specify a level to make it work,               Select[#, NumberQ[#] & ] & /@ data[[1]]      and I am supposed to automate this for twelve tables, rather that typing for each element. Any suggestions what I am doing wrong? I think that my list of tables needs to be specified different, but I don't know how.


Populate an upper triangular matrix from a vector of elements

What is the best way to populate an upper triangular (or alternatively: lower triangular or symmetric) matrix from a vector of elements? This example input:               {1, 2, 3, 4, 5, 6}      should give               {{0, 1, 2, 3},      {0, 0, 4, 5},      {0, 0, 0, 6},      {0, 0, 0, 0}}      or alternatively               {{0, 1, 2, 3},       {1, 0, 4, 5},       {2, 4, 0, 6},       {3, 5, 6, 0}}      or even               {{0, 0, 0, 0},      {1, 0, 0, 0},      {2, 3, 0, 0},      {4, 5, 6, 0}}      This problem has many solutions of course. I'm looking for the best (criteria: most elegant/readable, shortest, fastest) ones. The input has length $\binom{n}{2} = \frac{n(n-1)}{2}$. Consider $n$ known. Feel free to use any version 10 functionality.


Solving for the time-evolution operator in a periodically driven system

I am looking at the Hamiltonian $$H(t)=\begin{pmatrix} 0 & e^{i\Omega t}\\\ e^{-i\Omega t}& 0\end{pmatrix}$$ I am trying to solve for the unitary operator $U(t,0)=\mathcal{T}\exp(-i\int_0^t dt'\, H(t'))$, where I have transformed this into $$ U(t,0)\approx\prod_{n=0}^{N}\exp\left( -iH(ndt)dt \right) $$ To calculate it with _Mathematica_ , I then implemented a similar code to the one found here: Solving a time-dependent Schroedinger equation. I changed it a little, so that my code reads               U[H_,  ti_,  tf_,  n_] :=        Module[{dt = N[(tf - ti)/n], Value = ({{1, 0},{0, 1}})},          Do[Value = Dot[MatrixExp[-I*H[t]*dt], Value], {t, ti, tf, dt}];          Value]      I then evaluated               U[λ/2 {{0, Exp[I Ω t]}, {Exp[-I Ω t], 0}}, 0, 20, 100]      However, this just gives me a long product of matrix exponentials: > >     MatrixExp[(0. - 0.2 I) {{0, 1/2 E^((0. + 20. I) Ω) λ}, {1/2 E^((0. - 20. > I) Ω) λ, 0}}[20.]]. >     MatrixExp[(0. - 0.2 I) {{0, 1/2 E^((0. + 19.8 I) Ω) λ}, {1/2 E^((0. - > 19.8 I) Ω) λ, 0}}[19.8]] ... >   I really want to write it in the form $$ H(t)=P(t)e^{-iH_Ft} $$ where the function $P(t)$ has a period of $T=2pi/\Omega$. This way, I can simply take $t=T$ and take a matrix log and get $H_F$. How can I get my product in this form and thus find the value of $H_F$? Am I doing something wrong with the code, or am I just missing a step?


Removing non-word characters from a string

I'm trying to get a list of words from a string. Sounds like an easy task for Mathematica. I have the following code:               text = "Merçi d'avoir pris le temps.";     ToLowerCase[#] & /@ StringSplit[text, Except[WordCharacter] ..]      However, the output is               {"merçi", "d", "avoir", "pris", "le", "temps"}      and not               {"merçi", "d'avoir", "pris", "le", "temps"}      because the `'` is not a word character. Hence, I'd like to ignore the `'`, just like the `-`. Any idea on how to do that?


Higher derivative

Is there more efficient way to rewrite this code in order to compute 2nd and higher derivatives of r=sqr{x^2+y^2+(z-a)^2}?               Table[D[r[x, y, z], xIN[[i]]] -> xIN[[i]]/r[x, y, z], {i, 1, 3}]      Thank you for your help!


Solution Curves and Order of Evaluation Question

I'm new to Mathematica, so I thought I'd try to exercise some solution curves. Consider a simple first order ODE: $y'(x)=\cos(x)$. We know the solution will be of the form $y = \sin(x)+c$ I tried to use a `Table` function to generate a list of solutions that I'd then use with the `ContourPlot` function as follows:               solns = Table[y = Sin[x] + i, {i, -5, 5}]      Then use `ContourPlot`:               ContourPlot[y == solns, {x, -5, 5}, {y, -5, 5}, FrameLabel -> Automatic]      But examine the label of the ordinate! It appears as:               sin(x)+5      The trouble lies in the definition of `solns`; when `y=Sin[x]+i` is used, for some reason the output is still the correct list that we expect:               {-5 + Sin[x], -4 + Sin[x], -3 + Sin[x], -2 + Sin[x], -1 + Sin[x],       Sin[x], 1 + Sin[x], 2 + Sin[x], 3 + Sin[x], 4 + Sin[x], 5 + Sin[x]}      However `y` is set equal to the last value in this list as an unintended consequence. My question here is several fold:   1. Is `y` being set to each element in the output list in turn, and only the last value is being used?   2. Why didn't the output after I had evaluated this function show this sort of 'side effect'? I'd have expected it to be on the 'output' line associated with the Table function.


How to test if optional argument has been given?

I understand that the last call (`f[1]`) returns `True` because `arg` does not exist and thus `SameQ` tests a single argument (`"ArgValue"`) which always returns `True`. Therefore no comparison can be done here at all. Now it is not possible to use `ValueQ` either, as `arg` does not exist, and thus it has no value so `ValueQ[arg]` would evaluate to `ValueQ[]`. How to test whether `arg` exists or not? I am aware that I can define another signature for just one argument (`f[first_] := ...`), but I want to solve it inside the function, if it is possible.               ClearAll[f];     f[first_, arg___] := (arg === "ArgValue");     {f[1, "ArgValue"], f[1, "NonArgValue"], f[1]}      > {True, False, True}    **UPDATE** In general, I want to test whether any optional argument was passed to `f`. Since `f` is in reality a quite large function with a lot of optional arguments and occasionally called with a quite complex argument structure, I decided that I do not want to create complex patterns for each case (i.e. a different signature). Insted I check inside `f` whether any extra argument was passed or not - which in tha baseline case means that there should be **no** extra argument. Thus `f` shouldn't return `False` in reality for only one argument (i.e. it still should perform some computation on its single argument), this is only for testing purposes here. A more realistic function would look like this:               ClearAll[func];     func[first_, arg___?overcomplicatedArgumentStructureQ] := Module[{...},         (* heavy computation *)         If[argExistQ[arg], (* do this *), (* do that *)];         (* some more heavy computation *)     ];


How to prevent the welcome screen from showing up after I close my last notebook? (Ubuntu 11.10, MMA 8.0.4.0)

I would like to prevent the welcome screen from showing up after I close my last notebook. This is not an issue on my Windows machine, so I suspect it is system dependent. I am running Ubuntu 11.10. Any ideas? Edit 1: This only happens when I close the last notebook by clicking on the "x" button. As Szabolcs pointed out, I can avoid this issue using File -> Quit or Ctrl-Q. This seems to be a Linux-specific problem.


How to develop an Import/Export converter for Compress[]ed data?

Mathematica has a cross platform data exchange format, WDX. Unfortunately importing or exporting large data from/to WDX is very slow. Using MX files is very fast, but they are not compatible across different computer architectures (32 or 64 bit). Sometimes it is suggested to `Compress` the data and write out or read it in manually. **Question: How can we extend`Import` and `Export` to allow convenient and fast importing/exporting of arbitrary Mathematica expressions using `Compress`?** The aim is to define a fast-to-load format, and make importing from it as easy as `Import["data.mmaz"]` or `Import["http://server.com/myfile.mmaz"]`, by integrating it into the `Import`/`Export` framework. Ideally the format should be recognized based on a file extension. If there is a better solution than using `Compress`, I'd like to hear it!


How to do http POST in Mathematica?

The Import command lets you do a HTTP GET from a URL, like this               Import @ "http://merkosoncampus.com/wp-content/uploads/2011/05/higgs-boson.jpg"      This sends an HTTP GET request to the server and presumably parses the response according to some rules for inferring the type of data, from the content or from the extension ".jpg" or whatever. Listening on the socket, we see something like this               GET http://merkosoncampus.com/wp-content/uploads/2011/05/higgs-boson.jpg HTTP/1.1     User-agent: Mathematica/8.0.4.0.0 PM/1.3.1     Host: merkosoncampus.com     Proxy-Connection: Keep-Alive      whereas what I want is something along the lines of               POST http://foo.bar.com/myService HTTP/1.1     User-Agent: Mathematica/8.0.4.0.0 PM/1.3.1     Host: foo.bar.com     Accept: */*     Connection: Keep-Alive     Content-Length: 76     Content-Type: application/x-www-form-urlencoded          { "myJsonStuff" : {"number" : 1} }      I looked for options in `Import`, praying for something like `Method->"POST"`, but didn't find anything useful. I'd be grateful for clues, experience, ideas, sample code. In the mean time, I intend to work around it by writing my desired JSON to a file and using curl to POST it, but it's way sub-optimal.


How to get rid of Panel margins?

I have a feeling that there is something wrong in general with _Mathematica_ 's way of dealing with margins and spaces among/around objects in `Graphics`, `Grid`-s, and alike. This is a constant problem for me, and for many others I assume. I usually end up to do some pixel-pushing or other workarounds, but this is getting more and more annoying with every year. Consider the following example:                Panel[          Graphics[{Circle[]},             ImageSize -> 300, ImageMargins -> 0, ImagePadding -> 0,              Frame -> True, FrameTicks -> None, PlotRange -> {{-1, 1}, {-1, 1}},              PlotRangePadding -> 0, Background -> White,              Method -> {"ShrinkWrap" -> True}],          FrameMargins -> 0, ImageMargins -> 0, ImageSize -> All,           Background -> Lighter[Pink, .6]]      ![Mathematica graphics](http://i.stack.imgur.com/KwgIS.png) I have two questions related to the code above: **Q1** : How to get rid of the pink frame margin without setting `Panel`'s `FrameMargins` explicitly to a negative number? I would assume, a zero-width margin is ... zero-width. **Q2** : Why does the ~~left~~ right and bottom part of the `Frame` of the internal `Graphics` disappear and how can I prevent it? **Edit** Various workarounds can be used, e.g. `Pane` or `Framed`. The problem with these is that they don't have the look and feel `Panel` provides:               CreateDialog[Pane[{1, 2, 3}], WindowTitle -> "Pane"];     CreateDialog[Framed@Pane[{1, 2, 3}], WindowTitle -> "Framed Pane"];     CreateDialog[Panel[{1, 2, 3}], WindowTitle -> "Panel"];      While `Panel` looks good in a dialog window, the other two do not. ![Pane, Panel, Frame](http://i.stack.imgur.com/WJyh3.jpg)


How to use button to evaluate a cell

I would like to create a button that when I click it it evaluates a cell containing a manipulate code. Also, I would like another button that when I click the output of manipulate disappears. How can I do it ?


Explanation about RegionFunction and MeshFunctions?

In the link, `ParametricPlot3D`, consider the example( _Variation on the Spheres_ ) given in the _Neat Examples_ section. ![enter image description here](http://i.stack.imgur.com/GdCTm.png) Can someone please explain how `RegionFunction` and `MeshFunctions` are working out there?


Printing a string in a Mathematica script

Here's a simple script saved in the file `hello`               #!/usr/local/bin/MathematicaScript -script     Print["Hello world"]      I can then run this file using `math -script hello` or, if the file is set to be executable, `./hello`.   In Windows or OSX, run `MathKernel -script hello` It prints > "Hello world" to the terminal. How can I change this so it does not print the quotation marks?


Position of a pattern-matched part of an expression

**What you have**   1. A pattern, with certain part of it labeled  As an example — Label: `wally`              pattern = h : HoldPattern@f[x, __, 3[5], wally_, y]        2. An expression that matches a pattern such as:              expr = f[x, 9, v, h[v], 3[5], v, y]      **What I want** The position of the part of the expression `expr` that matched the label `wally`. In the above example, that would be               gimmeWhattaWanna[expr, pattern, wally]     (* {{6}} *)      **Note** If the labeled pattern is a sequence such as `wally__`, either finding the position of the first, or the first and last, are acceptable. If the labeled pattern is repeated such as in `f[wally_, 2, wally_]`, then a list of the positions seems the most natural solution. However, a solution that limits itself to non-repeated labels, or even non-sequence ones is useful.