title: Creating diagrams for category theory

text: Lately I've been doing algebra and I have found myself drawing a bunch of diagrams when I attempt to solve a problem. Most of the diagrams are very simple so I thought, I bet I can do this in _Mathematica_ and include these pictures in a nice document. What I would like to do is create diagrams like the ones found in category theory: ![img1](http://i.stack.imgur.com/tPUJa.png) ![img2](http://i.stack.imgur.com/vSYNi.png) Here is an attempt based on a solution provided by Mr.Wizard               vertex = {         {White, Disk[#2, 0.04]},         Text[#, #2]         } &;     GraphPlot[{        {"A" -> "B", "f"},        {"A" -> "C", "h"},        {"B" -> "C", "g"}        },       DirectedEdges -> True,       VertexLabeling -> True       ] /. {Text -> vertex, Framed -> (# &)}      ![img3](http://i.stack.imgur.com/MeJJ0.png) I like the idea of how in `GraphPlot` you can define the vertices and the labels. Unfortunately I'm still not very savvy on controlling many aspects of the `Graphics`. Does anyone know how to create diagrams like the ones I'm attempting to draw? It would be awesome if the font size could be specified. ## Edit: As belisarius pointed out: > Text length and font size should be considered with care As requested by Mr.Wizard, here is are some interesting diagrams: http://scientopia.org/blogs/goodmath/category/good-math/category-theory/ ![imglink1](http://scientopia.org/img-archive/goodmath/img_11.jpg) ![imglink2](http://pdp7.org/blog/wp-content/uploads/2011/01/Screen- shot-2011-01-24-at-16.11.06-.png) The second picture can be found here A quick search on google images for "category theory diagrams" will give you some other diagrams including the ones I have put in here. It seems based on the figures that most of them involve simple rectangles with diagonal lines. In some cases some lines might be curved but this can all be done with straight lines. Since the arrangement of the lines is up to personal choice it would be good to have a solution in which we can move the vertices locations, a similar functionality should be done with the edge labels. I picture an edge label as an image that can rotate around a point in a line. That way we can select a position in the line and the position angle. In most cases this angle is multiples of 45 degrees.


title: Checkbox Matrix

text: Is it possible to create a dynamically changing binary $n \times n$ matrix $A$, which appears to the user as a $n \times n$ matrix/table of checkboxes and the user can change the entries of $A$ by checking or unchecking these checkboxes? If yes, what would be the easiest way?


title: Building sparse array from packed arrays

text: Suppose I have two _large_ packed arrays `a` and `b`, that respectively contain the position of the elements of a _square_ matrix (i.e. `a` has the explicit form {{1,2},{2,3},{3,4},...}) and the value for each matrix element (i.e. `b` has the explicit form {0.2938,0.091,-0.4984,...}). **Now, is there a way to build a sparse array from`a` and `b` without having unpacking in the internal process of creating the sparse array ?** **Refining the question + example below:** The usual `SparseArray[a->b]` command seems have some unpacking in the process although a and b are unaffected. Really, what I'm concerned about is : suppose you have `memA=ByteCount[a]` and `memB=ByteCount[b]`. In the process of constructing `c=SparseArray[a->b]` _I do not want my kernel to suck up all my memory by unpacking a or b (or doing some other unpacking in the internal code)_ , i.e. the kernel memory required during the process should not exceed something like memA+memB, which seems like a very natural requirement to me... In eldo's answer below, it seems there is no unpacking since the arrays considered are too small. Considering larger arrays will lead to the above mentioned problem. **Is there a simple solution (or not so simple) to this issue ?** *Specific example:               On["Packing"]           a=Table[{i, i + 1}, {i, 1, 10000000}]; (* Position of the elements *)     b=Table[RandomReal[], {i, 1, 10000000}]; (* Value of the elements *)     c=SparseArray[{a -> b}]; (* Generating the sparse array *)     ByteCount[a]     ByteCount[b]     ByteCount[c]      > 80000168 > > 80000168 > > 160000952 Plus you get the following messages : > FromPackedArray::punpack: Unpacking array with dimensions {10000000,2} in > call to Rule. >> FromPackedArray::punpack: Unpacking array with dimensions > {10000000} in call to Rule. >> FromPackedArray::punpack1: Unpacking array > with dimensions {10000000}.>> So it seems there is some unpacking in the internal process. In this specific examples the kernel memory during the process goes up by 1 GB, although the final results takes only 160 MB...               $Version      > 8.0 for Mac OS X x86 (64-bit) (October 5, 2011)


title: On Parameter Estimation using FindDistributionParameters

text: I am a novice of Mathematica and have recently started my self-study of maximum likelihood estimation (MLE) using Mathematica. I would like to estimate the parameters associated with a distribution following the Laplace distribution. I have created experimental data following the Laplace distribution, using the following code:               data = RandomVariate[ExponentialPowerDistribution[1, 0.5, 1], 1000];      Given the data, I found the shape, location, and scale parameters by using `FindDistributionParameters`:               FindDistributionParameters[data, ExponentialPowerDistribution[Kappa, Mu, Sigma]]      > The obtained result was {1.11375, 0.504605, 1.10716}. But, if my understanding is correct, the Laplacian distribution is not differentiable at "Mu" (the single peak of the distribution), which gives me trouble understanding the estimation results because MLE assumes the differentiability of the distribution function. So, my questions are: (Q1) Are the above estimation results reliable (reasonable, or plausible)? (Q2) If the answer to (Q1) is yes, what is the algorithm used in FindDistributionParameters dealing with the non-differentiability of the distribution function? (Q3) If the answer to (Q1) is no, then, is there any reasonable way to come up with the parameter estimation for the above example? (In fact, I would like to obtain the standard error of each parameter in a reasonable way too.) Thank you very much for your help in advance!


title: How do I define a function that, when given a list of parameters, plots a family of functions?

text: So far I've got this:               draw[a_, b_] := Plot[{f[a, b[[1]], x], f[a, b[[2]], x]}, {x, 0, 5}]      The function `draw` will be used like this:               draw[10, {4, 7}]      The example is written for the case with two elements in the list that is the second argument. How do I do it when the second argument is a list with any number of elements?


title: Position of Subsets in a List

