title: How can I combine two Pick expressions into one?

text: I want to speed up my code, i.e., replace `Select` by `Pick`. I think using two `Pick` expressions isn't pretty, but I have no good idea on how to combine them.               Select[Permutations@ Range@9,         #1 < #4 < #7 && #1/(10 #2 + #3) + #4/(10 #5 + #6) + #7/(10 #8 + #9) == 1 & @@ # &]          Pick[#, #1/(10 #2 + #3) + #4/(10 #5 + #6) + #7/(10 #8 + #9) & @@ Transpose @ #, 1] & @       Pick[#, Thread[#1 < #4 < #7] & @@ Transpose@#] & @ Permutations @ Range @ 9


title: Expression for the real 7/3 power

text: I need an expression for the real 7/3 power of a real-valued function, i.e., a reformulation of               f[x_] := g[x]^(7/3)      that works for negative values of `g[x]`. This function and its first and second derivatives are used in heavy computation (i.e. in objectives to `FindMinimum`) and need to be well-defined at all values of `x`. In particular, I've tried the following, which don't work:               f[x_] := g[x]^(7/3)      which gives complex values at negative values of `g[x]`, and               f[x_] := Surd[g[x],3]^7      which gives a "Infinite expression" error when its derivative is evaluated at 0.


title: Working with abstract vectors

