title: Solving a PDE containing DiracDelta

text: I want to get the answer from a PDE: $$\begin{align*} \frac{\partial \rho(r,t)}{\partial t}&=Dr^{-2}\frac{\partial}{\partial r}r^2h(r)e^{-U(r)}\frac{\partial}{\partial r}e^{U(r)}\rho(r,t)-\left(\frac{\lambda}{g(\sigma)}\frac{\delta(r-\sigma)}{4\pi\sigma^2}+\frac{3\lambda}{4\pi r^6}\right)\rho(r,t)\\\ U(r)&=-\frac4r\text{; }\sigma=D=\lambda=h(r)=1\\\ \rho(r,t=0)&=g(r)=e^{-U(r)}\text{; }\lim_{r\to\infty}\rho(r,t)=1\text{; }\left.4\pi\sigma^2 Dh(\sigma)\frac{\partial}{\partial t}e^{U(r)}\rho(r,t)\right|_{r=\sigma}=\lambda e^{U(\sigma)}\rho(\sigma,t) \end{align*}$$ The PDE has one `DiracDelta[]` function. When I tried to solve the equation with `NDSolve[]`, it gave me               NDSolve::ndnum: Encountered non-numerical value for a derivative at t==0.         So I wanted to know the reason of message.   Using `r-sigma` instead of the delta function, `DiracDelta[r-sigma]`, I could get an answer from `NDSolve` without the above error message. However, it was not the answer of interest. How can I solve the problem with `DiracDelta[]` function? Thanks in advance :) *Codes start from here :               σ = 1     rc = -4     λ = 1     sink[r_, λ_] = (3 λ)/(4 π r^6)     U[r_] = rc/r     g[r_] = Exp[-U[r]]     Dif = 1     h[r_] = 1     r0 = 1;     tmax = 0.01;     rmax = 1000 Sqrt[6 Dif tmax] + r0;          sol = NDSolve[{D[ρ[r, t], {t, 1}] ==      Dif r^-2 D[        r^2 h[r] Exp[-U[r]] D[Exp[U[r]] ρ[r, t], {r, 1}], {r,          1}] - (λ/g[σ] DiracDelta[r - σ]/(          4 π σ^2) + sink[r, λ]) ρ[r,         t], ρ[r, 0] == Exp[-(U[r] - rc/rmax)], ρ[rmax, t] ==      1, 4 π Dif h[σ] (        D[Exp[U[r]] ρ[r, t], {r, 1}] /.         r -> σ) == λ Exp[U[σ]] ρ[σ,        t]}, ρ, {r, σ, rmax}, {t, 0, tmax},        PrecisionGoal -> 4, StartingStepSize -> 0.0001,        Method -> {"MethodOfLines",      "SpatialDiscretization" -> {"TensorProductGrid",        "MinPoints" -> 100, "MaxPoints" -> 200}}]          ρn = First[ρ /. sol]     Plot3D[ρn[r, t], {r, σ, rmax/100}, {t, 0, tmax}, PlotRange -> All]


title: How to preserve clipping when exporting a framed histogram with font embedding?

text: I work with histograms and would like to export it to EPS format. I've noticed that my exported image loses the PlotRangeClipping option that I set up when I export the plot. This is true for at least EPS, PNG and PDF. Based on this question and its accepted answer, I defined the function               OutlinedExport[name_,gr_,opts:OptionsPattern[]]:=     Export[         name,         First@ImportString[             ExportString[                 gr,                 "PDF"             ],             "PDF",             "TextOutlines"->True         ],         FilterRules[             {opts},             Options[Export]         ]     ]      Now here is an example of histogram               data = Table[InverseCDF[NormalDistribution[0, 1], Random[]], {i, 1000}];     PlotB = Histogram[data, 20,         PlotRange -> {{-2, 2}, Automatic},         Frame->True]     OutlinedExport["output2.pdf", PlotB, ImageSize -> 600]      which appears to have lost the clipping during the export. ### The questions are :   * Is there a way to preserve clipping as defined through options like PlotRangeClipping and PlotRangePadding ?    * If the problem is related with the OutlinedExport, is there a way to answer my question while also keeping the outline of fonts (which I need but have here removed for the sake of example) ?


title: Perfect numbers

text: The question given to me: **a**. Find the _perfect numbers_ between $1$ and $10^6$ **b** : Find the _abundant numbers_ between $1$ and $1000$ * * * For **a** , I wrote               Select[Range[1, 10^6], All]      I think I'm suppose to use divisor in there somewhere, but I'm not sure where to put that since I think me selecting all the numbers between $1$ and $10^6$ won't give me the list of all the perfect numbers... For **b** , I think it's similar to part **a** , which I'm in a dead end with. * * * I'm trying to find a simple input since I'm still a beginner and want to stay with the basics.


title: DSolve not finding solution I expected