text: I have a particular list of integers and a matrix whose entries are lists. Say I know that my particular list is a subset of at least some of the elements in the matrix. I want to find an efficient way to find the positions of all of the elements of the matrix of which my list is a subset. Right now, I just loop through all of the entries in the matrix and keep track of which ones entirely contain my list (M is the matrix I want to search through and mylist is my list of integers):               Matches[mylist_] := (     match = {};     Do[Do[If[Intersection[M[[i, j]], mylist] == mylist, match = Append[match, {i, j}]]     ,{j,Length[M[[i]]]}];     ,{i,Length[M]}];     match);      As an example of my desired output:               M = {{{1, 2, 3}, {1, 2, 4}}, {{5, 4, 3}, {1, 2, 1}}};     Matches[{1, 2}]     (*={{1, 1}, {1, 2}, {2, 2}}*)      This function works how I want it to, but in the code I'm working on I wind up using it thousands of times with matrices and lists containing many more elements. Calling it so many times becomes the limiting factor in how quickly my code runs. Are there any ways to accomplish this that would be more efficient? I've tried using Position:               Matches2[mylist_]:=(Position[M, _?(Intersection[#,mylist]==mylist&)]);      Using Intersection in a pattern like this generates errors that I don't know how to correct, though, and I'm not sure whether this approach would be faster to begin with. If anyone knows of any more efficient ways to do this, it would be greatly appreciated. Thanks!


title: A problem with "RiccatiSolve::ncsol: Cannot compute a stabilizing solution to the matrix equation "

text: I have a SSM ( State Space Model ) and I want to calculate its optimum gains unisng `LQOutputRegulatorGains[]` command. When I run the code, it solves the equations and give an answer, but this error also appears :                   RiccatiSolve::ncsol: Cannot compute a stabilizing solution to the matrix equation.>>      What's wrong with it ?! And is it possible to change the method which `RiccatiSolve[]` command uses to solve the equation ? It is good to mention that `RiccatiSolve[]` uses two methods : 1.Eigensystem 2.Schur. I don't know how to change the `RiccatiSolve[]` methods in the `LQOutputRegulatorGains[]` command. Thank you in advance.


title: Adapt ColorFunction in Array Plot

text: The problem I'm facing is how to adapt `ColorFunction` so that it ranges from green (low values) to red (high values):               ArrayPlot[{a1, a2, a3, a4, a5}, ColorFunction -> (* ??? *)]


title: Apply an image as a texture to text

text: I have the following equation               eq = Sum[x^2, {x, 0, 10}]      and an image `image = Import["http://creativity103.com/collections/Graphic/rainbowbars.jpg"]`. How might I output a transparent version of the equation above with the image used as a **tile** for the text. For example I'm looking for something similar to this gradient image expect for the text above. **Edit: it wasn't very clear in the question, but I am looking to tile the background image if possible.** ![enter image description here](http://i.stack.imgur.com/SXSf7.png)


title: Problem with NDSolve and NDSolve::ivone error

text: I was trying to solve an diffusion-reaction rate model for the oxidation of Silicon (based on the nice paper by Almeida et.al.) with the help of NDSolve. In this model the boundary conditions are a bit unusual compared to the way Mathematica expects them. The command I tried looks like the following:               res = NDSolve[{      D[nO2[x, t], {t, 1}] == D0 Exp[-(ED/(kB T))] D[nO2[x, t], {x, 2}] -                               K0 Exp[-(EK/(kB T))] nO2[x, t] nSi[x, t],      nO2[0.0, t] == nO20[1, T],      D[nSi[x, t], {t, 1}] == -K0 E^(-(EK/(kB T))) nO2[x, t] nSi[x, t],      nSi[x, 0.0] == 1.0      } //. {      D0 -> 1.291 10^11, ED -> 2.22,      K0 -> 2.022 10^7, EK -> 1.42,       nSi0 -> 0.91 10^15,       kB -> QuantityMagnitude[UnitConvert[Quantity["BoltzmannConstant"/"ElementaryCharge"]]],       T -> 700 + 273.15      }, {nO2, nSi}, {x, 0, 3000}, {t, 0, 60 60}][[1]]      where Mathematica complains about the way how the boundary condition for the function nO2[x,t] has been defined and drops an NDSolve::ivone error. Playing around with this boundary condition I came up with a setup which gave solutions to the functions nO2[x,t] and nSi[x,t], however the choice of the x coordinate for the upper boundary where nO2 is zero is causing a strong influence on the solution as one can see when NDSolve is run for two different settings for the x coordinate:               res = NDSolve[{      D[nO2[x, t], {t, 1}] == D0 Exp[-(ED/(kB T))] D[nO2[x, t], {x, 2}] -                               K0 Exp[-(EK/(kB T))] nO2[x, t] nSi[x, t],      nO2[x, 0.0] == Piecewise[{{0.161/T, x == 0}}, 0],      nO2[3000.0, t] == 0.0,      nO2[0.0, t] == nO20[1, T],      D[nSi[x, t], {t, 1}] == -K0 E^(-(EK/(kB T))) nO2[x, t] nSi[x, t],      nSi[x, 0.0] == 1.0      } //. {      D0 -> 1.291 10^11, ED -> 2.22,      K0 -> 2.022 10^7, EK -> 1.42,       nSi0 -> 0.91 10^15,       kB -> QuantityMagnitude[UnitConvert[Quantity["BoltzmannConstant"/"ElementaryCharge"]]],       T -> 700 + 273.15      }, {nO2, nSi}, {x, 0, 3000}, {t, 0, 60 60}][[1]]     Plot[1 - (nSi /. res)[x, 60 60], {x, 0, 30}, PlotRange -> {0, 1.1}]      yields the following Graph: ![nSiO2 with nO2===0 at x=3000](http://i.stack.imgur.com/zRKNv.png) whereas the following code               res = NDSolve[{      D[nO2[x, t], {t, 1}] == D0 Exp[-(ED/(kB T))] D[nO2[x, t], {x, 2}] -                               K0 Exp[-(EK/(kB T))] nO2[x, t] nSi[x, t],      nO2[x, 0.0] == Piecewise[{{0.161/T, x == 0}}, 0],      nO2[300.0, t] == 0.0,      nO2[0.0, t] == nO20[1, T],      D[nSi[x, t], {t, 1}] == -K0 E^(-(EK/(kB T))) nO2[x, t] nSi[x, t],      nSi[x, 0.0] == 1.0      } //. {      D0 -> 1.291 10^11, ED -> 2.22,      K0 -> 2.022 10^7, EK -> 1.42,       nSi0 -> 0.91 10^15,       kB -> QuantityMagnitude[UnitConvert[Quantity["BoltzmannConstant"/"ElementaryCharge"]]],       T -> 700 + 273.15      }, {nO2, nSi}, {x, 0, 300}, {t, 0, 60 60}][[1]]     Plot[1 - (nSi /. res)[x, 60 60], {x, 0, 30}, PlotRange -> {0, 1.1}]      gives the following graph ![nSiO2 with nO2===0 at x=300](http://i.stack.imgur.com/tNjYr.png) It's obvious that one gets different results by moving the position of the boundary condition and thus using the boundary condition in this way is not an option. I would be interested in finding a possibility to specify the boundary condition for nO2 as shown in the first code snippet.


title: How to merge Datasets representing matrices with named rows/columns?

text: I am working with square (non-symmetric) matrices with named rows and columns. The data I receive is sometimes messy and rows/columns may come in various permutations. I usually need to semi-manually put every matrix into a canonical permutation before I can work with it. I'd rather never have to think about permutations and not even define a canonical one, just index the matrices using the names of their rows/columns. I was hoping that `Dataset` would be helpful here, and I made `Dataset` objects like these:               ds1 = Dataset[<|"a" -> <|"a" -> 1, "b" -> 2|>, "b" -> <|"a" -> 3, "b" -> 0|>|>]      ![Mathematica graphics](http://i.stack.imgur.com/NgsA5.png)               ds2 = Dataset[<|"a" -> <|"b" -> 1, "a" -> 5|>, "b" -> <|"b" -> 1, "a" -> 2|>|>] (* I used a different permutation on purpose *)      ![Mathematica graphics](http://i.stack.imgur.com/KkfQn.png) What is the simplest way to merge these together to obtain the following?               Dataset[<|"a" -> <|"a" -> {1, 5}, "b" -> {2, 1}|>, "b" -> <|"a" -> {3, 2}, "b" -> {0, 1}|>|>]      ![Mathematica graphics](http://i.stack.imgur.com/vxdps.png) Instead of merging with `List` I will usually need to merge with other operations, e.g. `Plus`. Once I've built a dataset with `List` it's easy to do that though.


title: Using MapIndexed[List] on a dataset fails -- why?

text: The following works:               MapIndexed[List]@{1, 2, 3}     (* {{1, {1}}, {2, {2}}, {3, {3}}} *)      This works too:               Dataset[{1, 2, 3}][MapIndexed[f]]      ![Mathematica graphics](http://i.stack.imgur.com/XbyOa.png) Why does this not work?               Dataset[{1, 2, 3}][MapIndexed[List]]      ![Mathematica graphics](http://i.stack.imgur.com/0yjpN.png) This works fine again:               Dataset[{1, 2, 3}][MapIndexed[{##} &]]      ![Mathematica graphics](http://i.stack.imgur.com/rSeIb.png)


title: Manipulate expression overlaid on plot of data

text: I am trying to use the `Manipulate` function in _Mathematica_ and want to plot an expression over a scatterplot of (x,y) data. I can programme the `Manipulate` function, but am unable to do this on the same axes as the scatterplot - any hints much appreciated I want to plot this data and then use `Manipulate` to visually fit a curve to the data... The code I have written for the Manipulate function is:               Manipulate[      Plot[c*k*(x^(c - 1))/((1 + x^c)^(j)), {x, 0, 5},        PlotRange -> {{0, 5}, {0, 10}}], {c, 0, 10}, {k, 0, 10}, {j, 0, 5}]      and I want to include a command so the following plot is included on the axes in the manipulate environment. The following data plot is created with:               ListPlot[ddata, PlotRange -> {{-6, 6}, {0, 0.05}}, AxesOrigin -> {-6, 0}]      ![This is the scatterplot I want in the background...](http://i.stack.imgur.com/HsAs0.jpg) ddata is given by:               ddata = First@ToExpression@Import["http://pastebin.com/raw.php?i=KwJSvA2r", "Data"];


title: Unable to copy/paste CDF embed code in Ubuntu

text: I tried this question in superuser but no luck, maybe somebody here knows what is going on... Mathematica offers export to a format they call Computed Document Format (CDF) - it is basically a player for the notebooks you work in that environment. One way to use them is to embed it on a web page. While the pop-up window that generates the embed code offers a way to copy the code to the clip board (this is under Ubuntu), it doesn't appear to register and there is nothing to paste once I get to the text editor to incorporated it in my web page. Any suggestions of what might be amiss would be appreciated. Is there a secondary clipboard where the text goes? Copy/paste works fine otherwise in this software... I run Mathematica 9.0 on Ubuntu 12.04


title: How to adjust parameters to experimental data on a NDSolve problem

text: I have 2 differential equations with 2 variables, x and y,which are a function of t and I have the parameters k1, k2 y k3.                                      dx/dt=-k1 x2+ k2 x y                           dy/dt=k1 x2-k2 x y- k3 y      I have to adjust the equations to the following experimental data                                      xo=70.26, x(t=720)=45.78                            xo=71.04, x(t=720)=46.32                            xo=37.23, x(t=720)=24.67                            xo=37.91, x(t=720)=28.78      I tried FindFit and NMinimize. The problem with FindFit is that I have multiple initial conditions. Then I used NMinimize, I tried to create a function error only with the first data (eventually, I will use the rest of the data) but NMinimize gives me the following error This is the funtion.               Remove["Global`*"]      f[k1_?NumericQ,k2_?NumericQ,k3_?NumericQ]:=          Module[{x,y,out},out=Abs[45.78-x[720] /.                NDSolve[{x'[t]==-k1 x[t]^2+k2 x[t]y[t],y'[t]==k1 x[t]^2-k2 x[t]y[t]-k3 y[t],                         x[0]==70.26,y[0]==0},{x,y},{t,0,800}]]]     res=NMinimize[{f},{k1,k2,k3}]      And this is the error > NMinimize::nnum: The function value f is not a number at {k1,k2,k3} = > {8.17269,8.09533,4.9417}. >> If anybody can help


title: Why is Mathematica 10 giving me the junk data from Instagram?

text: Instagram:               instagram = ServiceConnect["Instagram"]      ![enter image description here](http://i.stack.imgur.com/uz38Z.png) ServiceExecute[conn,"request",params] sends a request to the connection identified by conn, in my example it is Instagram. This seemed like it would be cool functionality in v10. But almost all queries that I form return missing, incomplete, or just wrong data. Note: I have elided the data for privacy, but rest assured the UserID's are correct. Bugs with this functionality are quite simple indeed to reproduce: Search for a user:               In[3]:= instagram["UserData", "UserID" -> 10206720]          Out[3]= <|"Website" -> "http://barackobama.com", "Username" -> "barackobama",       "FullName" -> "Barack Obama", "Media" -> 179, "FollowedBy" -> 3347187,       "Follows" -> 11, "ID" -> "10206720"|>          Import recent media from a user:          In[5]:= instagram["FollowerCount", "UserID" -> 10206720]          Out[5]= 50


title: How do I draw a hemisphere?

text: I want to draw a solid or partially transparent hemisphere above a partially transparent cuboid object in Graphics3D. However, I do not know how to do this s.t. only half the sphere is drawn. Here's what the object looks like with the full sphere:               SphereOpacity = 0.5;     CuboidOpacity = 0.5;     SphereColor = Blue;     CuboidColor = Orange;     Graphics3D[{SphereColor, Opacity[SphereOpacity], Sphere[{0, 0, 0.5}, 0.5],                  CuboidColor, Opacity[CuboidOpacity], Cuboid[{-5, -5, 0}, {5, 5, 0.5}]},                  Boxed -> False     ]      ![enter image description here](http://i.stack.imgur.com/3HWhX.png) How might I proceed to "remove" the bottom half the sphere embedded in the cuboid primitive? In general, is there a way to not render/draw parts of a graphics primitive conditioned intersection with another primitive?


title: Cannot call custom function loaded from script using C/C++ MathLink

text: I am using MathLink with C/C++ on a Unix system in order to call a _Mathematica_ (version 9) function and get the result. The function I need to call is a personal function of mine `MyFunct[x,y,z]`. The function takes three arguments and will return a `Real`. This function is defined in `myscript.m` file at this path: `/home/myuser/Documents/mym/myscript.m`. I have the following C code:               #include <mathlink.h>     #include <stdio.h>          int main(int argc, char** argv) {            MLENV env = (MLENV)0;       MLINK ml = (MLINK)0;            // Init and open       env = MLInitialize((char*)0);       int err = 0;       char* argv[5];       argv[0] = "ml";       argv[1] = "-linkmode";       argv[2] = "launch";       argv[3] = "-linkname";       argv[4] = "/usr/local/Mathematica/9.0/Executables/MathLink";       *link = MLOpenArgcArgv(*env, 5, argv, &err);            fprintf(stdout, "All ok!\n");            // Putting function       MLPutFunction(ml, "N", 1);       MLPutFunction(ml, "Cos", 1);       MLPutInteger(ml, 2);       MLEndPacket(ml);       MLFlush(ml);            // Getting       int pkt;       while ((pkt = MLNextPacket(ml),pkt) && pkt != RETURNPKT) {         MLNewPacket(ml);         if (MLError(ml)) fprintf(stdout, "Error!\n");       }       double r = 0;       MLGetReal(ml, &r);       fprintf(stdout, "Got %f!\n", r);            // Close and deinit       envCloseLink(&ml);       fprintf(stdout, "Closed!\n");       envDeInitEnv(&env);       fprintf(stdout, "Deinitialized!\n");            fprintf(stdout, "Over!\n");     }      The above code works! Now consider the following:               int main(int argc, char** argv) {            MLENV env = (MLENV)0;       MLINK ml = (MLINK)0;            // Init and open       env = MLInitialize((char*)0);       int err = 0;       char* argv[5];       argv[0] = "ml";       argv[1] = "-linkmode";       argv[2] = "launch";       argv[3] = "-linkname";       argv[4] = "/usr/local/Mathematica/9.0/Executables/MathLink";       *link = MLOpenArgcArgv(*env, 5, argv, &err);            fprintf(stdout, "All ok!\n");            // CALLING 'GET' ////////////////////////////////////////////////////////       fprintf(stdout, "Putting [GET]...\n");       if (!MLPutFunction(ml, "Get", 1)) fprintf(stdout, "Err!\n");;       if (!MLPutString(ml, "/home/myuser/Documents/mym/myscript.m")) fprintf(stdout, "Err!\n");       MLEndPacket(ml);       if (!MLFlush(ml)) fprintf(stdout, "Err!\n");       int pkt = 0;       while ((pkt = MLNextPacket(ml),pkt) && pkt != RETURNPKT) {         MLNewPacket(ml);         if (MLError(ml)) fprintf(stdout, "Error!\n");       }       // END //////////////////////////////////////////////////////////////////            // CALLING FUNCT ////////////////////////////////////////////////////////       fprintf(stdout, "Calling impulse...\n");       MLPutFunction(ml, "MyFunct", 3);       MLPutInteger(ml, 1);       MLPutInteger(ml, 4);       MLPutInteger(ml, 2);       MLEndPacket(ml);       MLFlush(ml);       int pkt2 = 0;       while ((pkt2 = MLNextPacket(ml),pkt2) && pkt2 != RETURNPKT) {         MLNewPacket(ml);         if (MLError(ml)) fprintf(stdout, "Error!\n");       }       double r = 0;       if (!MLGetReal(ml, &r)) fprintf(stdout, "Error in getting!\n"); // LINE REF1       fprintf(stdout, "Got %f\n", r);       // END //////////////////////////////////////////////////////////////////            // Close and deinit       envCloseLink(&ml);       fprintf(stdout, "Closed!\n");       envDeInitEnv(&env);       fprintf(stdout, "Deinitialized!\n");            fprintf(stdout, "Over!\n");     }      I got an error in `LINE REF1`. I understood that the problem is the `CALLING 'GET'` block. If I delete this block and call a _Mathematica_ built in function (like in the previous code), I get no errors. But if I insert the block `CALLING 'GET'` and then try to call one of the functions defined in my external file or a built in _Mathematica_ function, errors are raised at the specified line (`LINE REF1`). Maybe I've made a mistake when trying to perform two sequential operations on the link... How do I solve this?


title: Why ImportString[ExportString[, "PDF"], "PDF"] sometimes gives an extra point

text: Consider this code:               fc = ImportString[ExportString[Style["Ma"], "PDF"], "PDF"][[1, 1, 2, 1, 1]];     lines = GeometricFunctions`DecodeFilledCurve[fc][[1]];     {lines // Length,Graphics[JoinedCurve[#]] & /@ lines}      will give what is expected: ![enter image description here](http://i.stack.imgur.com/p4xpf.jpg) but this code:               fc = ImportString[ExportString[Style["Ma", FontFamily -> "Times"], "PDF"], "PDF"][[1, 1, 2, 1, 1]];     lines = GeometricFunctions`DecodeFilledCurve[fc][[1]];     {lines // Length, Graphics[JoinedCurve[#]] & /@ lines}      gives four things, with the fourth element is just a point: ![enter image description here](http://i.stack.imgur.com/hH3j2.jpg)               lines[[-1]]     (*{Line[{{10.5607,9.40406},{10.5607,9.40406}}]}*)      Why there is an extra point in the second case? I'm using version 9 on Mac. **Update** screenshots of the problem on version 8 and 9 on mac, and version 8 on windows 7, the results seems different: ![enter image description here](http://i.stack.imgur.com/ATowD.png) ![enter image description here](http://i.stack.imgur.com/qTaOS.png) ![enter image description here](http://i.stack.imgur.com/v5YzB.jpg)


title: Simulating a Stochastic Process within certain bounds

text: I would like to simulate paths of a Geometric Brownian Motion till it hits one of two barriers, say 10 or 200.               data2 = RandomFunction[       GeometricBrownianMotionProcess[0.05, .15, 100], {0, 10, .01}, 1]     ListLinePlot[data2]      ![enter image description here](http://i.stack.imgur.com/KQrfI.jpg)               data3 = %69["Path"]          data4 = {}          j = 1; While[data3[[j, 2]] < 200 && data3[[j, 2]] > 10,       data4 = Append[data4, {data3[[j, 1]], data3[[j, 2]]}]; j++]          ListLinePlot[data4]      ![enter image description here](http://i.stack.imgur.com/qvBjJ.jpg) This works but is clunky and inelegant. Is there someway I can do it better or maybe run the simulation till some barrier is hit instead of truncating the data post simulation?


title: How to send a function definition to MathLink from C/C++?

text: In this tutorial some _MathLink_ concepts are introduced. At page 33 in the last lines the author is talking about sending to _MathLink_ a function definition like `F[x_] := x^2`. In C/C++ (Unix) I want to to do exactly like that! Which function should I use to put a definition? `MLPutFunction`? `MLPutSymbol`?


title: How do I constrain movement for lists of Locators using 2nd argument of Dynamic?

text: I need to display edge labels of a graph in a way that allows the edge labels to be moved. `Locator` seems the simplest and most obvious function to use. My application requires an interface that generates new graphs with different numbers of vertices and edges, so I can't treat the locators individually.               With[      {coords = {{1.08, 0.94}, {1.08, 0.036}, {0., 0.97}, {0., 0.}, {1.94, 0.49}},       edges = {{1, 2}, {1, 3}, {2, 5}, {3, 4}, {4, 2}, {5, 1}}},      DynamicModule[       {edgePosns = Table[0.5, {Length@edges}]},       (betweenPnt[a_, b_, l_] := (1 - l) a + l b;        DynamicModule[         {edgeCentres =           MapThread[            With[{av = coords[[#1[[1]]]], bv = coords[[#1[[2]]]]},              Dynamic[betweenPnt[av, bv, #2]]] &,            {edges, edgePosns}]},           Graphics[            GraphicsComplex[             coords,             {{Line[edges]}, {Darker@Red, PointSize[0.02],                Map[Point, Range[5]]},              Map[Locator, edgeCentres]}], ImageSize -> 400]])]]      ![picture of output of above](http://i.stack.imgur.com/PZTtl.jpg) The locators can be moved, as expected. What I did _not_ expect was that, (even) if the output is deleted and the cell is re-evaluated, the locators retain their new positions. However, I've now learned that this is standard behaviour (see m_goldberg's comment below), which can be fixed by `Initialization` (see Kuba's solution). Also, I would like to constrain the movement of locators to lie on the edges, for which I hope to use the 2nd argument of `Dynamic`. Can I do it with this (admittedly flawed) design? My attempts so far have resulted in unresponsive locators. I think I need to update `edgeCentres` using the callback of the 2nd argument, but whether it is because it is a list, or for some other reason, this is ineffective. I do not know how (or if) I can implement this constraint by adding a second argument to `Dynamic` in the code above. In fact, I prefer to update `edgePosns`, which is list of the proportions of respective edges that the locators mark, but I need to be able to walk first. Related question now split from original question following Kuba's suggestion.


title: Randomly selecting and reinserting a subset of elements in a list

text: This question is similar to my other question: How do I randomly select 'k' positions in a list and shuffle their respective elements without effecting the other elements? Imagine first a pack of cards. We randomly draw $k$ cards from the pack, and then sequentially reinsert them 'somewhere' in the deck (between cards or above or below the deck). Now I'd like to do the same thing with list elements using some hypothetical function `pluckReinsert`:                k = 3;      list = {card1, card2, card3, card4, card5, card6, card7, card8, ..., cardN}      pluckReinsert[list,k]           output > {card2, card1, card3, card7, card4, card5, card42, card6, card8, ...}      Here, by chance, we randomly chose to "pluck" the set of cards: `{card2, card7, card42}`. We then, sequentially, placed `card2` on top of card 1 (there were $N+1$ total choices given the $N$ cards in the deck), placed `card7` between `card3` and `card4`, and finally, placed `card42` between `card5` and `card6`. At any of these sequential addition steps, there are were $N+1$ choices for placing the card (i.e. there would be nothing to stop us from an ordering like: `{card42, card2, card1, card3, card4, card5, card6, card8, ..., cardN, card7}`). Is there a clever Mathematica trick to do this in one or two lines?


title: how to create a slope field in mathematica?

text: Anyone have any good resources for learning mathematics, already sufficient in JAVA. not math... only in calc 2. I want to plot the slope field of `y(x)= (1200e^(kx))/ (c + e^(kx))`? Any suggestions? Code so far.               VectorPlot[{1, 1200 e^kx/c + e^kx} {x, -2, 2}, {y, -2, 2}]


title: How to expand function $\cos(y+i\log{x})$ in powers of $x$?

text: I have the following, probably very simple question. How can I get $\it{Mathematica}$ to power expand function $\cos(y+i \log(x))$ in powers of $x$? This function obeys a well defined Laurent expansion about $x=0$ and I would like $\it{Mathematica}$ to give $\frac1{x}e^{i y}/2+x e^{-iy}/2$ upon evaluation of               Series[Cos[y + I Log[x]], {x, 0, 1}]      However, the result is               Cos[y + I Log[x]]      i.e. the original expression. I can bet that in some circumstances such expansion worked without any effort from my side. I wonder what is the right way to obtain the expansion of the function $\cos(y+i \log(x))$ in powers of $x$. Any help is appreciated.


title: Open a pre-existing CDF file from a stand-alone CDF file

text: This is related to my previous question here A series of my questions are related to an important problem: It is important to be able to CDF-publish a document, and be able to open a separate interactive window from this document. Let me explain in more details. In my concrete situation I have a document in a form of a cdf file. I would like to open, say, a manipulate-based demonstration in a separate window. To enable the reader to read the rest of the document, and to use the demonstration while reading further. The discussion here has shown that it is likely to be impossible. What is impossible, however? What I tried to achieve at that point was to open an nb notebook from a cdf file within the CDF Player. That is clear that it is counter logic. If this would be possible, it would be the work around to use the free CDF Player instead of Mathematica. OK, is it possible to create a cdf document, and then to embed this document into another one in a form of a code? This is to be able to open one (slave) cdf document from another (master) CDF document. Then one will open a cdf, rather than nb within the CDF Player. This should not be forbidden. To be precise, let us assume a notebook with this simple code:                Manipulate[Plot[Sin[a*x],{x,0,6}],{a,1,2}]      This notebook can be saved as a stand-alone cdf. My question is this: Is it possible to get a code corresponding to this cdf document, such that it can be launched by, say, the following code:               Button["Launch cdf file", the_code_in_question]      from another notebook. This notebook will also be transformed into the cdf form So, do you see such a possibility?


title: ParallelSum in Mathematica 9 vs 10

text: Here's part of a package I'm working on:               BeginPackage["TestPackage`"]          reduction::usage = "reduction[x] returns x after some rules have been applied.";          Begin["`Private`"]          auxReduction1[exp_]:=Module[{matched,pointsMatched},          If[StringMatchQ[ToString[exp,InputForm],{"*θ"~~DigitCharacter..~~"θ"~~DigitCharacter..~~"^2*"}]==True,     matched=ToExpression[StringCases[ToString[exp,InputForm],"θ"~~DigitCharacter..~~"θ"~~DigitCharacter..~~"^2"]];     pointsMatched=StringCases[ToString[matched[[1]]],"θ"~~x:DigitCharacter..->x];     (exp/.{matched[[1]]->1})(-(1/2)ToExpression["θ"~~pointsMatched[[1]]~~"sq θ"~~pointsMatched[[2]]~~"sq"]),          exp     ]     ]          (*This function allows the application of the previously defined function on a sum of terms*)     auxReduction2[exp_]:=Module[{auxList,i,ans},     auxList=Flatten[{Replace[exp,HoldPattern[Plus[a___]]:>{a}]}];(*Create list of the terms in the sum*)     ans=ParallelSum[auxReduction1[auxList[[i]]],{i,1,Length[auxList]},DistributedContexts->Automatic]     ]          reduction[exp_]:=FixedPoint[auxReduction2,exp];          End[]          EndPackage[]      In Mathematica 9 this works just fine. In Mathematica 10, shadowing messages appear the first time I use the function defined in the package. For example, if I run               reduction[θ1θ2^2]      then I get the message               Global`θ1sq::shdw: Symbol θ1sq appears in multiple contexts {Global`,System`}; definitions in context Global` may shadow or be shadowed by other definitions.      and after it the expected answer. Why is this happening in Mathematica 10 but not 9? By the way if `Sum` is used instead of `ParallelSum`, then everything works fine in both Mathematica 10 and 9.


title: Compiling a recursive formula

text: My question is related to computing what is called "invariant measure" for a particular well known fractal - the Sierpinski triangle. We have an array m of four two by two matrices, say               m = {{{1.22951,-0.102459},{0.058548,1.1856}},{{2.34016,2.08943},{-2.31509,1.50439}},     {{1.52091,2.98751},{2.58555,-2.0641}},{{-11857.1,6214.29},{3214.29,-1678.57}}};      and an array a of four vectors, say:               a = {{-0.127561,-0.238217},{-0.322608,0.247723},{-0.601847,-0.165997},{1304.29,-353.571}};      We also have an array c of four coefficients (related to probabilities and determinants of the matrices), for instance:               c = {0.817674, 1.95388, 2.22763, 180.714};      Then we have four functions of a two-dimensional vector x, for i=1,2,3,4 defined as               w[i_,x_] := m[[i]].x + a[[i]]      **The recursive formula I am trying to code** is               f[ n_, x_ ] := Sum[c[[i]]*f[ n-1, w[i,x] ],{i,1,4}]      with f[ 0 ,x ] = 1 over the unit square 0 < x[[1]] < 1, 0 < x[[2]] < 1, and zero elsewhere:               f[0, x_] := If[x[[1]] > 0 && x[[1]] < 1 && x[[2]] > 0 && x[[2]] < 1, 1, 0]      I would like to plot functions f[ n, x ] for, say, n=1 up to n=10. It takes a lot of recursions, so I would like to find the optimal code that can be compiled for a fast execution. I tried to compile, but all my efforts failed, probably because I do not really understand what can be compiled and how. Without compiling it takes Mathematica 22 seconds to compute just one value::               Timing[f[10, {0.5, 0.5}]]          {22.667, 0.869726}      Can it be done faster with Mathematica? If so, how? Any help will be appreciated


title: Map of United States as a 3D histogram

text: By combining the state data from here and the extrusion code from here I have managed to make prisms of the various US states such as ![enter image description here](http://i.stack.imgur.com/gP9ej.jpg) However, the extrusion method looses information about the states relative position so I cant reassemble them into a map of the US states which is my final goal: a map with states projected upward by different amounts corresponding to a parameter I have (something like population or total sales) to make a 3D histogram of sorts. I have the seen the last example here(How to Plot Prism in Graphics3D) which has the right geometry but is not at a level of quality I can use in my work. Moreover, the final infographic may have additional data on the state surfaces like colored points indicating hotsopts so that solution wont extend.


**How to simplify my expression to the style of "a+b*I"?**               Expand[(E^(I θ) (-1 + E^(I n θ)))/(-1 + E^(I θ))]      > >     -(E^(I θ)/(-1 + E^(I θ))) + E^(I θ + I n θ)/(-1 + E^(I θ)) >   ![the result I want to achieve](http://i.stack.imgur.com/wT6Ec.jpg)


title: Different Poincaré maps for same Equation

text: I've seen the Wolfram Poincaré example. I'd like to modify this sample in order to have a list of Poincaré maps. In the example the event is captured only when `Mod[t, 2 Pi] == 0`. I want to create a map of angles (0, Pi/2, Pi, 3 Pi/2, 2Pi for example) and create the Poincaré for every angle, in order to create an animation showing the map for every angle. Obviously I can create data for every angle, putting the the example inside a `Table` command and varying the angle, but it seems a waste of time, because I must perform `NDSolve` every time. Instead it can be helpful to find a way to use `NDSolve` only once and save directly the list of data for all angles that I want. I've tried to change `Mod[t, 2 Pi] == 0` to `Mod[t, 2 Pi] == 0 || Mod[t, Pi] == 0`, because I wanted to create a unique list, check it's length and then rearraing data in some way in order to obtain the map list, but I obtain the following error               Part::partw: "Part 1 of {} does not exist.      And data is               {{{}}, {}}[[-1, 1]]      Why I obtain this error and how can I have different sections using `NDSolve` only once?


title: How to copy an image given as a GraphicsBox expression to the clipboard?

text: I have a `GraphicsBox` expression encoding an image. I need to copy this image to the clipboard so that it can be inserted in a _Microsoft Word_ document. When I invoke this command:               CopyToClipboard@GraphicsBox[        RasterBox[CompressedData["        1:eJwBMAPP/CFib1JmAgAAAHMIAAAAUmF3QXJyYXlTBAAAAEJ5dGViAwAAABAA        AAAQAAAAAwAAAOWJcN1+aq1DUL9UV89iX9JjYNBfXM1cWs9hXsJZXs5wauKE        bOSVdtCIc8FYW5lCU+iIbNx3Y6s/TMBRVdBeXc1fYspwcc6Gf8xpacNOVcpk        Z+OFctp2ZeylgZhIV1UNOsVaV9p0YaU8TbxOVclWWL1bYsVzdtirnuHDtbpr        c8dYW8xlZN5oXb5fXlgWP3gwT65HUNp1ZqQ6TL1RVr9TWcJbYcx3dtmon+LF        utnFvdJ3cqRFUsqIh3YqS2geRsuCfbhNUt17Z6Y4ScNcWcRaW8RcZNaJhOGj        l+GqntqzrNyrn92zptrBt2IgSLBgbNyRgb1QU+GAaKM1R8RjW9Z2ZsliacZq        daZefKJeddKbk9q5rN6vo5lVY3guUNqOhM6GfLxQVN9/aKU4SrpTVdh9b7RP        ZXcuXGQiWbB9jOO3psmMj5xNX18VO6hga9qWhs6Hf7ZMU92AbKY8TsVTVblZ        Y24nVV4bTbN1fMp+f+qil82Ih3MmS28nSsuEe82Lf8N+faxET96Ba7FEUKhW        Znk8bF4gVZBNX9GAfrRTZeCEhKROYXYpTI9GWtaMfcV+eMeKfZM1St5+aa5M        YnhCe2YoV386VptSX9ZkauqIg+SBgMRlb3YpSrJoasqDe82NePDEkZU3TeOE        caBCXnA5coZHbJZTYnknRdpdYN5qa+R/fZFAWH8xTM6Ed8F5dOOshfLTqYgw        SOeLdo47W2w6cqJpjngyTWQXPK1ATeJrbMdkcF0SO5VDVMuIe7l5durBmu/K        n41CV9+Dcns2V2oxZIhbjHM0WlwWPZI1S9ttbtqWipxlcJJBVLpxcq5pauKw        iZ5NVZZdbtyEcHIuUVwdS3pGd4RQdm4fP7dLVd5oZeSOfvHHsLFwc7t0cNid        gdKEbJk3TZNaat2IcXEsT1cYRHE7aWgtV4cqP81dXuBqZNpyaeu2pNKblJZJ        VNeXdK1RVI48VKRtddmKdWklS2UoVm84ZmwkSLFCSNpkXuBuZ91vZeWcjNir        o5pJVK5VVYo7U4M6U7TRiLk="], {{0, 16}, {16, 0}}, {0, 255},           ColorFunction -> RGBColor]]      and paste the clipboard contents to the document, it is displayed as a plain text, not an image. How do I copy the corresponding image?


title: Limits explanation in doc

text: `Limit[expr,x->Subscript[x, 0],Direction->1]` computes the limit as x approaches `Subscript[x, 0]` from smaller values. `Limit[expr,x->Subscript[x, 0],Direction->-1]` computes the limit as x approaches `Subscript[x, 0]` from larger values. This to me is confusing, I though x->4- that x are approaching xo from smaller values, in other words from the left hand side. Why would one therefore use 1 for left hand side and -1 for right hand side. Do not see the logic


title: Nonlinear system of equations

text: I have been working to find an equilibrium solution for a Hamiltonian dynamical system. I have reduced the problem to the simultaneous solution of 3 equations:               1/(4 Sin[x]) - (a Sin[x])/(Sqrt[1 + a^2 + 2 a Cos[x]])^3 == 0          r^3 - 3/a^3 + (2 (a + Cos[x]))/(Sqrt[1 + a^2 + 2 a Cos[x]])^3 == 0          r^3 - 3 + (1 + a Cos[x])/(Sqrt[1 + a^2 + 2 a Cos[x]])^3 + 1/(4 Sin[x]) == 0       The conditions on the variables: $r>0,\,a>0,\,x\in[0,\pi]$. Can anyone see a way to simplify this even further? Mathematica brute force style on my lowsy pc just sits there. Is there an effective way to analyze this system with Mathematica? For a more complete discussion of this problem: http://math.stackexchange.com/questions/794747/3-equations-and-3-unkowns


title: Apply color function to matrix plot

text: I want to apply the following color rules to a large table of numbers. I have extracted a part of the table to use as an example. I would like to assign 5 different colors to 5 different ranges of numbers in the plot. I have attempted to use `ColorRules`. Additionally I would not like any of the number sets to overlap. IE the intersection of the sets should be zero. The five colors I would like to use as specified by their RGB values are > >     rgb(215,25,28), rgb(253,174,97), rgb(255,255,191), rgb(166,217,106), > rgb(26,150,65) >   And the colors can be visualized here. I have been trying to use `ColorRules` but I have not been successful. I would like to specify the ranges in a substituion rule like so:               subs = {r1, r2, r3, r4, r5}      then I would like any number in range 1 to get the first color value in the list. Any number in range 2 should get the second color in the list etc.               MatrixPlot[data]      I am trying something like this:               MatrixPlot[data, ColorRules -> {colors we assign} /. subs]               data = {{-3.24293,-1.47187,-1.69071,-6.51991,-12.991},{-2.92423,-1.61127,-1.48652,-6.57345,-4.54179},       {-2.81276,-1.60509,-1.42055,-5.76192,-5.01714},{-2.69414,-1.7745,-1.16451,-10.9609,-5.70199},{-1.55186,-1.90981,-2.51796,-9.72864,-5.1199},      {-2.88007,-1.79372,-1.81939,-6.33952,-5.42191},{-2.94096,-1.8705,-1.04659,0,-5.9382},      {-3.00545,-2.5603,-1.14478,-12.637,-5.87252},{-3.12462,-2.05841,-1.2814,-6.63924,-4.56169},      {-3.15717,-1.87809,-2.13397,-6.53378,-9.22608},{-5.96966,-1.56194,-10.0711,-6.48629,-7.5176},      {-2.8825,-1.60735,-1.30394,-6.72428,-5.83372},{-2.54989,-1.65592,-1.29924,-7.26422,-5.02008},      {-2.55175,-1.92627,4.36713,-8.24918,-3.24031},{-2.68259,-2.46921,-1.35072,-5.1584,-5.81326},      {-2.7642,-2.04738,-1.49208,-5.78859,-5.51309},{-2.83568,-2.13715,-0.966458,-6.29401,-5.50667},      {-3.25703,-2.21809,-1.0429,-6.48135,-4.83744},{-3.41949,-2.23744,-1.41273,-6.48503,-5.86511},      {-2.81817,-1.62158,-1.31235,-6.42587,-7.46793},{-2.55747,-1.66047,-2.3501,-7.22216,-4.75924},{-2.7658,-1.52766,4.42157,-5.87914,-4.5517},      {-2.68263,-1.85017,-1.45391,-4.80219,-6.08356},{-2.96828,-2.01866,-1.25234,-5.48023,-4.93588},      {-3.08165,-2.10359,-0.963033,-6.26121,-6.0361},{-3.24358,-2.14413,-1.10553,-6.2898,-5.69808},      {-3.46909,-2.26438,-1.01026,-6.484,-5.94237}}


title: Is it possible to write a function immune to symbol redefinitions in any Block surrounding its invocation?

text: Normally, semantics of symbols used in a function definition can be changed by their redefinitions in `Block`s surrounding the function invocation:               primeCheck[n_Integer] := If[PrimeQ[n], "prime", "composite"];          primeCheck[10]     (* composite *)          Block[{PrimeQ = True&}, primeCheck[10]]     (* prime *)      Is it possible to make a function definition immune to any symbol redefinitions in `Block`s or somehow restore the original global definitions of symbols being used in the function body (without making the symbols `Locked` that would globally prevent changing their meaning)? * * * A related question:   I assume there is no way whatsoever to unlock a `Locked` symbol, right?


title: Create a list of random reals

text: How can I create a list of random pairs $(x,y)$ where $0<y<x<1$ and $x,y \in \mathbb{R}$ ? I can't seem to place that inequality restriction on the random numbers that are generated.


title: Is it possible to create an event handler for changes in values of variables?

text: I am creating a networking application in Mathematica that runs a non-stop simulation, and periodically receives new information from the remote server that affects the simulation. Whenever values of certain variables inside the simulation change, Mathematica needs to send an update with the values to the remote server. Is there a way to catch an event in Mathematica that corresponds to the change in the value of a specific variable? For example, assume that initially I have two variables: `a` and `b`, such that `a=1`, and `b=1`. Then, throughout the simulation one of the variables changes, while the second one remains the same: `a=2`, `b=1`. Is it possible to write an event handler that knows which variable has changed and what the new value is? I've seen this discussion: Triggering actions when a variable is set, that recommends using upvalues for `Set` and `SetDelayed`: `$var /: Set[$var, value_] := Block[{$in = True}, Print["$var set to ", value]; $var = value] /; Not@TrueQ[$in]` But this seems to not cover all possible cases when a variable might change, and requires defining UpValues for every variable. Is there a better way?


title: plot a tube via a 4D plot

text: I have a function               f[x_, y_, z_] := Exp[-x^2]*Exp[-z^2]      which traces out a tube along $y$. Is there a way to plot this 4D function, where the plot color is the 4th dimension?


title: Using NDSolve for Integro-Differential Equations

text: I have a fairly complicated set of coupled non-linear integro-differential equations that I am trying to solve using NDSolve. The equations are: $\dot{x}=\big|y(t)-x(t)\big|^{1/n}\left[\text{Sign}[y(t)-x(t)]-x(t)\right]$ $\big|y(t)-x(t)\big|^{1/n}\text{Sign}\left(\big|y(t)-x(t)\big|\right)=\cos(t+\pi\alpha/2)-\int\limits_0^t (t-\xi)^{\alpha-1}\ \dot{y}(\xi)\ d\xi$ with initial conditions $x(0)=0, y(0)=0$. Some of you may notice that the last integral is nothing but the definition of the fractional order integral with order $0<\alpha<1$. I implement this system of equations in Mathematica as follows               \[Alpha] = .5;     n = .5;     tmax = 10;     Intermediate[t_Real, y_Real] :=      Evaluate[Integrate[(t - \[Xi])^(\[Alpha] - 1) y, {\[Xi], 0, t},      PrincipalValue -> True]]     SolutionOfSimultaneousEquations :=       NDSolveValue[{x'[t] == (Abs[y[t] - x[t]])^(1/n)*(Sign[y[t] - x[t]] - x[t]),       (Abs[y[t] - x[t]])^(1/n) Sign[y[t] - x[t]] == Cos[t + Pi/2 \[Alpha]] - Intermediate[t, y'[t]],         x[0] == 0,y[0] == 0}, {x, y}, {t, 0, tmax}]      and then use the following bit of code to plot my results:               SolutionForx = SolutionOfSimultaneousEquations[[1]];     SolutionForxFn[t_] := SolutionForx[t];     SolutionFory = SolutionOfSimultaneousEquations[[2]];     SolutionForyFn[t_] := SolutionFory[t];     Plot[{SolutionForxFn'[t], SolutionForxFn[t]}, {t, .001, tmax},          PlotStyle -> Automatic, PlotRange -> Full]      Essentially I have defined a function called `Intermediate[t_Real,y_Real]` and this function is called by NDSolve everytime the value of the integral is required. However the solution I get from this code does not make physical sense. My main concern is with the way I have implemented the integral. Notice that the integral required the value of $y(t)$ for all times between $0$ and $t$. However, currently my code only passes a single value for $y(t)$ and the integral is completely different. Is this correct? What do I do to ensure that this integral is performed for all times $t$? I understand that only using something like an Euler forward scheme starting from $t=0$ will ensure that the integral can be performed (so that I have the value of $y$ for all prior times). Is there a better way to solve integro- differential equations?


title: Defining a user defined function in DynamicModule

text: How can I define a user defined function within `DynamicModule`? For example, if               h[x_] := x^2      I want to find `h[2]`.


title: Performance in parameter estimation from ParametricNDSolve using varied initial conditions

text: I have 250 data points from a timecourse exeriment in a list, with columns specifying (1) time, (2-4) initial conditions, (5) absorbance reading. I want to fit 4 parameters (k1, k2, k3, k4) in a DAE system of 7 species to this dataset, where species7 is absorbance. At the moment, the program needs 20 seconds for two NMinimize iterations and seems to break down after 10 minutes. I'm also using a different program (Copasi), which is able to solve the problem and perform the computations about 2 magnitudes faster. So where does this code get stuck and how do I solve it? I suspect part of the problem is that the system must be calculated for every single time point.               func[ic1,ic2,ic3] :=     species7[k1, k2, k3, k4] /. ParametricNDSolve[     {"species1-7 DAEs, species1-7 initial conditions, partly given by ic1-3"},     species7,     {t, 0, 120},     {k1, k2, k3, k4}     ]          fit = NMinimize[     {     Sum     [     (data[[i, 5]] -       func[data[[i, 2]], data[[i, 3]], data[[i, 4]]][data[[i, 1]]]      )^2, {i, Length[data]}     ],     {{10^-2 < k1 < 10^2},     {10^-2 < k2 < 10^2},     {10^-2 < K3 < 10^2},     {10^-2 < k4 < 10^2}}     },     {k1, k2, k3, k4},     ]      Thanks edit: here is a notebook with data https://www.dropbox.com/s/4mvnn4m8ldy7373/2013-05-16%20Stackexchange.nb please note, I'm not expecting a great fit at the moment. It takes ~1min to run


title: Bounds on random number

text: I have a Markov Chain Monte Carlo code that uses a chi squared function to fit some data. I am running into an issue now with getting unrealistic values for some of the free parameters in the code. What I would like to do is place an lower and upper bound on the parameter value (say `k1[[i]]` below ). Each iteration (`k1[[i]]`) of the function produces a random number that is added or subtracted from `k1[[i-1]]` giving the next step in the random walk. I would like to be able to test each current parameter (`k1[[i]]`) and if it is above or below a cutoff value, choose another random number until I return to the specified range. If `k1[[i]] < lowest` or `k1[[i]] > largest`, choose another Random number until `lowest < k1 < largest` However I am not quite sure how to implement this into the code for each parameter.   Does anyone have any suggestions?               Table[       {             k1[[i]] =  k1[[i - 1]] + weight*k1[[i - 1]]*RandomReal[{-1.0, 1.0}],             k2[[i]] = k2[[i - 1]] + weight*k2[[i - 1]]*RandomReal[{-1.0, 1.0}],             k3[[i]] = k3[[i - 1]] + weight*k3[[i - 1]]*RandomReal[{-1.0, 1.0}]        },           {i,1,range}          ]


title: How to color ParametricPlot3D based on the parameter?

text: I have a set of ODEs I am solving, and then plotting (several) trajectories of in ParametricPlot3D. I want to have a color of each plot reflect the time (i.e. the Parameter) at that point. I tried what something along the lines of:               ParametricPlot3D[{{Sin[t], Cos[t], t/10}, {Sin[2*t], 3*Cos[t], Tan[t]}}, {t, 0, 20},     ColorFunction -> Function[t, Hue[t]]]      which colors the function in a seemingly arbitrary way. Cheers!


title: Plotting a frequency function

text: I have a list of numbers and I want to plot the fraction of numbers >= k against k which will naturally be a decreasing curve. How do I do that?


title: Speed up Schwarz-Christoffel mapping

text: I would like to ask your advice how to speed up Contour and Parametric plots in the following example. Let as start by defining a function               A = {(8 Sqrt[1035741])/15625, 0, 0, 0, 0, Sqrt[6597877/15]/6250, 0, 0, 0,      0, -(Sqrt[(6338501/10)]/3125), 0, 0, 0, 0, (29 Sqrt[27347/30])/3125, 0, 0,      0, 0, -(Sqrt[(4358874/5)]/3125), 0, 0, 0, 0, -(Sqrt[(352454081/3)]/31250),      0, 0, 0};     Clear[s]     s[m_, l_] := If[m < 0, (-1)^m s[-m, l]]     s[m_?NonNegative, l_] := If[Abs[m] <= l, A[[m + 1]], 0]     Clear[ysaf]     L = 28;     ysaf[θ_, ϕ_] =      ExpToTrig[Sum[s[m, L] SphericalHarmonicY[L, m, θ, ϕ], {m, -5 IntegerPart[L/5], L, 5}]];      _ysaf_ is a pretty complicated trigonometric function of two angles in spherical coordinate system. Next, we define a few parameters for a stereographic projection. I am plotting a part of the unit sphere as seen from a point on _z_ -axis.               θmx = ArcCos[1/Sqrt[5]];     λ = 3/4;     rmx = Sin[θmx/λ];      Following plot takes a minute or so               gr = ContourPlot[{ysaf[λ ArcSin[Sqrt[x^2 + y^2]] , ArcTan[x, y]] == 0,     Sqrt[x^2 + y^2] == rmx}, {x, -rmx, rmx}, {y, -rmx, rmx},      RegionFunction -> Function[{x, y, z}, Sqrt[x^2 + y^2] <= rmx],      Axes -> False, Frame -> False]      Next, I am constructing interpolating functions for contour lines (like in this post)               lines = Cases[Normal[gr], Line[i__] -> i, Infinity];     fns = Map[Map[ListInterpolation[#, {{0, 1}}] &, Transpose[#]] &, lines];      and define a Schwarz-Christoffel map (see p. 468 of Complex Analysis with MATHEMATICA® by W. T. Shaw, isbn 0521836263):               PolyMap[z_] = Integrate[1/(1 - ξ^5)^(2/5), {ξ, 0, z}];      This final plot is the objective of my question. How can I speed it up?               ParametricPlot[     Table[PolyMap[(Through[fns[[a]][x]]/rmx) /. {List -> Complex}] /.      Complex[i_, j_] :> {i, j}, {a, 1, First[Dimensions[fns]]}], {x, 0, 1}, Axes -> False, Frame -> False]      ![plot1](http://i.stack.imgur.com/tydrM.gif) ![plot2](http://i.stack.imgur.com/GtKPR.gif) Any help is appreciated!


title: Documentation build failed with Workbench

text: I'm starting to use Wolfram Workbench 2 to develop a Mathematica package. For the first time I tried "Documentation - Build" under the "Application Tools" but got fatal errors: BUILD FAILED /Users/[...]/docbuild.xml:132: The following error occurred while executing this line: /Users/[...]/docbuild.xml:90: taskdef A class needed by class com.wolfram.jlink.util.MathematicaTask cannot be found: org/apache/tools/ant/Task This is with Mathematica 9.0.0.0 on a Mac with OS 10.9. Any idea on what's wrong here?


title: Aborting Multiple Trial Divisions if a Factor is found

text: I am using Mathematica to perform trial divisions on large Mersenne numbers using specific prime numbers (e.g., primes of the form 8n+1 or 8n-1) and would like the program to abort once a factor is found. Here is an example of the code I have so far:               For[n = 1, n < 2^30, n++,       If[PrimeQ[8 n - 1],        If[Divisible[2^115770329- 1, 8 n - 1], Print["Factor at n = ", n];         Abort[]]]]      This is fine for just testing one form of prime numbers, however, I would like to test both forms at the same time in parallel and have both abort if one finds a factor. I can open two notebooks and have two separate sets of code running at the same time, window / kernel 1 running for 8n-1 and window / kernel 2 running for 8n+1 however if kernel 1 finds a factor and aborts, kernel 2 will needlessly continue running until it also finds a factor or reaches "n max". I would like both to run at the same time and both to abort if one finds a factor and then print the "n" that caused both to abort. Thank you for any help or advice!


title: HighlightGraph and Hyperlink

text: In the documentation of _Mathematica_ it is mentioned that you can use `Hyperlink` and `Tooltip` as _wrapper_ in a similar manner as `Style`. However, the following example does not seem to work: vertices `1` and `2` are highlighted in `Red` but there is neither hyperlink access nor tip.               HighlightGraph[Graph[{1 -> 2, 2 -> 3}], {Tooltip[1, "TEST IT!"],                       Hyperlink[2, "http://stackexchange.com/"]}]      Did I miss something ?


title: looping in mathematica for using the current value as initial state of next value

text: i have some initial state $psi[x,t]$. I perform some operation on it and store the value in another state $pi1[x,t]$. Now on the next step i have to use $psi1[x,t]$ as initial state and perform the functions again and store in $psi2[x,t]$, Please anybody help me how to use loops for this.


title: Bilateral Laplace Transform in Mathematica (to be used with Moment Generating Functions)?

text: I am trying to solve a linear ODE for a Kolmogorov forward equation to get a stationary distribution of a random variable. The easiest approach may be to transform the ODE with a two-sided Laplace transform and then solve for the equation, which would be the moment-generating function. BUT: I can't figure out how to do a two-sided Laplace transform. To give the concrete test for what I am looking for:               MomentGeneratingFunction[NormalDistribution[\[Mu], \[Sigma]], t]      Properly spits out $e^{\mu t + \sigma^2/2 t^2}$. But `LaplaceTransform` defaults to the one-sided transform Laplace transform). If I can figure out the options to make these match, then I can solve my ODE. Also, note that I will need to do the Two-sided Laplace transform of $-t$ instead of just $t$. To see the connection of MGF and Laplace Transforms: http://en.wikipedia.org/wiki/Moment-generating_function#Calculation I found some old documentation for an obsolete package, http://reference.wolfram.com/legacy/applications/signals/MathematicalTransforms.html, that used to do this with the TransformDirection option, but it doesn't work any more.


title: How does PlotLegends actually work with ListPlot3D?

text: I'm sensing this might be a rookie mistake but normally I roll my own legends but decided to try the built in legends for a `ListPlot3D`. `PlotLegends` is listed as an option for `ListPlot3D` but curiously in V9 there are no usage examples. On the other hand there are several examples for `Plot3D`. Specifically I was trying to create a legend analogous to this example from the `Plot3D` docs.               ListPlot3D[Table[Sin[x y], {y, 0, 3, 0.1}, {x, 0, 3, 0.1}],       ColorFunction -> "Rainbow", PlotLegends -> Automatic]      ![enter image description here](http://i.stack.imgur.com/Ur5ot.png) However I want to use my own specific `ColorFunction` but it appears that as soon as you depart from the named built-in string colour functions `PlotLegends` ceases to work. I know how to "roll my own" so I am not seeking assistance with creating my own function. I simply want to know if it is possible to make something similar using the built in options for `ListPlot3D`, whether I am overlooking something or whether this is a bug. **Edit** From Wolfram: _the current design of the PlotLegends -> Automatic option is to turn off the plot legend when a pure function (as`ColorFunction`) is present._ which means that this               With[{cf = Blend[{Blue, White, Red}, #] &,     data = Table[Sin[x y], {y, 0, 3, 0.1}, {x, 0, 3, 0.1}]},         ListPlot3D[data, ColorFunction -> cf,              PlotLegends -> Automatic         ]     ]      doesn't work ...which would appear to make it a design oversight rather than a bug.


title: Colors not showing in Graphics3D

text: The following code works, except that the colors aren't showing in the output. Wh? I probably made a trivial mistake, but I'm yet unable to find it.                 Flatten[Table[{x, y, z} =            {RandomReal[{-10, 10}], RandomReal[{-10, 10}], RandomReal[{-10, 10}]};         p = 0.1;         {u, v, w} = {0.0, 0.0, 0.0};         NestList[(u += RandomReal[NormalDistribution[0, s]];            v += RandomReal[NormalDistribution[0, s]];            w += RandomReal[NormalDistribution[0, s]];            # + p {u, v, w}) &, {x, y, z}, 50],         {s, 0.1, 1, 0.05}], 1];     PlotColor = ColorData["SunsetColors"];          Graphics3D[{PointSize[0.1], {PlotColor[Norm[#]], Sphere[#, 0.1]}& /@ RandomWalkCoords},        Boxed -> False, Background -> Black, Lighting -> "Neutral", SphericalRegion -> True]      I'm not very familiar with this way of programming _Mathematica_ (I'm on version 7.0 by the way), but I'm learning! The output should show a bunch of random curves made of small balls (no lines), with a radial color gradient. Maybe there's a simpler way of doing this?


title: 3D heatmap density plot

text: I have a set of data that looks like `{{x1, y1, z1}, {x2, y2, z2}, ...}` so it describes points in 3D space. I want to make a heatmap out of this data. So that points with a high density are shown as a cloud and marked with different colors dependend of the density. In fact, I want the result of this script just for 3D:               data = RandomReal[1, {100, 2}];     SmoothDensityHistogram[data, 0.02, "PDF", ColorFunction -> "Rainbow", Mesh -> 0]      ![enter image description here](http://i.stack.imgur.com/VoXLo.png)


title: Export notebook file without launching front-end

text: I am using a Mathematica script to programmatically generate a Mathematica notebook. The script generates a `Notebook` expression and then uses `Export` to write the notebook to a file. The following interactive kernel session sketches the necessary commands:               $ /Applications/Mathematica.app/Contents/MacOS/MathKernel     Mathematica 9.0 for Mac OS X x86 (64-bit)     Copyright 1988-2012 Wolfram Research, Inc.          In[1]:= notebook = Notebook[ { Cell["Hello World", "Text"] } ];                                                                                In[2]:= Export["HelloWorld.nb", notebook]                                                                                Out[2]= HelloWorld.nb      The problem is that the `Export` command always launches the Mathematica front-end as a side effect. Is there a way to write the `Notebook` expression to a file without having the kernel launch the front-end?


title: How to get exact roots of this polynomial?

text: The equation $$ 64x^7 -112x^5 -8x^4 +56x^3 +8x^2 -7x - 1 = 0 $$ has seven solutions $x = 1$, $x = -\dfrac{1}{2}$ and $x = \cos \dfrac{2n\pi}{11}$, where $n$ runs from $1$ to $5$. With `NSolve`, I tried               NSolve[64 x^7 - 112 x^5 - 8 x^4 + 56 x^3 + 8 x^2 - 7 x - 1 == 0, x, Reals]      and I get               {{x -> -0.959493}, {x -> -0.654861}, {x -> -0.5}, {x -> -0.142315}, \     {x -> 0.415415}, {x -> 0.841254}, {x -> 1.}}      With `Solve`, I tried               {{x -> -(1/2)}, {x -> 1},        {x -> Root[1 + 6 #1 - 12 #1^2 - 32 #1^3 + 16 #1^4 + 32 #1^5 &, 1]},        {x -> Root[1 + 6 #1 - 12 #1^2 - 32 #1^3 + 16 #1^4 + 32 #1^5 &, 2]},        {x -> Root[1 + 6 #1 - 12 #1^2 - 32 #1^3 + 16 #1^4 + 32 #1^5 &, 3]},        {x -> Root[1 + 6 #1 - 12 #1^2 - 32 #1^3 + 16 #1^4 + 32 #1^5 &, 4]},        {x -> Root[1 + 6 #1 - 12 #1^2 - 32 #1^3 + 16 #1^4 + 32 #1^5 &, 5]}}      How to get exact solutions of the given equation?


title: Speed optimization

text: I have a part of a program that I have to repeatedly call many times (about 2000 to 10000 times)               f = Reap[Do[Sow[{0, 0, 0}], {i, 1, nparticle}];][[2, 1]];     vir = 0.;     hL = L/2.;     e = 0.;     Do[       Do[         dr = r[[i]] - r[[j]];         dr = Map[If[# > hL, # - L, If[# < -hL, # + L, #]] &, dr];         r2 = Dot[dr, dr];         If[r2 < rc2,          r6i = 1./(r2^3);          e += 4*(r6i*r6i - r6i) - ecut;          valuef = 48*(r6i*r6i - 0.5*r6i);          df = dr*valuef/r2;          f[[i]] += df;          f[[j]] -= df;          vir += valuef;          ];          If[r2 <= rc^2,            gr[[IntegerPart[Sqrt[r2]/dh]]] += 2;          ]         , {j, i + 1, nparticle}         ];       , {i, 1, nparticle - 1}       ];      r is a list of the form {{3,4,6},{5,7,8},.....}.   hL, L, rc2 are parameter I initialize at the start. Is there any ways I can optimize the code like using `compile` or `parallelization`? I have tried these but always getting various kinds of errors or wrong calculations.   Is the two `Do` loops avoidable in this case? As requested, here is the value of parameters:               rc = 2.5;     rc2 = rc^2;     nparticle = 108;     rho = 0.4;     L = (nparticle/rho)^(1./3.);     hL = 0.5*L;     rr3 = 1/(rc^3);     ecut = 4.*(rr3^4 - rr3^2);      The initialization of r:               LinCell = Round[(nparticle/4.)^(1./3.)];     lattconst = L/LinCell;     r = Reap[        Do[          Do[            Do[              Sow[{ix + 0.25, iy + 0.25, iz + 0.25}*lattconst];              Sow[{ix + 0.75, iy + 0.75, iz + 0.25}*lattconst];              Sow[{ix + 0.75, iy + 0.25, iz + 0.75}*lattconst];              Sow[{ix + 0.25, iy + 0.75, iz + 0.75}*lattconst];              , {iz, 0, LinCell - 1}              ];            , {iy, 0, LinCell - 1}            ];          , {ix, 0, LinCell - 1}         ];        ][[2, 1]];      \--edit-- Now I need to add an output to the program               If[r2 <= rc^2,      gr[[IntegerPart[Sqrt[r2]/dh]]] += 2;      ]      which is added to the inner the `Do` loop. (I have modified the above code)   gr is initialized to {0,0,0,...}.   dh=0.02


title: LocatorPane and PlotRange

text: Consider the following snippet from the documentation on LocatorPane                 DynamicModule[{pt = {0, 0}},         LocatorPane[Dynamic[pt], Framed@Graphics[{}, PlotRange -> 10]]]      I would like to use a different shape for the LocatorPane, i.e. parallelogram, hexagon, rectangle ). ( In further processing they are 'translated' to a nice tiling. ) **Question: How can I limit the LocatorPane to a shape other than a square?** **EDIT:** From **kguler** 's Answer 'Locator in a Diamond' I made this so that it works with multiple locators.                  pts = RandomReal[1, {3, 2}];        g = Graphics[{Blue, Polygon[Dynamic[pts]], Opacity[.1], Disk[]},          PlotRange -> 1.25];         LocatorPane[         Dynamic[pts, (If[Apply[And, Map[Norm[#] < 1 &, pts]], pts = #,              pts = pts1]) &], g]      The limiting region is a circle here, but can be changed to any function that returns a Boolean. There is one remaining problem and I think that it is related to the problem I found here: LocatorPane, Dynamic and deleting locators


title: Is it possible to make Mathematica reformulate an expression in a more numerically stable way?

text: I'm writing a numerical optimization, and I'm having a problem with an expression of the form $$ e^{-t} (1+\mathrm{erf}(t)) $$ The overall shape of the function looks correct, but when $t$ is small, $e^{-t}$ is huge while $(1+\mathrm{erf}(t))$ is very small, and their product is also small. This leads to horrible floating point inaccuracies. I know, of course, that there are multiple things I can do to remedy this, including scaling my problem so that the values are more reasonably sized. Another is to reformulate the expression to avoid ever computing the huge intermediate values. In the particular example I've given, this is simple: $$ e^{-t} (1+\mathrm{erf}(t)) \\\ \exp{\left[ \log(e^{-t}) + \log{(1+\mathrm{erf}(t))} \right]} \\\ \exp{\left[ -t \log{(1+\mathrm{erf}(t))} \right]} $$ ...which is well behaved for all reasonable values of $t$. However, in my actual expression, there are various parameters with respect to which I take the derivative. The resulting expressions are _hideous_ and reformulating them by hand is daunting (although tractable). Is there a way to make Mathematica reformulate an expression while attempting to avoid expressions that will be numerically unstable? I don't expect Mathematica to be automatically aware of which expressions will be problematic, but if I could, for example, simply instruct it to avoid using `Exp[]` unless it absolutely must, this would be a very useful tool for me (and I suspect for other people working on numerical optimization!). Note: I am not doing the optimization work in Mathematica. I'm only using Mathematica to help derive analytical gradients for my merit function. Therefore, any features of Mathematica which would eliminate the numerical inaccuracy _only in Mathematica_ doesn't really help me.


title: How can I make CDF which uses user defined function

text: I have a user defined function which is called many times in the code. I want to ask that when I am deploying the code to`CDF`, I need to define that user defined function also. I tried it using `DynamicModule` and `With`. But none is working. How should I give that user defined function so that it can be deployed into `CDF`.


title: Problem with FTP import in V10

text: _Mathematica_ V10 returns an error when download directory. > URLFetch :: invhttp: "FTP: could not retrieve (RETR failed) the specified > file." V9 successfully retrieves the same reference. This code successful: `Import["ftp://source:get@ftp.palemoon.org/integrated_statusbar-3.0.zip"]` But this failed: `Import["ftp://source:get@ftp.palemoon.org/"]`


title: Can you apply the Cellular Automata function to a grid containing numbers?

text: Im attempting to simulate a simple evacuation model using cellular automata theory.My study aims to determine whether Cellular Automata can effectively represent how people would behave in a fire situation. I have a grid filled with values that represents the floor plan of a building (see below) and I wish to write rules that will dictate the occupants movement when evacuating. The corridor is supposed to be the safe area although I may have to adjust it slightly so that just the end corridors are the safe area. I am looking to model a fire evacuation, so each cell will contain one person. I was going to assign the value of 0 to cells that contain fire, injured people or debris (obstacles). when designing the simulation by hand I used rules such as if the product of the 2 neighbouring cells was less than 20 the person could move to the next cell, if the product was 20 the cell remained the same and if the product was 0 (when cells meet fire, obstacles etc) then the cell dies and becomes 0 itself. It worked well but obviously I need to now apply a system similar into Mathematica. I have been looking at using 2 options to do this:   1. use the built in cellular automata function   2. write my own cell states as functions and use an update function to update the system. Any suggestions which one would be better to use? Below is the grid I have set up, the values 500 represent walls, 1 represents the doorways and evacuation route, the other numbers 2-7 represent the distance from the nearest exit.               {      {500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500},      {500, 1, 1, 500, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 500, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 500, 5, 5, 5, 5, 5, 500, 1, 1, 500},      {500, 1, 1, 500, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 7, 500, 4, 4, 4, 4, 4, 4, 4, 4, 5, 6, 500, 4, 4, 4, 4, 4, 500, 1, 1, 500},      {500, 1, 1, 500, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 500, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 500, 3, 3, 3, 3, 3, 500, 1, 1, 500},      {500, 1, 1, 500, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 500, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 500, 3, 2, 2, 2, 3, 500, 1, 1, 500},      {500, 1, 1, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 1, 1, 500},      {500, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 500},      {500, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 500},      {500, 1, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1, 500, 500, 500, 500, 500, 1, 500, 500, 500, 1, 1, 500},      {500, 1, 1, 500, 7, 6, 5, 4, 3, 2, 2, 2, 2, 2, 2, 500, 6, 5, 4, 3, 2, 2, 2, 2, 2, 2, 500, 3, 2, 2, 2, 3, 500, 1, 1, 500},      {500, 1, 1, 500, 7, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 500, 6, 5, 4, 3, 3, 3, 3, 3, 3, 3, 500, 3, 3, 3, 3, 3, 500, 1, 1, 500},      {500, 1, 1, 500, 7, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 500, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 500, 4, 4, 4, 4, 4, 500, 1, 1, 500},      {500, 1, 1, 500, 7, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 500, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 500, 5, 5, 5, 5, 5, 500, 1, 1, 500},      {500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500}     }      ![floor evacuation model](http://i.stack.imgur.com/BoMWK.png)


title: How to substitute variables in interpolated function?

text: I'm looking for the way to substitute variables in interpolated function again to original one. (I want to know how to get P(r, theta) from Psol(v, w).) The original variables :                   r , theta (d<=r<=Infinity, 0<=theta<=Pi).      New variables :                   v , w (0<=v<=1, 0<=w<=1).       The relationship is ![Relations of variables](http://i.stack.imgur.com/F7tGG.gif). I now have the interpolated solution Psol(v, w). Psol(v,w) has no analytic expression, and was interpolated from numerical calculation. The final goal is to get P(r=d), after angle-averaging the P(r,theta) ![Angle-averaged P](http://i.stack.imgur.com/UOCCU.gif). I want to know how to get P(r, theta) from Psol(v, w) using above variable-to- variable relationship. May I have your advice? Thanks in advance.


title: Parts of Module body evaluated in external scope?

text: I have an expression that suggests that some expressions in a module body are dragging in definitions from outside the scope in a surprising way. First, consider a symbolic constant, `y`:               ClearAll[y]      Now, define a couple of expressions that should evaluate to this constant, one immediate and one delayed:               z = y; w := y;      Let's also define a "function" `v` (actually a rewrite rule in the `DownValuess` of `v`), that will return its argument:               v[y_] = y;      Now, the surprise is that if I define a local variable `y` in a Module, various symbolic expressions involving the symbol `y`, specifically `w` and `z`, seem to be evaluated in the environment outside the Module, where `y` evaluates to itself, and other expressions involving the symbol `y`, namely `y`, `v[y]`, and `D[y^2/2, y]` seem to be evaluated in terms of the local variable. To wit:               Module[{y}, {w, v[y], y, z, D[y^2/2, y]}]        produces               {y, y$668, y$668, y, y$668}      Naturally, if I give the local variable `y` a value from outside, then I don't see the secret fresh variable:               ClearAll[x];     Module[{y = x}, {w, v[y], y, z, D[y^2/2, y]}]        produces               {y, x, x, y, x}      I surmise that what's happening is that in a pre-evaluation step, any _overt_ occurrences of `y` are rewritten to the (value of the) fresh variable and then the body is evaluated. Thus, `w` and `z` don't get evaluated until _after_ an equivalent to               ReplaceAll[Hold[{w, v[y], y, z, D[y^2/2, y]}], y -> y$668]      or               ReplaceAll[Hold[{w, v[y], y, z, D[y^2/2, y]}], y -> x]      is done. Is my surmising correct?


title: Convert an expression to a Function

text: I need a function which can take an expression and return a pure function based on the symbols in the expression. The symbols might have values so must be protected from evaluation. It is probably easiest to give an example: I would like to evaluate something like               x = y = 1;     extractPureFunction[Sin[Pi x^2] + y]      and obtain               Function[{x, y}, Sin[Pi x^2] + y]      or               (Sin[Pi #1^2] + #2) &      Any ideas?


title: NDSolve::derarg error: requiring pure function in solving differential equations

text: I'm trying to numerically solve 2 partial differential equations `eq1` and `eq2` given the boundary conditions in `cond1` using the following code               T = 325;     R = 8.314      p = ceq[t, z]*R*T;      q = (30000*p)/(1 + (2000*p)^0.38)^(1/0.38);     L = 0.0695 ;     cinlet = 0.9;      eq1 = D[c[t, z], t] == D[c[t, z], z, z] - D[c[t, z], z] - D[q[t, z], t];      conds1 = {c[0, z] == 0, c[t, 0] == cinlet, D[c[t, L], z] == 0, q[0, z] == 0};     eq2 = D[q[t, z], t] == (c[t, z] - ceq[t, z]);     NDSolve[Join[{eq1}, {eq2}, conds1], c[t, z], {t, 0, 100}, {z, 0, L}]      It currently provides the error that `D[c[t, L], z] == 0` is simply `True`. But even if I remove this one boundary condition to get `conds1 = {c[0, z] == 0, c[t, 0] == cinlet, q[0, z] == 0};` I get an error: `NDSolve::derarg: "The derivative operator Derivative[1,0] in .... should act on the pure function"` I'm not sure how to avoid this error. Any help would be appreciated.


title: How to Rasterize in "Printout" style

text: I am trying to ascertain how large a justified text block will be when printed by rasterizing it in the `"Printout"` style environment. However, `Rasterize` is reverting to the `"Working"` environment. How can I obtain a raster of the graphic as it appears in `"Printout"` style? The following code illustrates the problem. Note the text differs in size in the two environments: In the `"Printout"` environment the text occupies eight lines, but in the rasterised `"Working"` version it takes up only seven lines. I am using text height prediction for page layouts.               SetOptions[EvaluationNotebook[], ScreenStyleEnvironment -> "Printout"];          lorem = StringTake[ExampleData[{"Text", "LoremIpsum"}], {198, 922}];          {wd, ht} = {564, 120};          box = Graphics[{Green, Rectangle[{0, 0}, {wd, ht}],        Black, Inset[TextCell[lorem, LineSpacing -> {0, 16},          TextJustification -> 1], {0, 0}, {Left, Bottom},         {wd, Automatic}]},       BaseStyle -> {FontFamily -> "Times", FontSize -> 13},       PlotRange -> {{0, wd}, {0, ht}}, ImageSize -> wd]          Rasterize[box]      ![enter image description here](http://i.stack.imgur.com/biLcl.png) The notebook screen environment can be restored with the following statement:               SetOptions[EvaluationNotebook[], ScreenStyleEnvironment -> Inherited]      **Edit** Further to george2079's suggestion I made an automated procedure to produce a rasterised `"Printout"` graphic. It is subsequently processed in a separate procedure (not shown here) to ascertain the height of the text box required for print output.               createPrintBox[text_] := Module[{wd = 564, ht = 120, nb},       nb = CreateDocument[ExpressionCell[          Graphics[{Green, Rectangle[{0, 0}, {wd, ht}],            Black, Inset[TextCell[text, LineSpacing -> {0, 16},              TextJustification -> 1], {0, 0}, {Left, Bottom},             {wd, Automatic}]},           BaseStyle -> {FontFamily -> "Times", FontSize -> 13},           PlotRange -> {{0, wd}, {0, ht}}, ImageSize -> wd], "Print"],         ScreenStyleEnvironment -> "Printout", Visible -> False];       SelectionMove[nb, Next, Cell];       FrontEndExecute[FrontEndToken[nb, "CopySpecial", "MGF"]];       SelectionMove[nb, After, Cell];       FrontEndExecute[FrontEndToken[nb, "Paste"]];       SelectionMove[nb, All, Cell];       cellcontent = NotebookRead[nb];       NotebookClose[nb];       output = ToExpression[First@cellcontent];       Rasterize[Show[output, ImageSize -> wd]]]          lorem = StringTake[ExampleData[{"Text", "LoremIpsum"}], {198, 922}];          printoutbox = createPrintBox[lorem]      ![enter image description here](http://i.stack.imgur.com/235jX.png) As you can see, this is a useable raster image showing the correct `"Printout"` style, justified text height of eight lines. In contrast, here is the seven line `"Working"` screen-style raster produced by the code below:- ![enter image description here](http://i.stack.imgur.com/71s8k.png)               lorem = StringTake[ExampleData[{"Text", "LoremIpsum"}], {198, 922}];     {wd, ht} = {564, 120};     Rasterize[Graphics[{Green, Rectangle[{0, 0}, {wd, ht}],        Black, Inset[TextCell[lorem, LineSpacing -> {0, 16},          TextJustification -> 1], {0, 0}, {Left, Bottom},         {wd, Automatic}]},       BaseStyle -> {FontFamily -> "Times", FontSize -> 13},       PlotRange -> {{0, wd}, {0, ht}}, ImageSize -> wd]]


title: Caching data in Mathematica package

text: Consider the following:               m=Quantity[1,"meter"]      If I run the package, it will return `1m` But when I load the package, the package is re-evaluated meaning, that internet i required. Is it possible to use cached results in a Mathematica package?


title: How to center the labels on a bar chart so they are directly under their respective bar?

text: I am using v8 and have the following code:               BarChart[#, ChartStyle -> "Pastel",      ChartLabels -> (Rotate[#, Pi/3] & /@ #2)] & @@ Transpose[totals4]      It creates a bar chart and places the labels at a angel that slopes from the bottom, up to the right (slants to the right). The labels are not centered with the bars. In other words if there are 10 vertical bars, the corresponding labels are not centered, rather they are shifted to the right. How can I center the labels? How can I have the labels slant to the left? Example of how it looks currently: ![countries](http://i.stack.imgur.com/1HBsF.png) Thank you for any help.


title: Convert a symbol name to a Symbol and pass it as an argument to a HoldAll function unevaluated

text: ClearAll[holdingFunction];     SetAttributes[holdingFunction, HoldAll];     holdingFunction[a_] := Print[FullForm[Hold[a]]]; (* Actual implementation is different *)          ClearAll[evaluateOneStep];     evaluateOneStep[expr_] := (* Some magic *);          ClearAll[invokeHoldingFunction];     invokeHoldingFunction[symbolName_String] :=        holdingFunction[evaluateOneStep[Symbol[symbolName]]];          ClearAll[fail];     fail := Abort[];      I need to find such an implementation for `evaluateOneStep` so that, for example, `invokeHoldingFunction["fail"]` prints `Hold[fail]` — I need only the symbol itself to be constructed from its name, but no definition that may exist for it to be applied until the function `holdingFunction` decides to `ReleaseHold`. Could you please suggest how to do this?


title: How to perform a breadth-first traversal of an expression?

text: _Mathematica_ provides functions that perform a depth-first traversal, or which use such a traversal, including: `Scan`, `Count`, `Cases`, `Replace`, and `Position`. It is also the standard evaluation order therefore functions Mapped (`Map`, `MapAll`) will evaluate in a depth-first order. It is quite direct to do this:               expr = {{1, {2, 3}}, {4, 5}};          Scan[Print, expr, {0, -1}]      > 1 > > 2 > > 3 > > {2,3} > > {1,{2,3}} > > 4 > > 5 > > {4,5} > > {{1,{2,3}},{4,5}} How can one do a `Scan`-type operation breadth-first? (Simply storing then reordering the output is not adequate as it doesn't change the order in which expressions are visited.) `Scan` has the property that it does not build an output expression the way that e.g. `Map` does, which is quite appropriate for breadth-first scans, and conserves memory.


title: Determining the total illumination of a polygon

text: > Is it possible to determine the total illumination of a particular polygon > with the given light sources? I truly acknowledge that _Mathematica_ is not supposed to do this modeling, but it is what is at fingertips for the time being and, according to the Documentation Center, _Mathematica_ somehow does it when rendering a 3D object: > "Directional lighting" simulates a uniform field of light pointing in the > given direction. The Wolfram Language adds together the light from all of > these sources in determining the total illumination of a particular polygon. The only thing I want is to take out that brightness number from processing of graphics and now I wonder does anybody know how to accomplish that?


title: How do you skip missing data values in a data file?

text: In scanning through a simple imported file of weather station data, some dates have missing data. What is a test to use to check whether a datum is valid? I tried `If[tempData[index][[4]]≠NaN, ]` and `If[tempData[index][[4]]≠Indeterminate, ]`, but neither seemed to work. Most of my data is valid, and so it is just a matter of skipping/ignoring the occasional missing entry, and not incrementing my accumulators or counters. The data are already arranged in a Mathematica list, and a missing entry is represented by two adjacent commas with nothing in between. So, what I need is an `If[ ]` statement that will trigger (or not trigger) when it encounters such a missing data element. Here is the code, along with a first snippet of output:               f[x_ /; MemberQ[Range@12, x]] :=       Switch[x, 2, 28, 4 | 6 | 9 | 11, 30, _, 31]          Do[           Do[ sum = 0.0; count = 0; index = 1;            While[index < 20454,             If[Part[tempData, index][[{2, 3}]] == {month, day},              sum = sum + Part[tempData, index][[4]]; count++ ]; index++];             Print[{month, day}, " ", sum, " ", count],            {day, 1, f[month]}            ],           {month, 1, 12}           ]          {1,1} 87.5 +5  56          {1,2} 60.4 +5  56          {1,3} 59.5 +5  56          {1,4} 54.5 +5  56          {1,5} 37.4 +5  56          {1,6} 39.6 +5  56      I interpret these results to mean that Mathematica found, for these six days in January, the sums of the temperatures for the corresponding days in the 20454 days of data (about 56 years) contained in tempData which had valid data. I think the +5 means that the program encountered 5 Null values, so that the data count should really be 51. If I wanted an average temperature for 01 January based on these data, I would divide 87.5 by 51. My main concern is not computing the average, or any of the other manipulations I plan to do, but merely how to skip the Null data values. My most recent attempt was to add               If[!Null === Part[tempData, index][[4]], sum = sum + Part[tempData, index][[4]], count++]      but that did worse than not work — the sums and counts are all zero. Here is a sample of the input data, tempData:               {{1955, 1, 1, 0.4, 1.9, -0.3, 4.2},          {1955, 1, 2, -0.5, 0.5, -1.1, 2.5},          {1955, 1, 3, 0.5, 2.7, -1.9, 0.8},           {1955, 1, 4, 1.4, 2.6, 0.6,"0T"},          {1955, 1, 5, 0.8, 2.3, -0.3, 0},          {1955, 1, 6, 0.7, 3.7, -1.7, 0}, etc. }


title: ErrorBars with BarChart, PlotLabels are not working?

text: In the Add Error Bars to Charts and Plots How To in the Mathematica documentation a function `ErrorBar` is given:               errorBar[type_: "Rectangle"][{{x0_, x1_}, {y0_, y1_}}, value_, meta_] :=         Block[{error},            error = Flatten[meta];           error = If[error === {}, 0, Last[error]];            {ChartElementData[type][{{x0, x1}, {y0, y1}}, value, meta],               {Black, Line[{                  {{(x0 + x1)/2, y1 - error}, {(x0 + x1)/2, y1 + error}},                   {{1/4 (3 x0 + x1), y1 + error}, {1/4 (x0 + 3 x1), y1 + error}},                   {{1/4 (3 x0 + x1), y1 - error}, {1/4 (x0 + 3 x1), y1 - error}}                 }]            }}           ]      that adds error bars to `BarChart`. Here is an example using some random data with random errors:               chartData = MapThread[{#1 -> #2} &, {RandomReal[1, 10], RandomReal[0.1, 10]}]      and some random labels:               labels = ToString /@ RandomReal[100000, 10]      Now plotting it, as per the tutorial:               BarChart[chartData, ChartElementFunction -> errorBar["Rectangle"],      ChartLabels -> Placed[labels, Axis, Rotate[#, Pi/2] &]]      The labels are:               {"99539.6", "17862.9", "14683.4", "32667.2", "42690.",       "70230.8", "59050.4", "59204.7", "9138.2", "19080.3"}      However, in the plot: ![Mathematica graphics](http://i.stack.imgur.com/kk5wW.png) The first label is repeated incorrectly for all the bars, what's going on here? Without error bars the labels on the plot are correct: ![Mathematica graphics](http://i.stack.imgur.com/sVPkE.png)               BarChart[RandomReal[1, 10], ChartLabels -> Placed[labels, Axis, Rotate[#, Pi/2] &]]


title: How to test whether an expression is a valid variable?

text: I would like to test whether an argument is a valid variable for functions like `Solve` and `DSolve`. For instance several functions generate a `"dsvar"` or `"ivar"` message on bad input: > DSolve::dsvar: 2 x cannot be used as a variable. >>   >  Integrate::ivar: Sin[x] is not a valid variable. >> I would like to check an argument before passing it onto one of these functions. I used the function `withBlockedVars` in this answer to come up with what seems like a maybe-not-very-bad way. I block the variable and attempt to assign a value to it.               ClearAll[withBlockedVars];     SetAttributes[withBlockedVars, HoldRest];     withBlockedVars[Hold[expr_], code_] :=      With[{heldVars =         Thread[Cases[Unevaluated[expr],             s_Symbol /; Context[s] === "Global`" && DownValues[s] === {} :> HoldComplete[s],             Infinity,             Heads -> True],          HoldComplete]},       heldVars /. HoldComplete[vars_List] :> Block[vars, code]]               SetAttributes[variableQ, HoldAll];     variableQ[x_] := withBlockedVars[Hold[x], Quiet@Check[x = 0; True, False]];      Tests:               t = 2;     variableQ[2^t]     (* False *)          t = 2; x = 3;     variableQ[x[2^t]]     (* True *)          variableQ[t[2]]     (* True *)          variableQ[Subscript[t, 2]]     (* True *)      My use-case is for defining functions, something like this:               f[eqn_Equal, var_?variableQ] := code      The `code` might call `NDSolve` or `Plot` and so on. Is there a better way to check `var`? Perhaps there is a built-in function I missed? [ _Edit:_ Any solution involving `Pattern`, `PatternTest`, `Condition` etc. would be acceptable. I'm not sure I can think of all the alternative possibilities.]


title: How to use `FindRoot` to solve an equation containing a parameter?

text: I'm trying to derive some of the results of the following paper: _Electrodynamics of semiconductor-coated noble metal nanoshells_ , JT Manassah - Physical Review A In the paper there is matrix $\mathbf M_l^M$, defined as follows, with $\alpha$ as a parameter: ![enter image description here](http://i.stack.imgur.com/S19Wx.png) as you know, $j$ and $n$ and $h$ are different types of spherical Bessel functions. Now, I want t solve the following equation: $$\det ({\bf M}_l^M)=0$$ and obtain the roots in terms of $\alpha$.( I think the equation doesn't have analytical solution, and so I tried to use `FindRoot` command, but this equation has $\alpha$ as a parameter and the roots should be founded with respect to $\alpha$. If there is no (better) way other than `FindRoot`, how can I do this using this command? I mean, how can I make `FindRoot` to solve the equation for different $\alpha$s and what is $x_0$ in the `FindRoot`? (The roots are complex numbers.) (All I want is to obtain a plot, showing the real part of the root versus $\alpha$) **Here is my code (definition of $\bf M$):** http://i.stack.imgur.com/ZV8Rs.png


title: Prevent Plus from threading InterpolatingFunction

text: For an `InterpolatingFunction` $y:\ \mathbb{R}\to\mathbb{R}^2$, `Plus` is unaware of this, so when I do any modifications to it in an unevaluated form, it breaks the result               y = Interpolation[Table[{i, RandomReal[{0, 1}, 2]}, {i, 1, 10}]];     y[t]     y[t] + {1, 2}          (* InterpolatingFunction[{{1.,10.}},<>][t]`     {1+InterpolatingFunction[{{1.,10.}},<>][t],2+InterpolatingFunction[{{1.,10.}},<>][t]} *)      I ran into it doing things like:               y = Interpolation[Table[{i, RandomReal[{0, 1}, 2]}, {i, 1, 10}]];     f[t_] := Piecewise[{{ {1, 2} + y[t], t < 5}}];     df[t_] := Evaluate[D[f[t], t]]     df[t]     df[3]      And I can't figure out how to prevent expressions like `{1,2} + y[t]` from being evaluated while still being able to differentiate them. If `Plus` just realized that `y[t]` is $\mathbb{R}^2$ valued, I think that would simplify everything for me. Is there some way to set this property?


title: Varying plot sizes for identical PlotRanges in ListLinePlot, where one has a legend

text: I am trying to make some figures using ListLinePlot in Mathematica 8. Although the PlotRanges are the same, the resulting frame sizes are different. The only difference (as I see it) between the two plots is that one has a Legend, while the other does not; I made sure the legend sits well within the plot and does not stick out. I experimented with AspectRatio and ImageSize, they only modify the overall size but is not changing the frame size. I am trying to align these plots one below the other in a document, and this varying frame size is causing misalignment. I am attaching a screenshot, and please note the "excess space" on the right hand side plot in comparison to the left. ![enter image description here](http://i.stack.imgur.com/Xv3Kp.png)


title: Calculate the power spectral density of a Markov chain

text: I would like to calculate the symbolic power spectral density of a two state Markov process with a symbolic transition matrix characterised by two parameters. I have tried the below, but it doesn't seem to work. Any help much appreciated!               M = {{1 - pdw, pdw}, {pwd, 1 - pwd}}     P  = DiscreteMarkovProcess[{1, 0}, M]     PowerSpectralDensity[P, omega]


title: Plot with non-standard domain

text: I have data `{x, y}` where x starts at -25 degrees and goes up to +25 degrees in 1 degree steps, and then comes back down to -25 degrees in 1 degree steps again. I want to plot this sinusoidal-type data without the y-data overlapping in the ranges -25 - +25 degrees. I have attached an image of the kind of graph I am after. ![enter image description here](http://i.stack.imgur.com/3O6SS.png) How does one do this?


title: Correct properties for LinearModelFit to produce an ARprocess

text: I have AR model where the dependent variable has been lagged from one to six and added on the right hand side as independent/explanatory variables. From this explanation /AR and OLS, you can see that its the same method used for bot processes but they have different properties. Would it be possible to correct for these differences in properties so that they would produce similar output?               In[367]:=          LinearModelFit[           oneModel6, {Lag6, Lag5, Lag4, Lag3, Lag2, Lag1}, {Lag6, Lag5, Lag4,             Lag3, Lag2, Lag1}] // Normal          Out[367]= 0.0731966 + 0.94007 Lag1 + 0.065967 Lag2 + 0.0138268 Lag3 -       0.00506139 Lag4 - 0.0396571 Lag5 + 0.0246181 Lag6          In[371]:= EstimatedProcess[datafile[[2 ;;, 1]], ARProcess[6]]          Out[371]= ARProcess[{0.969106, 0.031289,        0.0108835, -0.00257615, -0.0160354, 0.006491}, 18.3826]


title: possible bug in Mathematica TeXForm? Generating \left\left

text: I asked about this in the TeX chat. It seems Mathematica generate invalid Latex in this example.               ClearAll[y,x];     ode = D[y[x], x] - (y[x]^2 + 1)/(Abs[y[x] + (1 + y[x])^(1/2)]*(1 + x)^(3/2));     TeXForm[ode]      The output is               y'(x)-\frac{y(x)^2+1}{(x+1)^{3/2} \left\left| y(x)+\sqrt{y(x)+1}\right\right| }      Using `\left\left` is illegal. TeXLive 2014 will not compile it. MWE               \documentclass{article}     \usepackage{amsmath,mathtools}     \begin{document}     \begin{equation}          y'(x)-\frac{y(x)^2+1}{(x+1)^{3/2} \left\left| y(x)+\sqrt{y(x)+1}\right\right| }          \end{equation}     \end{document}      Compile:                pdflatex foo.tex          ! Missing delimiter (. inserted).     <to be read again>                         \left      l.7 ...eft\left| y(x)+\sqrt{y(x)+1}\right\right| }          ?       Just wanted to confirm with others if this is a bug before send email to supprt@wolfram.com unless someone finds a smart fix or an option to solve this. V9.01 and V10. **Update:** If any one gets such a case, the fix in this example is to simply remove the extra `\left` at the outers. Like this               \documentclass{article}     \usepackage{amsmath,mathtools}          \begin{document}         \begin{equation}         y'(x)-\frac{y(x)^2+1}{(x+1)^{3/2} \left| y(x)+\sqrt{y(x)+1}\right| }         \end{equation}         \end{document}       Compiles now ok. The output is ![Mathematica graphics](http://i.stack.imgur.com/x1ax3.png) fyi, just send an email to support@wolfram.com as well. Experts in Latex at TeX forum confirmed the code generated by Mathematica is wrong.


title: Expand 2f[x] to f[x]+f[x] (Simplify sums of ArcTan)

text: I'm trying to simplify an expression with sums of `ArcTan`, for which I've written a transformation rule that works for simple sums, so that `ArcTan[a] + ArcTan[b] -> ArcTan[(a+b)/(1-ab)]`. However, it fails for terms of the type `5 ArcTan[a] + ArcTan[b]`. One way to simplify this expression would be to expand the integer into a sum of units, then transform repeatedly until the expression consists of only one `ArcTan`, but I haven't been able so far to find the way. I've tried `Hold`,`Distribute`, `Sum`,`Fold` with `Plus`to no avail.