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

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?


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

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)


Simulating a Stochastic Process within certain bounds

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?


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

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


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

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.


Randomly selecting and reinserting a subset of elements in a list

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?


how to create a slope field in mathematica?

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


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

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.


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

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?


ParallelSum in Mathematica 9 vs 10

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.


Compiling a recursive formula

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


Map of United States as a 3D histogram

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)


Different Poincaré maps for same Equation

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?


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

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?


Limits explanation in doc

`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


Nonlinear system of equations

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


Apply color function to matrix plot

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


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

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?


Create a list of random reals

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.


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

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?


plot a tube via a 4D plot

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?


Using NDSolve for Integro-Differential Equations

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?


Defining a user defined function in DynamicModule

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


Performance in parameter estimation from ParametricNDSolve using varied initial conditions

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


Bounds on random number

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


How to color ParametricPlot3D based on the parameter?

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!


Plotting a frequency function

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?


Speed up Schwarz-Christoffel mapping

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!


Documentation build failed with Workbench

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?


Aborting Multiple Trial Divisions if a Factor is found

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!


HighlightGraph and Hyperlink

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 ?


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

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.


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

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.


How does PlotLegends actually work with ListPlot3D?

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.


Colors not showing in Graphics3D

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?


3D heatmap density plot

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)


Export notebook file without launching front-end

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?


How to get exact roots of this polynomial?

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?


Speed optimization

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


LocatorPane and PlotRange

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


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

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.


How can I make CDF which uses user defined function

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


Problem with FTP import in V10

_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/"]`


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

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)


How to substitute variables in interpolated function?

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.


Parts of Module body evaluated in external scope?

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?


Convert an expression to a Function

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?


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

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.


How to Rasterize in "Printout" style

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


Caching data in Mathematica package

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?


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

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.


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

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?


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

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


Determining the total illumination of a polygon

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


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

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


ErrorBars with BarChart, PlotLabels are not working?

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


How to test whether an expression is a valid variable?

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


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

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


Prevent Plus from threading InterpolatingFunction

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?


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

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)


Calculate the power spectral density of a Markov chain

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]


Plot with non-standard domain

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?


Correct properties for LinearModelFit to produce an ARprocess

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]


possible bug in Mathematica TeXForm? Generating \left\left

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.


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

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.


How to get the determinant and inverse of a large sparse symmetric matrix?

For example, the following is a $12\times 12$ symmetric matrix. `Det` and `Inverse` take too much time and don't even work on my computer. I don't consider the numerical case.               mat = {       {a[1, 1], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10], 0, 0},       {0, a[1, 1], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10], 0},        {0, 0, a[3, 3], 0, 0, a[1, 4], 0, 0, a[1, 7], 0, 0, a[1, 10]},        {a[1, 4], 0, 0, a[4, 4], 0, 0, a[4, 7], 0, 0, a[4, 10], 0, 0},        {0, a[1, 4], 0, 0, a[4, 4], 0, 0, a[4, 7], 0, 0, a[4, 10], 0},       {0, 0, a[1, 4], 0, 0, a[6, 6], 0, 0, a[4, 7], 0, 0, a[4, 10]},        {a[1, 7], 0, 0, a[4, 7], 0, 0, a[7, 7], a[7, 8], a[7, 9], a[7, 10], 0, 0},        {0, a[1, 7], 0, 0, a[4, 7], 0, a[7, 8], a[8, 8], a[8, 9], 0, a[7, 10], 0},       {0, 0, a[1, 7], 0, 0, a[4, 7], a[7, 9], a[8, 9], a[9, 9], 0, 0, a[7, 10]},       {a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], 0, 0,  a[10, 10], a[10, 11], a[10, 12]},        {0, a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], 0, a[10, 11], a[11, 11], a[11, 12]},        {0, 0, a[1, 10], 0, 0, a[4, 10], 0, 0, a[7, 10], a[10, 12], a[11, 12], a[12, 12]}     }


How to Use ProbabilityScalePlot with Censored Data?