text: I often need to compute derivatives or integrals involving N-dimensional vectors (where the dimension could be equal to 2 or 3 but is not particularly relevant for the sake of the derivation). The only way I know to translate this into valid Mathematica input is to specialize to a particular N and define all quantities component-wise. A simple example: computing the time derivative of a normalized quantity ![Time derivative of a normalized quantity](http://i.stack.imgur.com/QnzXB.png) While correct, this can obviously get extremely messy fast. At that point, I find it easier to just do the computation by hand using generic vector calculus identities which work for vectors of any dimension. I was wondering if there is a way of doing such computations using an abstract vector type? This post references a `Vectors` command that is potentially related, but it was not clear to me how to use it for calculus. **Edit** : After some more experimentation with `Vectors`, I was able to get quite close to what I was looking for:               $Assumptions = V[t] \[Element] Vectors[3, Reals];     Simplify[D[V[t]/Sqrt[Dot[V[t], V[t]]], t]]      $$\frac{2 V(t).V(t) V'(t)-V(t) \left(V(t).V'(t)+V'(t).V(t)\right)}{2 (V(t).V(t))^{3/2}}$$ However, neither `Simplify[]` nor `TensorReduce[]` could simplify the commutative dot product in the expression above.


title: Potential pollution of Global` context in fresh kernel

text: If I evaluate, with a fresh kernel               Names["Global`*"]      I get > >     {"rhs", "z"} >   I think this is not caused by any packages in `$UserBaseDirectory` or `$BaseDirectory`, because if I evaluate the same expression under V9.0.1, which has the same strings for these variables (directories), I get               Names["Global`*"]      > >     {} >   As expected. I was wondering if others are getting the same result. `rhs` and `z` do not have values, but still I am a bit concerned about the safety of               Remove["Global`*"]      when certain functions may depend on the existence of these symbols in Global`. For example if I set               sys`f[Global`xxxx_] := Global`xxxx      and evaluate               Remove[Global`xxxx]      then the following looks a bit scary                sys`f // Definition      > >     sys`f[Removed[xxxx]:_]:=Removed[xxxx] >   `sys`f` still works, but I still think it may lead to trouble (e.g. with `Save`). Kirma came up with the nice idea of testing this on the cloud. I get               Apply[And,       MemberQ[CloudEvaluate[Names["Global`*"]], #] & /@ {"z", "rhs"}]      > >     True >   But there are many other symbols in the `Global`` context there. So, is this a bug?


title: Variable name string to expression

text: I'm not sure how to name this problem appropriately. But anyway. I have, say, three variables (arrays in my case), which I call:               A1, A2, A3      I would like to perform a certain operation on all of these arrays. Obviously I don't want to duplicate the code. What I figured is the following:               For[id = 1, id <= 3,     INPUT = ToExpression["A" <> ToString[id]];     INPUT = Table[{INPUT[[j, 1]], 10^4*INPUT[[j, 2]]}, {j, 1, Length[INPUT]}];     id += 1;     ];      This unfortunately does NOT work. It's just an example. But the big question is how to handle names of variables in "such" cases? Any help greatly appreciated.


title: Keeping Integrate from making unnecessary assumptions

text: I would like to evaluate the integral $\int_{-\infty}^\infty \mathrm{d}x \, \exp\left(- a x^2 - x^4\right)$ for any real value of $a$. _Mathematica_ 8.0.4 gives the following result:               Integrate[Exp[- a x^2  - x^4], {x, -∞, ∞}, Assumptions -> {a ∈ Reals}]      > >     ConditionalExpression[1/2 Sqrt[a] E^(a^2/8) BesselK[1/4, a^2/8], a >= 0] >   Can I keep _Mathematica_ from restricting its answer to non-negative values of $a$, especially since it can do the integral also for negative values:               Integrate[Exp[- a x^2  - x^4], {x, -∞, ∞}, Assumptions -> {a < 0}]      > >     (Sqrt[-a] E^(a^2/8) π (BesselI[-(1/4), a^2/8] + BesselI[1/4, a^2/8]))/(2 > Sqrt[2]) >   I can construct the solution for all real $a$ from these two restricted solutions using `Piecewise`, but I'd rather not do that.


title: Stop Computation - Is Exit[] overkill?

text: The following example either finds a factor of the number $n$ or returns a message saying that the number in question is prime (I specifially wrote this to demonstrate my question below).               n = 125;     For[i = 2, i <= Sqrt[n], i++,         If[Mod[n, i] == 0, Print["Factor found: ", i]; Break[];]      ]     If[i <= Sqrt[n], Exit[];]     Print[n, " is prime."]     ...      I know I could simply include the last Print statement in the if-condition, but I am specifically looking for a command that makes Mathematica skip the last _Print_ statement (and all other statements that might come thereafter...). I tried _Break_ , _Abort_ and _Interrupt_ , but none have the desired effect. Now the commands _Exit_ and _Quit_ work, but they terminate the entire Mathematica kernel, which is a bit of an overkill. How could I bypass this issue? I need something like _SkipRemainingCommands_.


title: How to solve system of integral equations

text: I have two integral equations               -Sin[v]*Integrate[          (x[v, z]*b*Sin[v])/Sqrt[(a^2*(Cos[v])^2 + b^2*(Sin[v])^2 + z^2)^3],          {v, 0, 2*Pi}, {z, -l, l}] == 0          -Cos[v]*Integrate[         (x[v, z]*a*Cos[v])/Sqrt[(a^2*(Cos[v])^2 + b^2*(Sin[v])^2 + z^2)^3],         {v, 0, 2*Pi}, {z, -l, l}] == 0      I would like to find a solution for `x[v,z]`, that is going to solve bough equations. Than I would like to plot 3D graph with axes `v,z,x[v,z]`. Can anyone help me in finding a solution?


title: expression contained across multiple cells

text: Is it possible to span one expression across multiple cells? E.g. long if statement or function evaluation. I looked in documentation and searched forum/google and could not find.


title: Creating event handler with ImplementJavaInterface inside a package

text: I am trying to make my Mathematica function to serve as an event handler for the events generated by a Java object. Specifically, I have a Java object that connects as a client to a server that periodically pushes updates to all clients. I also have an observer object that calls it's `update` method whenever the client receives any updates. My goal is to catch this updates inside Mathematica, and handle them with a Mathematica function It appears that JLink has a way of doing this with `ImplementJavaInterface` command http://reference.wolfram.com/mathematica/JLink/ref/ImplementJavaInterface.html. Here is how I've used it:               (* create a client that connects to localhost:3000 *)     client = JavaNew["me.kutrumbos.DdpClient", "localhost", MakeJavaObject[3000]];          (* create an observer that monitors client's events *)     observer = JavaNew["me.kutrumbos.examples.ObservableDdpClientObserver"];          (* create a variable that will be updated with data from incoming events *)     collections = {};          (* define event handler that updates collections variable with the new value *)     onCollectionUpdate[msg_] := collections = observer@getJSONObjectsList["coll"];          (* add event handler to the observer *)     observer@addMessageHandler[        ImplementJavaInterface["me.kutrumbos.examples.MessageHandler",          "update" -> "onCollectionUpdate"]];          (* add observer to the client *)     client@addObserver[observer];          (* connect to the server *)     client@connect[];      When I run this inside a notebook, everything works. Every time an event occurs, `collections` variable gets updated with the data contained in the event. However, when I put this code in the package, and expose `collections` by adding `collections::usage = "global var"` in the preamble of the package, the variable doesn't update, and the event handler doesn't even seem to run. I tried inserting `MessageDialog["Event Handler alert"]` inside the event handler to see if the event handler is even called, and I am not getting any pop-up alerts when I generate new events on the server. Any idea why this might be happening?


title: VariationalD giving the wrong solution?

text: EDIT: As pointed out in the comments, `VariationalD` gives a variational derivative (which I don't want), not a derivative with respect to a function (i.e. $\frac{df[x]}{dlog_e(x)}$ as a simple example - this is what I thought it did the first time I read the description). Is it even possible in Mathematica to take the derivative of a function with respect to another function? I know you can use the chain rule to rewrite, using the example just above, $\frac{df[x]}{dlog_e(x)}=x\frac{df[x]}{dx}$. In my case the equivalent would be much more cumbersome and I want to be able to change the function w.r.t. which I'm differentiating. Is it possible to do this in Mathematica?   _ I am using the `VariationalMethods`` package, specifically the `VariationalD` command. I am trying to take the derivative of one (complicated) function fitted to experimental data with respect to another (complicated) function. First I wanted to make sure that the command does what I wanted. So I inputted the example given in `VariationalD`'s "Examples" section:                VariationalD[y[x] Sqrt[y'[x]], y[x], x]      This gives a result of $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=\frac{2 y'[x]^2+y[x] y''[x]}{4 y'[x]^{3/2}}. $$ Trying to reproduce this by hand I started with the product rule: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=y[x]\frac{d}{dy[x]}y'[x]^{1/2}+y'[x]^{1/2}\frac{d}{dy[x]}y[x] $$ The second term is just $$ y'[x]^{1/2}\frac{d}{dy[x]}y[x]=y'[x]^{1/2}. $$ The first term, you use the chain rule on: $$ y[x]\frac{d}{dy[x]}y'[x]^{1/2}=y[x]\frac{1}{2}y'[x]^{-1/2}\frac{d}{dy[x]}y'[x] $$ $$ \frac{d}{dy[x]}y'[x]=\frac{dx}{dy[x]}\frac{d}{dx}y'[x]=(\frac{dy[x]}{dx})^{-1}y''[x]=\frac{y''[x]}{y'[x]}. $$ Putting all of that together: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=y'[x]^{1/2}+\frac{1}{2}\frac{y[x]y''[x]}{y'[x]^{3/2}}. $$ Simplifying: $$ \frac{d}{dy[x]}(y[x] \cdot y'[x]^{1/2})=\frac{2 y'[x]^2+y[x]y''[x]}{2 y'[x]^{3/2}}, $$ which is identical to the solution given by `VariationalD` except for a factor of 2. So I assumed it was a mistake I made somewhere (and it might be) and tried comparing every step I made when doing it by hand with the corresponding step in `VariationalD`. Eventually I discovered one difference in the step                VariationalD[Sqrt[y'[x]], y[x], x]      which gives an answer of $\frac{y''[x]}{4y'[x]^{3/2}}$, a factor of 2 different than when I do it. I'm still not sure where the factor of 2 in the $y'[x]^{1/2}\frac{d}{dy[x]}y[x]$ step comes from. I kept messing around with it and found that                VariationalD[y'[x],y[x],x]=0      which can't be right. For example, if $y[x]=x^2$ and $y'[x]=2 x$, $$ \frac{dy'[x]}{dy[x]}=\frac{d(2x)}{dx^2}=2(\frac{dx^2}{dx})^{-1}=2(2x)^{-1}=\frac{1}{x}. $$ So why is `VariationalD` giving a zero answer? It's even weirder because $\frac{dy'[x]}{dy[x]}$ comes up when you perform the original differentiation by hand as well. It can't be zero there either or the first term would vanish and the answer would just be $y'[x]^{1/2}$. So am I making a stupid mistake in my differentiation? Even if so, why is `VariationalD` giving zero for the derivative with respect to a function of its derivative? I've spent about an hour searching for anything relevant online, and...nothing. Any help would be appreciated! EDIT: I've been looking at the description of `VariationalD` more closely and now I'm not sure it does what I think it does, i.e.                VariationalD[f[x],g[x],x]      gives $\frac{df[x]}{dg[x]}$ as output. Is this correct? Looking at the description it now seems to me that it would give $f[x]\frac{df[x]}{dg[x]}$. But if that's the case then the output for my original expression is still wrong.


title: Can I enter the traditional form for Binomial as input in an expression?

text: Is there a way to enter the traditional form of a binomial coefficient, i.e. ${n \choose k}$ instead of `Binomial[n,k]`, like I would enter a radical sign $\sqrt{x}$ using control-shift-2? I would like to enter it that way in a notebook, and see it in that form in the input as well as output equations, just like the radical. I know that I can use `TraditionalForm` to convert it on output, but I don't need to do that to see radicals instead of `Sqrt`.


title: Why does Mathematica list the variables in a double integral backwards?

text: I am an advanced novice Mathematica user and have done a fair amount of single-variable calculus things with it. This semester I am using Mathematica for multi-variate calculus and when I tried to use Mathematica to solve a double integral I got incorrect results. I discovered that the syntax for the Integrate command has you list the variables in the opposite order they appear in the integrand. At first blush this seems dumb and annoying but perhaps there is a good reason for it. If so, I'd like to know what it is. If not, is anyone else annoyed by this?


title: Correct way to remove matrix columns?

text: I start off with `m = 1000 x 5` matrix, and I would like to remove first column to get `1000 x 4` matrix and repeat again for `1000 x 3` and so on. Is there an efficient way to do this? I see Insert to add columns or rows but don't see command for removing? I see maybe use the extract but is this only for a single vector extraction?


title: Behavior of $PreRead in Kernel

text: I am interested in making a simple accounting style line calculator that allows me to interact with it something like this:               In[]:   4 + 5     Out[]:  9     In[]:   +3     Out[]:  12     In[]:   *2     Out[]:  24     In[]:   /4     Out[]:  6      In the front end, I can do this with:               $PreRead = (ReplaceAll[#, {"*" :> "% *", "+" :> "% +", "-" :> "% - ",       "/" :> "% /"}] &)      (And stop it by `$PreRead =.`) which works nicely, however I would like to use the numberpad, and the + key on the number pad starts a free form input. So, I thought I'd be sneaky and open up a kernel window. Sadly, the above assignment of $PreRead doesn't seem to execute in the Kernel, even though it looks like the variable has been assigned properly. I'm interested in why $PreRead isn't behaving the same in the Kernel window as it would in the front end, and it wouldn't hurt to know if it is possible to shut off the keymapping of the numberpad + key to free form input.


title: Hold expression with RandomInteger

text: One more question for today: I'm trying to show two random integers with a plus (+) sign between them, in an unevaluated form. I know how Hold and HoldForm work, but they hold everything, including the RandomInteger:               Hold[RandomInteger[100] + RandomInteger[100]]      I've tried then Evaluate before RandomInteger, but that doesn't seem to do the trick. Any help with this? Very much appreciated, as always!


title: CDF Player: MathKernel.exe uses a lot of memory

text: When I run this CDF document http://x6174x.blogspot.pt/2013/04/bankroll- growth-simulator.html on my desktop, each time I press "Run again" the Task Manager shows that the MathKernel.exe process associated with the CDF player uses increasingly more RAM. However if I try it on a laptop with the same OS (Win 7 Ultimate) the memory usage remains more or less constant. What could be wrong with the first CDF Player? I tried to reinstall it but the problem persists. I should add that the first computer has Mathematica 9 installed but the laptop has only the CDF Player. Could this be some interaction between the CDF player and Mathematica? Even if I have Mathematica closed when I run the CDF document it will show a Mathematica.exe process running. Thanks.


title: How to simplify an expression with special functions to zero

text: The following is a well-known Bessel function identity: $$J_{-n}(z)=(-1)^n J_n(z),\qquad n\in\mathbb Z$$ To check this, I used the following code and the result is as what I expected.               In[2]:= FullSimplify[(-1)^n*BesselJ[n, z] == BesselJ[-n, z], n ∈ Integers]     Out[2]= True      The problem is that _Mathematica_ does not return zero when I try to simplify the following expression: $$(-1)^n J_{n}(z)-J_{-n}(z),\qquad n\in\mathbb Z$$ I tried the following code, but the output is as complex as the input:               In[3]:= FullSimplify[(-1)^n*BesselJ[n, z] - BesselJ[-n, z], n ∈ Integers]     Out[3]= -BesselJ[-n, z] + (-1)^n BesselJ[n, z]    (*result I expected : 0*)      My goal is to command _Mathematica_ to reduce the expression to zero, and I need some advice.


title: How to delete all rows in datafile that contain a string

text: I'm importing some data from a file. However, the file was created by an unreliable instrument, such that the data looks like this:               in: data = Import["D:\\6000s.txt", "Table"]       out: {...{5,0,46.4109},{6,0,46.6017},{7,0,No,Data},{8,0,45.7324}...}      The lines containing "No Data" can be safely deleted, but I don't know how to do this well. How can I efficiently map over my table and erase all rows that contain a string? Thanks in advance for your help. Edit: An example of my data is  here . Also, a closely related question is here Edit 2: @RunnyKine's and @MikeHoneyChurch's answers in the comments did the trick. I ended up doing the following:               data = Import["my_data.txt", "Table"];     data = DeleteCases[data, {__, _String, _String}]      This is _much faster_ than the ugly for loops I had used previously. Thanks for your help!


title: Assigning symbolic operators to built-in functions

text: Can I do something like this: $$\partial_t = D[f, t]$$ i.e. create a symbol instead of a function so that each time I call it, it executes the operation as defined?


title: storing rescaled images in new variables

text: I'm trying to assign random image files that undergo rescaling to a list of variable names. The images I'm trying to assign are the result of mapping the ImageResize function of two arguments to the Randomly generated images, where the 2nd argument has a fixed value. However when I assign the values to a list of variables, the `Scaled[50]` argument is not being applied to the images. Thanks. I store 15 random images in variables `tmp[1]`, `tmp[2]`, ... using a Do statment and recall them using another statement:               Do[tmp[i] = Image[RandomReal[1, {8, 12, 3}]], {i, Range[1, 15]}];     tmp /@ Range[1, 15]      (See Assigning values to a list of variable names) Now I want to Scale all the images 50x and store them in a list of variables. It can overwrite the tmp variables, but for simplicity I'll use new variables:               Do[var[j] = ImageResize[#, Scaled[50]] & /@ tmp[j], {j, Range[1, 15]}];      (See Mapping a function of two arguments where the 2nd arg has a fixed value) When I recall them using               var /@ Range[1,15]      they are not scaled, it is the same images as in `tmp /@ Range[1,15]` unscaled. This code produces the desired result on a single image               var[1]=ImageResize[tmp[1], Scaled[50]]      so I'm not sure why the second Do statment does not produce the desired list of rescaled images. If there is a way to do it in the initial creation of the images (in the first Do statement) that is better.


title: How to get more accurate orthonormal eigenvectors?

text: I have a matrix `M` with real entries in `MachinePrecision`. I compute its eigenvectors and construct matrix `U`:                 ev = Eigenvectors[M];           U = Transpose @ ev;      `U` is supposed to be an orthogonal matrix and thus `Transpose[U].U == IdentityMatrix[ Length @ U]`.   _Mathematica_ gives the latter equality with the accuracy of `10^(-16)`:               Transpose[U].U - IdentityMatrix[ Length @ U]// Abs// Max == 8.8131 * 10^(-16).      Is it possible to make this difference smaller, let's say, order of `10^(-32)`? I need to get eigenvectors which are orthonormal with accuracy of order of `10(-32)` or higher.


title: Checking if a number is a perfect power

text: I wanted to know how would I use Mathematica in order to check if the number is a perfect power I saw the algorithm but couldn't grasp it enough to implement it, so can anybody help?


title: Infinite loop with While is very processor-intensive

text: This simple line of code:               While[True, Pause[1]]      uses 55% of one CPU core on my computer. Are there more efficient ways to construct simple infinite loops in Mathematica? _Edit_ I'm on OS X 10.9.1 using Mathematica 10.0. Further inspection: `While[True,]` uses 100% CPU; `While[True, x]` also uses 100% CPU; `Pause[10]` uses 55% CPU for the time it is waiting, so 10 seconds in this case.


title: Counting and extracting hit circles/triangles for randomly chosen points

text: Below, you see a triangle in which the incircle was inscribed. As we know, the center of this circle is the intersection of the angle bisectors. At this point, one could go further and find the points, where each of the angle bisectors intersect with the circle and create a tangent of the circle which will divide three new triangles from the big one. Each of the new triangles has again an incircle which can be created and cutting (from now on) only one triangle from each new one and repeating this process brings us to the picture: ![Right_Triangle_Incircles](http://i.stack.imgur.com/DytE7.png) First question: Is it possible create this figure in _Mathematica_? Unfortunately, I have no clue and cannot provide some code myself, but I have asked a similar question at TeX.SE and got some pretty nice answers. What I would like to do in the end is not only to create the figure; I want to _shoot_ random points at the figure and want to find out where the points hit the figure in a circle or not. I would be delighted to hear some ideas or if possible to collect sample code for my problem.


title: How to set up and minimize a large system of equations to resolve the individual components

text: I am trying to set up a system of 400*N equations to deconvolute spectral data for four different compounds. I monitored 400 different wavelengths in N solvents (3 solvents in this case). In order to do this, I want to try to minimize the following function: $A_{\lambda_i, N_i} - (\epsilon_{1 (\lambda_i, N_i)}C_1 + \epsilon_{2 (\lambda_i, N_i)}C_2 + \epsilon_{3 (\lambda_i, N_i)}C_3 + \epsilon_{4 (\lambda_i, N_i)}C_4 = 0 $ Here $A$ is the absorbance of the spectrum I want to deconvolute at specified wavelength ($\lambda$) in solvent ($N$).   $\epsilon$ is the molar extinction coefficient for each different compound that corresponds to the absorbance at the given wavelength and solvent. Then unknown quantities are $C_1$ to $C_4$ https://drive.google.com/folderview?id=0B5gGZ4-SD7-ZdHFveVY5b2J3OTQ&usp=sharing My data is organized as follows. Each row has 5 entries and I have 400 rows one (for each wavelength) [$A \; \epsilon_1 \; \epsilon_2 \; \epsilon_3 \; \epsilon_4$] Each solvent has a table organized just like this one. How do I used mathematica to set up this system of equations and get the error associated with the minimization? Also, the solution needs to be constrained such that C$_n$ is positive. Import the data (uploaded on google drive)               phosBB = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_BB.CSV"];     phosMR = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_MR.CSV"];     phosPT = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_PT.CSV"];     phosTB = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_TB.CSV"];     phosUI = Import["/home/marco/LatexDocs/analytical/uvvis/PHOS_UI.CSV"];      PreProcess data to get rid of headings:               phosBB = Delete[phosBB, 1];     phosMR = Delete[phosMR, 1];     phosPT = Delete[phosPT, 1];     phosTB = Delete[phosTB, 1];     phosUI = Delete[phosUI, 1];      Calculate $\epsilon$ from the known solutions (BB-TB):               \[Epsilon]PhosBB = phosBB[[All, 2]]/concPhosBB;     \[Epsilon]PhosMR = phosMR[[All, 2]]/concPhosMR;     \[Epsilon]PhosPT = phosPT[[All, 2]]/concPhosPT;     \[Epsilon]PhosTB = phosTB[[All, 2]]/concPhosTB;      Setup data table [$A_{unk} \; \epsilon_1 \; \epsilon_2 \; \epsilon_3 \; \epsilon_4$]               phosDataTable =        Transpose[{phosUI[[All, 1]], \[Epsilon]PhosBB, \[Epsilon]PhosMR, \[Epsilon]PhosPT, \[Epsilon]PhosTB}];


title: Replace a column in table with a list of numbers?

text: I have a Table of values e.g. {{x,y,z},{x,y,z},{x,y,z}…} How do I replace the the "z" column with a List of values?


title: Issues with $MachineEpsilon

text: I'm attempting to add `$MachineEpsilon` to numbers I am pulling from the domains of 3 interpolating functions. I pulled 3 numbers, and for one of these numbers adding `$MachineEpsilon` produces a number slightly larger than the first (as expected). For some reason for the second two numbers, adding `$MachineEpsilon` does nothing - the number stays the same. I noticed that there are more significant digits in the first number than the last two, which I suppose could have something to do with this, but how can I fix this so that adding `$MachineEpsilon` will create a higher number for the last two numbers? Below is the output that I got by adding `$MachineEpsilon` to my numbers (lim,lim1,lim2):                eps=$MachineEpsilon     InputForm[lim]          (*     1.7775896893621104 *)          InputForm[lim + eps]     (* 1.7775896893621106 *)          InputForm[lim1]     (* 4.925661999190314 *)          InputForm[lim1 + eps]     (* 4.925661999190314 *)          InputForm[lim2]     (* 8.10371456559119 *)          InputForm[lim2 + eps]     (* 8.10371456559119 *)      Additionally, this is how I'm pulling the numbers from the interpolating functions (leaving out some unneccessary code for simplicity):               dom = InterpolatingFunctionDomain[First[r /. g1]];     dom1 = InterpolatingFunctionDomain[First[r /. g2]];     dom2 = InterpolatingFunctionDomain[First[r /. g3]];     dom3 = InterpolatingFunctionDomain[First[r /. g4]];     {lim, b} = dom1[[1]];     {lim1, b1} = dom2[[1]];     {lim2, b2} = dom3[[1]];      Thanks for any help! I'm using the pulled numbers and their next closest in plot and have continued to get the pllp error message saying the two numbers are the same.


title: Log-Plots and PlotRange

text: Why does the `PlotRange` option in               list=Table[{x,Exp[Sqrt[x]]},{x,0,25}];     ListLogLogPlot[list,PlotRange->{0,10},Joined->True]      not work although there is no error-output? The same holds for `ListLogLogPlot`.


title: Speeding up ReplaceRepeated while truncating to desired order

text: I need to program in an algorithm that recursively makes algebraic replacements which leads to an utterly complicated algebraic function of $x$, but whose final result is only needed at fixed order in the Laurent series in $x$. I wish to use this fact to make the algorithm go faster. Here is sample problem that mimics the realistic problem: \begin{align}f_n(x) &= \sum_{j=1}^4\frac{1}{6+j x}n\left(\frac{1}{x}+j \,f_{n-1}(x)\right); \qquad f_0(x) = {\tt f[0]}\\\ F(x) &= \sum_{n=1}^6\frac{1}{2+n x}\left(\frac{n}{x}+f(n)\right) \end{align} The algorithm is to repeatedly insert the first equation into the second one until all instances of $f_n(x)$ turn into $f_0={\tt f[0]}$. All that is needed in the end is the Laurent expansion out to $\mathcal{O}(x^0)$ (just need the $1/x$ and constant terms). _nota bene: The sums are there only to lengthen the expression to make Mathematica work harder._ Here is a naive implementation (with the result on my machine):               (*Implementation 1*)     f[n_] /; n > 0 -> Sum[1/(6 + j x) n (1/x + j f[n - 1]), {j, 1, 4}];     Sum[1/(2 + n x) (n/x + f[n]), {n, 1, 6}] //. %;     Timing[Series[%, {x, 0, 0}]]      ![Result of implementation 1](http://i.stack.imgur.com/hRqaV.png) Performing the actual recursion in the second line is lightening fast. But the final step `Series` function is painfully slow (4.109 seconds), since the $x$ in the denominators forces _Mathematica_ to appeal to its analytical routines to expand things like $\frac{1}{1+x}\approx 1 -x$. Since all that I need is the first two terms of the Laurent series, I went ahead and, by hand, expanded the fractions $\frac{1}{6+jx}\approx(\frac{1}{6}-\frac{j x}{36})$ and $\frac{1}{2+nx}\approx(\frac{1}{2}-\frac{n x}{4})$, with the intention of partially freeing _Mathematica_ of painful analytics.               (*Implementation 2*)     f[n_] /; n > 0 -> Sum[(1/6 - (j x)/36) n (1/x + j f[n - 1]), {j, 1, 4}];     Sum[(1/2 - (n x)/4) (n/x + f[n]), {n, 1, 6}] //. %;     Timing[Series[%, {x, 0, 0}]]      ![enter image description here](http://i.stack.imgur.com/03tCw.png) This is 8 times faster; the more I save _Mathematica_ from doing analytic manipulations, the faster it goes. But I need it to go faster, yet. How can I carry out the alogorithm to minimize the extent _Mathematica_ has to do computationally costly analytic work? Here's my failed attempt: ask _Mathematica_ drop higher order terms at each stage in the recursion by adding an `O[x]` to the end of the line:               (*Implementation 3 [FAILURE]*)     f[n_] /; n > 0 -> Sum[(1/6 - (j x)/36) n (1/x + j f[n - 1]), {j, 1, 4}];     Timing[Sum[(1/2 - (n x)/4) (n/x + f[n]), {n, 1, 6}] + O[x] //. %]      ![enter image description here](http://i.stack.imgur.com/mYBD6.png) Very fast, but the wrong answer. It gets the wrong answer because it drops terms like `x*f[n]` as it thinks `f[n]` is order `O[x]^0` when in reality there is a `1/x` part. What can I do to speed this up?


title: Save icon in toolbar in v9

text: In previous versions of MMA there was a 'Save" icon in the toolbar when you do the "Show Toolbar" from the "Window" menu. This is not present in v9. Anybody know how to get it back?


title: Rapidly binning 3D data

text: I have a set of data (about 20 million datapoints for my real data) of the form `{x, y, z, m}`. There are 3 spatial coordinates `x`, `y` and `z` and a fourth value, the mass (`m`) of the element at that point. I want to bin the data onto a integer spaced 3D grid. And then bin the masses into a series of specific ranges. I want the number of masses that fall into each mass range for each point on the grid. I guess, for `n` ranges I will need `n` 3D arrays or alternatively a 3D array where each point has a list of `n` values. Let's start with some random data               coords = RandomReal[{-100, 100}, {10^5, 3}]; (*these can be negative*)     masses = RandomReal[400, 10^5]; (*these can't be negative*)      and some random ranges to bin the masses, we'll make 50 as this is about how many I have in my real data:               ranges = Partition[Union[Round[RandomReal[400, 100], 0.001]], 2];      Based on this related question: http://stackoverflow.com/questions/8178714/mathematica-fast-2d-binning- algorithm. I started by rounding the coordinates, I want to bin onto unit bins so I simply used `Floor` on the coordinates.               indices = Floor[coords];      and in my case the masses have more precision than the mass range specifications so lets round those now too.               roundedmass = Round[masses, 0.001];      Now based on the related question I used `GatherBy` to collect like coordinates into lists.               gathered = GatherBy[Transpose[{indices, roundedmass}], First];      However, I'm stuck as to how to quickly bin the masses in each of the gathered coordinate-bins into the various mass ranges. In the end I guess I will have 50 3D arrays where each coordinate-bin has a value corresponding to the number of masses in the specified mass-range. 50 mass ranges = 50 3D arrays (probably sparse as there will be lots of empty space), or alternatively a 3D array where each point has a list of 50 values. I've tried to use `BinCounts` but this also bins in between the mass ranges so I had to drop ever other bin that was returned, seems wasteful...:               fbinmasses = BinCounts[#, {Flatten@ranges}][[;; ;; 2]] &     binnedmass = ParallelMap[fbinmasses, gathered[[All, All, 2]]];      combinedoutput = Transpose[{gathered[[All, 1, 1]], binnedmass}];     sortedoutput = Sort[combinedoutput, OrderedQ[{#1[[1]], #2[[1]]}] &];      Now, I would need to make a sparse array, maybe like this (going to have issues with negative inidices...? And it seems like you can't store a list in a sparse array.               output = SparseArray[gathered[[All, 1, 1]] -> binnedmass]


title: What is an alternative to using backticks in separating namespaces from function names?

text: What is an alternative to the backtick (```) in separating the namespace from the function name? Can the function be called without using this symbol? I think in early versions of Mathematica one could use `::` but it does not seem to work now.


title: Exporting notebook to HTML, using conversion rules

text:
The idea is to export the whole notebook to HTML with all the math equations in latex form. In this way we can add the mathjax script and it will take care of the math. Suppose we have the following in a notebook: > This is an equation: $f(x) = x^2$. We let $x \in [0,1]$ for this example. The following is the expression that generates the above.               Cell[TextData[{      "This is an equation: ",      Cell[BoxData[       FormBox[        RowBox[{         RowBox[{"f", "(", "x", ")"}], " ", "=", " ",          SuperscriptBox["x", "2"]}], TraditionalForm]],       FormatType->"TraditionalForm"],      ". We let ",      Cell[BoxData[       FormBox[        RowBox[{"x", " ", "\[Element]", " ",          RowBox[{"[",           RowBox[{"0", ",", "1"}], "]"}]}], TraditionalForm]],       FormatType->"TraditionalForm"],      " for this example."     }], "Text"]      If you look here you will find an example of how to use the conversion rules. Unfortunately, I haven't been very lucky with it, as you can see in one of my previous posts. In any case, here is an attempt:               ExportString[      Cell[TextData[{"This is an equation: ",          Cell[BoxData[           FormBox[RowBox[{RowBox[{"f", "(", "x", ")"}], " ", "=", " ",               SuperscriptBox["x", "2"]}], TraditionalForm]],           FormatType -> "TraditionalForm"], ". We let ",          Cell[BoxData[           FormBox[RowBox[{"x", " ", "\[Element]", " ",               RowBox[{"[", RowBox[{"0", ",", "1"}], "]"}]}],             TraditionalForm]], FormatType -> "TraditionalForm"],          " for this example."}], "Text"       ],      "HTML", "ConversionRules" -> {"TraditionalForm" -> {"$",               Convert`TeX`BoxesToTeX[#] &, "$"}}]      The result is the following html code:               <?xml version="1.0" encoding="UTF-8"?>     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"             "HTMLFiles/xhtml-math11-f.dtd">                               <title>       Untitled      </title>      <link href="HTMLFiles/m0001756441.css" rel="stylesheet" \     type="text/css" />
      This is an equation: . We let \     x ∈ [0,1] for this example.

                    Created with Wolfram Mathematica 8.0
                     If we try to export to TeX I'm not so lucky either, instead of the dollar signs Mathematica just ignores it and it gives me:               \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          This is an equation: \(f(x) = x^2\). We let \(x \in  [0,1]\) for this \     example.          \end{document}      The question is: How do we export a notebook to HTML and TeX so that the math is wrapped around the dollar signs? Any other tips or comments are welcomed. # EDIT: This conversion rule for HTML might be more useful:               "Text" -> {"
\n",       If[MatchQ[#, _FormBox],          "$" <> Convert`TeX`BoxesToTeX[#[[1]]] <> "$", #] &, "\n
"}      Using that we obtain:
     This is an equation: $f(x) = x^2$. We let     $x \in  [0,1]$ for this example.
      Question now is... how do we get rid of the span tag?


title: Where do I get the mdefs.h file?

text: I want to generate some C code, and the reference here says that Mathematica comes with a `mdefs.h` file, but I cannot find it. Is there a place where I can download it?


title: Incorrect solution of diffusion equation with Neumann boundary conditions

text: I want to set up a PDE model, which takes a two-dimensional diffusion equation into account. The key problem is that I have some trouble in solving the two- dimensional diffusion equation numerically. Consider the following code:               L = 10;     T = 10;     system = {        D[c[x, y, t], {t, 1}] == D[c[x, y, t], {x, 2}] + D[c[x, y, t], {y, 2}],        Derivative[1, 0, 0][c][0, y, t] == 0,        Derivative[1, 0, 0][c][L, y, t] == 0,        c[x, 0, t] == c[x, L, t],        c[x, y, 0] == 1        };     sol = NDSolve[system, c, {x, 0, L}, {y, 0, L}, {t, 0, T}];     Manipulate[Plot3D[Evaluate[c[x, y, t] /. sol], {x, 0, L}, {y, 0, L}], {{t,T}, 0, T}]      ![Mathematica graphics](http://i.stack.imgur.com/gwrOZ.png) As you can see for `t = 10` there are artifacts at the two edges where the Neumann conditions were applied. Obviously, `c[x, y, t] = 1` solves the system and since this is the initial condition Mathematica should have no trouble to compute it numerically. It tried various ODE solvers (`"ImplicitRungeKutta"`, `"BDF"`, `"Adams"`), but it seems that there is some problem with the spatial discretization, perhaps because of the Neumann boundary condition for the variable `x`. Any suggestions how to fix it?


title: Colors for multiple piecewise functions

text: I have the following $3$ piecewise functions, and I would like that `f1`, `f2` and `f3` have $3$ different colours:               Plot[ Piecewise[{{{f1, f2,f3}, B < 1/2}, {{f1, f2,f3}, B > 1/2}}], {B, 0, 1}]      How can I do that?


title: Reconstruct text pages cut by shredder

text: **Q1** : I have a page of printed text file, but it was cut by a paper shredder (from top to bottom). You can download all the paper fragment here. There are some examples of them. How can I reconstruct it? ![enter image description here](http://i.stack.imgur.com/GscbS.png) **Q2** : This time, the situation is even worse - the page was cut by a shredder twice (from top to bottom and from left to right) ! Download Link. ![enter image description here](http://i.stack.imgur.com/h9Ldw.png) My code for **Q1** :               filenames = FileNames["*.bmp", "C:\\Users\\Liao\\Desktop\\B\\file1"];     pics = Import /@ filenames;     binarypic = Binarize[#, 0.9] & /@ pics;     binarydata = ImageData /@ binarypic;     leftandrightdata =      MapIndexed[{#2[[1]], #1[[All, 1]], #1[[All, -1]]} &, binarydata];     result = {};     firstPic = Select[leftandrightdata, ! MemberQ[#[[2]], 0] &][[1, 1]];     start = leftandrightdata[[firstPic]];     DeleteCases[leftandrightdata, start] //.            x_ /; Length[x] > 0 :> (sort =         SortBy[x, HammingDistance[#[[2]], start[[3]]] &];          AppendTo[result, start = sort[[1]]]; Rest[sort]);     Extract[pics,      Prepend[List /@ result[[All, 1]], {firstPic}]] // ImageAssemble      This code maybe dizzy for you, but it doesn't matter. The core idea is simple and straightforward, which use `HammingDistance` to determing whether two images can be combined together. But for **Q2** , I can't really find a good way to solve it.


title: Correcting a correlation matrix to be positive semidefinite

text: Does Mathematica have a way to "fix" a correlation matrix that is not positive semi-definite? I looked through the documentation and search the internet but could not find anything.


title: What strategies can I use to evaluate a limit when Limit[] returns unevaluated

text: I'm trying to find the following limit using _Mathematica_ : $$\lim_{N\to\infty}\sum_{k=1}^N\left(\frac{k-1}{N}\right)^N$$ The problem is taken from here and is known to converge to $\displaystyle\frac{1}{e-1}$. However, using `Limit` in a straightforward manner returns unevaluated:               Limit[Sum[((k - 1)/n)^n, {k, 1, n}], n -> ∞]     (* Limit[Sum[((k - 1)/n)^n, {k, 1, n}], n -> ∞] *)      How can I explore this problem using _Mathematica_ and obtain the limit?


title: Best way to compute row eigenvectors

text: Without qualification, the term eigenvectors (of a matrix) refers to the column eigenvectors (of a matrix) and can be directly computed with `Eigenvectors[]`. To get the row eigenvectors, one can invert the transpose of the matrix returned by `Eigenvectors[]` (or equivalently, the inverse of `JordanDecomposition[][[1]]`). This approach is usually fast enough, but sometimes computing the inverse takes an enormous amount of time compared to just computing the column eigenvectors. This can happen when the column eigenvectors are partially symbolic or involve `Root[]`. > Is there a better way to compute the row eigenvectors of a matrix? In > particular, is there a way to compute the row eigenvectors as fast as the > column eigenvectors?


title: How can this DivisorSigma code be made fast?

text: Since Project Euler problems are now fair game for questions I have a question of my own.   A certain problem* states: > For a positive integer n, let σ2(n) be the sum of the squares of its > divisors. For example, > > σ2(10) = 1 + 4 + 25 + 100 = 130. > > Find the sum of all n, 0 < n < 64,000,000 such that σ2(n) is a perfect > square. This _Mathematica_ code takes something like an hour to run on a modern machine:               Sum[If[IntegerQ @ Sqrt @ DivisorSigma[2, i], i, 0], {i, 64*^6 - 1}] ~Monitor~ i // Timing      The similarly naive PARI/GP code takes a minute or two:               sum(n=1,64*10^6,issquare(sigma(n,2))*n)      Is there some way to make the _Mathematica_ code fast, or otherwise solve the problem quickly in _Mathematica_? Using a faster perfect square test helps quite a bit but it is still far from the PARI/GP performance. Compilation does not seem possible as numbers exceed the maximum machine-size integer. (*To foil search engines please do not mention the number of the Project Euler problem related to this question. Thanks.)


title: Why the EuclideanDistance of these 2 exact points generates the warning N::meprec?

text: The two points are:               pts = {{1/4 (-1 - Sqrt[5]), Sqrt[5/8 - Sqrt[5]/8]},             {1/4 (-1 - Sqrt[5]), -Sqrt[5/8 - Sqrt[5]/8]}};     EuclideanDistance @@ pts      > N::meprec: Internal precision limit $MaxExtraPrecision = 50.` reached while > evaluating 1/4 (-1-Sqrt[5])+1/4 (1+Sqrt[5]). >>               (* Sqrt[4 (5/8 - Sqrt[5]/8) + Abs[1/4 (-1 - Sqrt[5]) + 1/4 (1 + Sqrt[5])]^2] *)      According to the document, `EuclideanDistance[u, v]` equals to `Norm[u - v]`, so it's not surprising that a `Norm` version generates the same warning and result:               Norm[Subtract @@ pts]      > N::meprec: Internal precision limit $MaxExtraPrecision = 50.` reached while > evaluating 1/4 (-1-Sqrt[5])+1/4 (1+Sqrt[5]). >>               (* Sqrt[4 (5/8 - Sqrt[5]/8) + Abs[1/4 (-1 - Sqrt[5]) + 1/4 (1 + Sqrt[5])]^2] *)      The warning disappears if we choose `Sqrt`:               Sqrt[Total[(Subtract @@ pts)^2]]          (* Sqrt[4 (5/8 - Sqrt[5]/8) + (1/4 (-1 - Sqrt[5]) + 1/4 (1 + Sqrt[5]))^2] *)      Why? Simply a bug?


title: How to program a clickPanel for chemical elements (like a periodic table)?

text: The command               ColorData["Atoms", "Panel"]      indicates RGBColors of "Atoms" by clicking a panel. As I don't want to reinvent the wheel, I asked myself: How to transform ColorData["Atoms", "Panel"] in a clickPanel for chemical elements, which could be used as argument for other functions like ElementData[ ] or IsotopeData[ ]?


title: NIntegrate with and without MaxRecursion

text: Ran a mathematica code using NIntegrate containing an integration over spherical and normal bessel functions. 1.Would the answer in the two cases change if I use MaxRecursion with some number of recursions and don't use it? 2. And also will it matter if I use the global adaptive strategy? 3. In case I want to exclude singularity points for x variable, would I use {x,a,b,c,d} where a and b are singular points and c and d are integration limits. The following is the integral $\mathbf{W}\left(k,l,m,\theta_{k}\right)=8\pi i^{l}\Gamma\tau_{rei}j_{2}\left(k\eta_{rei}\right)P_{2}\left(\cos\theta_{k}\right)\left[\beta P_{l-2}^{m}\left(\cos\theta_{k}\right)j_{l-2}\left(\xi\right)+\gamma P_{l+2}^{m}\left(\cos\theta_{k}\right)j_{l+2}\left(\xi\right)+2\zeta P_{l}^{m}\left(\cos\theta_{k}\right)j_{l}\left(\xi\right)\right].$ Integration is to be done of the following quantity: ($\Gamma$, $\beta$, $\gamma$ and $\zeta$ are just functions of l and m, $\Lambda$ is just a constant, $\xi=k*C$, C is some constant) $\int\mathbf{W}\left(k,l,m,\theta_{k}\right)\mathbf{W}\left(k,l^{\prime},m^{\prime},\theta_{k}\right)\cos\theta_{k}\frac{\Lambda}{k^{3}}\sin\theta_{k}d\theta_{k}$


title: Command to insert item into list

text: Is there a command to insert an item into a list such that they form pairs? In other words to take               InsertObject[{a,b,c},d]      which will output               {{a,d},{b,d},{c,d}}    ?      This would be equivalent to the function,               Table[{{a,b,c}[[i]],d},{i,1,3}]      This way works just fine, but it doesn't seem to be the "Mathematica way" of doing things. Is there a built in command this?


title: Master Document

text: I'm wandering is there Master document concept in Mathematica so that the counter will be counted sequencially in master document. Mean file in child document, the counter follow from master document. I knew that I can setup the counter in the specific file, but then if I add some new section in the first file, then I should change the start counter in the next file. I don't want it, I like next file change the start counter directly, just like Latex


title: How to use all the kernels efficiently

text: We build a project with _Java_ and _Mathematica_ technologies. For this project we have written a bunch of functions in _Mathematica_ and integrated some functions in one `JSP` file. In this way, we made four `JSP` files containing _Mathematica_ code. These `JSP` (in which files _Mathematica_ functions are integrated) files are linked and triggered by _Java_ `servlet's`. Note: for every request, _Mathematica_ (four `JSP`) files should be run. We are using _Mathematica_ for back-end computations purpose. I have two _Mathematica_ kernels, thus my **question** is: How can I use these two kernels efficiently for processing requests? I've never worked on more kernels than two, if anyone has some experience on that point please let me know.


title: Prevent mathematica from simplifying

text: How can i prevent _Mathematica_ from automatically simplifying the expression `Sqrt[a/b]`? In case `a=1` and `b=2`, _Mathematica_ will print `1/Sqrt[2]`, whereas case `a=3` and `b=4`, _Mathematica_ will print `Sqrt[3/4]`. The output of my program would be better readable, if the fractions stayed unsimplified under the square-root symbol.


title: Graphing a network with state transition flows (of varying size)

text: In one of Stephen Wolfram's recent blog posts (http://blog.stephenwolfram.com/2013/04/data-science-of-the-facebook- world/#more-5350) he provides the network plot below. The size of the arrows that connects the different countries is supposed to illustrate the volume of people that moved from country X to country Y. **My questions:**   1. Can somebody please illustrate how to replicate this graph in mathematica (or at least point out "relevant" documentation)?    2. [Bonus part] would it be possible to have the size of the flags (or just the end nodes) correspond to the size of the given country's population (i.e. Chinas flag will be relatively larger than USA's Flag, who's flag will be larger than that of the UK, etc.)?  ![Image from Wolfram's Blog Post](http://i.stack.imgur.com/DjWKV.png)


title: Start animation after choosing of initial values without Animate

text: I want to simply set some parameters with sliders and click a button to start animation. I know that I can manage this with Animate and Manipulate, but my animation is written like in this post, because I need to perform some calculations for stop condition. So the point is that I want to start loop after setting parameters and clicking button. Is it achievable? //edit Ok, lets say that in the animation from linked post is some variable m               Clear[p];     Dynamic[p]     Do[p = Plot[m Cos[a x], {x, 0, 100}, Frame -> True,          FrameLabel -> {{None, None}, {x,        Style[Column[{"doing my own animation !", Cos[a x]},          Alignment -> Center], 14]}}, GridLines -> Automatic];     If[a > 0.2, Break[]]; (*condition to stop*)     Pause[.2],     {a, 0.1, 1, .01}     ]      I'd like to start this animation with button, and before that set **m** with slider.


title: FrameLabel and OverTilde

text: What is the problem with this expression inside ListPrint? `OverTilde` generates here a mess:               FrameLabel->{{"f"<>"("<>ToString[OverTilde["x"]]<>")",None},{"x",None}}


title: Prevent FullSimplify from converting trigonometric expressions to exponential

text: There's an option for `FullSimplify`, which is `Trig`, and with it I could prevent a trigonometric identities from being used. I'm looking for a similar option that would prevent `FullSimplify` from using the Euler formula               Sin[x] -> 1/2/I (Exp[x] - Exp[-x])     Cos[x] -> 1/2   (Exp[x] + Exp[-x])      So I want `FullSimplify` to retain `Sin` and `Cos` functions and to use trig identities, but no conversions to `Exp`. ### Edit Example as requested from a comment:               Cos[2 B g t] Sin[u]^2 - I Sin[2 B g t] Sin[u]^2      In this formula, I want `FullSimplify` not to convert `Cos[2 B g t] - I Sin[2 B g t]` to `Exp[-2IBgT]`.


title: ListContourPlot memory problems?

text: I have a simple 3d dataset (size 7035 x 3, I put it on my site if you want to check) which I want to plot with ListContourPlot:               x = Import["http://www.inrim.it/~magni/a.dat"];     ListContourPlot[x, PlotRange -> {All, {0, 6}}]      ... and so far so good. But the x scale must - for various reasons - be rescaled, so I did this:               ListContourPlot[x /. {H_, f_, s_} -> {H*80, f, s}, PlotRange -> {All, {0, 6}}]      and M is unable to complete: after some seconds it exits _without errors_ , and I discover the kernel has quit!


title: Is it possible to insert new colour schemes into ColorData?

text: Because of the standards in my field, for many plots I need to use (or at least end up using) rather narrowly defined colour schemes, and in particular the Matlab "Jet" scheme, which is well described in this SO answer. I've typically done this by having a bit of boilerplate code which I include when necessary, and which creates the object `ColorData["Jet"]`:               Unprotect[ColorData];     ColorData["Jet"] =        Function[x,         Blend[Transpose[{             {0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0},              {Darker[Blue], Blue, Cyan, Green, Yellow, Red, Darker[Red]}        }], x]];     Protect[ColorData]      This is convenient because the new colour scheme can be handled using the same syntax as the in-built ones. In version 10, however, the choice of colour schemes has a bunch of additional niceties which I'd like to take advantage of it that's possible. For example, the autocomplete menu for `ColorDat...` gives you instant access to a drop-down menu with images of the schemes' gradients, and which inserts `ColorData["gradient-of-your-choice"]` when you click OK. ![enter image description here](http://i.stack.imgur.com/xkIdz.png) ![enter image description here](http://i.stack.imgur.com/Av0lK.png) Similarly, when you evaluate such `ColorData` objects, they come out with a nice preview of the gradient. ![enter image description here](http://i.stack.imgur.com/VazBL.png) So, my question is: is it possible to take advantage of this structure by 'injecting' additional data into `ColorData`, so that custom colour schemes come up in the choices and behave in the same way as in-built ones?


title: Sending a command to an already opened frontend

text: I'm trying to pipe low-level notebook commands to work through terminal and I've tried various ways, but I can't really get to the frontend that's already open. For example Opening a notebook from command line in an existing front end instance this no longer works. I've tried connecting to notebooks kernel, but it didn't work as I expected... perhaps I know too little. I'd imagine it to work like this: math -script file.m or mathematica file.m Where file.m would contain commands to evaluate on currently opened notebooks in an existing mathematica instance. How should I approach it?


title: Nothing appears in simple plot

text: I'm trying to get the following simple code to work. (The code is just supposed to graph the norm of the second derivative of a vector function).               z[t_] = {1, t^2, t^3}     Plot[D[D[Norm[z[t]], t], t], {t, 0, 5}]      Nothing appears on the graph, and I get errors like "General::ivar: ... is not a valid variable". I read that these errors can be avoided if one uses the Evaluate command:               Plot[Evaluate[D[D[Norm[z[t]], t], t]], {t, 0, 5}]      This code doesn't result in any errors, but nothing appears in the plot. Interestingly, the code that reverses the order of operations and graphs the second derivative of the norm works fine:               Plot[ Evaluate[Norm[D[D[z[t], t], t]]], {t, 0, 5}]      I tried using DiscretePlot as well, but that didn't help. What am I doing wrong? I suspect the problem somehow relates to evaluation, but I can't figure it out. Thanks in advance for any help!


title: fitting system of ODEs - "part2 of {} does not exist" errod

text: I'm trying to fit my data to a system of ODEs:               x'[t]==a*x[t]+b*y[t]     y'[t]==c*y[t]+d*x[t]+e*z[t]     z'[t]==f*z[t]+g*y[t]      having t,x[t],y[t],z[t]. I followed the code from here, but in the end got an error "Part::partw: "Part 2 of {{X[0]->6.99188*10^7,Y[0]->1.44163*10^6,Z[0]->1.22418*10^6}} does not exist. General::stop: Further output of Part::partw will be suppressed during this calculation. >>" I'm a newbie in mathematica, can you point out what I do wrong? Or maybe you can suggest better way to do such fitting? Here's my code:               data = {{0.0001, 69721851.824697, 1710041.15718086, 1249648.07662318},     {0.0002, 69043570.7566936, 2066441.5110575, 1844749.71071548},     {0.0005, 67932147.9362317, 2994541.62071368, 3108260.41352905},     {0.0009, 66863760.1248742, 3587039.29801347, 4282635.21874863},     {0.0015, 64345357.8511309, 968094.021795217, 10585640.3555617},     {0.003, 64768407.2504181, 3655819.53710869, 7812897.34991382},     {0.005, 63761257.6277216, 1222706.2166919, 12090416.0146563},     {0.01, 64307991.5530707, 1139370.28069903, 12657324.2458834},     {0.05, 68583353.8471158, 1802661.70625935, 13079855.4358155},     {0.08, 71169929.0580033, 1496318.92452295, 13991708.7133703},     {0.1, 72811456.5338936, 1853138.14008422, 13681128.3978895},     {0.2, 78742983.529449, 3190647.61480991, 13511961.6223572},     {0.5, 88513835.0051046, 3556145.38852813, 14771090.342085},     {1, 94765316.2395368, 4882322.77031356, 14796960.6588559},     {2, 98437836.0564595, 5353800.46123903, 14862252.8596808},     {5, 99708229.0609698, 3726362.20580859, 16993877.2198709},     {10, 99634510.8439181, 4858332.59695385, 16478819.0906012}};     {t, x, y, z} =       Transpose[data];(*extract data*){xdata, ydata, zdata} = (Transpose[{t, #}]) & /@ {x, y, z};(*get {t,x} and {t,y} pairs*)fx =  Interpolation[xdata, Method -> "Spline"];(*spline interpolation*)fy =  Interpolation[ydata, Method -> "Spline"];     fz = Interpolation[zdata, Method -> "Spline"];     dx = fx'[t];     dy = fy'[t];     dz = fz'[t];     ab = FindFit[Transpose[{fx[t], fy[t], dx}], a*X + b*Y, {a, b}, {X, Y}]     cde = FindFit[Transpose[{fx[t], fy[t], fz[t], dy}], c*Y + d*X + e*Z, {c, d, e}, {X, Y, Z}]     fg = FindFit[Transpose[{fz[t], fy[t], dz}], f*Z + g*Y, {f, g}, {Y, Z}]     (*search backward*)NDSolve[{X'[u] == a*X[u] + b Y[u] /. ab,      Y'[u] == c*Y[u] + d*X[u] + e*Z[u] /. cde,      Z'[u] == f*Z[u] + g *Y[u] /. fg, X[0.0001] == 69721851.824697, Y[0.0001] == 1710041.1571808, Z[0.0001] == 1249648.07662318}, {X[0], Y[0], Z[0]}, {u, 0, 10.01}, MaxSteps -> 20000]     (*find solution of x[t],y[t],z[t] with NDSolveValue*)     sol = NDSolve[{X'[u] == a*X[u] + b Y[u] /. ab,      Y'[u] == c*Y[u] + d*X[u] + e*Z[u] /. cde,      Z'[u] == f*Z[u] + g *Y[u] /. fg, X[0.0001] == 69721851.824697,      Y[0.0001] == 1710041.1571808,      Z[0.0001] == 1249648.07662318}, {X[0], Y[0], Z[0]}, {u, 0, 10.01}, MaxSteps -> 20000]     (*plot the results*)     Show[{ListPlot[{xdata, ydata, zdata}, AxesLabel -> {"time", "value"}, PlotLegends -> {"xdata", "ydata", "zdata"}, PlotStyle -> {Red, Green, Pink}], ListLinePlot[{Table[sol[[1]], {u, 0.0, 10, 0.01}], Table[sol[[2]], {u, 0, 10, 0.01}], Table[sol[[3]], {u, 0, 10, 0.01}]}, PlotStyle -> {Orange, Blue, Yellow}, PlotLegends -> {"solution.x", "solution.y", "solution.z"}]}]


title: Problem with Label in a Do loop, "nolabel"

text: Can someone tell me why this code doesn't work and how to fix it ? Thanks.               k = 0;     Do[{       Label[top],       k = k + 1,       Print["k = ", k],       If[k < 4, Goto[top]]},     {10}]      > >     k = 1 >   >     Goto::nolabel: Label top not found. >> >   >     Hold[Goto[top]] >


title: Replacing whole strings

text: I imported a text and seperated al words by using `StringCases`. After this I would like to manipulate the text, for example to replace all singular verbs to plural. When I use `StringReplace`, then _Mathematica_ search for a part of the string and replaced it. For example               texttest = "walking walk routes walks"     texttest1 = StringCases[texttest, RegularExpression["\\w(?<!\\d)[\\w'-]*"]];     newwords= {"walk" -> "walking", "walks" -> "walking"};     texttest2 = StringReplace[texttest1, newwords];      The result is: > {"walkinging", "walking", "routes", "walkings"} I would like to get: `{"walking", "walking", "routes", "walking"}`.


title: Values (or positions) of array row elements within a specified number of positions from target value

text: I have the need to collect values from the rows of rectangular arrays of arbitrary precision integers, given a target element value and allowed "distance" (positions +/- within the row from found targets). E.g., given a target array of               ar={{6, 10, 6, 5, 7}, {10, 2, 2, 0, 7}, {0, 6, 3, 7, 5}, {2, 8, 6, 9, 1}, {8, 8, 5, 0, 8}}      and a target value of `5`, with an allowed "distance" of `2`, the result should be               {10, 6, 5, 7, 3, 7, 5, 8, 8, 5, 0, 8}      Result must be order-preserving, i.e., as if the array were "read" left to right, top to bottom. I'm using this:               nearEles[array_, ele_, dist_, posOnly_: False] :=        With[{r = Range[-dist, dist], d = Dimensions[array][[2]]},        If[posOnly, #, Extract[array, #]] &[SparseArray[           Map[IntegerDigits[BitOr @@ (BitShiftLeft[FromDigits[#, 2], r]), 2, d] &,                SparseArray[BitXor[1, Unitize[array- ele]]]]]["NonzeroPositions"]]];      so in the above example, called as `nearEles[ar,5,2]` gets me what I need. On actual data (typically 1K X 1K to 4K X 2K array size), performs pretty well. Any ideas for a more efficient (and perhaps less ungainly) method?


title: Delete contexts from a string representation of a symbol

text: I want to delete the string representing the context of a symbol. For info I need such a functionality in my `ShowIt` function defined here I'd like to know how I can replace such a string with a rule so that for example,               "MyFunc[ShowIt[Q1`Private`var1$123], ShowIt[Q2`Private`var2$456], 0., 1.]"      gives               "MyFunc[ShowIt[var1], ShowIt[var2], 0., 1.]"      or               "Q1`Private`var1$123"      gives               "var1"


title: CustomTicks and ListPlot - Can't seem to get them working

text: I have a very large list of numbers like               list={{a1,b1},{a2,b2},...,{ai,bi}}      where a1 ranges between 10^-9 and 10^-5 and bi varies between 0 and 100. I have generated successfully the plots and am now tweaking them with CustomTicks to look a bit better. But I'm not able to get the XX axis as I want. The YY axis should be linear and the XX axis should be Logarithmic. But the best I could get was this: ![Mathematica graphics](http://i.stack.imgur.com/rLWha.png) Could someone please tell me what I'm doing wrong? I've been trying different things for so long and I can't figure this out. Here is my code:               a = {#, Random[Real, {0, 100}]} & /@               Union[     Range[1*^-9, 1*^-8, 1*^-9]                   ~Join~Range[1*^-8, 1*^-7, 1*^-8]                                     ~Join~Range[1*^-7, 1*^-6, 1*^-8]                   ~Join~Range[1*^-6, 1*^-5, 1*^-7]]          ListLogLinearPlot[a, Joined ->True, Axes -> False, FrameLabel -> {{"A", None}, {"B", None}},                 Frame -> {{True, False}, {True, False}}, LabelStyle -> {Bold, 25},                 PlotStyle -> {{Thickness[0.003], Black},                               {Thickness[0.003], Dashing[0.015], Black},                               {Thickness[0.003], Dashing[0.005], Black}},                PlotRange -> {0, 100}, ImageSize -> {800, 600},                 FrameTicks - {{LinTicks[0, 100, 20, 2], None},                               {LogTicks[E, -8, -5], None}},                FrameTicksStyle -> Directive[Thickness[0.01]]]


title: vectorial ODE in mathematica with matrix exponentials

text: I want to solve the following equation in mathematica : `DSolve[{X'[t] == A.X[t], X[0] == ( {{0},{0}} )}, X[t], t]` It is a system of 2 ODEs coupled by the matrix A, that I don't want to put in the form `{{a,b},{c,d}}` in order to have the output as a function of matrix exponential. Mathematica understands that but gives a solution strangely expressed as:                {{X[t] ->       InverseFunction[Dot, 2, 2][A,           E^(t A.1)          InverseFunction[InverseFunction[Dot, 2, 2], 2, 2][A, 0]]}}      Where it indeed uses a matrix exponential, but also relies on a strange notation `InverseFunction [...]` My question is how to get rid of this `InverseFunction` notation to have a more readable expression. Do I for example have a manner to postulate that A is a (2,2) matrix, invertible, with inverse B? Or more generally, how to solve vectorial ODE's and make Mathematica write the solution by relying on exponential matrix notation? If I can hope a better result with maxima, please advise. Thanks a lot for help


title: Given a symbolic expression how to find if starts with a minus or not?

text: I am using a Mathematica function which returns some error term in symbolic form. I needed a way to determine if this term starts with a minus sign or not. _There will be only one term_ This is to avoid having to worry about Mathematica auto arranging terms like `x-h` to become `-h+x` and hence it is not fair to ask for more than one term solution. Here are some examples of the expressions, all in input form               negativeTruetests = {(-(71/12))*h^2*Derivative[4][f],     (-1)*h^2*Derivative[10][f],     (-(359/3))*h^2*Derivative[10][f], -2*h, -x*h^-2, -1/h*x }          negativeFalseTests = { h^2*Derivative[4][f] , h^2*Derivative[4][f],     33*h^2*Derivative[4][f], h^-2, 1/h}      I need a pattern to check if the expression starts with minus sign or not. ![Mathematica graphics](http://i.stack.imgur.com/5GB80.png)


title: Problem while solving system of two second order non linear coupled differential equations using NDSolve function

text: I am a completely new to _Mathematica_ , and I am sorry if this question is dumb. I have to solve a system of two second order non linear coupled differential equations (that I got from the Lagrangian equation of motions for a particular system). The following is my code: I hope it is clear.               NDSolve[      {       -29.4 + 9.8 Cos[y[t]] + x[t] Derivative[1][y][t]^2 - 4 x''[t] == 0,          9.8 Sin[y[t]] + 2 Derivative[1][x][t] Derivative[1][y][t] + x[t] y''[t] == 0,        x[0] == 1, y[0] == 1.57, Derivative[1][x][0] == 0,        Derivative[1][y][0] == 29.4      },      {x[t], y[t]}, {t, 0.1}     ]      But I am getting exactly the same output as the input. _Mathematica_ is returning the same piece of code.


title: Integrating over a region without singularity gives an error indicating the function has singularity in that region

text: I have the following 2D region over which I want to integrate a function:               r1  = Sqrt[mη^2 + (Sqrt[w1^2 - mπ^2] + Sqrt[w2^2 - mπ^2])^2] // Expand;     r2  = Sqrt[mη^2 + (Sqrt[w1^2 - mπ^2] - Sqrt[w2^2 - mπ^2])^2] // Expand;     mη  = 0.547;     mηp = 0.958;     mπ  = 0.137;          RegionPlot[mηp - w1 - w2 < Re[r1] && mηp - w1 - w2 > Re[r2],         {w1, .1, .25}, {w2, .1, .25}, BoundaryStyle -> Blue, FrameLabel -> {"w1", "w2"}]      ![Mathematica graphics](http://i.stack.imgur.com/xmdnv.png) Now I want to integrate the following function over this region:               function[w1_, w2_]=Abs[1.05133+ (6.16152 (0.656093- 1.916 w1 - 1.916 w2)         (0.958- 1. w1 - 1. w2))/(0.921055- 1.916 w1 - 1.916 w2) -          (10.1147 (0.656093- 1.916 w1 - 1.916 w2) (0.958- 1. w1 - 1. w2))/         (1.57895- 1.916 w1 - 1.916 w2) - 55.0594 (-((0.479 w1 (-0.618555 + 1.916 w1))/         (0.0307393+ 1.916 w1)) - ( 0.479 w2 (-0.618555 + 1.916 w2))/(0.0307393+ 1.916 w2))]^2      When I plot the function it doesn't have any singularity:               Plot3D[function[w1,w2],{w1, 0.137, 0.2445}, {w2, 0.137, 0.2445}, BoxRatios -> {1, 1, 4},        RegionFunction -> Function[{w1, w2, z}, mηp - w1 - w2 < Re[r1] && mηp - w1 - w2 > Re[r2]]]      ![Mathematica graphics](http://i.stack.imgur.com/5ABqL.png) But when I use the following command:               NIntegrate[function[w1,w2] Boole[Re[r2]< mηp - w1 - w2 <          Re[r1]], {w1, 0.137, 0.2445}, {w2, 0.137, 0.2445}]      _Mathematica_ says it has a singularity. Why?


title: Passing a matrix as a function argument

text: I am trying to do the following:               q = Table[i + j, {i, 1, 15}, {j, 1, 10}];     normalize[mat_] := (temp = Transpose[mat[[2 ;;, 5 ;;]]];       temp1 = Transpose[N[Map[Normalize[#] &, temp]]];       mat[[2 ;;, 5 ;;]] = temp1; Return[mat])     q1=normalize[q];      I get the following error:               Set::setps:      {{2,3,4,5,6,7,8,9,10,11},     {3,4,5,6,7,8,9,10,11,12},     {4,5,6,7,8,9,10,11,12,13},     {5,6,7,8,9,10,11,12,13,14},     {6,7,8,9,10,11,12,13,14,15},<<5>>,     {12,13,14,15,16,17,18,19,20,21},     {13,14,15,16,17,18,19,20,21,22},     {14,15,16,17,18,19,20,21,22,23},     {15,16,17,18,19,20,21,22,23,24},     {16,17,18,19,20,21,22,23,24,25}}      in the part assignment is not a symbol. >>      Can you please help me in finding out what is wrong? I am new to _Mathematica_.


title: Derivatives (divergence, gradient, curl) of interpolated 3D data

text: How can I calculate a vector derivative (i.e. divergence, gradient, curl) of interpolated data? For sample data, you can use:               f[x_, y_, z_] := Exp[I z] {1, 0, 0}     testdata=Flatten[Table[N@{x,y,z,f[x,y,z]},{x,0,4 Pi,Pi/10},{y,0,4 Pi,Pi/10},{z,0,4 Pi,Pi/10}],2];     intf = Interpolation[testdata]      I know that for 1D data, like               dim1 = Table[N@{z, f[0, 0, z]}, {z, 0, 2 Pi, Pi/10}];     int1 = Interpolation@dim1;      you can do `D[int1[x],x]`. However, I can't seem to get convince MMA that the interpolated function `intf` actually returns a "vector" quantity (i.e. `Length@intf[x,y,z]->3`), so that I can do something like:               curl = {D[#[[3]],y]-D[#[[2]],z],-(D[#[[3]],x]-D[#[[1]],z]),D[#[[2]],x]-D[#[[1]],y]}&;     curl@intf[x, y, z]     (* Out[] := {0,0,0} *)      Similarly, this should work for gradient:               grad = {D[#[[1]], x], D[#[[2]], y], D[#[[3]], z]} &;      and divergence:               div = (D[#[[1]], x] + D[#[[2]], y] + D[#[[3]], z])&;      I've posted my best attempt in an answer below, but I'm wondering what other solution approaches there are.


title: Plot hangs Mathematica through NETLink

text: I have a C# function that calls Mathematica via Wolfram.NETLink. On our home computers all the test calls work perfectly, but on our AWS server (both a microinstance and a beefy c3.xlarge instance), for some reason Plot commands seem to fail. We've tried Export with Plot, and also just computing a vanilla Plot and trying to grab the result through the kernel. Both hang MM indefinitely, and later kernel calls are rejected. When using Export no file is saved; when using Plot, no image comes through the MathKernel. Any and every Plot command, by itself or wrapped in an Export, produces this effect, but only through NETLink (running the exact same command via the MM notebook interface is successful), and only on our AWS server (this works fine on our home computers), and only these commands -- every other MM command we send gets processed just fine.


title: Accessing sublists conditional on their length

text: Say I have a list that looks like this:               list = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3}},      {{131.048`, 243.364`}, {3, 3}, {56, 56}, {76, 23}}, {{164.911`, 244.039`}, {4, 4}},      {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`}, {6, 6}}, {{184.767`, 234.228`},      {7, 7}}, {{213.044`, 234.24`}, {8, 8}}, {{26.6316`, 221.423`}, {9, 9}}};      How can I return the last element in each sublist conditional on the sublist being a critical length `k`? For example if we set `k=3`, we'd return `{{3, 3}, {76, 23}}` from the above list. Here's the naive way to do it:               k = 3;          list = {{{151.335`, 245.102`}, {1, 1}}, {{41.435`, 245.021`}, {2, 2}, {3, 3}},              {{131.048`, 243.364`}, {3, 3}, {56, 56}, {76, 23}}, {{164.911`, 244.039`},               {4, 4}}, {{98.1685`, 239.618`}, {5, 5}}, {{196.333`, 239.212`}, {6, 6}},              {{184.767`, 234.228`}, {7, 7}}, {{213.044`, 234.24`}, {8, 8}},              {{26.6316`, 221.423`}, {9, 9}}};     outputList = {};          For[i = 1, i <= Length[list], i++,       If[Length[list[[i]]] >= k,         outputList = Append[outputList, list[[i]][[Length[list[[i]]]]]];       ];     ];          outputList      Surely there must be a better way?


title: How can I access the internal function that plots a molecule from a formatted XYZ file?

text: Mathematica has the ability to plot a molecule using the data contained in an XYZ file. This is a simple text file, of which this is an example. The molecule is plotted using the Import command. Entering this:               Import["https://gist.github.com/anonymous/8fde18207e8abc7b770c/raw/8491d99e7fec7cc989fe38548319e09d6910ba02/form_MO_28","XYZ"]      gives this as the output: ![enter image description here](http://i.stack.imgur.com/4oaFq.jpg) I've been able to put this together with orbital plots, with results like this: ![enter image description here](http://i.stack.imgur.com/KpoVU.jpg) But I can only show other plots alongside the molecule plot, I can't modify the molecule. For example, I'd like to make the tubes forming the bonds smaller in diameter. As it is, the plots don't show if there is a single, double, or triple bond. Somewhere in mathematica, there must be a function which takes as its argument the XYZ text and returns the molecule plot. If I could see that function, I could modify it accordingly. Any clue on how to access this function? The documentation for this feature is minimal.


title: Remove elements at certain positions from all sub-lists?

text: Consider a big list where all the inner lists length's are the same                list = {{x1, y1, z1, t1}, {x2, y2, z2, t2}, {x3, y3, z3, t3}, ...};      elementNo = {4, 3, 2};      I want output like this,               {{x1}, {x2}, {x3}, ...}      That is, when I specify `elementNo` as `{4, 3, 2}`, I mean the elements at positions 2, 3 and 4 in the sub-lists should be removed -- I want the elements at position 1 only. When I specify `elementNo` as `{2, 3}`, I want                {{x1, t1}, {x2, t2}, {x3, t3}, ...}      How can I do this?


title: Dynamic inside Button

text: This bit of code runs a little animation of a stochastic process:                (* a random walk bm, its min and max  *)      {bm, m, M} = {Table[Random[] - .5, {100}] // Accumulate, Min[bm], Max[bm] }           (* plot of trajectory of bm up to i-th step *)      traj[i_] := ListLinePlot[({Range[1, 100], bm} // Transpose)[[;; i]],          Joined -> True, PlotRange -> {{0, 100}, {m, M}}]           (* animation using Clock *)      q = Dynamic[r = Clock[{1, 100, 1}, 5, 1]; traj[r] ]      Next I'd like to use Button to run the animation. Something like               Button["Run", q]      but this doesn't work. Eventually I'd like to have two buttons, "Repeat" and "Clear" like this:               x = {{0, 0}};        min[x_] := (Sort[x, #1[[2]] < #2[[2]]  &])[[2]]; Column[ {Row[{Button["Repeat",       x = Append[x, { Random[], Random[]  }]],      Button["Reset", x = { {0, 0}}]  }  ],     Dynamic[Show[{ ListPlot[x, PlotRange -> {{0, 1}, {0, 1}}, ImageSize -> 300,        Frame -> True, Axes -> None] , If[Length[x] > 1,        Graphics[{Red, Line[{min[x], {min[x][[1]], -.1} }]}], {}],      If[Length[x] > 1,        Graphics[{Red, Line[{min[x], {0, min[x][[2]]} } ]}], {}]      }]]}]      but instead of dots, I want to plot animated functions involving Clock.


title: Turning Off Error messages locally

text: I'm trying to turn `Off` an error in an expression.               myFunction[x_] = 1/x     myFunction2[x_] = Quiet[1/x]  (*1/x*)     myFunction[0]     myFunction2[0]      I do not want to use `:=`, I also do not want to Globally turn Off this error. I want it using `=` such that it looks like:               myFunction3[x_] = TurnedOffError[1/x]  (*TurnedOffError[1/x]*)     myFunction3[0]


title: Hue function for negative arguments

text: I want to use `Hue` function for different colours with the argument being a function, i.e.,               Hue[f[i,j]]      Now, `f[i,j]` in my case can take negative values. The range of my function is `[-2,2]` (which can be rescaled to `[-1,1]` if necessary, by dividing the function by 2). The problem is that `Hue` automatically rescales its argument to put it into the range of `[0,1)`. This is a problem for me as it will then show the same colour when my function is either `-1` or `0` or `1`, for example. The actual figure I want to work on can be generated by the following code:               Clear["Global`*"];      n := 10;      angles = Table[RandomReal[{-Pi, Pi}], {i, n}, {j, n}];      f[here_, down_, right_] := Cos[down - here] + Cos[right - here]      g[list_, {i_, j_}] := Module[{m, n}, {m, n} = Dimensions[list]; {list[[i, j]],          If[i != m, list[[i + 1, j]], -list[[1, j]]],            If[j != n, list[[i, j + 1]], -list[[i, 1]]]}]      GraphicsGrid[ MapIndexed[ Graphics[{LightGray, Circle[{0, 0}, 1],          Hue[Rescale[f @@ g[angles, #2], {-2, 2}, {-1, 1}]], Thin,            Arrowheads[Small], Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &, angles, {2}]]


title: How to only work on sublists with non-zero (or positive) values

text: i have a large compositional dataset which contains non-zero and zero values. here is a sample:                 data = {{22054., 70.62, 0.37, 14.21, 2.89, 0.6, 2.05, 4.18, 4.04},               {22055., 67.84, 0.52, 14.32, 3.77, 0.91, 3., 2.72, 4.62},               {22581., 62.79, 0.62, 13.79, 7.27, 0.46, 2.92, 1.21, 7.97},               {27601., 0., 0., 0., 0., 0., 0., 0., 0.},               {27602., 0., 0., 0., 0., 0., 0., 0., 0.},               {27603., 0., 0., 0., 0., 0., 0., 0., 0.},               {28681., 0., 0., 0., 0., 0., 0., 0., 0.},               {22757., 61.06, 0.77, 16.62, 5.72, 1.66, 4.66, 2.76, 3.46},               {22803., 64.55, 3.01, 16.3, 0.48, 0.09, 0.05, 0.25, 14.29}};      i'm trying to convert the values from weight percent to mol percent. i wish to use the following function to generate a new array of the same length (at level 1) as the original:                    mw = {60.084, 79.866, 101.961, 71.844, 40.304, 56.077, 61.98, 94.2};               molPct[oxw_, mw_] :=             Module[{oxcomp, divmw},             oxcomp = Drop[oxw, None, 1];             divmw = Transpose[Transpose[oxcomp]/mw];             (divmw/ Total[divmw, {2}])*100             ];               dataMolPct = molPct[data, mw]      unfortunately, this function fails due to the zero elements within the array (where it tries to divide by zero..). this code seems to work fine when i delete the rows containing zero-values. I tried the following in an attempt to ignore the 'zero' rows:                    molPct[oxw_ /; oxw > 0, mw_] :=             Module[{oxcomp, divmw, oxmol},             oxcomp = Drop[oxw, None, 1];             divmw = Transpose[Transpose[oxcomp]/mw];             (divmw/ Total[divmw, {2}])*100             ];      ...no luck as i said, it is important that i end up with an array of the same size (as i will join the new data onto the original array). it would be nice to know how to do something similar for excluding negative numbers. any suggestions?


title: FindInstance with a Diophantine equation seems to go on forever

text: I tried to find a non-trivial integer solution to the equation   $$2012^2=a^2+b^2+c^2+d^2+e^2$$ with Mathematica but the computation takes minutes; I might be doing something wrong.               FindInstance[2012^2 == a^2 + b^2 + c^2 + d^2 + e^2          && a > 0 && b > 0 && c > 0 && d > 0 && e > 0, {a, b, c, d, e}, Integers]      But when I try               FindInstance[2012^1 == a^2 + b^2 + c^2 + d^2 + e^2          && a > 0 && b > 0 && c > 0 && d > 0 && e > 0, {a, b, c, d, e}, Integers]      I get an immediate result.


title: How to calculate this integral?

text: I am trying to Integrate the following Integral : $\int_1^{\infty } \dfrac{\left(x^2-1\right)^{13/2} e^{-ax} }{x^{10}} \, dx \,\, \,\,\,\,\,\,\,\,\,\,\,\,(a=\textrm{real>0})$ Mathematica didn't calculate this integral. Maybe it is too complicated to be done. In Mathematica input form:               Integrate[Exp[-a x] (x^2 - 1)^(13/2)/x^10, {x,1,Infinity}]      If I simply enter that into Mathematica, it instantly returns the same expression. How do I go about this? Is there any tricks that can be applied? Thank's.


title: Handling output that was returned unevaluated from a function

text: When evaluating functions, including those described in this post, how do _Mathematica_ users handle values returned from a function that are unevaluated? For example (based on 1):               i[{a_, Longest[b__], c__}] := {"a" -> a, "b" -> {b}, "c" -> {c}} /; Length[{a, b, c}] > 3;     test = {{1, 2}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}};     j=i/@test          (* returns {i[{1, 2}], {"a" -> 1, "b" -> {2, 3, 4}, "c" -> {5}}, {"a" -> 1,  "b" -> {2, 3, 4}, "c" -> {5}}}  *)      So the first element of _j_ is `i[{1, 2}]` \- this is neither the original input `{1,2}` nor in the form of the rest of the output. Two questions: a) While it is likely to be application specific, what approaches do others use to handle unevaluated values that are returned? b) Is there a generic way to detect unevaluated 'returns' for additional parsing ? My current thought is to use `Identity` and `ReplaceAll` to eliminate the 'unwanted' function `i`:               k=j/.i->Identity     (* returns {{1, 2}, {"a" -> 1, "b" -> {2, 3, 4}, "c" -> {5}}, {"a" -> 1,   "b" -> {2, 3, 4}, "c" -> {5}}}  *)      but this approach requires the name of the function (here _i_ ) that was evaluated. Are there any other tricks or approaches to handle this? Am I overlooking benefits to retaining the unevaluated output ?


title: Horrific Looking Contour Integral in Mathematica Plot:

text: I'm attempting to display the geometric meaning of a contour integral![enter image description here](http://i.stack.imgur.com/pHRzR.png) but as you can see, the typesetting of the contour integral (created via the Epilog function) looks awful because the contour integral is too high relative to the integrand. In addition, the text is too small. How can this be fixed? My code for this figure is               a = 1.5;     b = 1;     RegionPlot[         q^2/a^2 + p^2/b^2 <= 1, {q, -a - .1, a + .1}, {p, -b - .1, b + .1},         AspectRatio -> Automatic,         Axes -> True,         AxesLabel -> {q, p},         Frame -> False,         PlotStyle -> Directive[Green, Opacity[0.9]],         Ticks -> False,         Epilog -> {Text["\[ContourIntegral]p\[DifferentialD]q",          Offset[{0, 0}, {.7, .35}]]},         ColorFunction -> "Pastel"]


title: OpenSCAD like functionality with Mathematica?

text: I keep seeing reference to use of Mathematica as a CAD tool (for instance: http://www.makerbot.com/support/guides/design/). I'd like to use it as such if feasible, but I'm having trouble locating equivalents of the functionality I use in my current design tool, OpenSCAD. I know how to create simple shapes (`Graphics3D[]`, `Cylinder[]`, etc.) and I'm aware that Mathematica can export to STL format. But does Mathematica have equivalents of the following OpenSCAD functions, or is it the wrong tool for the kind of thing I'm trying to do?   * linear_extrude()   * union()   * intersection()   * difference()   * translate()   * rotate()


title: How to show many data lines with MAnipulate?

text: How could I show many lines with data, usin Manipulate??               Manipulate[      Print["Number...Square...Cube"];      Do[Print[z, "...", z^2, "....", z^3], {z, 1, zmax}];      PieChart[Table[i^3, {i, 1, zmax}], ChartLabels -> Range[zmax]]      , {zmax, {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16}}]      I see the PieChart inside the CDF-place, but the data is showed outside, after the Square of CDF. I´m interesetd too in Show the text of the PieChart greater, and with a label of the data, for example 9 and under the 9.... (21%)


title: How to solve correctly inside a DO loop and then plot

text: Here is the corresponding code First the equations setup               Vcl[x_, y_, z_] := (-G*(Mcl/a))/Sqrt[(x^2 + y^2 + z^2)/a^2 + c^2];     V[x_, y_, z_] := Vcl[x, y, z] + 1/2*(κ2 - 4*ω^2)*x^2 + 1/2*v2*z^2;          G = 1;     Mcl = 2.2; a = 0.182; c = 1;     ω = 1; κ2 = 1.8; v2 = 7.6;     cl = -3.264444506;     ch = 0.1;     E0 = cl*(1 - ch);      Then the DO loop with the `Solve`               data = {};     Do[       Vx = V[x, 0, z0];       sol = Solve[Vx == E0 && -1.01 < x < 1.01,x];       xmin = x /. sol[[1]];       xmax = x /. sol[[2]];       AppendTo[data, {xmin, xmax, z0}],       {z0, 0, 0.6, 0.001}       ]      And finally the plot               neg = data[[All, {1, 3}]];     pos = data[[All, {2, 3}]];     L1 = ListPlot[neg, Joined -> True,           PlotStyle -> {Black, Thickness[0.003]}];     L2 = ListPlot[pos, Joined -> True,           PlotStyle -> {Black, Thickness[0.003]}];      L0 = Show[{L1, L2}, Axes -> False, Frame -> True,           PlotRange -> {{-1, 1}, {0, 0.6}}, ImageSize -> 550]      which produces this ![enter image description here](http://i.stack.imgur.com/6dUga.png) The plot has several issues: (i) it should be a continuous line from -1 to 1, while we observe a gap near 0 and also it never reaches +1, (ii) the lower horizontal line it should not be there; probably `Joined` joins two extreme points. I suspect, that both issues are related to the `Solve` inside the DO loop. There z0 belongs to the interval [0, 0.6] but the equation does not have solutions for all these values. The `data` list should somehow store only the correct solutions and reject the cases where there are no solutions at all. Many thanks in advance.


title: Cell background color changes cell layout

text: When I change the background color of a cell like in ![enter image description here](http://i.stack.imgur.com/QnYDL.png) the colored cells become slightly indented and their line spacing is increased. How can I change the cell background color while keeping the other cell layout elements fixed?


title: Filling -> Axis leaves a gap

text: Filling leaves a gap between the function curve and the axis               Show[Plot[PDF[NormalDistribution[0, 1], z], {z, -3, 6}],      Plot[PDF[NormalDistribution[0, 1], z], {z, c=1.4, 6}, Filling -> Axis]     ]      ![enter image description here](http://i.stack.imgur.com/5PoDc.png) But for other values (e.g., c=0.5 instead of c=1.4 in the above code), the Filling is correct. Is this a bug or am I making some subtle error?


title: Detecting patterns of black and white stones on a 2D board

text: I'm writing a program to play a game of Pente, and I'm struggling with the following question: > What's the best way to detect patterns on a two-dimensional board? For example, in Pente a pair of neighboring stones of the same color can be captured when they are flanked from both sides by an opponent; how can we find all the stones that can be captured with the next move for the following board? ![sample board](http://i.stack.imgur.com/cV3Gb.png) Below I show one possible straightforward solution, but with a defect: it's hard to extend it for other interesting patterns, i.e. three stones of the same color in a row surrounded by empty spaces, or four stones of the same color in a row which are flanked from one side but open from another, etc. > I'm wondering whether there is a way to define a DSL for detecting > 2-dimensional structures like that on a board - sort of a _2D pattern > matching_. P.S. I would also appreciate any advice on how to simplify the code below and make it more idiomatic - for example, I don't really like the way how `sortStones` is defined. ## Straightforward solution Here is one way to solve this problem (see below for graphics primitives to generate and display random boards):   * Enumerate all subsets of 3 stones from the board above   * Select those that form an _AABE_ or _ABBE_ pattern, where E denotes an unoccupied space Lets store the board as a list of black and white stones,               a = {black[2, 1], black[4, 3], black[2, 5], black[4, 2], black[5, 3],      black[1, 2], black[1, 3], black[5, 4], black[1, 5], white[3, 1],      white[4, 1], white[4, 4], white[3, 5], white[3, 4], white[5, 1],      white[5, 2], white[3, 3], white[1, 1]}      First, we define `isTriple` which checks whether three stones sorted by their x and y coordinates are in the same row next to each other and follow an ABB or AAB pattern:               isTriple[{a_, b_, c_}] := And[       (* A A B or A B B *)       Head[a] != Head[c] /. {black -> 1, white -> 0},       (* x and y coordinates are equally spaced *)       a[[1]] - b[[1]] == b[[1]] - c[[1]],       a[[2]] - b[[2]] == b[[2]] - c[[2]],       (* and are next to each other *)       Abs[a[[1]] - b[[1]]] <= 1,       Abs[a[[2]] - b[[2]]] <= 1]      Next, we determine the coordinates and the color of the stone that will kill the pair:               killerStone[{a_, b_, c_}] :=       If[Head[a] == Head[b] /. {black -> 1, white -> 0},       Head[c][2 a[[1]] - b[[1]], 2 a[[2]] - b[[2]]],       Head[a][2 c[[1]] - b[[1]], 2 c[[2]] - b[[2]]]]      Finally, we only select those triples where killer stone's space is not already occupied:               sortStones[l_] :=       Sort[l, OrderedQ[{#1, #2} /. {black -> List, white -> List}] &]          triplesToKill[board_] := Module[       {triples = Select[sortStones /@ Subsets[board, {3}], isTriple]},       Select[triples,        Block[          {ks = killerStone[#]},          FreeQ[board, _[ks[[1]], ks[[2]]]]] &]]          displayBoard[a, #] & /@ triplesToKill[a]  //        Partition[#, 3, 3, {1, 1}, {}] & // GraphicsGrid      ![straightforward solution](http://i.stack.imgur.com/QHj2c.png) ## Graphics primitives               randomPoints[n_] := RandomSample[Block[{nn = Ceiling[Sqrt[n]]},         Flatten[Table[{i, j}, {i, 1, nn}, {j, 1, nn}], 1]], n];     (* n is number of moves = 2 * number of points *)     randomBoard[n_] := Module[       {points = randomPoints[2 n]},       Join[        Take[points, n] /. {x_, y_} -> black[x, y],        Take[points, -n] /. {x_, y_} -> white[x, y]        ]]          grid[minX_, minY_, maxX_, maxY_] :=        Line[Join[         Table[{{minX - 1.5, y}, {maxX + 1.5, y}}, {y, minY - 1.5, maxY + 1.5,            1}],         Table[{{x, minY - 1.5}, {x, maxY + 1.5}}, {x, minX - 1.5, maxX + 1.5,            1}]]];          displayBoard[board_] := Module[        {minX = Min[First /@ board], maxX = Max[First /@ board],         minY = Min[#[[2]] & /@ board], maxY = Max[#[[2]] & /@ board], n},        Graphics[{          grid[minX, minY, maxX, maxY],          board /. {            black[n__] -> {Black, Disk[{n}, .4]},            white[n__] -> {Thick, Circle[{n}, .4], White, Disk[{n}, .4]}            }}, ImageSize -> Small, Frame -> True]];          displayBoard[board_, points_] := Show[       displayBoard[board],       Graphics[        Map[{Red, Disk[{#[[1]], #[[2]]}, .2]} &, points]]]


title: Basic questions about running Mathematica

text: 1. Is there a command window and an editor in Mathematica 8 similar to those in Matlab? In Mathematica GUI mode, all I saw is write code and run it in the same notebook.   2. In my Ubuntu terminal, I successfully started Mathematica by `./math` (which is the only way I know by the way and I would also like to know what options are available when starting up).  When I simply copy and paste the code from Heike , nothing new appears, and when I copy and paste the code of Daniel, it works. Wonder why?   3. Is it correct that there are exactly two ways of running Mathematica code: in a notebook, and in a Mathematica session running in my Linux terminal?  Are the notebook way and the GUI mode the same thing? What does "kernel" mean in Mathematica? What are some basic concepts and common sense of running Mathematica?


title: logplot for negative valued function

text: I would like to plot the following function               Plot[(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2)), {x, 0, 10},       Frame -> True, PlotRange -> All]      which is very peaked at 0.01 in log scale, to show it up to higher values, i.e.:               LogPlot[-(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2)), {x, 0, 100},       Frame -> True, PlotRange -> {10^-9, 10}]      However, since function is negative, I must add a minus sign to the function. I would like to get something like the log plot above, but with the y-axis going downwards and with negative values, looking similar to the plot below               LogPlot[-(1/x (0.01/(0.01 + x^2) - (10/(10 + x^2))^2))^-1, {x, 0, 10},       Frame -> True, PlotRange -> {0.1, 10^3}]      but with the right scaling for log axis and negative value sin stead of positive ones, is it possible? Thanks in advance


title: Visualizing 3x3 spectrahedra

text: I'm trying to visualize the SDP cone over 3x3 matrices by plotting random 3d sections of it. Since each region is a system of inequality constraints, I'm using RegionPlot, but I think the plots would look better if they only showed the surface...what is a good way to achieve this?               spectro2 := (        X = ( {           {x1, x2, x3},           {x2, x4, x5},           {x3, x5, x6}          } );        vars = Union@Flatten@X;        dvars = {x, y, z};        m = Length@vars;        n = Length@dvars;        makeMat := X /. (Thread[vars -> #]) &;        proj = makeMat /@ Orthogonalize@RandomReal[{-1, 1}, {n, m}];        mat2 =          Total@MapThread[Times, {proj, dvars}, 1] + IdentityMatrix@Length@X;        cons = And @@ (Thread[Eigenvalues[mat2] >= 0]);        RegionPlot3D[cons, {x, -3, 3}, {y, -3, 3}, {z, -3, 3}, Mesh -> 5,          PlotStyle -> Opacity[.7], PlotPoints -> 5]        );     Table[spectro2, {2}, {3}]      ![](http://yaroslavvb.com/upload/sdp-cone.png)


title: Does there exist any way to add type annotations?

text: Is there any way to add my own annotations to values or functions in Mathematica? Imagine, for example, that I wanted to annotate a `List` specifically as a `List` of `String`s. I don't think Mathematica will really do anything to enforce such a thing, but what I'd like to use this for is for connecting Mathematica to .NET generic functions. If I know that a `List` is expected to only contain a single type, I could more easily decide what type to call into a generic function with. An example syntax might be something like:               mylist = {"Alice", "Bob", "Carol"}     SetAttribute[myList, NETType[String]]          (* The NETType[] attribute is used to call "GenericListMethod<String>(myList);" *)     NETGenericCall[GenericListMethod,Sequence[myList]]      Update: It's also significant that `myList` should retain (nearly?) native behavior in Mathematica. For example, I should be able to iterate over the list with Map[] without having to explicitly unwrap the list first. I figure it's asking almost entirely too much for normal Mathematica functions to preserve type information.


title: Using Mathematica to help to determine the consistency of and numerically solve systems of non-linear equations

text: # The formal problem The question I am about to ask is applicable to many scientific and engineering problems. In short, I am bout to ask for pointers and practical advice for Mathematica beginners who would like to use Mathematica to find a solution to a multi-dimensional non-linear constraint optimization problem, i.e. a problem of the form: Find $\vec{\mathbf{x}}$ so that $\mathbf{F}\left(\vec{\mathbf{x}}\right) = \vec{\mathbf{0}} $. To expand this expression: Find a value of $\vec{\mathbf{x}} = \left| \begin{array}{c} x_{1} \\\ x_{2} \\\ \vdots \\\ x_{n} \end{array} \right|$ so that $\begin{cases} f_1\left(x_0, x_1, \ldots, x_n\right) = 0 \\\ f_2\left(x_0, x_1, \ldots, x_n\right) = 0 \\\ \mbox{ }\vdots& \\\ f_m\left(x_0, x_1, \ldots, x_n\right) = 0 \end{cases}$ Typically, we are looking for $\vec{\mathbf{x}} \in \Re^n$ (i.e. ignore complex solutions in most engineering and scientific disciplines), we have $n \neq m$, and $n$ and $m$ are of single-digit to two-digit numbers. The functions $f_i$ are arbitrary, non-linear and only defined on subspaces of $\Re^n$. There may be additional inequality constraints. * * * # The practical problem I would like to know all the **tools, functions and tricks** experienced Mathematica users like to use to approach this kind of problems. I am **not asking** for a one-command magic "solve that for me" function, as I know that function optimization is in general very hard, and a combination of formal analysis, plotting and numerical exploration are what guides one to a solution, if a solution exists. What I am asking is how Mathematica can help this exploration. * * * # Example Let's take a real-world example in Mathematica syntax, taken form a problem on which I am currently working. I believe this particular set of equations has no real solution (so don't try to actually work on it!) and could be better formulated, but that makes it an even better example. The system looks like that (you don't need to download the file, it's not very interesting):               eq1 = Dhtmp==Chbar+Ghtmp     eq2 = Dfstartmp==Cfstarbar+Gfstartmp     (* ... *)     eq31 = Lmbar==((Dmtmp+Dmstartmp*((1-n)/n))/Wbar)*(1-zprimebar)     eq32 = Lmstarbar==((Dmtmp+Dmstartmp*((1-n)/n))/Wstarbar)*zprimebar*(n/(1-n))     eq33 = Wstarbar==((t/tstar)*(((1-zprimebar)/zprimebar)^(1/theta)))*Wbar     eq34 = zeta==(Ptmp*(Ctmp^phi))/(Pstartmp*(Cstartmp^phi))     eq35 = Wbar==Phbar/(Pmbar*ahbar)     eq36 = Wstarbar==Pfstarbar/(Pmstarbar*afstarbar)     eq37 = ibar==(1/beta)-1      This is the raw set of equations, in that case, a copy-paste from a Matlab file followed by a bit of search/replace to remove underscores, change implicit functions to explicit, label them, etc... With that, some pre- determined values or intervals are given for some of the variables, like `ibar = 1`, etc... As a beginner Mathematica user, the first "trick" that I've learnt that lets me look at the system (thanks to MMA.SE user Simon) is to define a set of pretty-printing "replacements" for the ugly matlab variable names:               MakeBoxes[afstarbar, form_] :=         InterpretationBox[OverscriptBox[SuperscriptBox["af", "*"], "_"], afstarbar]     MakeBoxes[alpha, form_] := InterpretationBox["\[Alpha]", alpha]     (* ... there are 53 of those; I paste them before the equations. *)      In Matlab, typically, I try to plot each equation individually, holding all but one or two variables constant. It helps me get a better idea of the search intervals of the free variables. Then I feed simplified versions of the system to various solvers (`fsolve` for simple stuff, or I write some simulated annealing-like one-time-use solver, etc...), and tune the system until I get a solution. Now, I want to give Mathematica a try, but as a beginner, I know that it's going to be a lot of fumbling around, because I did not find a good list of pointers on what Mathematica users use in real-world to help themselves solve non-linear multi-dimensional constraint optimization problems. I think that the Mathematica Stackexchange website is where such a guide should be found.