text: Try to solve the following ODE via `DSolve` $$ \left\\{\begin{aligned} y'(x)+2 y(x) e^x-y(x)^2 &= e^{2 x}+e^x \\\ y'(0) &=1 \end{aligned}\right. $$ The expected solution is $y(x)=e^x$, but _Mathematica_ produces the message: > For some branches of the general solution,``the given boundary conditions > lead to an empty solution **Note:** $y(x)=e^x$ is obviously a special solution to the original ODE and satisfies the initial/boundary value condition which can be easily verified by substituting it into the ODE. Additionally, it is easy to deduct that: $y'(0)=1\Leftrightarrow y(0)=1$ for this ODE; How to handle it?


title: Right aligning a button in a dialog

text: What is the best way to right align a button in a dialog window, regardless of the window's `WindowSize`? Here is a resizable window to test on:               CreateDialog[      Column[{"Here's some text text text text text text text",               ChoiceButtons[]}],       WindowFrameElements -> {"ResizeArea"},       WindowFrame -> "Normal"]      I would like the button to always be right aligned. Some unsatisfactory solutions I thought of:   * Put the button in an `Item` and right align. Then the right margin is determined by the `Column` size which can't easily be set in pixels.   * Put the button in a `Panel`, right align it, and set a fixed size on the panel. Again, the size is determined by the panel size, not the window size. **Use case:** Suppose we need to create an alternative to `MessageDialog`. This new function, `myMessageDialog`, should take the `WindowSize` option, and the created notebook should respond to `SetOptions[nb, WindowSize -> ...]` The dialog buttons should always be aligned to the right edge of the window regardless of the window size.


title: Saving my code before cell evaluations: Insurance against front end hanging

text: I guess my programming working style is not unique. I develop programs one cell at a time, and when I have some confidence about what I did, I put all my mess together refining the code, building up functions from nailed constructs, scoping variables, etc. That usually means being on a dirt road most of the time: evaluating a lot of cells, inspecting FullForms, checking different conditions, clicking the `|Show More|` button, etc. Before I perform any action on my ongoing `.nb` I _should_ save my work in advance.   But alas! My mind is weak, my memory fades and my feeble fingers are too quick for my tired eyes.   So, when I press `Shift-Enter` or `|Show More|` and my Front End hangs, I remember Michael Douglas' D-FENS character in "Falling Down" with utmost sympathy. I would like an automatic way to save _my input cells_ (not the output ones, as they could be really large) in a backup .nb file before and every time any computation is requested. How? PS:   I must confess, my FrontEnd-fu is still in its teens.   I _think_ `$pre` could be set to the desired command, but I don't know how to select only the input cells and save them programmatically.


title: Possible to import Excel formatted text?

text: Is it possible to import Excel text markup such as underlines? For example: ![enter image description here](http://i.stack.imgur.com/zGGZ6.jpg) Yet               Import["/Users/alancalvitti/Dropbox/Understars/text.is.lyte/litany.of.\     duals/litany.of.duals.xlsx"][[1, 1]]      returns a list with the plain string:               {"nyt 7.23.12", "question for a ceo: what is yahoo?", "17 years after \     the company was founded, you still have to wonder whether the frothy \     trademark yahoo! should be replaced with yahoo? to convey the \     uncertainty of purpose", "david carr @nyt"}      Note that the formatting is partial, not a global formatting selection (such as font) that affects the whole cell.


title: How to eliminate the need to double evaluate a Manipulate so that a Module in its Initialization section works?

text: Using V 8.04 on windows. _I think_ this issue might be related to the fact that Mathematica reads main body the Manipulate before evaluating or running the Initialization option. Or, might be related to, and I quote "Symbols (and their contexts) are created when parsing, not evaluation" as per this question at SO Too complicated for me to figure it. I have a Manipulate with a Module in its Initialization section. I find that I need to evaluate the cell which Manipulate is in **2 times** to get the correct behavior (ie. have all symbols fully evaluated) There might be also a way to go around this using Leonid idea shown here but I can't use this method, if it applicable here, as it uses a BeginPackage which is not allowed for my setup. Since the code used will be in a CDF/demo, these are the symbols I had errors using before and I can't use in a demo: `SetOptions`, `ToExpression`, `Symbol` , `$Context`, `SetAttributes`, `Clear`, `Unprotect`, `DownValues`, `UpValues`, `OwnValues` and packages not allowed to be used or created. Also, `Manipulate[]` has to be the most outside construct. Now, here is the problem description. I Quit[] kernel, and clear everything               Remove["Global`*"]      Then in new cell I evaluate this Manipulate               Manipulate[      x;      init[obj];      get[obj],           Button["run", x++],      {x, None},      {{obj, makeObj[]}, None},      TrackedSymbols :> {x},           Initialization :>       {               makeObj[] := Module[{obj, u},          init[obj] ^:= u = {1, 2, 3};          get[obj] ^:= {u, Date[]};          Return [obj]          ]               }           ]      which gives this output ![enter image description here](http://i.stack.imgur.com/qzcsH.png) You can see that the value of symbol u is not evaluated. Now I go back the Manipulate cell, and evaluate it again (Hit ENTER in the cell) and now I see ![enter image description here](http://i.stack.imgur.com/AAsxZ.png) So, **it takes 2 evaluations** to have this work as expected. Is there a way to make this setup work with one evaluation? * * * ## **Update (1)** This is my finding comparing the 3 methods below to try to see which one will work for me best. First, the 3 methods solve the above problem for me. Next, I looked to see which method works best when I make a copy of the code, to see if the new copy will share anything with the old copy of Manipulate, as this is important issue in making demos. To do that, I modified the above Manipulate example a little to make it return the object itself (obj$nnnn) so I can see if it is named differently or not in the new copy, and also added a counter to see if changing the counter in one copy will update the counter in the other. Below are the 3 Manipulate example codes, one for each method, and below that I show a result of what I found from the test: Method 1 (Kugler method)               Manipulate[x;      get[obj],      Button["add to counter", x++],      Button["zero the counter", init[obj]],      {x, None},      {{obj, makeObj[]}, None},      TrackedSymbols :> {x},      Initialization :>       {        makeObj[] := makeObj[] = Module[{obj, u = 0},           init[obj] ^:= u = 0;           get[obj] ^:= {obj, u++, Date[]};           obj           ]        }      ]      Method 2: (Faysal method):               Manipulate[x;      get[obj],      Button["add to counter", x++],      Button["zero the counter", init[obj]],      {x, None},      {{obj,        makeObj[] := Module[{obj, u = 0},          init[obj] ^:= u = 0;          get[obj] ^:= {obj, u++, Date[]};          obj          ];        makeObj[]        }, None},      TrackedSymbols :> {x}      ]      Method 3: (Albert method)               Manipulate[x;      get[obj],      Button["add to counter", x++],      Button["zero the counter", init[obj]],      {x, None},      {{obj, None}, None},           TrackedSymbols :> {x},           Initialization :>       {        makeObj[] := Module[{obj, u = 0},          init[obj] ^:= u = 0;          get[obj] ^:= {obj, u++, Date[]};          obj          ];        obj = makeObj[];        init[obj];        }      ]      **Testing method and results:** Before running each test, I did               Remove["Global`*"]      Then evaluated the Manipulate cell, then clicked on the add counter to make it go to 10, then made a copy of the Manipulate output to a new cell (copy/paste). Then looked to see what shows up in the new copy, and if the new symbol will have zero as value, as that is the initial value for it, or not, and if the symbol name will be different as well. The results is: Method(1) and method(3) generate a new symbol. But With method (1), this happens only when I click the button on the first Manipulate to increment it one more time. Initially both output had the same obj$nnn value. Method (3), did not have this issue. The new copy immediately showed zero as value of the symbol, and also new symbol name obj$mmm. I was surprised, because I thought Method(2) since Module is inside Manipulate it will have a new symbol when I make a copy. Learned something new today. This screen shot shows the results. Therefore, Method (3) will work best for me in a demo, as it is a requirement that new copy of Manipulate do not interact with old one. ![enter image description here](http://i.stack.imgur.com/oQYlT.png) Thanks to everyone for their help, I learned from all of these answers.


I'd like to display field lines for a point charge in 3 dimensions. Not a force field (short arrows) but continuous field lines that start on the charge.


title: How to draw a coordinate system diagram?

text: I want to make drawings like these in _Mathematica_ : ![sc](http://i.stack.imgur.com/aj7y0.jpg) ![enter image description here](http://i.stack.imgur.com/5lxoz.jpg) I don't know if _Mathematica_ is a gppd solution for drawing such images. If it is, please tell me how to do it; if not, please suggest another solution.


title: How to Keep Input Cells Hidden After Evaluating Notebook

text: I've created a notebook for use in an in-class presentation. There is a fair amount of MMA code, and my students know nothing about MMA nor do they need to. I don't want to distract them with the code. I understand how to collapse the input cells and show only the output, but the input cells expand whenever I evaluate the notebook so I'm back to where I started. This notebook is meant to be interactive, so it has to be evaluated whenever I change the input. In this case, I have an InputField that requests a ticker symbol and then the code uses FinancialData to get the data and from that creates the results. I've tried creating a slideshow, but that has the same behavior. I've looked at the resources and answer in "Best way to give presentations with Mathematica" without finding any mention of this issue. So, in MMA 8.04 is there any way to force the input cells to stay hidden after the notebook is evaluated? Surely, there must be an option for this somewhere.


title: FeynCalc "May shadow or be shadowed by other definitions"

text: So I've downloaded the latest FeynCalc from this site and put the extracted folder in `user/me/library/Mathematica/application`, but when I write the command               << HighEnergyPhysics`FeynCalc`      _Mathematica_ says a bunch of lines saying stuff like: > `FeynAmp::shdw:` Symbol FeynAmp appears in multiple contexts > {`FeynArts``,`HighEnergyPhysics`FeynCalc`FeynAmp``}; definitions in context > `FeynArts`` may shadow or be shadowed by other definitions. >> Anyone know what to do, how to install FeynCalc on a Mac properly? I'm using _Mathematica_ version 8.


title: Plotting All Possible Points Belonging to a Group Orbit

text: Given that $$X = \\{(x,y,z) \in \mathbb{R}^3 |\, x^2 + y^2 + z^2 - 2(xy + xz + yz) = k\\}\,,$$ where $k$ is a constant. Also given that a group $G$ is represented by $$\langle g_1,g_2,g_3|\, g_1^2 = g_2^2 = g_3^2 = 1_G\rangle\,.$$ $G$ acts on $X$ such that $$g_1 \cdot (x,y,z) = (2(y+z) - x,y,z)\,,$$ $$g_2 \cdot (x,y,z) = (x,2(x+z)-y,z)$$ and $$g_3 \cdot (x,y,z) = (x,y,2(x+y)-z)\,.$$ So given $(x_0,y_0,z_0) \in X$, how do I go about plotting the orbit of the point $(x_0,y_0,z_0)$, ie $$\\{g \cdot (x_0,y_0,z_0) \,|\, g \in G\\}\,,$$ on a 3D graph? Would `ListPointPlot3D` be useful to plot all the points? How about other plotting functions?


title: The only usage for the option InterpolationOrder in NDSolve is to be set to All?

text: We know that changing the option `InterpolationOrder` in `ListLinePlot`、`ListPlot3D`、`ListContourPlot` will change the shape of the curve:               (*A example from the help*)     data = {{0, 0}, {1, 2}, {3, 4}, {4, 2}, {6, 0}};     Table[ListLinePlot[data, InterpolationOrder -> n], {n, {0, 1, 3}}]      ![Mathematica graphics](http://i.stack.imgur.com/KLxc6.png) But nothing changes for NDSolve:               Table[Plot[Evaluate[First[x[t] /. NDSolve[{x'[t] == y[t], y'[t] == -x[t], x[0] == 1,              y[0] == 0}, {x, y}, {t, 0, 10}, InterpolationOrder -> n]]], {t, 0, 10}], {n, 1, 3}]      ![Mathematica graphics](http://i.stack.imgur.com/AsyM8.png) I checked the help and found the only example for `InterpolationOrder` in `NDSolve` is to set it to `All`. (The same example appears in two different places…) So I met the question written in the title, and, what if I want to change the `InterpolationOrder` of the `InterpolatingFunction` worked out by `NDSolve`? * * * (Sigh…) Seems that `InterpolationOrder` in `NDSolve` is really "useless", and there's no option that can change the interpolation order of `InterpolatingFunction` worked out by `NDSolve`…whatever! here I've already picked up another approach for changing the order: I just need to replace the `InterpolatingPolynomial` with `Interpolation[…, InterpolationOrder -> …]` in the link.


title: How to leave function unevaluated programmatically?

text: Is it possible to write a function in such manner, that it can be either evaluated or left unevaluated? This is a general question. Sample below is just a sample. No need to find solution for this sample. Need a general solution. Hypothetical sample:               F[x_] := If[x>=0,         Sqrt[x],         Fail[]     ];      So that it gives               F[4]     (* ==> 2 *)      But               F[-4]     (* ==> F[-4] *)      I.e. hypothetical function `Fail[]` stays for "drop evaluation and leave expression unevaluated". I know I can use `Condition`               F[x_] := Sqrt[x] /; x >= 0      But I wish to do that in imperative programming way. Is this possible? **UPDATE** I don't understand why this is not working:               F[x_] := Block[{fail},       (If[x >= 0,          fail = False;          Sqrt[x],          fail = True          ]) /; ! fail]      **UPDATE 1** Manual has a good example               f[x_] := Module[{a}, a = Prime[10^x];       (FactorInteger[a + 1]) /; a < 10^6]      which is checking internal variables, not arguments. But why my version above not works then?


title: Implementing a For (?) or series or loop (?) for individual results for every x to n

text: I'm working on improving a modeling formula and have spreadsheets worth of data to use, but my work so far has been quite tedious. I'm essentially pulling 20 rows of data from each separate sheet of a spreadsheet to put through the new formula, and I'm having to do a cell evaluation for each row rather than a single evaluation per sheet. As I said, it's getting tedious. These can be declared first:               a = 0;     m = 34;     sheet = 1; (* which sheet of the spreadsheet I'm pulling from *)     r = 2; (* the first row I pull from *)     w = 8;     d = 4;     ex = .591;      For each sheet, these values (except `r`) will be the same (as I'm having to change `r` twenty times for each sheet). I then have this:               gs = Import["filename", {"Data", sheet, {r}, {6}}] + a     ga = Import["filename", { "Data", sheet, {r}, {7}}]      Here I pull the data from the sheet and row declared earlier, from static columns 6 and 7. From here, it's just plugging this data into the components of the formula:               y = ((gs + ga)/m)^ex     k = Gamma[1 + 1/y]     gsa = (gs/m) + 0.5     gaa = (ga/m) + 0.5     new = m*((3*N[Sum[-((Exp[-((k (c + 1))/gsa)^y] - Exp[-((k* c)/gsa)^y]) (1 -                   Exp[-((k* c)/gaa)^y])), {c, 0, w}], 40]) +          N[Sum[(Exp[-((k (c + 1))/gsa)^y] -               Exp[-((k* c)/gsa)^y]) (Exp[-((k (c + 1))/gaa)^y] -               Exp[-((k* c)/gaa)^y]), {c, 0, d}], 40])     final = Ceiling[new]      Redundant statements: as of right now, for every row I want to import, I have to manually adjust `r` for each evaluation. That's 20 tedious adjustments per sheet, and while it takes all of, like, ten seconds to then record the `final` value and increase `r` by 1, it's just not a feasible way of churning through volumes and volumes of data. Is there a way to split this into two cells, with the first declaring everything before `gs`, and the second giving the value of `final` for each `r` from 2 to 21? This would, quite honestly, be a 20x time saver. I'm just too unfamiliar with _Mathematica_ (still on the trial, licensing when it expires) to figure out the matrix or loop (?) to save me the time. Any help would be so, so, so appreciated.


title: How to get better quality EPS graphics

text: Yesterday, I was doing any Tables of 15 graphs similar to the next example, to save .eps and use in latex. In the generation of the graphs Mathematica spends many time. Is possible to reduce this time, and work for the cpu? I found that Mathematica save .eps with a big (not necessary) size. between 4 and 5 MB. When it´s obvious that for this image 400 or 500 KB is enough. So... how to obtain eps from MAthematica with a reasonable size (10-20% of the size that I have commented) In this example               ContourPlot[peaks[x, y], {x, -2, 2}, {y, -2, 3},       ColorFunction -> "DarkRainbow", ContourLines -> False,       Contours -> 25, LabelStyle -> {Bold, 20},       Epilog -> {Black, PointSize -> .036, Point[ {{1, 2}, {1.5, 2.5}}],         Cyan, PointSize -> .036, Point[ {{-1, 2}, {-1.5, 2.5}}]},       ImageSize -> 300]      Yesterday I resolve the problem, saving jpg/png and converting to .eps to can use in latex, because I put 12 or 15 images per page, and don´t need a high quality, but I would like any solutions to this issue.


title: What exactly happens when adding a Blank after a built-in function used in the rules of ReplaceAll?

text: Well, this question is just for curiosity, personally I never use `ReplaceAll` like this:               Cos[2 x] /. Sin_[2 x_] -> 2 Sin[x] Cos[x]     (* => 2 Cos[x]^2 *)      How to explain the result?


title: Specifying view angle of a 3D plot

text: I would like to create a stereogram from a 3d plot; I would like to export two images of a 3d plot at a slightly different angle, so that when each picture is presented to a different eye, one gets the feeling it is actually 3 dimensional. I have tried to put two plots next to eachother, then turn one plot slightly by hand (mouse), but when I then export, it is as if I hadn't turned the plot at all! example:               s1 =        Plot3D[PDF[MultinormalDistribution[{0, 0}, {{1, 1/2}, {1/2, 1}}], {x, y}],         {x, -2.3, 2.3}, {y, -2.3, 2.3}]     Show[GraphicsArray[{s1, s1}]]      How can I specify at which angle the 3d plot is exported? PS: Just to be clear: I don't want to rotate the function which is plotted, I want to rotate the plot, including the edges of the bounding box of the plot.


title: Type Vietnamese in Mathematica

text: I type Vietnamese using UTF-8 Encoding but Text Display got error. How to type Vietnamese, Chinese in Mathematica. Please help me.


title: What's the correct method to simplify exponentials?

text: I have a sum of exponentials that I'd like to simplify. The issue is when I use `Simplify`, Mathematica loves to factor out one exponential factor. See below: $$e^{-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})} \left((e^{i (d (\text{kx1}+\text{kx2})+2 \beta )}+2 e^{i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta )}+e^{i (d (\text{kx1}+\text{kx2})+2 (\beta +\gamma +\delta ))}+2 e^{i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +2 \text{$\theta $1})}+e^{i (d (\text{kx1}+\text{kx2})+2 (\beta +\text{$\theta $1}))}\right....))$$ Otherwise, when I try to `Expand` it I get $$e^{i (d (\text{kx1}+\text{kx2})+2 \beta )-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})}+2 e^{i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta )-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})}+e^{i (d (\text{kx1}+\text{kx2})+2 (\beta +\gamma +\delta ))-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})}+2 e^{i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +2 \text{$\theta $1})-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})}+e^{i (d (\text{kx1}+\text{kx2})+2 (\beta +\text{$\theta $1}))-i (d (\text{kx1}+\text{kx2})+2 \beta +\gamma +\delta +\text{$\theta $1}+\text{$\theta $2})}$$ Any help on how to "simplify" correctly would be greatly appreciated. Note, `Refine` does nothing in my case.


title: WebServices context problem

text: I'm using two web services from the same host: Earth Orientation Center I can get each one to work on a fresh kernel but I cannot get both of them to work during the same instance of the kernel. I think this is a context problem so I have tried loading each one into their own context. **The Code** Instal the service:               Needs["WebServices`"]          InstallService["http://hpiers.obspm.fr/eop-pc/webservice/server_MATRICE_EOP.php?wsdl"]      Make a call:               year = 2005;     month = 12;     day = 31;     hour = 12;     minute = 34;     seconde = 34;     pm = 1;     ut = 1;     nut = 1;     tides = 1;          wservice =       MATRICEfromDate[      LaDate["theyear" -> year, "themonth" -> month, "theday" -> day,       "thehour" -> hour, "theminute" -> minute, "thesecond" -> seconde,       "thepm" -> pm, "theut" -> ut, "thenut" -> nut,        "thetides" -> tides]]      This works and I get a matrix.               complexType$2200["a11" -> 0.318954, "a12" -> 0.94777,       "a13" -> 0.000580507, "a21" -> -0.94777, "a22" -> 0.318954,       "a23" -> 0.0000409354, "a31" -> -0.000146358, "a32" -> -0.000563244,       "a33" -> 1.]      But now if I install the other web service               InstallService["http://hpiers.obspm.fr/eop-pc/webservice/server_EOP2.php?wsdl"]      Then make a call:               year = 2005;     month = 12;     day = 31;          wservice =       C04fromDate[       LaDate["theyear" -> year, "themonth" -> month, "theday" -> day]]      It also works!               complexType$3424["MJD" -> 53735, "x" -> 0.053717, "y" -> 0.384245,      "UT1UTC" -> -0.661133, "LOD" -> -1.6*10^-6, "dX" -> 0.000228,      "dY" -> -0.000287, "xerr" -> 0.00014, "yerr" -> 0.000141,      "UT1UTCerr" -> 1.7*10^-6, "LODerr" -> 0.0000135, "dXerr" -> 0.000098,      "dYerr" -> 0.000091]      So what is my problem? When I go back an run the first function `MATRICEfromDate` I get:               SerializeSchemaInstance::children: Invalid children: thehour->12.      I cannot get both of them to work consistently in one kernel session. I think is has to do with the context of the `LaDate` **Edits** I have tried adding `AllowShortContext -> False` as was suggested. However, this did not work but it help open the door to a better understanding of the problem. I have now explicitly added a context:               InstallService["http://hpiers.obspm.fr/eop-pc/webservice/     server_MATRICE_EOP.php?wsdl", "First`", AllowShortContext -> False]          InstallService["http://hpiers.obspm.fr/eop-pc/webservice/     server_EOP2.php?wsdl", "Second`", AllowShortContext -> False]      I then call the web service with the following functions (I use the same inputs as above)               wservice =       First`MATRICEfromDate[       First`LaDate["theyear" -> year, "themonth" -> month,        "theday" -> day, "thehour" -> hour, "theminute" -> minute,        "thesecond" -> seconde, "thepm" -> pm, "theut" -> ut,        "thenut" -> nut, "thetides" -> tides]]      and...               wservice =       Second`C04fromDate[       Second`LaDate["theyear" -> year, "themonth" -> month,         "theday" -> day]]      The problem revolves to the context of `LaDate`. Here is a look at the variables in the two contexts:               ?Second`*          C04fromDate dYerr$2982 MJD$2946   themonth$2872 xerr$2967     complexType$2943 dY$2964 thedate$2939 theyear$2867 x$2949         dXerr$2979   LODerr$2976 thedate$2939$2987                           dX$2961  LOD$2958 theday$2877 UT1UTC$2955 y$2952      Notice there is no `LaDate`. Now look at the other context:               ?First`*          a11$2737 a23$2752 LaDate  thehour$2545 thesecond$2555     a12$2740 a31$2755 MATRICEfromDate theminute$2550 thetides$2575     a13$2743 a32$2758 thedate$2730 themonth$2535 theut$2565         a21$2746   a33$2761 thedate$2730$2766 thenut$2570     a22$2749 complexType$2734 theday$2540 thepm$2560        Here you will find the `LaDate`. Some how I need to get a `LaDate` into each context because they are different. Another attempt I have taken the two web servers and placed them in separate packages inside the `Begin["`Private`"];` section and then wrote a wrapper function which I exposed via `usage` and still no luck. I think I'm just going to parse old FORTRAN data files from the USNO


title: How to get the mean color of an artwork?

text: I got a piece of artwork in dimension of 20x20 pixels. I attempted to divide it into a 5x5 array of elements each of a smaller size of 4x4 pixels, and would like to find the mean color of the elements. I got the job done in a double for-loop. Is there a better way to do it? I need a faster way to treat much larger pieces. ![enter image description here](http://i.stack.imgur.com/U81QN.jpg)               Clear[avg]     avg = ConstantArray[0, {5, 5}];     image = Import["http://i.stack.imgur.com/ZZWEu.jpg"] ;     idata = ImageData[image];     ddata = Partition[idata , {4, 4}, 4] ;     For[i = 1, i <= 5, i++,      For[j = 1, j <= 5, j++,       avg[[i, j]] = Mean@Flatten[ddata[[i, j]], 1 ];       ]]     Image[avg]      This is what I got: ![Mathematica graphics](http://i.stack.imgur.com/b4gnW.png)


title: Random filling of L-length line with l-length segments

text: I have discrete L-length line filled randomly with 2-length segments so its cover line with gaps 0 or 1. So we can describe cover configuration as sequence of gaps such as {0,0,1,0,1}. How I can calculate the probability of any cover? I tried to do it using weighted graphs but it works only for small values of L < 30\. Increase the line length on 1 leads to 10-times increase in calculation time. Here is my slow code:               l = 2;     detach = Function[{cov, l}, s = Last[cov];      Table[Append[cov, Delete[ReplacePart[s, i -> l + Total[s[[i ;; i + 1]]]], i + 1]], {i, 1, Length[s] - 1}]];     getProbability = Function[{cov, l},        cc = NestWhile[Flatten[(detach[#, l] &) /@ #, 1] &, {cov}, Length@Last@Last@# != 1 &];        Total[Map[(Apply[Times, #]) &, MapThread[(p = Total[Select[#1, # >= l &] - l + 1];         If[ p === 0, 1, 1/p]) &, {cc,ConstantArray[ConstantArray[l, Length[First[First[cc]]]], Length[cc]]}, 2]]]      ];     Table[getProbability[{ConstantArray[0, i]}, l] // AbsoluteTiming, {i, l, 10}]          Output: {{0.031540, 1}, {0.000216, 2/3}, {0.000547, 7/15}, {0.002399, 34/105}, {0.013129, 638/2835}, {0.089803, 4876/31185}, {0.694457, 220217/2027025}, {6.223379, 6885458/91216125}, {63.263433, 569311642/10854718875}}      Here is example graph: ![enter image description here](http://i.stack.imgur.com/qguoU.png) Maybe it is possible to solve this problem using recurrence sequence or generating functions?


title: Equation Solving: Solution in terms of predefined functions

text: Is there a way that I can have Mathematica give me the solution of a problem it has solved in terms of functions that I have predefined? The specific problem I'm trying to solve is:               s = alp^2 (E0*mu1 + N01);     k = 1 - E^(-Pmax/s^2) + Sqrt[π*Pmax]/(2*s)*Erfc[Sqrt[Pmax]/s];          E1 = s^2 (1 - E^(-Pmax/s^2));          epsd = E1 - (s*k)^2;          A = 1 + epsd/((k*alp)^2 N01);          c = E1/(N01*(k*alp)^2);          SIG1 = (E0*mu1)/N01; SIG2 = (E1*mu2)/N02;          D[1 - 2 E^(-((A SNRth)/SIG1)) Sqrt[(c SNRth)/(SIG1 SIG2)]          BesselK[1, 2 Sqrt[(c SNRth)/(SIG1 SIG2)]], {alp}]      The solution given by _Mathematica_ is extremely lengthy. However, by observation it can be seen that many of the functions that I have defined above the differentiation operator are contained within the solution.


title: How to slice TimeSeries data?

text: When retrieving curated data, v10 now returns `TimeSeries` objects. For example,               ts = WeatherData["KP60", "Temperature", {{2013, 7, 1}, {2013, 9, 30}}]          DateListPlot[ts]      What is the most convenient way to extract a range from this temporal data, for example for plotting purposes? E.g. only plot the first two weeks of August from this data. I know I can simply convert it to a list using `Normal` and then use e.g. `Select` to filter. Is there anything better?


title: Convert expression to C-form and simplifying

text: I have an expression which is the sum of many terms of the form $$ \frac{0.00000000274341}{(0.000363856+(0.611425+z)^2)^{3/2}} $$ My problem is that I need to include this long expression in a C++-program I made, so all the exponents $^2$ and $^{3/2}$ I need to bring on a C++-compatible form. If I use `CForm`, then the exponents become `pow(..., 2)` and `pow(..., 1.5)`, respectively. In order to speed up my program, I would like for all the `pow(..., 2)` expression to be converted to `(...)*(...)` and for the `pow(..., 1.5)` to be converted to `(...)*pow(..., 0.5)`. Is there an easy way to do this?


Is it possible to compute trapezoidal rule numerical integration? I know that Mathematica has `Interpolation`, and that a list of points can be interpolated and then integrated simply using `Integrate`. However, my functions are highly oscillatory (they are based on simulation data), and I am not convinced that the interpolation is perfect, even when I set `WorkingPrecision` to a very high value. Also, I know that `ListIntegrate` is deprecated, and even if I use it, I am not certain if it is using the trapezoidal rule, which I would like to use. Do you know if any resources where I can find Mathematica or pseudocode for trapezoidal integration of lists of points? Or do you have any suggestions about how I can use Mathematica efficiently to program such an algorithm myself? Thanks!


title: Making a BarChart showing many data points look better

text: I have a `BarChart` used to show traffic on a network interface. I have data for every 0.5s, upto 1 min, which gives a lot of points. Is there a way to make it look less chaotic and messy?               data = Import["/Users/matek/NetworkTest/without_use_in_and_out.csv", "Table"];          maxValues = 121;     labelValues = Range[0.0, maxValues*0.5, 0.5];     Show[         BarChart[             data[[1 ;; maxValues]],             ChartLegends -> Placed[{"Outbound (TX)", "Inbound (RX)"}, {{0.5, 0}}],             ChartLabels -> {labelValues, None},             AxesLabel -> {"Duration [s]", "Bandwidth [byte/s]"}         ],          ImageSize -> 600,          BaseStyle -> {12, FontFamily -> "Helvetica"},          PlotRange -> All      ]      The result ![enter image description here](http://i.stack.imgur.com/IFboA.png) It's evident that the ticks and ChartLabels in the resulting BarChart look awful.


title: Stopping Evaluation of Manipulate after it goes through once

text: I do quite a bit of textual analysis with _Mathematica_ , and am currently making some `Manipulate` objects to walk people through key terms in the database. One issue I am running into with `Manipulate` however is that it continues to evaluate. For example, please consider the following code: ( **warning, this code does loop FWIW** )               testInput = {{"the", 4415}, {"of", 1284}, {"and", 1608}, {"in",          1384}, {"to", 1353}, {"a", 1205}, {"coal", 815}, {"was",          753}, {"by", 459}, {"were", 449}, {"for", 382}, {"is",          362}, {"with", 324}, {"from", 322}, {"on", 317}, {"that",          311}, {"as", 302}, {"mines", 264}, {"s", 257}, {"mining",          257}, {"it", 253}, {"this", 244}, {"at", 244}, {"be",          225}, {"cape", 216}};          testInput2 = {{"the", 4415}, {"of", 1284}, {"and", 1608}, {"in",          1384}, {"to", 1353}, {"a", 1205}, {"coal", 815}, {"was",          753}, {"by", 459}, {"were", 449}, {"for", 382}, {"is",          362}, {"with", 324}, {"from", 322}, {"on", 317}, {"that",          311}, {"as", 302}, {"mines", 264}, {"s", 257}, {"mining",          257}, {"it", 253}, {"this", 244}, {"at", 244}, {"be",          225}, {"cape", 216}};          files = {testInput, testInput2};          Manipulate[      viewerCount1 = {};      Do[       input = access;       AppendTo[viewerCount1,         If[Length[Flatten[Cases[input, {word1, _}]]] == 0, 0,          Flatten[Cases[input, {word1, _}]][[2]]]];       , {access, files}];      Print[viewerCount1];      , {{word1, "the", "First Word:"}}]      It goes through, runs the `Do` loop which picks out the word frequencies of `word1' in the sample text provided. But then, it **continues to loop**. It goes back through and does it again. And again. And again. This is all without any change to the `Manipulate` input. Is there a way to get to the end of the line `Print[viewerCount1]` and then **stop** until the input changes? I have tried to figure out the behaviour by looking elsewhere, such as "Manipulate Evaluation Sequence" and in the documentation, but there seems to be a paucity of textual examples like this.


title: What is the meaning of the last argument passed to the ColorFunction of a ParametricPlot3D?

text: According to the docs, the meaning of the arguments passed to `ParametricPlot3D` is $x, y, z, u, v$. This is 5 arguments: the Cartesian coordinates and the two parameters. Similarly, for `ParametricPlot` it's $x, y, u, v$. Let's look at how many arguments are _actually_ passed to the `ColorFunction`:               Reap[ParametricPlot3D[{Cos[u] Cos[v], Sin[u] Cos[v], Sin[v]},             {u, 0, 2 Pi}, {v, -Pi/2, Pi/2}, ColorFunction -> ((Sow[{##}]; Gray) &)]]      If you evaluate this, you'll notice that actually 6 arguments are passed to the colour function, but the last one is always zero. If we use the one- parameter form of `ParametricPlot3D`, then still six arguments will be passed, but now the last _two_ are zero.               Reap[ParametricPlot3D[{Cos[u], Sin[u], 0}, {u, 0, 2 Pi},        ColorFunction -> ((Sow[{##}]; Gray) &)]]      Similarly, the colour function of `ParametricPlot` receives 5 arguments instead of 4. **What is the meaning of the last argument passed to the`ColorFunction` of these functions? Does it have any use? Does `ParametricPlot3D` have a form where the last argument of the colour function will not be zero and has an application?**


title: Assumptions in mathematica when Symplify on Log[Exp[a/b]]

text: In mathematica 9.0: This:               Assuming[b > 0 || b < 0, Simplify[Log[Exp[a/b]]]]      yields:               a/b      However, this:               Assuming[FullSimplify[b > 0 || b < 0], Simplify[Log[Exp[a/b]]]]     enter code here      or this:               Assuming[b !=0 , Simplify[Log[Exp[a/b]]]]      Yield:               Log[Exp[a/b]]      Shouldn't be both equivalent? Why isn't the expression simplified in the second case?. Also tried to add ass an assumption a and b to be real, just in case, but doesn't work either. Could someone shed any light on this?


title: How to extract input part of a notebook?

text: For example, how to make Mathematica display only the lines beginning with `In[some number]`?               In[8]:= m1 = {{1, 1, 1}, {8, 4, 2}, {64, 16, 4}}      > >     Out[8]= {{1, 1, 1}, {8, 4, 2}, {64, 16, 4}} >                 In[9]:= m1.{b1, b2, b3} == {1, 1, 1}      > >     Out[9]= {b1 + b2 + b3, 8 b1 + 4 b2 + 2 b3, 64 b1 + 16 b2 + 4 b3} == {1, > 1, 1} >


title: Question about designing a particular data structure

text: Background: I store polygons with a color assigned at the face level. In some occasions I want to use vertex colors but I want to store data efficiently, i.e. don't want to duplicate data to the vertex level when it is not necessary. Consider the following _simplified_ data structure ( I had in mind, but does not work ):                tf := TableForm      def = {{10, 20}, {30, 40}};      def2 = Array[def &, 12];      col = {def2, def2};      pcl := {{col[[1]], col[[1]], col[[1]], col[[1]]}, {col[[2]], col[[2]]}};           col[[1]] // tf      col[[2]] // tf      pcl[[1]] // tf      pcl[[2]] // tf      `def` represents the data of one instance of a shape; `def2` represents the data of a shape with p6mm symmetry ( 12 copies ); `col={def, def}` represents the main data structure which currently stores two shapes; `pcl={{col[[1]], col[[1]], col[[1]], col[[1]]}, {col[[2]], col[[2]]}}` represents the desired data structure which currently stores two shapes with the first having four vertices and the second two vertices; Now if I set `col[[1,1,1]]` to `{11,21}` this shows up in `pcl`. So far, so good. I can't however overwrite it at the vertexlevel `pcl[[1,1,1,1]]={12,22}` _Mathematica_ generates a `Set::noval: Symbol pcl in part assignment does not have an immediate value. >>` message. **Question: How do I set up the required data structure** such that a change at the face level propagates through all vertices unless a vertex has been modified for that particular shape?


title: Link ITK with Mathematica

text: I would like to know if someone has tried to link Mathematica with ITK code (call ITK code in Mathematica)?


title: Returning multiple results from a LibraryLink function

text: What is the best way to return multiple inhomogeneous results from a LibraryLink function? Imagine that the result of a single computation is several tensors of different dimensions and several numbers. They should all be returned at the same time. I see two ways:   1. Get a MathLink connection and use MathLink API functions to return the results. Is there any advantage at all to using LibraryLink (instead of pure MathLink) in this case? Did anyone compare LibraryLink/MathLink data transfer performance so I can more easily assess what the performance hit would be?   2. Have several LibraryLink functions: one will send the input, do the computation and store the result; there would be separate functions for retrieving each result; finally there would be a function to free up the library memory used to store those results. I'm not particularly keen on doing this. It seems more trouble and it forces me to manually manage memory from Mathematica. Are there any better options?


title: Settings to disable global scope

text: I am building a fairly large application in Mathematica, and globally scoped variables are causing issues. I would like globally scoped variables to be out-of-scope for my expressions, except by request. Here is a simple, albeit contrived, example (where //GlobalScope is something with the intended behavior, I guess):               B := 0;          f[x_, m_, b_] := m*x + b;          Manipulate[      Plot[       f[X, M, B],        {X, 0, 10}      ],       {M, 0, 10},       {B, 0, 10}     ]//GlobalsAvailable      should be allowed, but               B := 0;          f[x_, m_, b_] := m*x + B;          Manipulate[      Plot[       f[X, M, B],        {X, 0, 10}      ],       {M, 0, 10},       {B, 0, 10}     ]//GlobalsAvailable      should not be allowed. I'm also open to suggestions which fix the underlying problem (which is caused by the combination of mutability, global scope and the reactive development style encouraged by notebooks).


title: There is a button in the "basic math assistant" which wraps highlighted text in chosen brackets. Is there no keyboard command for this?

text: This counts as something of a basic question, but one for which I cannot find an answer. I checked the documentation, I checked google, I searched it here, I read a bunch of different things, but nobody seems to have an answer. Basically, I'm very lazy, and I rarely feel like dealing with wrapping things in brackets if it can be avoided. Things like '@' and '//' are very useful, but there are times when things just must be put in suitable brackets, which can get annoying when working around already written code. If only one could highlight the text and press a keyboard command and suddenly have that text wrapped in brackets... But wait! In Basic Math Assistant there is a button that does exactly this! It's just quite cumbersome to use given that you need to have that assistant open and click on it, you might as well just do it by hand. Is there any way to get something like this to be done via a keyboard command or something similar?


title: How can I access documentation from the Workbench?

text: In Mathematica there is a hot key for searching words (that your cursor is within or adjacent to) in the documentation center, is there a way to do this from the Workbench instead of having to first switch back to Mathematica?


title: Custom image as plot marker

text: Is there a quick and easy way with `Graphics` to replace the standard data points in a plot with a custom image?


title: How to add new nodes to an existing graph with fixed (coordinates) nodes?

text: I'm ultimately trying to create a directed graph with some of the nodes in fixed positions and the other nodes placed around them in "acceptable" positions. It's better if I ask the question by showing an example of the code. E.g. I have this graph:               node = {11, 12, 13, 14, 15, 16};     edges = {11 -> 14, 11 -> 16, 12 -> 16, 12 -> 15, 13 -> 15, 13 -> 16,       14 -> 16, 14 -> 15, 15 -> 16, 15 -> 13, 16 -> 15, 16 -> 14};     vertexposition = {{6.51493919050084`, 44.04756585632944`},                        {75.59445680043342`, 50.47455242214042`},                        {87.32825501506514`, 13.395648943951699`},                       {28.795707353492418`, 3.420138063734413`},                        {60.729164933330765`, 16.915777496473908`},                        {51.85158892659126`, 25.803692768150313`}};          Show[          Graph[node, edges, VertexCoordinates -> vertexposition, Frame -> True,                              VertexSize -> {"Scaled", .02}, VertexLabels -> "Name"]          , FrameTicks -> True, ImageSize -> 600]      I have these fixed critical nodes with positions that are important to me, however I have many other nodes that I want to add to the graph and connect to these nodes without having to specifically add their coordinates. For example, I want to remove the connection between node $11$ and node $14$ but add three arbitrary nodes that link in series to connect nodes $11$ and $14$ without having to define their position, and have mathematica put an "appropriate" default position for them. That is, I don't want to add the nodes and have them all bunch up at the origin; the graph should look more organic. Here's the kicker, I want to add edgeweights to all the nodes and don't necessarily want them to space out according to the edgeweights.


title: How to graph in Cylindrical coordinates in 3D

text: I need help figuring out how to plot in cylindrical coordinates. I read that `CylindricalPlot3D` was replaced with `RevolutionPlot3D`. Here is my function:               Integrate[ r^3*(Cos[ θ])^2, { θ, 0, 2 π}, {r, 0, 1}, {z, 0, 2 r}]      > >     (2 π)/5 >   when I try `RevolutionPlot3D` I get:               RevolutionPlot3D[ r^3*(Cos[θ])^2, { θ, 0, 2 π}, {r, 0, 1}, {z, 0, 2 r}]      > >     RevolutionPlot3D::nonopt: Options expected (instead of {z,0,2 r}) beyond > position 3 >     in RevolutionPlot3D[r^3 Cos[θ]^2,{ θ,0,2 π},{r,0,1},{z,0,2 r}]. >     An option must be a rule or a list of rules. >> >


title: Understanding FullForm in front end

text: I want to understand the following effect better (In Mathematica 9) .. Or, maybe, is it a bug? Running the following line               FullForm[Subscript[α,β_]]      gives as output,               (*Output*)     Subscript[\[Alpha], Pattern[\[Beta], Blank[]]]      But then, when I try to _edit_ the above output, I get some unexpected stuff: ![enter image description here](http://i.stack.imgur.com/mryVM.png) There is some strange spacing at the end, and the front end disagrees with the syntax (as evidenced by the red carat). How do I understand what's going here?


title: How to integrate this cumbersome piece-wise function?

text: I have this systems of equation:               kt = Sqrt[h/(π (y1 - y2))]*Integrate[p[y]*Sqrt[(1 + y)/(1 - y)], {y, -1, 1}]       kb = Sqrt[h/(π (y1 - y2))]*Integrate[p[y]*Sqrt[(1 - y)/(1 + y)], {y, -1, 1}]        In which: `y1` and `y2` are two variables that I need to find, `-1<y2<0`, `0<y1<1`, and `y1` and `y2` are real. The problem is that `p[y]` is a piece-wise function and is defined by:               p[y] := Piecewise[{         {p + a*(y1 + y2)/2 - a*2 h y/(y1 - y2) - t1, y2 < y < y1},          {p + a*(y1 + y2)/2 - a*2 h y/(y1 - y2) - t2, y1 < y < 1},          {p + a*(y1 + y2)/2 - a*2 h y/(y1 - y2) - t3, -1 < y < y2}}]        In which: `a`, `p`, `t1`, `t2`, `t3`, `h` are constants. I need to find `y1` and `y2` so that:               kt==c1&&kb==c2        where `c1` and `c2` are two constants. I had tried to solve this integration manually and the answer was lengthy and involved the inverse trigonometric equations. I also tried to use `Solve`, `NSolve`, `Reduce`, `FindInstance` and `NIntegrate` but _Mathematica_ usually hangs. Since I have to solve this system of equations repeatedly, I really want to know how can I perform these calculations in _Mathematica_ automatically?


title: Solving inequalities for positive Integers

text: Consider the following;               all = {a, b, c, d, e};     mean = Mean[all];     a1=Accumulate@Prepend[all, 0];     a2=Accumulate@Append[Table[mean, {i, Length[all]}], 0];     a3=a2-a1;     a4=Map[Reduce[# >= 0, all] &, a3]      Now I would like Mathematica to solve this with the restriction that all elements of `all` are positive Integers.


title: How to force Mathematica not to use Erf and DawsonF functions in its output

text: In ODE solutions _Mathemathica_ uses `Erf` and `DawsonF` functions instead of the integral expressions they represent. How can I force _Mathematica_ to show the integrals in its output? For example,               ClearAll[A];     A[x] /. DSolve[A'[x] == E^-x^2, A[x], x] /. C[1] -> 0      > >     {1/2 Sqrt[π] Erf[x]} >   But I would like to see the integral for `Erf`.


title: Upper bound for x

text: I want to ask a question about `Reduce`. I have a function, say `f[x]`. When I use the command `Reduce[f[x] > 0, {x}]`, it gives me an interval for `x`. But, I don't want to have an interval. I want to have an upper bound for `x`. For example: After the command `Reduce[f[x] > 0, {x}]`, the output is `a_1 < x < a_2`. But I want to have only `a_2`. How can I get it?


title: Finding intersection of two graphs

text: Here is a toy problem: I have a (directional) line that starts from `{2,0}` and goes through `{1.8, 0.01}`. Also I have a parametric plot defined like this: `{Sin[u], Sin[2 u]}` where `0 <= u <= 2 Pi`.   I would like to find the intersection of these two. I tried something like:               Solve[a*({1.8, .01} - {2, 0}) + {2, 0} == {Sin[u], Sin[2 u]}        && 0 <= u < 2 Pi && a > 0, {u, a}]      But both `Solve` and `NSolve` seem to struggle with this. `Findroot` is able to find an answer quickly but it gives me only one answer depending on the starting point while I'd like to have all correct answers, four in this case. Also I see if I redefine the line section so that it has only one intersecting point with the curve (e.g. line starts at `{0, 0}` and goes through `{-0.1 , 0.01}`) then `Solve` is able to find that one answer comfortably! Any idea how to solve this?


title: Alternative for citation management in Mathematica 9 for Mac

text: I have just read that Mathematica 9 for Mac does not support Citation Management. Any ideas of a poor's man replacement so I can still use Mathematica on Mac for editing? I mean, have someone written a script to "import" a .bib into a notebook or something like that? I took the time to put all my references in a .bib file. I also imported them into EndNote. If this is of any help... regards, Mr. Disappointed


title: Thick border on some ParametricPlot3D objects

text: Object `x` should be composed of thick lines, object `su` should have no or a thin border. With `BoundaryStyle`, I am not able to differentiate between `x` and `su`. I haven't had much luck with `PlotStyle -> {Thick, }` or `PlotStyle -> {EdgeForm[Thick], }` either.               x1 := {u, 0, 0}     x2 := {u, 1, 1}     x3 := {0, w, w}     x4 := {1, w, w}     x := {x1, x2, x3, x4}     su := {u, (1 - u) w^2 + u w^2, (1 - u) w + u w}     ParametricPlot3D[{x, su}, {u, 0, 1}, {w, 0, 1}]      ![enter image description here](http://i.stack.imgur.com/IqCDx.png)


title: On Reverting Code that Mma Switches to Raw Input Form Back to Standard Form

text: I experienced a similar issue to what is described in this post while editing formatted usage messages (that contained italics) in the declaration section of a package that I'm developing in the notebook front-end. **Question 1** : Does anyone know what exactly causes Mma to convert code that contains formatted text to raw input form without explicitly being requested to do so by the user? Is this behavior part of a feature that several of us apparently do not fully understand ... or does it represent a bug in the parser that Wolfram acknowledges? The solution described in the post linked above did not quite solve my problem because I need to evaluate the sequence of usage messages as part of setting up the package. I eventually found that               FrontEndExecute@FrontEnd`CellPrint["myFunction::usage=\"myFunction does ...\";"]      recovered the cell with usage messages displayed in standard input form exactly as I originally entered them (i.e. no explicit Styleboxes and escaping of quotes etc.). In the process I reviewed the documentation on CellPrint and its FrontEnd- equivalent version. The main difference from what I could gather is that the former is handled by the kernel while the latter is processed solely in the FrontEnd. While experimenting with the two versions of CellPrint, I noticed the following:               CellPrint[Cell["a", "Input"]]      produces the cell expression               Cell["a", "Input"]      whereas               FrontEndExecute@FrontEnd`CellPrint["a"]      produces a BoxData-wrapped version of the above               Cell[BoxData["a"], "Input"].      One obvious consequence of this discrepancy is that the syntax highlighter colors the latter in blue but not the former. **Question 2** : Why does the version of CellPrint evaluated in the kernel not wrap the input text in a BoxData structure too? While my issue with the auto-conversion of usage messages to raw input form is now resolved I feel that my understanding from reading the documentation of how Mma parses and produces different formatting structures is still far from complete. Perhaps an answer here will shed additional light on this topic.


title: Overlapping pure functions

text: Let say I need and option for `Plot`:               RegionFunction -> (-6 < #2 < 6 &)      But I also want those `-6` and `6` to be take as arguments from overlapped function. The following is not going to work, I only want to show an example               RegionFunction -> ((#1_2 < #2 < #2_2 &)&_2 @@ {-6, 6})      This construction `#2_2` means second argument reffered to the function closed by `&_2`. I know I can do this in about 432 different ways, **this is an abstract question** about particular construction/input syntax. **Edit** After reading answers of Mr. Wizard and jVincent I have to clarify the question. > My goal was to find out if there is a way to reffer `#` to desired `&` if > there is some type of mix like in the example `((#1 < #_2 < #2)&)&_2`. jVincent note about `\[Function]` seems to be the closest to the general idea.


title: What are some advanced uses for Block?

text: I read the answer to this question and this one. According to those, `Block` is safer (if something aborts, it restores the values) and faster (perhaps something to do with the low-level pointer redirection that I believe it uses) than `Module`, but less memory-efficient if the function is defined a certain way. That being said, (1) why does Leonid say that `Module` is "safer" when it doesn't have as-good garbage collection, and (2) if I am to use `Module` for most of the time, what are some of the "advanced" uses which require `Block`?


title: Possible to export Excel formulas?

text: I would like to export an .XLS file complete with data and formulas. Is this possible using `Export`? For example, here is data and a formula :- ![enter image description here](http://i.stack.imgur.com/RcyqI.png) I can import them, (separately), but cannot export them both. ![enter image description here](http://i.stack.imgur.com/LAIXD.png) I am looking into trying with .COM objects (as per Formatting in XLS(X) files).


title: LetL and Module efficiency

text: I was recently introduced to the `LetL` macro thanks to Leonid's answer to one of my prior questions. I was, needless to say, impressed by the simplicity of its recursive definition. However, I noticed that it may not necessarily be optimized. As it is defined, if my `LetL` statement contains a definition which does not need to be nested, then it will call `With` unnecessarily:               testLetL := LetL[{x = 1, y = 2, z = 2 x y}, {x, y, z}]     ?testLetL     (* testLetL:=With[{x=1},With[{y=2},With[{z=2 x y},{x,y,z}]]] *)      So I compared it to `Module`.               testModule := Module[{x = 1, y = 2, z}, z = 2 x y; {x, y, z}]     (Do[#, {i, 5000000}] // AbsoluteTiming) & /@ {testLetL, testModule}     (* {{0.9390537, Null}, {0.9270530, Null}} *)      As you can see, there doesn't seem to be much speed gained in using `LetL` \- essentially nested `With`s - instead of `Module`. I thought perhaps that it was the extra `With` being called that was slowing things down. So I tried another test:               testLetL2 := LetL[{x = 1, y = 2 x }, {x, y}]     testModule2 := Module[{x = 1, y}, y = 2 x ; {x, y}]     (Do[#, {i, 5000000}] // AbsoluteTiming) & /@ {testLetL2, testModule2}     (* {{0.9270531, Null}, {0.9120521, Null}} *)      This again showed that they were pretty much the same, if not `Module` being a bit faster. * * * My question is, then, is `LetL` simply used for convenience or are my tests missing something?


title: How to silence all messages associated with a built-in symbol?

text: The post title's pretty much says it all... The reminder of this post just describes the little headway I made with this problem, FWIW. * * * One would hope that               In[100]:= Quiet[whatever[], Messages[SomeArbitraryBuiltIn]]      would do it, but no. For one thing, `Messages` shows only those messages that have been defined in the current session, and (from the docs):               In[1]:= Messages[NDSolve]     Out[1]= {}          Typically, for system commands, messages are only loaded when they are required:          In[2]:= NDSolve[{x'[t] == x[t, s], x[0] == 0}, x, {t, 0, 1}];             Messages[NDSolve]                       NDSolve::dvlen :                   The function x[t,s] does not have the same number of arguments as                   independent variables (1). >>          Out[2]= {HoldPattern[NDSolve::"dvlen"] :>                The function `1` does not have the same number of                 arguments as independent variables (`2`).}      Besides, even when `Messages` delivers the goods, it does so in a form that is not readily usable by `Quiet`; e.g.:               In[109]:= Take[Messages[General], 3]          Out[109]= {HoldPattern[General::appname] :>                  The name `1` is not valid for the application. A valid name starts with                  a letter and is followed by letters and digits.,                 HoldPattern[General::argtu] :>                  `1` called with 1 argument; `2` or `3` arguments are expected.,                 HoldPattern[General::bktmcp] :>                  Expression "`1`" has no closing "`2`"`4`.}      I'm sure that, after a few afternoons of torture, I'd just manage to come up with an incantation that's just _ridiculous enough_ to get all those `HoldPattern`'s to cooperate with `Quiet` (which, for additional pain, has attribute `HoldAll`), but I'd appreciate a leg up on that too.


title: How to get UV mapping of 3D tube

text: Here is cylinder data: file We can mesh the surface, thanks to lalmei, Belisarius and Simon (link) How to achieve uv mapping from a 3d straight and curved tube? Working code:                 Needs["TetGenLink`"]      file="http://pastebin.com/H9y9SqYy";      dat = Import[file, "Table"];      {pts, tetrahedra} = TetGenDelaunay[dat];      csr[{aa_, bb_, cc_, dd_}] :=       With[{a = aa - dd, b = bb - dd, c = cc - dd},       Norm[a.a Cross[b, c] + b.b Cross[c, a] +       c.c Cross[a, b]]/(2 Norm[a.Cross[b, c]])]      radii = csr[pts[[#]]] & /@ tetrahedra;      alphashape[rmax_] := Pick[tetrahedra, radii, r_ /; r < rmax]      faces[tetras_] := Flatten[tetras /. {a_, b_, c_, d_} :> {{a, b, c},       {a, b, d}, {a, c,     d}, {b, c, d}}, 1]           externalfaces[faces_] := Cases[Tally[Sort /@ faces], {face_, 1} :> face]      polys = externalfaces@faces@alphashape[0.01];      Graphics3D[GraphicsComplex[pts, Polygon@polys], Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/fg0Ci.png)


title: Can anyone explain how to use Mathematica's OAuth package?

text: I noticed that in `HTTPClient.m` which is included with _Mathematica_ 9 and is located in               FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "HTTPClient"}]      there was a dependency on `HTTPClient`OAuth``, so I poked around and found it. `OAuth.m` seems to contain all of the necessary functions to perform OAuth authentication, which is interesting to me since I'd like to build an API manager for sites like fitbit, withings, etc. I managed to figure out that `SocialMediaData` uses OAuth (which makes sense, since that is the authentication method that I gather Facebook and Twitter require), but the code for that is hidden and trying to read `SocialMediaData.mx` only confirms that OAuth is used without showing me how it's called. Can anyone figure out how to actually use `HTTPClient`OAuth`` in _Mathematica_? Or perhaps can anyone figure out how to read the `SocialMediaData.mx` file to get the code for `SocialMediaData` so I can see how Wolfram made use of the package?


title: How to define a global variable in Mathematica?

text: I have restricted the context of my notebooks to each individual notebook. So variables in each notebook are local and are not seen in another notebook. But in two of my notebooks I have two functions that I want to plot simultaneously with the command `Show`. Please note that I want variables of each notebook to be local except for those two functions. So I need to define two global variables and then plot that two functions in `Show`. How can I define global variables in Mathematica?


title: How can I run .exe file in Mathematica

text: we have a `.exe` file. It takes input as `.txt` file and gives output as another `.txt` file. Now, I want to run that `.exe` file from `MM`. I tried in 2 way, Case 1 : using `SystemOpen[]`. It showing the following Window, Once I run the `SystemOpen[path]`. ![enter image description here](http://i.stack.imgur.com/JVtfm.jpg) I click on `Run` button.after it's not showing anything. for my conformation, Manually I double click on `.exe` file. it's working fine. but `SystemOpen[]` was not working. case 2: I created `.bat` file with the following code                  cd C:\Users\Infratab Bangalore\Desktop\Rod's        Infratab1-2.exe      Now I open `.bat` file using same function `SystemOpen[]`. here it's working great. How can I fix `case 1` problem. If anybody knows suggest me. Thanks.


title: How to eliminate (hide) output numbers in a slide show

text: I am creating a slide show with several imbedded `Manipulate` objects. I can hide the `Manipulate` command by clicking on the output cell bracket. I would like to eliminate (or to hide automatically generated output number, e.g. `Out[2] = ...`.   Is there a notebook level option to do this?


title: Solve set of non-linear equations with least-squares-fitting - constrain results?

text: I'm trying to solve a set of functions to determine the material properties from a set of measurement values. (To set up this method I just want to fit my model with some already calculated data). My equations look like this:               eqns = {        fres[L1] - f1,        fres[L2] - f2,        fres[L3] - f3,        fres[L4] - f4,        fres[L5] - f5        };      fres[L_] is defined earlier (very long equations which do not need to matter at the moment) - here is just a working example:               fres[L_] := C1^2 / (L^2)*Sqrt[Sum[Subscript[a, i] + Subscript[b, i], {i, 1, 5}]]      Now I wanted to solve this set of equations by the method of least squares fitting to determine the a_i (note: I'm not using subscript in my code but I'm using a vector with a[[i]]):               sol = FindMinimum[{Total[eqns^2], a1 >= 50*10^9, a2 >= 100*10^9, a3 >= 70*10^9, a4 >= 100*10^9}, {a1, a2, a3, a4}, Method -> "LevenbergMarquardt"]          eqns /. Last@sol (* for manual control *)      The problem is, that I cannot get any solution here, because the LevenbergMarquardt method do not allow constrainted problems. As far as I understoot, the least squares fitting method is best done by this method... My a1..a4 are only positive values in the range of 10^9 to 10^12... When I remove the method my input looks like this:               sol = FindMinimum[{Total[eqns^2], a1 >= 50*10^9, a2 >= 100*10^9, a3 >= 70*10^9, a4 >=100*10^9}, {a1, a2, a3, a4}]      And the output:               FindMinimum::eit: The algorithm does not converge to the tolerance of 4.806217383937354`*^-6 in 500 iterations. The best estimated solution, with feasibility residual, KKT residual, or complementary residual of {0.0157055,8.38758*10^-7,0.00491086}, is returned. >>      Increasing the iterations won't deliver good results either (i tried up to 10 000). It only results in a1..a4 which are very close to my starting values:               Out:     {1.12792, {a1-> 5.*10^10, a2-> 1.*10^11, a3 -> 1.03486*10^11, a4 -> 1.*10^11}}     {-0.908837, -0.252209, -0.100982, 0.361948, 0.311647}      Do you have any idea how I could get the a1..a4 (or even more)? Is there any elegant way of doing this? Your help would much be appreciated!


title: How to select a certain portion of a piecewise function?

text: For example, if I have `Piecewise[{{x^2, x < 0}, {x, x > 0}}]`, how do I select only the function that is for `x < 0`? I want to set a new function equal to the `x^2` only, not the entire piecewise function.


title: How to include constraints in `NMaximize`

text: I am trying to find maximum likelihood estimates of parameters for a fairly complicated multivariate distribution. The support of the distribution depends on its parameters so I need to include some constraints in `NMaximize`. The following is a simplified version of the problem. Consider the following code which generates 1000 observations from a Max Stable distribution and estimates the parameters:               SeedRandom@100;     data = RandomReal[MaxStableDistribution[0, 1, 1], 10^3];     pars = FindDistributionParameters[data, MaxStableDistribution[μ, σ, ξ]]     (* {μ -> -0.0296428, σ -> 0.946788, ξ -> 0.945316} *)      Suppose now we want to find these estimates using `NMaximize`. Let's assume that $\gamma\ne 0$ so I just need to include the constraint $\frac{\gamma (x-\mu )}{\sigma }+1>0$ in the log likelihood function where the `PDF` is given by the following:               ClearAll[G]           G[x_] = PDF[MaxStableDistribution[μ, σ, γ], x] //      FullSimplify[#, γ != 0 && 1 + (γ (x - μ))/σ > 0] &      I have tried to include the constraint $\frac{\gamma (x-\mu )}{\sigma }+1>0$ in the definition of `G` by using `Boole` to no avail. I should add that even without that constraint `Nmaximize` does not return a result:               NMaximize[{Total[Log[G[data]]], σ > 0, γ != 0}, {μ, σ, γ}]      Any suggestions on how to do this would be gratefully appreciated.


title: How to export data files using specific format

text: Very often, I have to export data files from Mathematica. These output files contain several columns and hundreds of lines with data. For the sake of the question let's create a sample list               data = Table[{RandomReal[i], RandomReal[i^10]}, {i, 0, 100, 0.1}];      Then, I export the data in an external file using the following command               Export["data.out", data, "Table"];      Now let's take a look at the output file. I present here only the first ten lines of data, but of course the whole file is easily reproducible.               0.  0.     0.01599700768300292    9.144414172338937e-12     0.05264806593747054    5.191535295682516e-8     0.26762136311267287   2.6644991730537336e-6     0.01121545335019451     0.000014373686962031977     0.05282872336357303   0.0005555775821525191     0.39492299878320175   0.0005639987736085206     0.6483050598753638    0.016687867077835535     0.5871008451356092    0.029518547448633307     0.2613882661983659    0.046494918800056996     ..................    ....................      My problem is that the format of the data is very bad. When I create external output files in FORTRAN I can control the exact format. So, I am wondering: Is this possible in Mathematica? Can I control the number of decimal digits of the data, using exponential form or even the gap between the two columns? In FORTRAN, I would use this format 2(4X,E16.8), meaning that the data would be in exponential form (E), having total 16 digits in total from which the 8 are decimal and finally the gap between the two columns is 4 blank characters. EDIT: Following cormullion's instructions the exported data files look like this               0.0000000000000000E     0.0000000000000000E     0.0292206329521133E     3.5660981240075680E-12     0.0110286543632250E     7.1403083420409010E-8     0.1512525645232069E     3.4764180261918010E-8     0.1802104544376126E     0.0000150833977857E     0.1909866023262902E     0.0004442874170494E     0.1977662892883431E     0.0047809317792338E     0.1043698170574586E     0.0116230093104291E     0.2452055184319113E     0.0756524674940767E     0.4203148306922685E     0.0682570346613104E     0.4640953468992068E     0.6204923184434734E     0.4361142873366830E     0.8423302837693910E     0.3853270077185619E     1.9278084597534120E     0.9173409732335570E     1.9391384326481460E     0.2309798126928349E     6.9819944783354480E     0.9064707972602210E     55.0683061788128700E     1.1871007725662080E     47.5205793705051100E     0.0657321188104301E     165.0478398165293000E     0.6501851799068231E     261.9422532326231000E     0.1976942785179729E     83.6983691851117000E     0.1781317179022484E     877.1531182356240000E     0.9603071406080800E     610.9760718811238000E     1.2678697679679910E     2107.5934446883950000E     1.2555519112242100E     695.2293658225135000E     1.4503489860688380E     6300.5931889760220000E     2.3698084216652830E     9336.5466490215000000E     0.9495735185410430E     8100.1159435400300000E     2.3382755917778770E     18471.7912516294500000E     1.3595555295319900E     27021.6788394801700000E     1.1450366450215240E     20223.3331979412600000E     0.6496852979125343E     14269.5720554042100000E     1.4074545584871190E     22413.5903375179000000E     1.8790499719570280E     85437.5672819188000000E     3.0597774075552670E     37024.4278765415400000E     3.2694586701530210E     99567.9453873553000000E     2.7064643220362330E     226071.8308196532000000E     ...................     ........................      As everyone can observe, there are some inconsistencies regarding the format (i). The exponential part (E) should always have the same pattern; two digits (i.e. E-08 not just E-8) and when is zero should be E+00 (ii). In some cases, the second column contains some additional (more than 16) decimal digits (in fact they are unwanted zeros). I filtered this data file using a very simple FORTRAN code and here is the corresponding output               0.0000000000000000E+00    0.0000000000000000E+00     0.2922063295211330E-01    0.3566098124007568E-11     0.1102865436322500E-01    0.7140308342040901E-07     0.1512525645232069E+00    0.3476418026191801E-07     0.1802104544376126E+00    0.1508339778570000E-04     0.1909866023262902E+00    0.4442874170494000E-03     0.1977662892883431E+00    0.4780931779233800E-02     0.1043698170574586E+00    0.1162300931042910E-01     0.2452055184319113E+00    0.7565246749407670E-01     0.4203148306922685E+00    0.6825703466131040E-01     0.4640953468992068E+00    0.6204923184434734E+00     0.4361142873366830E+00    0.8423302837693910E+00     0.3853270077185619E+00    0.1927808459753412E+01     0.9173409732335570E+00    0.1939138432648146E+01     0.2309798126928349E+00    0.6981994478335448E+01     0.9064707972602210E+00    0.5506830617881287E+02     0.1187100772566208E+01    0.4752057937050511E+02     0.6573211881043010E-01    0.1650478398165293E+03     0.6501851799068231E+00    0.2619422532326231E+03     0.1976942785179729E+00    0.8369836918511170E+02     0.1781317179022484E+00    0.8771531182356240E+03     0.9603071406080800E+00    0.6109760718811237E+03     0.1267869767967991E+01    0.2107593444688395E+04     0.1255551911224210E+01    0.6952293658225135E+03     0.1450348986068838E+01    0.6300593188976022E+04     0.2369808421665283E+01    0.9336546649021500E+04     ......................    ......................      Now, everything is OK! Well, as Xerxes pointed out, why care what the file looks like as long as the next computer program knows how to parse it? The answer is very simple. Because scientists love neatness and order in their work and they hate sloppy jobs! Moreover, I refuse to believe, that a sophisticated and modern software like Mathematica cannot export data using predefined format.


title: Controlling preferences of deployed notebooks

text: The following screenshot shows a toy example to illustrate what I want to accomplish: ![enter image description here](http://i.stack.imgur.com/gFHUz.png) The above mimics the structure a type of notebook that I want to deploy for both Mathematica and PlayerPro environments. In actual use, an accompanying package handles the heavy work load. _**What I need to do_** \-- I need to make deploying these notebooks as simple as possible. Especially, I don't want to have to manually configure a bunch of settings on each computer where they will run. Examples of the kind of settings that I want to accompany the deployment include:               Notebook Options, Evaluation Options, InitializationCellEvaluation -> True     Notebook Options, Evaluation Options, InitializationCellWarning -> False     Notebook Options, Notebook Properties, CellGrouping -> Manual     Notebook Options, File Options, Editable -> False     Notebook Options, File Options, Saveable -> False     Notebook Options, File Options, ClosingSaveDialog -> False           Cell Options, Display Options, ShowGroupOpener -> True       _**Don't forget the groups_** \- In addition to the above, on my development machine I set specific groups of text cells. I would like these groups preserved when I deploy the notebooks. _**Some of the problems_** Some things seem inconsistent. I can create an initialization cell, but if the target platform hasn't had the following set:               Notebook Options, Evaluation Options, InitializationCellEvaluation -> True      the cell won't run on opening the notebook. I haven't found a way to do this programmatically from the deploying notebook. Grouping of text cells (maybe all grouping) disappears when I've tested deployment. _**Questions_** So, can a notebook deployed to a Mathematica environment, different from the one on which one created it or similarly to a PlayerPro environment, encapsulate all such configurable FrontEnd options (including the grouping of cells)? To clarify, if I make an application and configure all these options on my development machine, how can I distribute the application such that it will carry ALL such settings to different machines, platforms, or even operating systems? An explanation for how the developers think about this might better help me/everyone understand how to do this. How do I go about doing this? Can one configure such FrontEnd options programmatically from an initialization cell? This seems unlikely given the chicken and egg problem. Can some lower level call do this? Can some accompanying stylesheet do this? Can some other configuration means do this?


title: Sync Animated Plots

text: Here is my Lorenz code:               sol = NDSolve[{x'[t] == -10 (x[t] - y[t]),        y'[t] == -x[t] z[t] + 24.74 x[t] - y[t],        z'[t] == x[t] y[t] - 8/3 z[t], x[0] == 3, y[0] == 5,        z[0] == 8}, {x[t], y[t], z[t]}, {t, 0, 100}, MaxSteps -> Infinity]      Here is `x[t]` vs `z[t]` and `x[t]` vs `t`:               p = ParametricPlot[{x[t], z[t]} /. sol, {t, 0, 30}];     pdata = p[[1, 1, 3, 2, 1]];     Manipulate[       ListLinePlot[pdata[[1 ;; m]], PlotRange -> {{-20, 20}, {0, 45}}], {m,       1, Length[pdata], 1}]          p2 = Plot[x[t] /. sol, {t, 0, 30}];     p2data = p2[[1, 1, 3, 2, 1]];     Manipulate[       ListLinePlot[p2data[[1 ;; m]],        PlotRange -> {{0, 30}, {-18, 18}}], {m, 1, Length[pdata], 1}]      Is it possible run `p` and `p2` simultaneously in sync?


title: Why does array packing in Table behave like this?

text: Consider the following example, which generate two identical arrays. Why sometimes the array is packed and sometimes it doesn't? And why they perform differently? Here the arrays are packed:               ht = 0.002; Ti = 0.4;     a1 = Table[Sin[x], {x, 0.2, 50., 0.02}]; // AbsoluteTiming     a2 = Table[Sin[x], {x, 0.5 Ti, 125 Ti, 0.05 Ti}]; // AbsoluteTiming     Developer`PackedArrayQ[a1]     Developer`PackedArrayQ[a2]     a1 == a2          (*     {0.010927, Null}     {0.335707, Null}     True     True     True     *)      Here one array is packed and the other is not:               a1 = Table[Sin[x], {x, 0.2, 50., 0.2}, {t, 0.002, 25., 0.002}]; // AbsoluteTiming     a2 = Table[Sin[x], {x, 0.5 Ti, 125 Ti, 0.5 Ti}, {t, ht, 12500 ht, ht}]; // AbsoluteTiming     Developer`PackedArrayQ[a1]     Developer`PackedArrayQ[a2]     a1 == a2          (*     {0.371184, Null}     {1.610365, Null}     True     False     True     *)      Since they have huge difference in performance, does that mean we should avoid using variables , instead we should use numbers in the code? Or add `Evaluate` everywhere we have variables?


title: FromQuaternion and QuaternionQ not working symbolically?

text: How can I get _Mathematica_ to work with quaternions symbolically? I want to do some quaternion math without defining the actual coefficients, and then extract the coefficients from the resulting quaternion. For some reason, however, `FromQuaternion` only seems to work when values rather than symbols are the coefficients. The following simple examples illustrate the problem. If I run the following:               QuaternionQ[Quaternion[1, 2, 3, 4]]     FromQuaternion[Quaternion[1, 2, 3, 4]]      The output is as expected: > True   >  3J + 4K + (1 + 2I) However, if I run the following (with A0-A3 undefined):               QuaternionQ[Quaternion[A0, A1, A2, A3]]     FromQuaternion[Quaternion[A0, A1, A2, A3]]      I get > False   >  FromQuaternion(Quaternion(A0, A1, A2, A3)) I was expecting               True     A0 + A1 I + A2 J + A3 K      However, Mathematica seems to be perfectly happy to perform functions like:               Quaternion[A0, A1, A2, A3] ** Quaternion[B0, B1, B2, B3]      With the following result > Quaternion[A0 B0 - A1 B1 - A2 B2 - A3 B3,   >  A0 B1 + A1 B0 + A2 B3 - A3 B2,   >  A0 B2 - A1 B3 + A2 B0 + A3 B1,   >  A0 B3 + A1 B2 - A2 B1 + A3 B0] but there seems to be no way to extract the components. Finally, is there a function for just extracting one of the components. For instance, say `Q = Quaternion[a, b, c ,d]`. I would like a function like `I[q]` which returns `b`, `J[q]` which returns `c`, etc.


title: How do I edit the background of Axis labels in my plot?

text: I'm using the standard report stylesheet in _Mathematica_ and when I output a plot, I've set it up so that I get a white background, however the axis labels still have a gray background. How do I change it to white? Here is a small example (you have to change your stylesheet to _StandardReport_ ):               Plot[Sqrt[x], {x, 0, 10},      PlotStyle -> {Thickness[0.025], Red},      AxesLabel -> {"Prob[Drug,X]", "Prob[Drug,XgivenPos]"},      PlotRange -> All, AspectRatio -> 1/2, Background -> White     ]      ![enter image description here](http://i.stack.imgur.com/APx07.png)


title: Function optimization errors

text: I have the following _Mathematica_ code ( _Mathematica_ version 9):               DH[x_] := (0.399582 Exp[-0.501606 (-3.57699 + Log[x])^2])/x        F[n1_, n2_] := Integrate[DH[x], {x, n1, n2}];                 G[n_] := Integrate[DH[x], {x, 0, n - 1}];           Cp[n1_, n2_] := Piecewise[{{F[n1, n2]*Log2[n1], n1 < n2},                                {0, n1 >= n2}}];            Et[n1_, n2_] := Piecewise[{{-F[n1, n2]*Log2[F[n1, n2]], n1 < n2 },                                 {0, n1 >= n2}}];       H[n1_, n2_] := Piecewise[{{Cp[n1, n2] + Cp[n2, 233]- Et[n1, n2]-Et[n2, 233]-G[n1], n1 < n2},                                {0, n1 >= n2}}];      I want to maximize value of `H[n1,n2]` and I use the `Maximize` function:               Maximize[{H[n1, n2],2<=n1<=231 && 3<=n2<=232 && n1 < n2}, {n1, n2}, Reals]      After I run the program, I obtained the solution: {2.64505, {n1 -> 11.6199, n2 -> 232.}} and many error messages. How obtain the maximum?


title: plot an exponential statistical function

text: I have this exponential function, where j is unknown. How can I plot the variance function for $k= 0.1, \; 1, \;10$ $$f_{j,k}(y)=\frac{\sqrt{j}}{\sqrt{2 \pi}}e^{\sqrt{jk}}y^{-\frac{1}{2}} \text{exp}\left( -\frac{1}{2} (j y + \frac{k}{y}) \right) \quad \quad y>0$$


title: Conditional clustering of elements

text: I have a long list like:               list={{"2014 03 12 08 59 34", 0.3849}, {"2014 03 12 08 59 36", 0.38492},            {"2014 03 12 08 59 38", 0.38495}, {"2014 03 12 09 16 20", 1.38522},            {"2014 03 12 09 16 22", 1.38523}, {"2014 03 12 09 16 24", 1.38524},           {"2014 03 12 09 16 26", 1.38524}, {"2014 03 12 09 16 28", 1.38524},           {"2014 03 12 09 16 30", 1.38525}, {"2014 03 12 09 16 32", 1.38525},            {"2014 03 12 09 16 34", 1.38525}, {"2014 03 12 10 10 01", 1.38529},            {"2014 03 12 10 10 03", 1.38528}, {"2014 03 12 10 10 05", 1.38531},           {"2014 03 12 10 10 07", 1.38532}, {"2014 03 12 10 10 09", 1.38534},           {"2014 03 12 10 10 11", 1.38537}}      The first column is dates and the second some values. The list is sorted by date. I want to gather the elements in a way that every two consecutive elements have time difference less than _4 seconds_. The solution should be like:               {{{"2014 03 12 08 59 34", 0.3849}, {"2014 03 12 08 59 36", 0.38492},        {"2014 03 12 08 59 38", 0.38495}}, {{"2014 03 12 09 16 20", 1.38522},        {"2014 03 12 09 16 22", 1.38523}, {"2014 03 12 09 16 24", 1.38524},       {"2014 03 12 09 16 26", 1.38524}, {"2014 03 12 09 16 28", 1.38524},       {"2014 03 12 09 16 30", 1.38525}, {"2014 03 12 09 16 32", 1.38525},        {"2014 03 12 09 16 34", 1.38525}}, {{"2014 03 12 10 10 01", 1.38529},        {"2014 03 12 10 10 03", 1.38528}, {"2014 03 12 10 10 05", 1.38531},       {"2014 03 12 10 10 07", 1.38532}, {"2014 03 12 10 10 09", 1.38534},       {"2014 03 12 10 10 11", 1.38537}}}      What I have done is I defined               date@da_ :=  DateList[{da, {"Year", " ", "Month", " ", "Day", " ", "Hour", " ",                                  "Minute", " ", "Second"}}]      Then               ReplaceList[list, {___, {a_, b_}, ___, {c_,     d_}, ___} :> {{a, b}, {c, d}} /;                 Abs@DateDifference[date@a, date@c, "Second"][[1]] < 4]      However this does not match the preferred output. So how may I cluster my data?


title: MapThread over a nested list

text: This may be a simple question. Please close it if it is already answered. I have a nested list               kr = {{35, 32, 27, 20}, {36, 33, 28, 21}, {37, 34, 29, 22}}       I want to use a function `flo[x_,y_,z_]` on each of the lists after modifying it. So the Mapthread on a given list `k0` (eg. {35, 32, 27, 20}) will look like this               MapThread[flo[L, ##] &, {Most@k0, Rest@k0}];      I want the output to look like this.               qfr = {{flo[L,35,32], flo[L,32,27],flo[L,27,20]},{flo[L,36,33],                 flo[L,33,28],flo[L,28,21]},{flo[L,37,34], flo[L,34,29],flo[L,29,22]}}      I tried to do the following without much luck. what am I missing?               MapThread[flo[L, ##] &, {Most@#, Rest@#}] & kr


title: Tough Inverse Fourier Integral: why does the sign matter?

text: I'm computing the Inverse Fourier Integral of                            ((a^2 + omega ^2) c^2)         /((b^2 + omega^2) ((r^2 + omega^2 - omegaInt^2)^2 + (2 omegaInt r)^2))      where all parameters are positive real numbers. Mathematica does a great job of solving it in around 10 seconds. However, if one makes the substitution                   omegaInt=I*omegaInt      So that the new expression is                           ((a^2 + omega ^2) c^2)         /((b^2 + omega^2) ((r^2 + omega^2 + omegaInt^2)^2 - (2 omegaInt r)^2))      (the difference being the sign in front of the two terms containing omegaInt) the integral is no longer solvable, at least in any reasonable amount of time. I think it is because an additional pole appears, but even then, the over all 1/omega^2 scaling makes me think it should still be integrable. Any ideas anyone? Am going to have to do some contour integral on paper? ugh. please no. Any comments are appreciated. kind regards. ps. this expression is the power spectral density of a damped, noisy-driven oscillator (fed through another highpass filter) and I'm after the system's autocorrelation function.


title: Apply a Function Pairwise

text: I'm new to Mathematica I'd like to apply `Mean` pairwise to a list to achieve the following.               badSource = {{0, 0}, {1, 1}, {2, 0}, {3, 1}, {4, 0}};     badInterpolation = {{.5, .5}, {1.5, .5}, {2.5, .5}, {3.5, .5}};     ListLinePlot[{badSource, badInterpolation}, Mesh -> All]      ![Pairwise Mean](http://i.stack.imgur.com/lS1xN.png) **How can this be done in general? Do I need pure functions?**


title: Plot sublists as different colors

text: I have one big list with many sublists inside. All sublists consist of three numbers. For example:               {{83, 85, 82}, {65, 49, 46}, {65, 76, 45}, {70, 65, 84}, {73, 72, 65}, {40, 84, 72}, {69, 79, 80}, {69, 78, 73}, {78, 71, 41}, {10, 10, 49}}       This is part of a list and I want that each sublist is one point on graphic. For example RGB(83,85,82) is color of first pixel, then 65,49,46 is color of the next pixel and so on. Is there any way to plot that list in such way that one sublist represents one color in RGB system and somehow to specify the width of a plot. Thanks.


title: Track object movement

text: Referring to this link I happen to realize that actually the trace being projected is dependent on an equation and not on disk or circle. Though I was presuming that it is getting traced because of the movement of circle/disk. So, in mathematica is it possible that the object can be traced automatically, say the same output of cycloid program without using parametric equations for trace of point on circle.


title: Some _atomic elements' TreeForm looks confusing with Level in appearance

text: In[1]:= Level[1/2,{-1}]     Out[1]= {1/2}          TreeForm[1/2]      ![enter image description here](http://i.stack.imgur.com/loKtu.png) * * *               In[2]:= Level[1/2,{-1}]     Out[2]= {1/2}          In[3]:= Level[Unevaluated[1/2],{-1}]     Out[3]= {1,2,-1}          In[4]:= 1/2//FullForm     Out[5]//FullForm= Rational[1,2]      Rational[1,2] in TreeForm,but Times[1,Power[2,-1]] when Level.               In[5]:= Level[Unevaluated[1/2],{-1},Heads->True]     Out[5]= {Times,1,Power,2,-1}      How to comprehend this? How to obtain `TreeForm[Hold@Unevaluated[1/2]]` without Hold and Uevaluated in whole TreeForm's graph or `TreeForm@{{{Hold[1/2],b}},b,c}` with out hold? ![enter image description here](http://i.stack.imgur.com/hovvA.png) And How to get {1,2} from Level[1/2, {-1}]?


title: Getting arrays of values out of Manipulate

text: More about getting variables out of `Manipulate`: If I execute the following:               Manipulate[{xb1, xb2, xb3},        {xb1, 0, 1},        {xb2, 0, 1},        {xb3, 0, 1},        LocalizeVariables -> False]      I get 3 sliders and the list `{0,0,0}`. If I ask for the value of `xb1`, I get `0`. If I execute the similar form:               Manipulate[{xb[1], xb[2], xb[3]},        {xb[1], 0, 1},        {xb[2], 0,  1},        {xb[3], 0, 1},        LocalizeVariables -> False]      I get $3$ sliders and the list `{0,0,0}`. HOWEVER, if I ask for the value of `xb[1]`, I just get `xb[1]`. Why? `LocalizeVariables->False` seems not to work in this case. More importantly, how can I get a list of the values of the `Manipulate` variables as `Global` variables? The actual case I'm using has multiple lists of `Locator` variables, which seems to be even more difficult to get at than, say, multiple lists of `Slider` variables.               inputgraphs[inputrangex_List,                  inputrangey_List,                  name_String, indexnumber_] :=        DynamicModule[{         pts = {{0, 0}, {inputrangex[[2]]/4, 0}, {inputrangex[[2]]/2, 0},                 {3 inputrangex[[2]]/4, 0}, {inputrangex[[2]], 0}},          locatoricon},         locatoricon =            Graphics[{Red, PointSize[Medium], Point[{0, 0}]}, ImageSize -> 18];         Column[{           LocatorPane[Dynamic[pts],              Dynamic[Plot[               InterpolatingPolynomial[pts, x], {x, 0, inputrangex[[2]]},                  PlotRange -> {inputrangex, inputrangey}, Frame -> True,                  ImageSize -> Medium, Axes -> True, FrameLabel -> name]],              Appearance -> locatoricon, LocatorAutoCreate -> True],           Button["Save", With[{p = pts}, points = p]]}]]      I would like to have used the argument `indexnumber` to be an index for each use of manipulate variables (one for each graph), but that doesn't work, probably because for the same reason the example using indexed variables in `Manipulate` given above doesn't work.


title: Trouble getting FindInstance to return multiple results for certain constraints

text: I'm having a hard time getting `FindInstance` to return multiple results. Consider this simple example:               FindInstance[a > 0 && b >= 0 && c >= a + b && a >= c/3 , {a, b, c}, Integers, 2]      Mathematica (8.0.1 on Mac) quickly returns               {{a -> 244, b -> 206, c -> 618}, {a -> 306, b -> 299, c -> 860}}      Good. But if I change `c/3` to `c/4`, which only relaxes the constraints, Mathematica goes busy for 18 sec. For a little more complicated case (9 variables with 15 similar constraints) it never returns (I left it running for several days). Asking for one solution for the `c/4` case (and for the 9 variable case) gets an immediate result:               FindInstance[a > 0 && b >= 0 && c >= a + b && a >= c/4, { a, b, c}, Integers, 1]      returns               {{a -> 1, b -> 0, c -> 3}}      What accounts for the difference? _One more edit:_ for completeness, here's the 9 variable case:               FindInstance[{a0 >= 0, a1 >= 0, a2 >= 0, a3 >= 0, a4 >= 0, a5 >= 0,        a6 >= 0, a7 >= 0,       nn == a0 + a2 + a4 + a6 + a1 + a3 + a5 + a7,       (a1 + a3 + a5 + a7) / nn >= 0.5735, (a1 + a3 + a5 + a7) /nn  <= 0.5745,       (a2 + a3 + a6 + a7) / nn >= 0.4715, (a2 + a3 + a6 + a7) / nn <= 0.4725,       (a4 + a5 + a6 + a7) / nn >= 0.5225, (a4 + a5 + a6 + a7) / nn <=  0.5235,       (a3 + a7)           / nn >= 0.2325, (a3 + a7)           / nn <= 0.2335,       (a6 + a7)           / nn >= 0.2775, (a6 + a7)           / nn <= 0.2785,       (a5 + a7)           / nn >= 0.2655, (a5 + a7)           / nn <= 0.2665,       ( a7)               / nn >= 0.1195, (a7)                / nn <= 0.1205       },      {a0 , a1, a2, a3, a4, a5 , a6, a7, nn}, Integers, 2]      I tried a few variants, such as replacing the decimals with fractions and expanding `nn`, to no avail.


title: Why does one of my Manipulate integer variables get turned into a real?

text: I'm developing code for manipulating graphs. Spot the difference in the 2 Manipulates below:               Manipulate[      {n, m},      {{n, 10, "no of vertices"}, 1, 18, 1},      {{m, n, "number of edges"}, n, n (n - 1)/2 , 1}      (* using the +/-/slider for the number of edges does not generate Reals          but only Integers as expected *)]      ![first image of Manipulate](http://i.stack.imgur.com/xJo1C.jpg) this first example works as expected but               Manipulate[      {n, m},      {{n, 10, "no of vertices"}, 1, 18, 1},      {{m, n, "number of edges"}, n - 1, n (n - 1) /2, 1}      (* using the +/-/slider for the number of edges now generates Reals          not Integers: what gives? *)]      ![second image of Manipulate](http://i.stack.imgur.com/7au2q.jpg) turns my nice integers into reals as soon as I change the number of edges. I can turn this back into an integer when that's what I need, but I'd prefer not to. Naturally I have a more complex task to complete but these examples are simple enough to illustrate the issue. Version: Mathematica 9.0.1.0 Platform: Mac


title: Modified Cell Different Display

text: Is there a way to show maybe a slightly different color, or change the cell bracketing color of a Mathematica cell when it has been modified? ![enter image description here](http://i.stack.imgur.com/WuZtS.png) Ideally it would be nice to follow the standard of using asterisks but cells don't really have names. Just to clarify a cell is modified when it has been edited but hasn't been run. **Code In Progress:** This code basically is supposed to check to see if `CellChangeTime` changes on a set interval. It doesn't work currently but it is getting there.


title: How to produce the ILU0 or ILUT as stand-alone procedures on sparse matrices?

text: Mathematica uses the ILU0 procedures automatically to precondition large sparse linear systems; e.g.               LinearSolve[mat, rhs,         Method -> {Krylov, Preconditioner -> ILU0}]; // Timing      I wish to have the incomplete factorization of the large sparse matrix A in a standalone procedure. I would be grateful if someone could give some tips or written code to provide the ILU0 or ILUT approximate inverses as standalone procedures.


title: How to ReplaceAll independent of depth?

text: I have a big list which in principle can be described as this more compact list :               list1 = {{e, {{a, 0.1}, {b, 0.3}, {c, 0.5}, {d, 0.7}},          f, {{a, 0.2}, {b, 0.4}, {c, 0.6}, {d, 0.8}}, g, h, i}};      I am interested in rewriting to the following :               {{e, {"abcd", 0.1, 0.3, 0.5, 0.7}, f, {"abcd", 0.2, 0.4, 0.6, 0.8}, g,        h, i}}      which works well when applying this simple rule:               list1 /. {{a, x1_}, {b, x2_}, {c, x3_}, {d, x4_}} -> {"abcd", x1, x2,         x3, x4}      However when the affected sublists `{a,x1}` to `{d,x4}` are not on the same depth, I have difficulties constructing a rule that works. So for instance:               list2 = {{e, {a, 0.1}, {b, 0.3}, {c, 0.5}, {d, 0.7},         f, {{a, 0.2}, {b, 0.4}, {c, 0.6}, {d, 0.8}}, g, h, i}}      does not give the desired result. So my questions are: 1\. Is there a way to ReplaceAll independent of depth? 2\. Is there a more elegant method that does the job?


title: Plot3D in Mathematica: how to plot in presence of parameters

text: I do thank you Vitaly and Celtschk. I should have disclosed my ultimate goal earlier so as to receive the best help.While the previous suggestions were very helpful, I think I realize I ill-posed the question earlier I am trying to find the values of A and B that will maximize function f on the domain `{x,0,100},{y,0,100}`. I have had trouble using Maximize or NMaximize, etc. So I am trying to find x and y in terms of A and B, which will maximize the function. this function f has two parameters A and B in it with constraints such that $ 0< A < 100 $ and $A < B \le 100$. My actual function is: Mathematica Input: * * * (B^3 - B^2 (x + y) + x (A^2 - y^2 + A (-x + y)) + B (x^2 + x y + y^2 - A (x + y)))/(A - B)^2 * * * $$ (B^3 - B^2 (x + y) + x (A^2 - y^2 + A (-x + y)) + B (x^2 + x y + y^2 - A (x + y)))/(A - B)^2\bigl) $$


title: Appropriate application of plotstyle directives

text: I am attempting to style a `Plot` in which all of the lines are Thick and I have selected the colors manually:               solid[t_] := -292 - 0.41 t;     liquid[t_] := -286 - 0.07 t;     gas[t_] := -242 - .189 t;     Plot[{gas[t], liquid[t], solid[t]}, {t, 0, 400},       PlotStyle -> ({Thick, #} & /@ {Black, Blue, Red})]      The above code gives me the desired result, but I can't believe that the use of a pure mapped pure function is the best way to get these results. Is there a less obfuscatious method to assigning some `PlotStyle` directives to all functions and then a set of directives that will apply to each function individually?


title: PlotMarkers problem in ErrorListPlot, Mathematica 10

text: I recently upgraded to Mathematica 10, very excited about the multiple undo function of course. However I very quickly noticed that if I specify a setting for `PlotMarkers` in the `ErrorListPlot` function, the error bars disappear. Even just setting `PlotMarkers->Automatic` makes the error bars disappear. This was not a problem in Mathematica 9, but appears to be a new 'feature'. Has anyone else noticed this since upgrading, and are there any possible fixes?