I am trying to reproduce a ProbabilityScalePlot of censored data shown here (see Sample Analysis Plot). Here is my Mathematica code. First I deal with the uncensored case.               probscaleplotFix =      Graphics[Append[First@#, Epilog /. Options[#, Epilog]],      FilterRules[Options[#], Except[Epilog]]] &;     SetOptions[ProbabilityScalePlot,      DisplayFunction ->      probscaleplotFix]; (* Needed to fix a software bug, see solution \     by Alexey Popkov on StackExchange *)          data = {30, 49, 82, 90, 96};     distA = EstimatedDistribution[data,      WeibullDistribution[a, b], {{a, 3}, {b, 50}}]     plot1 = Plot[PDF[distA, t], {t, 0, 200}, Frame -> True,      FrameLabel -> {"Time", "PDF"},      PlotLabel -> "Distribution 1 (no censoring)", PlotRange -> All,      PlotStyle -> Red]      ![Plot 1](http://i.stack.imgur.com/OZfTu.jpg)               plot2 = ProbabilityScalePlot[data, "Weibull",      PlotRange -> {{10, 200}, {1, 90}}, PlotStyle -> Red, Frame -> True,      FrameLabel -> {"Time", "CDF"},      PlotLabel ->      "ProbabilityScalePlot for Distribution 1 (no censoring)",      GridLines -> Automatic]      ![Plot 2](http://i.stack.imgur.com/aQjBi.jpg) So far so good . . . now for the censored data.               eventdata =      EventData[{30, 49, 82, 90, 96, 10, 45, 100}, {None, None, None, None,     None, Right, Right, Right}]          dist2 = EstimatedDistribution[eventdata,      WeibullDistribution[a2, b2], {{a2, 3}, {b2, 50}}]          plot3 = Plot[PDF[dist2, t], {t, 0, 200}, Frame -> True,      FrameLabel -> {"Time", "PDF"},      PlotLabel -> "Distribution 2 (censoring)", PlotRange -> All]      ![Plot 3](http://i.stack.imgur.com/Elven.jpg)               plot4 = ProbabilityScalePlot[dist2, "Weibull",      PlotRange -> {{1, 100}, {1, 99}}, PlotStyle -> Blue, Frame -> True,      FrameLabel -> {"Time", "CDF"},      PlotLabel -> "ProbabilityScale Plot for Distribution 2 (censoring)"]      ProbabilityScalePlot::estmd: Unable to estimate a reference distribution from the data. >>               plot5 = ProbabilityScalePlot[eventdata, "Weibull",      PlotRange -> {{1, 100}, {1, 99}}, PlotStyle -> Blue, Frame -> True,      FrameLabel -> {"Time", "CDF"},      PlotLabel -> "ProbabilityScale Plot for Distribution 2 (censoring)"]      ProbabilityScalePlot::ldata: EventData[8] is not a valid dataset, distribution, or a valid list of datasets and distributions. >> Can someone tell me how to produce the ProbabilityScalePlot for either eventdata or dist2 ? Many Thanks.


How to solve this nonlinear 2 by 2 equations?

I have a equation (x^2 + q1^2 - y^2)/2*(x + q1 - y) + (1 - 2*a)*q + 2*F = 2*(1 - a)*c[q] in q(variable) with parameters q1,a,F and function c(in variable q also, and I define it outside Solve so I can change it easier), when q=x,y the equation will be satisfied. I am new to mathematica, and not sure whether I define c in right way, whether I write my question in correct code. Any suggestion will be appreciated! Thanks in advance.               a = 0.25     F = 0.015641     q1 = 5.3415     c[b_] = ln[b + 1]     Solve[{(x^2 + q1^2 - y^2)/2*(x + q1 - y) + (1 - 2*a)*x + 2*F -       2*(1 - a)*c[x] ==      0 && (x^2 + q1^2 - y^2)/2*(x + q1 - y) + (1 - 2*a)*y + 2*F -       2*(1 - a)*c[y] == 0}, {x, y}]      and the output is:               Solve::inex: Solve was unable to solve the system with inexact coefficients or the system           obtained by direct rationalization of inexact numbers present in the system. Since many of      the methods used by Solve require exact input, providing Solve with an exact version of      the system may help. >>     Solve[{0.031282 + 0.5 x +       1/2 (5.3415 + x - y) (28.5316 + x^2 - y^2) - 1.5 ln[1 + x] == 0 &&     0.031282 + 0.5 y + 1/2 (5.3415 + x - y) (28.5316 + x^2 - y^2) -       1.5 ln[1 + y] == 0}, {x, y}]      I do not understand the above paragraph, and what are inexact coefficients?


Why does Mathematica order polynomial forms in reverse from traditional order?

I could very well be missing something obvious, but this has always bugged me with Mathematica and I don't know why it does it or how to fix it. If I enter any polynomial, say, x^2 + x - 1 for example, the output is always in the form:               -1 + x + x^2      And again:               input: Expand[(x^2 - 1) ((-3 + x)^2 - 4)]     output: -5 + 6 x + 4 x^2 - 6 x^3 + x^4      I find this much more difficult to read than the traditional way, from highest power to lowest. Is there anything I can do to change this? I'm aware that TraditionalForm prints them properly, but it is generally not recommended to do calculations with TraditionalForm so I'd like to avoid that if possible. Then again, IS IT that bad to do calculations with TraditionalForm like it warns?


How do I switch between dashed and undashed styles in ParametricPlot?

I am trying to generate a parametric plot in _Mathematica_ 8 using the following:               pp1=ParametricPlot[{Evaluate[Qin[t]]*10^3,Evaluate[PhiOut[t]]},{t,0,1/f0},AspectRatio->1/1,PlotRange->All,AxesOrigin->{0,0},PlotStyle->Directive[Thickness[Medium],colour]];      This works fine but I was wondering if it is possible to switch the styling of the line from solid to dashed for a certain range of the plotting parameter `t` e.g. for `t>0.5*1/f0`. I know that this can be done by generating separate plots and then combining them. This is not very convenient in my case. Is it possible to do this in a single `ParametricPlot` command?


Display a labeled multigraph

Despite the integration of graphs and networks, multigraphs are not supported in Mathematica 8+. In Mathematica 9+, `GraphPlot` misbehaves for multigraphs having labelled parallel edges:               GraphPlot[{{1 -> 2, "a"}, {1 -> 2, "b"}, {2 -> 1, "c"}}]     GraphPlot[{{1 -> 2, "a"}, {1 -> 2, "b"}, {2 -> 1, "c"}}, DirectedEdges -> True]      ![GraphPlot multidigraph misbehavior](http://i.stack.imgur.com/x5DkF.png) ![GraphPlot multigraph misbehavior](http://i.stack.imgur.com/34Xum.png) `EdgeRenderingFunction` is passed the nonsense labels, so using it is out of the question. Due to this bug, it appears there is no easy way for Mathematica 9+ to render a multigraph with labels. Are there any workarounds, or should I look somewhere other than Mathematica?


Shrinking the size of exported 2D density, vector field, and streamline plots

My question concerns the size of exported eps files that were created using density, contour, vector-field, and/or streamline plots: these files are so huge that whenthey are are inserted into a LaTeX manuscript (using \includegraphics) and a PDF file is created for printing (or viewing on screen), the time to render those pages in the PDF plot is extreme. Typical file sizes range from on the order of 600,000 to 4,400,000, depending on how I tweak various options to the plot commands. At prior suggestions of various people I’ve tried tweaking many of the myriad options for these commands, both individually and in combination (including PlotPoints). By doing so, I can induce _minor_ changes in the size of exported files, but nowhere near enough to make this viable. [The, to me, obvious idea of wrapping the name of the plot in Rasterize (within the Export command) does radically shrink the size of the exported graphic but at way too high cost: of so much loss of clarity as to defeat the purpose of including the graph in the manuscript in the first place.] To illustrate the effects of a few of these tweaks I’ve tried, here is a little data table:               No tweaks:                          759,192         NormalsFunction->None           759,189         Mesh->Full                      759,189         MaxRecursions->2               4,460,439         Rasterize (in Export)           224,000      From my research on the internet, I deduce that this is a common problem. There to be no simple fix I have tried some things suggested by at various sites---multi-step methods involving generating the plots in four or five separate graphics commands (axes, content, color, etc.), then combining them using Show. So far, everything I’ve tried works on the test cases posted where I found the idea but not for my graphs, and because the explanations are absent or lacking, I’ve not been able to figure out how these fixes work well enough to adapt them intelligently to my needs. This issue is important for me: I'm preparing final graphs for a long book, which contains many tens of plots of this type. Yesterday, for example, I tried to print the draft of a chapter that contains four of these density plots. The printer hung when it hit the page of the PDF file that contained the first of these density plots and remained hung for 8 hours, after which time I killed the job. (When I used the option draft->true, to \includegraphics, the file printed in about 2 minutes. Of course, it contained none of the figures, since this option includes in your PDF file not the figure but the full file name of the figure---not what one would need while revising or to give to students or colleagues for comment or to post on a web site or to send to a journal). On reflection, I find it hard to believe that there is not some straightforward way within Mathematica to fix this problem. But, hunt as I might on Wolfram’s site, I’ve not been able to find enough guidance to reduce, let alone solve, the problem. My friend and colleague Paul Abbott, whom I queried about this issue, suggested that I post this information here. Any help would be most appreciated! Thanks a lot. A couple of people offered the useful suggestion that I try a fix posted elsewhere on this site, a fix designed for 3D plots that adds a Prolog to all 3D plots that forces the conversion to bitmap upon export. This does, indeed, shrink the size of 3D plots appreciably but does not affect the size of the 2D plots that are the topic of this question.


Package FiniteFields

In a _Mathematica_ session, I evaluate:               Needs["FiniteFields`"];     fld = GF[2];      Now, for example, I'd like to compute $a^3+a^5$ for $a \in{Z_2}$. The result I'd like to have is $0$, because in $Z_2$, $a^n=a$ and $a+a=0$. I tried:               fld[{a^3}] + fld[{a^2}]      But _Mathematica_ gives me:               Subscript[{Mod[a^2 + a^3, 2]}, 2]      How can I simplify $a^3+a^2$ in $Z_2$ to get zero?


Deleting all characters in a string that do not belong to a small set of elements

Say I have a string {100 aa bbc%j%b%wa ajjcj11j0%2wj fc} with a lot of undesired characters or spaces in it, for example: {" ", "%", "w", "j"}. I'd like to strip the string of these characters, with the provided example giving us the output string:               testString = "100 aa bbc%j%b%wa ajjcj11j0%2wj fc";     StringReplace[testString, {" ", "%", "w", "j"} -> ""]          out: "100aabbcbaac1102fc";      Now, say we don't have a convenient list of undesired characters / spaces / paragraph indicators / etc. Is there a way to select for certain characters instead of specifying that certain characters should be deleted (as in the example)?


How to prevent axes label and tick labels from being placed inside a 3D plot

Consider the following toy-code:               data = Table[{k, Sin[k], 0}, {k, 0, 1, 0.01}];          ListPointPlot3D[{data},      PlotStyle -> {Gray, PointSize[Small]},      Boxed -> False,      AxesOrigin -> {Floor[Min[data]], Floor[Min[data]], 0},      AxesLabel -> {"x", "y", "z"}     ]      which generates the following plot: ![enter image description here](http://i.stack.imgur.com/nQ95M.jpg) Note that the axis label "y" is inside the plot, i.e. to the right of the axis. How can I get the tick labels as well as the axis label to left of the axis?


ReadList error with negative very small numbers

When I try to import data with `ReadList` from a file containing very small numbers `(~10^-318)`, positive data is handled well, whereas negative data casts an error: > "General::digit: "Digit at position 1 in !(\"-5.5137726\") is too large to > be used in base 10." The actual number in the file is `-5.5137726e-318`. It works fine for positive numbers, or smaller exponents. I know `Import` handles well the data, but wanted to use `ReadList` since its ~10 times faster. I also tried truncating the data in the text file (in case it was a precission problem), to no avail. Using Mathematica 9.0.1 with Windows 7 Home Premium. **EDIT** Here is a sample of the data; its a list of the components of a 3D vector:                  124000            0            0        124000 -5.5137726e-318 4.9011312e-318        124000 -6.0038857e-317 -8.1481306e-317        124000 8.7730249e-316 -6.6839177e-316        124000 7.2959464e-315 9.1491867e-315        124000 -9.4449699e-314 7.9490222e-314        124000 -8.6193193e-313 -9.6701831e-313        124000 9.823401e-312 -9.2906591e-312        124000 9.9467387e-311 9.9039764e-311        124000 -9.9117558e-310 1.0571814e-309        124000 -1.1151265e-308 -9.8472336e-309        124000 9.7116423e-308 -1.1671959e-307        124000 1.2122543e-306 9.5070421e-307        124000 -9.2363979e-306 1.2493669e-305      I ran the processing code again, and it seems now that any numbers (positive or negative) smaller than `2e-318` (`$MinMachineNumber`) give the same error. The `Import` command automatically truncates small numbers to 0:               {124000, 0, 0}, {124000, 0., 0.}, {124000, 0., 0.}, {124000, 0., 0.}, {124000, 0., 0.},      {124000, 0., 0.}, {124000, 0., 0.}, {124000, 0., 0.}, {124000, 0., 0.}, {124000, 0., 0.},      {124000, 0., 0.}, {124000, 9.71164*10^-308, -1.1672*10^-307},      {124000, 1.21225*10^-306, 9.50704*10^-307},  {124000, -9.2364*10^-306, 1.24937*10^-305}      I was looking for an output in this way, but with `ReadList`.


Fastest way to sum pairwise potentials

I've been writing a function to sum a pairwise potential on two lists, i.e. two charged bodies, each containing `N >> 1` and `M >> 1` atoms respectively. I need to be able to calculate the potential of atom-atom, residue-residue or body-body potential. In order to do so, I've defined the atom-atom, residue-residue, and body-body potentials as               Caa[atom1_,atom2_]:= Coulomb[atom1,atom2];     Crr[res1_,res2_]:= Total[Outer[Caa,res1,res2,1],2]     Cbb[body1_,body2_]:= Total[Outer[Crr,body1,body2,1],2]      where               body1 = {res11,res12,res13,...}     body2 = {res21,res22,res32,...}          res11 = {atom111,atom112,atom113,...}     res12 = {atom121,atom122,atom123,...}     ...     res21 = {atom211,atom212,atom213,...}     res22 = {atom221,atom222,atom223,...}     ...          atom111 = {{x111,y111,z111},q111}     atom112 = {{x112,y112,z112},q112}     ...     atom211 = {{x211,y211,z211},q211}     atom212 = {{x212,y212,z212},q212}     ...      i.e, two lists (bodies) of residues, which in turn are lists of atoms, all properly indexed. My question is, what is the most efficient way to define `Crr`and `Cbb`? I've tried with loops, `Sum`, `Table`, and a the `Total[Outer[...],2]` definition shown, but all seem to take almost the same (very long) time when doing a `Timing` check. Needless to say, `Coulomb` is a radial function, i.e., it only depends on the distance between `atom1`and `atom2`, and `atom = {{x,y,z},q}`, where `q` is the charge. **\--EDIT 1--**               Coulomb[atom1_,atom2_]:= atom1[[2]] atom2[[2]]/Norm[atom1[[1]]-atom2[[1]]]      **\--EDIT 2--** In http://pastebin.com/Yf9TKSDx, you can find a _small_ example of `body1` and `body2`. Here, `body1[[i]]`, will give you the _ith_ residue of the first body, `body1[[i,j]]`, the _jth_ atom of the _ith_ residue of `body1`. The atom-atom potential is calculated by doing               Caa[body1[[i,j]],body2[[k,l]]]      the residue-residue potential               Crr[body1[[i]],body2[[j]]]      and the body-body potential               Cbb[body1,body2]      hope this clarifies the problem.


Can DSolve solve systems with unspecified function coefficients?

I am an economic research student with no previous experience with _Mathematica_ , so please pardon me if my questions sounds really stupid. I am hoping to solve a system of nonlinear ODEs symbolically. I heard that the `DSolve` utility is very handy for this sort of problem, but before I invest my time in it, I hope to make sure that _Mathematica_ is the answer I want. Specifically, my system contains some function coefficients, but I do not know their explicit expression as of now, and they are just expressed as $\phi(t), \;\psi(t)$ etc. It also contains some unspecified constant coefficient as well. Can `DSolve` handle this situation? If not, I'd very much appreciate it if someone could suggest any alternative methods. Thank you!! * * * **Edit:** My system looks something like this: $\beta\phi(t)\lambda(t)x(t)^{\alpha}y(t)^{\beta-1}-\psi(t)=0\\\ \frac{dx}{dt}=\phi(t)x(t)^{\alpha}y(t)^{\beta}-\gamma{}x(t)\\\ \frac{d\lambda}{dt}=k\psi(t)-\lambda(t)[\alpha\phi(t)x(t)^{\alpha-1}y(t)^{\beta}-\gamma]$ where $\lambda(t)\text{, }x(t)\text{ and }y(t)$ are the functions I want to solve for, and $\phi(t)$ and $\psi(t)$ are function coefficients without explicit expressions, $\alpha,\;\beta,\;\gamma$ and $k$ are unspecified coefficients. I hope the solutions can be expressed in terms of integrals of $\phi(t)$ and $\psi(t)$. Is that possible?


Is it possible to use RandomChoice to choose without other choices being evaluated?

I'm trying to do this:               i1 = 1;     i2 = 1;          RandomChoice[{       (i1 = i1 + 1),       (i1 = i1 - 1),       (i2 = i1 + 1),       (i2 = i2 - 1)}]      In order to chose randomly which variable is going to be incremented or decremented - but it's not working. I've also tried with `--` and `++` but I had the same problem. I am clueless about what may be the problem.


How do we turn off automatic smart quotes/special character substitution?

In Mathematica 8, whenever I enter "hello" into a cell of style "text", the quote marks are automatically converted to special characters: `\[OpenCurlyDoubleQuote]hello\[CloseCurlyDoubleQuote]` This automatic substitution does not happen in a cell of style "input" (good!). Because I use Mathematica notebooks as a front-end to LaTeX, for me this substitution is a disaster, no matter where it occurs. What is the preferred idiom for turning-off this smart-quote feature (and all similar automatic character substitution features) for all cells in a Notebook? The ASCII characters that I type, are precisely the characters that I want in the notebook! The Mathematica documentation is unhelpful ... or possibly I am not looking in the correct place.


Visiting nodes in a tree bottom up

I have a problem that can be reduced to this one: Suppose I have an unbalanced (almost random) tree. The leaves of the tree have one property already set, and all vertex (including the leaves) have another property that I have to update upon visiting. To update that property, I need to cast a function `f[father_Vertex,{son_Vertex..}]` in an ordered way, as shown below: Example               (*build some tree*)     s = KaryTree[23, 3, DirectedEdges -> True];     leaves = Flatten@Position[VertexDegree[s], 1];     (*Draw it*)     HighlightGraph[#, leaves, VertexLabels -> "Name", ImagePadding -> 20] &@s     (*Assign a property to the leaves*)     leaves = Flatten@Position[VertexDegree[s], 1]     s1 = Fold[SetProperty[{#1, #2}, "leavesProp" -> RandomInteger[{1, 5}]] &, s, leaves];     (*Assign another property to all Vertex*)     s2 = Fold[SetProperty[{#1, #2}, "toUpdateProp" -> ""] &, s1, VertexList[s1]];      ![Mathematica graphics](http://i.stack.imgur.com/66wRC.png) Now, to cast my function, I need to visit node sets updating the properties in a hierarchical order: ![Mathematica graphics](http://i.stack.imgur.com/d0iRt.png) Which is the easiest way to accomplish this navigation scheme? **Edit** The visiting order at each tree level is interchangeable {s1, s2, s3, s4} and {s5, s6, s7} **Edit2** Trying to be more clear. This is the desired order of invocation. All calls to `f` within the same round could be done in any order. The red one could be done in the first or second round. ![Mathematica graphics](http://i.stack.imgur.com/cvwpm.png)