Combining BarChart and Grid - IPCC style

I would like to combine a plot with a table. Something like this famous plot/table from IPCC: ![IPCC plot](http://i.stack.imgur.com/mbOqy.png) So after reading Combining graphics & lists / tables I tried an approach using `Grid`. Pretty close but it feels quite hacked, especially the frame-ticks. The IPCC plot/table looks much nicer. Maybe they just used a graphics program and made it look nice. I wonder if it can be done nicely in Mathematica?               t1 = Table[BarChart[{{0, -0.2}, {0, 0.3}, {0, -0.1}}[[i]],     Frame -> False, PlotRange -> {{-0.45, 0.45}, {1.5, 2.5}},      BarOrigin -> Left, FrameTicks -> {Automatic, None},      GridLines -> {{0, {0.2, Dashed}, {-0.2, Dashed}}, None}], {i,      3}];     f1 = BarChart[{0, 1},       Frame -> {{False, False}, {True, False}},        PlotRange -> {{-0.45, 0.45}, {0, 0.1}}, Axes -> False,        BarOrigin -> Left, FrameTicks -> {Automatic, None},        AspectRatio -> 0.05]     reference = {"Sepp 2013", "Hans 2000", "Franz 1999"};     t2 = Thread@{{"c1", "c2", "c2"}, t1, reference};     PrependTo[t2, {"", "Plot", "Ref"}];     AppendTo[t2, {"", f1, ""}];     Style[Grid[t2, Frame -> All,        Background -> {None, {None, LightYellow, None, LightYellow, None}},        Spacings -> {Automatic, 0}], FontFamily -> "Helvetica"]      ![test2](http://i.stack.imgur.com/m4EP3.png)


Inconsistent display of TraditionalForm in version 9

After installing version 9, the default style sheet uses Arial font in text and formula cells. So far, so bad. At least one would hope this is done consistently. But now I see this: ![traditionalform](http://i.stack.imgur.com/p6cBy.png) You can see that the default font for `TraditionalForm` in output cells is Times, which will make such output look disjoint from the equations in inline or displayed maths. The $1$ on the output line has serifs, while the **1** on the third line (in the text cell) are sans-serif. This is what I would call visually disjoint, or incongruous. What would be the best way to change the default font for the `TraditionalForm` output so that it always remains consistent with Arial (i.e., is displayed as sans-serif) when the default stylesheet is chosen? I am aware that I could also try to change the default stylesheet back to version-8 style as discussed in "How to use version 8 default.nb style sheet in place of version 9 default.nb" \- but here I'm asking what to do if I don't want to go back to Times font, only trying to get a more uniform sans-serif appearance. **Edit** Sorry to say that the inconsistencies extend far beyond the above. I only realized this morning that many important math symbols **remain** in the old form that was based on Times glyphs, even when the rest of the expression is converted to Arial. Here is a screenshot where I typed the math symbol paired with a corresponding normal Arial character - first some double- struck glyphs, then $\hbar$, then some Greek. The square root also looks unchanged from Times font, which may be OK but isn't how I recall sans-serif square roots looking. One important problem in the juxtaposition between pairs of special and normal characters is not just the presence versus absence of serifs, but also the general mismatch in the heights. ![fonts](http://i.stack.imgur.com/1rDH3.png) The last comparison between $l$ and $I$ is of course just a reminder of how bad the Arial font is on general grounds, I'm not asking how to fix that... As a result, I think the inconsistencies I'm worried about can't be removed completely until a whole new set of glyphs is added to the Arial font. I'll have to give it some more time before perhaps accepting one of the answers, although I'm not at all happy and currently waiting for a miracle. **Edit 2** Two alternative titles for this question:   * How to un-xkcd `TraditionalForm` equations in version 9?   * Will Frankenformulas take over the world?


_**How to plot periodic function's graphic?_** For example, `f(t) = t` when `-5<t<5 && f(t+10) = f(t)`               f[t] := If[-5 <= t <= 5, t, f[t + 10] = f[t]];     Plot[f[t], {t, -20, 20}]      ![Output](http://i.stack.imgur.com/ylq0s.png)


Compute Triple Integral on spherical coords

I need to compute: $\int \int \int z dxdydz$ over the domain: $\\{x^2+y^2+z^2\leqslant 16,z\geqslant 0\\}$ Im trying to use spherical coords as: $$\int_{0}^{2\pi} \int_{0}^{\frac{\pi}{2}} \int_{0}^{4} r \cos(\theta )r^2\sin(\varphi ) \;dr\,d\theta \,d\varphi $$ I try this on Mathematica:               Integrate[Integrate[Integrate[r *Cos[theta]*r^2*Sin[phi], {r, 0, 4}], {theta, 0, Pi/2}], {phi, 0, 2 Pi}]      But re result is 0. What is wrong here?


Illustrating half life

I'm teaching some lessons on negative exponents and one application listed was half life since the rate of decay can be written as 2^-1 every ___ _ years. I found this nice animation on the net. http://www.absorblearning.com/media/attachment.action?quick=185&att=3167 I certainly don't need anything near that fancy, but wondered how I could model a similar kind of graphic using mathematica, where I could use a slider to represent years, and show a grid that responded by randomly choosing dots to "turn" off as time moved along. Any starting hints or answers are welcomed. Tom


Plot slope field in Mathematica for a difficult differential equation

I am trying to plot slope field for $\ddot{a}(t)$ for this differential equation but I don't know how to $\frac{d}{dt}\ddot{a}(t)=2\frac{\dot{a}(t)}{a(t)}\ddot{a}(t)$ I want to show that already accelerating solutions (with $\ddot{a}$ small and positive) are driven to accelerate even more, and already decelerating ones (with $\ddot{a}$ small and negative) are driven to further deceleration. So essentially I want to find out what $\dddot{a}(t)$ would look like with respect to time.


What is the correct way to use NIntegrate inside the FindMinimum function?

I'm having minor issues with the `FindMinimum` function when using `NIntegrate` inside. The functions work perfectly well but I get warning messages and I was wondering if maybe I could be enlightened on the correct usage of these two functions together. For the sake of illustration I provide the full set of functions I used on a simple example.               phi[t_, k_, h_] := (1/h)^3*        Piecewise[{{(h (1 - k) + t)^2 (h (1 + 2 k) - 2 t), (k - 1) h <= t <=             k*h}, {(h (1 + k) - t)^2 (h (1 - 2 k) + 2 t),            k*h <= t <= (k + 1) h}}];     psi[t_, k_, h_] := (1/h)^3*        Piecewise[{{(t - k*h) (h + t - k*h)^2, (k - 1) h <= t <=             k*h}, {(t - k*h) (h - t + k*h)^2, k *h <= t <= (k + 1)*h}}] ;     phipp[t_, k_, h_] := (1/h)^3*        Piecewise[{{2 (h (1 + 2 k) - 2 t) - 8 (h (1 - k) + t), (k - 1) h <=             t <= k*h}, {-8 (h (1 + k) - t) + 2 (h (1 - 2 k) + 2 t),            k*h <= t <= (k + 1) h}}];     psipp[t_, k_, h_] := (1/h)^3*        Piecewise[{{2 (-h k + t) + 4 (h - h k + t), (k - 1) h <= t <=             k*h}, {-4 (h + h k - t) + 2 (-h k + t),            k*h <= t <= (k + 1) h}}];     alpha[t_, k_, h_] := phi[t, k, h] + phipp[t, k, h];     beta[t_, k_, h_] := psi[t, k, h] + psipp[t, k, h];     T = Pi;     n = 2;     h = T/n;     FindMinimum[      NIntegrate[(h*beta[t, 0, h] - h*beta[t, n, h] +           a.Table[alpha[t, i, h], {i, 1, n - 1}] +           b.Table[h*beta[t, i, h], {i, 1, n - 1}])^2, {t, 0,         T}], {{a, {0.76}}, {b, {0.4}}}, Method -> "ConjugateGradient"]      I get the following warning message :               NIntegrate::inumr: "The integrand (a.{(8 Piecewise[{<<2>>},0])/\[Pi]^3+(8 Piecewise[{<<2>>},0])/\[Pi]^3}+b.{1/2\\[Pi]\(8\Power[<<2>>]\Piecewise[<<2>>]+8\Power[<<2>>]\Piecewise[<<2>>])}-1/2\\[Pi]\((8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3+(8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3)+1/2\\[Pi]\((8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3+(8 Piecewise[{{<<2>>},{<<2>>}},0])/\[Pi]^3))^2 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,3.14159}}"      I ask about this because `FindMinimum` takes unexpectedly long time to converge to the solution (which is a right one). But I thought that maybe using the functions correctly will accelerate the process.


Alternative to Except in StringExpression when using StringMatchQ

According to this answer and the documentation for StringExpression, `Except` can only be used in `StringExpression` for classes of characters or positions in strings. The referenced answer suggests using StringFreeQ in place of StringMatchQ. However, sometimes, this is not possible, if the pattern is one of many being passed to a function, like in the following situation               patt1 = WordCharacter..;     patt2 = "pattern";     patt3 = (*Some complicated StringExpression*);     ... (*more patterns*)     pattn = (*Everything except patt3*)          f[patt_, str_] := If[StringMatchQ[str, patt], (*stuff*), (*other stuff*)]      One possibility is to use               pattn = x: __ /; !StringMatchQ[x, patt3]      This seems repetitive and it could get verbose if repeated, but isn't too bad. However, my intuition is that there should be a better way. Is there?


Add to the last digit a number

I have data from a Multimeter that has a precision of 0.6%rdg+4dgt. So i want to take the last digit of, say, `12.007` and add 4 to the last digit like `12.011`. I'm doing `RealDigits[12.007,10,5][[1,-1]]`add 4 and then somehow with`FromDigits` get the result...it seems trivial but i don't see how.


Placing many arrowheads on curves

I can't find anything anywhere on the web to help me with this. My plot:               Plot[{(u (u + d) (1 - u))/u, u, 0}, {u, 0, 1},       PlotStyle -> {Orange, Green, Green}, PlotRange -> {-0.1, 1},       Frame -> True, Axes -> None, GridLines -> {{0}, {}},       GridLinesStyle -> Directive[Green]]      I would like to be able to put vertical arrows on the orange lines and horizontal arrows horizontal arrows on the green curve. If it helps, this is a plot of the nullclines of a system of ODEs and i need to draw the direction of the arrows of the vector field on each nullclines.


Multinomial logistic regression

Has anyone done multinomial logistic regression in _Mathematica_? The binomial case is essentially done on the `LogitModelFit` documentation page and works fine. I am following this formulation to obtain the outcome probabilities for k classes with k-1 calls to `LogitModelFit`. I am getting normalized probabilities out, but they depend on how the classes are encoded for each independent regression. I can post what I have on request but it's a lot of code for something that isn't working. Either multiple-binary or true multinomial would be fine for my purposes, but bonus for both implementations.


how to generate functions with changing array size?

I want to write a function in Mathematica which has two inputs 'n' and 'd', and the output should be (in Latex notation) $$F(n,d) = \sum_{i[1],...,i[n] =0; i[1]+...+i[n]\leq d}^{d} C[i[1],...,i[n]] f[i[1],x[1]] f[i[2],x[2]] ...f[i[n],x[n]]$$ n and d are integers. The problem is that I can hard code `F` for a given `n` and `d` alright. But when I want to write a generic function which take in any `n` and `d` and spits out the required right hand side, it becomes difficult as I have to keep changing the array size along the way depending on the values of `n` and `d`. Probably, there is a simpler way to do this in Mathematica?


Linearised Einstein equations

I need to compute the linearised Einstein Equations around a fixed metric $g_{μν}=\text{Minkowski metric} + h_{μν}$, which is not the flat metric. Does anyone know a _Mathematica_ package or a review paper that can help me?


How should a beginner figure out the context to use an expert answer provided on this forum?

J.M.'s answer to Extruding along a path related to custom cross-sections appears to answer a question I have been puzzling over for some time. I am interested in producing a tube with the stadium or stadion cross-section of oblong ductwork. I look at the code and am lost as to how to use it. Any suggestions?


Compile not correctly initializing a variable defined inside Module

In the following example, inside the `minimumX`'s `Module`, `x` is initialized to 1, but the results say otherwise:               solutionQ = Function[{x, d}, IntegerQ[Sqrt[(x^2 - 1)/d]] && x != 1];     minimumX =        Compile[{{d, _Integer}},         Module[{x = 1}, While[! solutionQ[x, d], x++]; x]];          minimumX[2]     minimumX[3]     minimumX[2]          (*     3          7          17     *)      If I define `minimumX` as:               minimumX =        Function[{d}, Module[{x = 1}, While[! solutionQ[x, d], x++]; x]];      or               minimumX =        Compile[{{d, _Integer}},         Module[{x = 1}, x = 1; While[! solutionQ[x, d], x++]; x]];      It works as I was expecting:               (*     3          2          3     *)      Is this expected behavior, or should I report a bug? (Mathematica 9.0.1)


Fast way of finding position of Interval containing an Integer

I have a large list (about 2.2 million) of pairs of integers. Each pair defines an `Interval[{}]`. Given some integer `x`, I need to find the position of the interval in my list that bounds `x` (or alternatively, return the element of the list). None of the intervals overlap, thus `x` can belong to only one of the intervals. You can assume the large list is sorted. The challenge is that I need to run this "look-up" millions of times, so even a small gain in speed would be very beneficial I tried a few obvious brute force approaches. First I created a list of intervals from the list of integer pairs, and then tried               Pick[myBigList,           Map[IntervalMemberQ[#, x] &, myBigList]]; //AbsoluteTiming      > >     4.196432 >   and then               Select[myBigList, IntervalMemberQ[#,x]& ]; // AbsoluteTiming      > >     8.814063 >   Assuming the list is ordered, then               LengthWhile[mySortedBigList, #[[1]] <= x &]      > >     3.556826 >   All of these methods seem too slow. Any suggestions would be much appreciated. (For those of you interested, here's the background on this problem. I need a fast way of translating an IP address to an approximate set of latitude- longitude coordinates. Each pair of integers in the list above corresponds to a range of IP addresses that have been converted from the zz.zz.zz.zz format to an integer. The interval defined by each pair of integers is associated with a set of lat-long coordinates. Again, this needs to be run millions or tens of millions of time on a regular basis. When this look-up was done on a 64-bit Windows desktop system running standard SQL, it took about 8 hours to geocode ten million IPs) Thanks, Mark


Time Varying Payoffs?

I'm trying to write some code that will return the final value of an annuity whose monthly payouts may or may not be constant each month. Right now I have working code for constant payments, but I'm not sure how to do changing payments. Would I use `Range`? Code:               vals = Function[{P, r, n}, P ((1 + r)^n)];     Total[Table[vals[200, .01, n], {n, 60}]]


Several questions on how to make a ListLogPlot look pretty

1- I have the following curve which is the result of evaluation of some calculation. the curve should have value at zero. but in the plotting I can see there is a gap between the y-axis and the starting of the curve. how I can make the curve to reach y-axis. I already have a value of BER when x is zero, why it is not appear in the plot? 2- How I can make the value of y-axis to be like this: 10^-5, 10^-4, 10^-3, 10^-2, ... ? I mean not be like this 0.001, 0.01, ... 3- how to make the label axis position be in the centre of the axis not at the end? 4- how to show the grid in the plot background? Thanks ![Ploting BER vs SNR](http://i.stack.imgur.com/p0MFJ.jpg) **Edit:** here is a sample values of abep for the (0 to 40) SNR:               {0.263671, 0.223935, 0.186064, 0.151073, 0.119779, 0.092718, 0.0700926, 0.0517928,      0.0374553, 0.0265532, 0.0184883, 0.0126685, 0.00856004, 0.0057148, 0.00377648,       0.00247428, 0.00160959, 0.00104095, 0.000669973, 0.000429521, 0.000274496,       0.000174975, 0.000111307, 0.0000706891, 0.0000448341, 0.0000284057, 0.0000179819,       0.0000113756, 7.19252*10^-6, 4.5457*10^-6, 2.87193*10^-6, 1.81396*10^-6,       1.14549*10^-6, 7.23233*10^-7, 4.56569*10^-7, 2.88196*10^-7, 1.819*10^-7,       1.14801*10^-7, 7.24499*10^-8, 4.57204*10^-8, 2.88515*10^-8}


Simulation Sample Paths for Stochastic Approximation Algorithm

Let $X_t$ be IID random variables in $[0,1]$ and CDF $F(\cdot)$. Suppose there exists a variable $Y_t$ given by: $Y_1 = X_1$ and $Y_t = \phi(X_t, \overline{Y}_{t-1}), \forall t >1$, where $\overline{Y}_{t} = \frac{1}{t} \sum_{i=1}^{t} Y_i$ and $\phi^{\alpha} (x,y) = \left\\{ \begin{array}{l l} \alpha x & \quad \text{if $x < y$}\\\ x & \quad \text{if $x = y$}\\\ \alpha x + (1 -\alpha) & \quad \text{if $x > y$}\\\ \end{array} \right.$ I wish to run a simulation for 5 random walks (each with length 100) of $\overline{Y}_{t}$ where $X$ is drawn from a beta distribution with parameters (3,1) and $\alpha = 0.5$. Normally, we should observe a convergence to the mean of $X$, i.e. $\mathbb{E}[X]$. I have for $\phi^{\alpha} (x,y)$:               f[a_, {x_, y_}] := Piecewise[{{a x, x < y}, {x, x == y}, {1 - a + a x, x > y}}, 0]      My Beta distribution (with 100 iterations) can be expressed as:               RandomVariate[BetaDistribution[3, 1], 100]      I have difficulties to form the aggregation of data, and plot the evolution of $\overline{Y}_{t}$. Any help would be highly appreciated.               ListPlot[Table[<%simulated_data%>], PlotRange -> All, Joined -> True, Frame -> True]


What is the new command for AffineMap?

`AffineMap` was present in _Mathematica_ version 4. What is the equivalent command in the current version of _Mathematica_?


Generating a random sample of elements from a list that includes a subset of the list

Imagine I have a list: `tList = {item1,item2,item3,item4,item5,item6,...}`, and I'd like to take a random sample of `numItems` elements of the list: `RandomSample[tList,numItems]`. Is there a way to specify the random sample should contain some subset of the elements in `tList`, e.g. `{item65,item70,item2,...}`? The hope is then that all of the elements from the random sample are returned scrambled, including the order of the elements in the subset?


Bar chart labels disappear when PlotRange is used

I have used `Placed[Before]` to place labels on the labels before the bars, but when I specify a plot range, the labels disappear. I need a solution wherein I can use `PlotRange` and `Placed[Before]` without the labels disappearing.


Evaluating expressions stored in notebook from Java

The _Mathematica_ kernel can generally open a notebook and evaluate the functions present in the notebook using `UsingFrontEnd Command`. Example:               UsingFrontEnd[SelectionEvaluateCreateCell[nb];]      However, when I try from Java the following command, no action happens:               m1.evaluate("UsingFrontEnd[SelectionEvaluateCreateCell[nb];]");       Can anyone please explain how I can evaluate expressions in some notebook file through Java. Note: I have tried all options like `NotebookEvaluate`, `SelectionEvaluate`, etc. I have also tried different combinations of `SelectionMove`.


Combined Elliptic-Parabolic PDE in 1D

Here is an example of solving a system of parabolic and elliptic PDE: http://reference.wolfram.com/mathematica/tutorial/NDSolveDAE.html (see the subsection "Combined Elliptic-Parabolic PDE in 1D"). In this example the equation and the initial conditions don't depend on $x$. How can I change this solution for accounting dependence on $x$? Can this system be solved easier, just by using NDSolve? _Clarification:_ I have another problem described on the page PDE combined with ODE 1D, and in my problem the initial conditions depend on $x$.


Simplify Sin[x]/x to Sinc[x]

I have an expression in the form of $\tt \frac{Sin[x]}{x}$ that I would like to simplify to the form of `Sinc[x]`. I've tried the `Simplify`, `FullSimplify` and `TrigReduce`, but none of them work.               Simplify[Sin[x]/x]     FullSimplify[Sin[x]/x]     TrigReduce[Sin[x]/x]      all gives the result $\tt\frac{Sin[x]}{x}$. However               FullSimplify[Sin[x]/x == Sinc[x]]      gives `True`. I have two questions:   1. Is there a way to tell MMA that I prefer `Sinc[x]` than `Sin[x]/x`, so that it can simplify $\sin(x)/x$ to $\mathrm{sinc}(x)$?   2. How doees `TransformationFunctions` and `ComplexityFunction` work in `Simplify`? Could you give some examples and explanations of how to use them to control the form of the outcome expression? Can I use them to let _Mathematica_ apply my own defined simplify rules (for example in this case `Sin[x]/x -> Sinc[x]`)? I found their documents are difficult to understand for me. Thanks. * * * _**update**_ `FullSimplify[Sin[x]/x,ComplexityFunction->Composition[StringLength,ToString,InputForm]]` also doesn't work. However,               Composition[StringLength,ToString,InputForm][Sin[x]/x]      gives 8 which is larger than               Composition[StringLength,ToString,InputForm][Sinc[x]]      which gives 7.


MathLink c++ passing lists of real values simple example

So this may come down to me not being a very competent programmer but I am struggling with passing list from Mathematica via MathLink that aren't of integers. The final code I am hoping to get out of this will pass a list of values to a C++ function I have written and return a different list of values. I decided to learn slowly using the examples given in the Wolfram documentation center. I was able to write a simple function that received a list of integers...did some math on it...and returned a different list of integers. This worked great. If I tried to do this with a list of real values I kept getting a linker error. To simply things I removed the returning of a list of values and just decided to use the list as input and return a value. This resulted in the same linker error. I used the addtwo code from the MathLink examples supplied by Wolfram. The relevant portion of the code is:               #include "mathlink.h"     extern int sumlist(int *a, long alen);          int tot = 0;          int sumlist(int *a, long alen)     {                for(int i = 0;i<alen;i++)             {                 tot = a[i] + tot;                    }                return tot;      }      with a template file (*.tm)               :Begin:     :Function:       sumlist     :Pattern:        SumList[a_List]     :Arguments:      {a}     :ArgumentTypes:  {IntegerList}     :ReturnType:     Integer     :End:      This code works great and gives me my desired result. Now if instead I wish to pass a list of Real numbers as in the following.               #include "mathlink.h"     extern double sumlist(double *a, long alen);          double tot = 0.0;          double sumlist(double *a, long alen)     {                for(int i = 0;i<alen;i++)             {                 tot = a[i] + tot;                    }                return tot;      }      with a template file               :Begin:     :Function:       sumlist     :Pattern:        SumList[a_List]     :Arguments:      {a}     :ArgumentTypes:  {Real32List}     :ReturnType:     Real32     :End:      I am following the directions for the Command Line compiling for Microsoft visual studio from this page. I am using Microsoft visual studio 2013(which may be the problem as it technically isn't supported yet) Everything is fine until I run:               Link sumlist.obj sumlisttm.obj ml32i3m.lib /OUT:sumlist.exe      Which results in the follow error               sumlisttm.obj : error LNK2019: unresolved external symbol "float __cdecl     sumlist(float *,int)" (?sumlist@@YAMPAMH@Z) referenced in function "int __cdecl     _tr0(struct MLink *)"(?_tr0@@YAHPAUMLink@@@Z)     sumlist.exe : fatal error LNK1120: 1 unresolved externals      I have done some testing and determined that I get this error just by trying to pass the list of real values rather than integers regardless of what the function actually does. I have looked for examples of Mathematica/MathLink code and most of them only deal with lists of integers.


FrameStyle in Inset with Framed expression

I am creating some plots that use `FrameStyle->AbsoluteThickness@5` and `PlotStyle->AbsoluteThickness@0.5`. In my plots' `Epilog` option, I want to use some `Inset[Framed@...,FrameStyle->AbsoluteThickness@0.5]` expressions. Upon exporting the graphics to PDF, I noticed that the `FrameStyle` option does nothing. This lead me to the following question on this site: Formatting `Framed` \- Some `FrameStyle` graphics directives don't work So I tried the following, to get a feeling for what `BoxFrame` does:               Plot[Sin[x], {x, 0, 2 Pi},      PlotStyle -> AbsoluteThickness@0.5,      Frame -> True,      FrameStyle -> AbsoluteThickness@0.5,      ImageSize -> 180,      Epilog -> {Inset[         Framed["sin(x)", BoxFrame -> {{0.1, 0.5}, {5, 0}}],         {3/2 Pi, 0.5}]}]      The resulting PDF looks like this: ![enter image description here](http://i.stack.imgur.com/cZSzN.png) It seems like only integer numbers work in the `BoxFrame` option. But how can I make the frame thinner? Especially, how can I make it exactly 0.5 pt thick?


Importing data from Excel for DateListPlot

I am importing data from Excel and plotting it with `DateListPlot`. My code is               DateListPlot[{       Join @@ Import[""][[1 ;;, 3 ;;]][[All, All, 2 ;; 3]],        Join @@ Import[""][[1 ;;, 3 ;;]][[All, All, 4 ;; 5]]},        Joined -> True,        FrameTicks -> All]      But my problem is this works for just for the first sheet (year 2013) of the many in the same file. Sheet 2 is for Year 2012 and has the same format, and so forth. I want to get all the sheets for all the years; they are continuations of each other. Could you help me to figure out what code will do this?


How to enter arrows in Notation function?

It is not clear, what symbol is used in Notation function description for arrows? How to enter it in textual mode within Workbench? Here: http://reference.wolfram.com/mathematica/Notation/ref/Notation.html


Labeling a grid

I have               m = {{0, -1, -2, -3, -4}, {1, 0, -1, -2, -3}, {2, 1, 0, -1, -2}, {3,          2, 1, 0, -1}, {4, 3, 2, 1, 0}};      And a grid `Grid[m,Frame->All]` I would like to label the grid such that every column has a number above it and every row has a number to its side. This is what I've currently managed to do.               Labeled[Grid[m,Frame->All],{Y:{1,5},X:{1,5}},{Left,Top}]       How can I label the grid appropriately?


Write-protect documentation for self-written Add-on package

My package works fine so far, and now I want to add some documentation. I have put a file in `FileNameJoin[{ $UserBaseDirectory, "Applications", "myPkg", "Documentation", "English", "Guides", "TableOfContents.nb"}]`. The content of the notebook is:                   Notebook[{Cell["Table of Contents for pkgTools", "TOCDocumentTitle",             ShowGroupOpener -> False, TextAlignment -> Center], Cell[TextData[             ButtonBox["Tutorial: CodingStandards", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/CodingStandards"]]],             "TOCChapter", ShowGroupOpener -> True], Cell[TextData[             ButtonBox["Tutorial: CreateNewApplication", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/CreateNewApplication"]]],             "TOCChapter", ShowGroupOpener -> True], Cell[TextData[             ButtonBox["Tutorial: ToDoList", Rule[BaseStyle, "Link"],                Rule[ButtonData, "paclet:pkgTools/tutorial/ToDoList"]]], "TOCChapter",             ShowGroupOpener -> True]}, StyleDefinitions ->            FrontEnd`FileName[{"Wolfram"}, "Reference.nb"]]      Now when I load the package, it appears in the Function navigator under "Add- Ons". When I click on it, the notebook opens. But it gets immediately the "modified" Tag, which is confusing to users of the package who just want to read the documentation. Is there a way to write-protect the documentation notebook?


Importing a named range of cells from Excel

I have a macro (is that what you call it?) set up in _Mathematica_ and it runs fine. What I want to do now is set up my notebook to look through an Excel document (.xlsx) and pick out a certain set of cells that I named in Excel using the name manager. How do I get _Mathematica_ to import that Named Range? Also I have noticed that _Mathematica_ will not recognize every excel document and I have checked to make sure that the file is an xlsx file and still _Mathematica_ tells me that the file can't be opened as an xls. So two problems.   1. _Mathematica_ doesn't accept every file name I give it and reports the it cannot be imported in XLS format.   2. How to I import a named cell from Excel without having to use row and column descriptors? Per request here is what I have tried so far               Import["NajaK5uLData.xls"]      > Import::nffil: File not found during Import. >>   >  $Failed               Import[NotebookDirectory[] <> "NajaK5uLdata.xlsx"]      > Import::fmterr: Cannot import data as XLS format. >>   >  $Failed


Can I use boolean parameters in LogitModelFit?

For example, to use `1` as `True` and `0` as `False`:               LogitModelFit[{{300, 0, 0}, {400, 0, 0}, {450, 1, 0}, {460, 1, 1}}, {x, y}, {x, y}]      where `y` is boolean parameter.


Change the inner color of markers

I would like to have a marker with white as its inner color, to be able to make this kind of graph: ![enter image description here](http://i.stack.imgur.com/OIQFn.png) If I use `PlotMarkers -> Style["\[FilledSquare]", White]`, it changes both the inner color + border color but not the inner color only. If I use `PlotMarkers -> Style["\[EmptySquare]", White]`, the line of the curve goes above the marker. How could I achieve that?


Fit convoluted Gaussian and Lorentzian functions to a peak profile

Thanks in advance for anyone who read this. I have a peak profile `data` like this:               DD = 100; theta2B = 13.742; Lamda = 0.999047433;     ϕ[DD_, theta2_] := 2 Pi DD (Sin[theta2/360*Pi] - Sin[theta2B/360*Pi]) /Lamda;     profile = 1/ϕ[DD, theta2]^2 - Sin[2 ϕ[DD, theta2]]/ϕ[DD, theta2]^3 + (     1 - Cos[2 ϕ[DD, theta2]])/(2 ϕ[DD, theta2]^4);     data = Transpose[{Table[i, {i, 7, 20, 0.01}],      Table[profile, {theta2, 7, 20, 0.01}]}];     ListPlot[data, PlotRange -> All]      And I have _Gaussian_ , _Lorentzian_ , and _Hat_ functions like this:               GUA[x_] := PDF[NormalDistribution[13.742, fwhm1/Sqrt[8 Log[2]]], x]     LUA[x_] := PDF[CauchyDistribution[13.742, fwhm2/2], x]     HAT[x_] := UnitStep[x + fwhm3/2] - UnitStep[x - fwhm3/2]      Now I want to fit the convolution of `GUA[x]`, `LUA[x]`, and `HAT[x]` to above peak profile `data`. The `fwhm1` `fwhm2` and `fwhm3` need be defined from the best fitting. Does anyone know how to do this? Thanks very much. P.S. I searched the documentation centre and found that the function `Convolve` cannot generate an analysis formula of `GUA[x] * LUA[x] * HAT[x]` (* is convolution).


Annoying window. How to remove it?

![How do I remove this wondow from my mathematica?](http://i.stack.imgur.com/1CRkn.jpg) How do I remove this window from my _Mathematica_?


Integrate returns unexpected result

Consider the following function $$g(x,y):= \frac{1}{( (1+y)^2+x^2 )( 1+ax^2y^2 )^2}$$, where I assume that $y\geq 0$ and $a\in (0,1]$ is a parameter. When I try to evaluate the integral $\int g(x,y)\,dx$ using Mathematica I get the following result: $$ \frac{\frac{axy^2(-1 + ay^2(1 + y)^2)}{(1 + ax^2y^2)} + \sqrt{a}y(-3 + ay^2(1 + y)^2)\arctan(\sqrt{a}xy) + \frac{2\arctan(\frac{x}{1 + y} )}{ 1 + y} }{2(-1 + ay^2(1 + y)^2)^2} $$ This result cannot be the correct primitive of $g(\cdot,y)$, since on the one hand the denominator is always has a positive root but the numerator is positive, and on the other hand we have that $$0\leq g(x,y)\leq \frac{1}{1+x^2 }$$ which implies that $g(\cdot,y)$ is Riemann integrable for all $y\geq 0$. Could someone please tele me how to obtain a correct answer to the problem? This would be very much appreciated! Code:               Integrate[1/(((1+y)^2+x^2)*(1+a*x^2*y^2)^2),x]      Output: > ((a x y^2 (-1 + a y^2 (1 + y)^2))/(1 + a x^2 y^2) + Sqrt[a] y (-3 + a y^2 (1 > + y)^2) ArcTan[Sqrt[a] x y] + ( 2 ArcTan[x/(1 + y)])/(1 + y))/(2 (-1 + a y^2 > (1 + y)^2)^2)


Deploy a dynamic report

What does it take to deploy a report to the Wolfram Cloud? I would like to deploy _the generated notebook_ (not the notebook with the slots) to a public URL so my customer can access it. Every time the URL is accessed the data within the slots should be updated. All of this works on my desktop but I don't see the documentation regarding the deployment of the dynamic report.


Benefit of using Dataset to collect SQLSelect output

Considering a `DatabaseExample` included with _Mathematica_ :               Needs["DatabaseLink`"]     conn = OpenSQLConnection["publisher"];     SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True]//Short      > > `{{TITLE_ID,LORANGE,HIRANGE,ROYALTY},{BS1011,0,5000,0.1},<<49>>,{PY2008,0,50000,0.1}}` Now with the introduction of v10 and functions such as `Association` and `Dataset`, we can convert this data to a `Dataset`:               sqltodataset[fields_, data_] /; Equal @@ Join[{Length@fields}, Length /@ data] :=      Dataset[Association[Thread[fields -> #]] & /@ data]               data = SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True];     ds = sqltodataset[First@data, Rest@data];      Querying should now be much faster:               Do[SQLSelect[conn, "ROYSCHED", {"ROYALTY"}, SQLColumn["TITLE_ID"] == "BS1001"], {100}] // Timing     Do[Normal[Select[ds, #"TITLE_ID" == "BS1001" &][[All, "ROYALTY"]]], {100}] // Timing      And it seems to be. Although not quite a fast as I expected: > `{0.171601,Null}` > > `{0.093601, Null}` But at the expense of RAM:               ByteCount[ds]      > `35644` Is there a real upside to converting to a `Dataset`, or should I just stick to SQL to query? And is there a more direct way to convert straight to a `Dataset`?


How to change the font of a color bar?

When using `DensityPlot` or similar, I want to change the font size of both frame labels and the color bar legend, but I can only get the frame labels to work. Example:               DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, PlotLegends -> Automatic,      BaseStyle -> {FontSize -> 30}]      ![enter image description here](http://i.stack.imgur.com/pSXx0.png)


Export dataset to JSON

I'm experiencing a weird issue. Consider a dataset defined like this:               dataset = Dataset[{<|"a" -> 1, "b" -> 2|>, <|"a" -> 3, "b" -> 4|>}];      Now I would expect `Export["test.json", dataset]` to create a JSON file with these contents:               [{"a": 1, "b": 2}, {"a": 3, "b": 4}].      Instead, the command returns > Export::badval: The element Data contains invalid values. >>. A workaround is to run               Export["test.json", Normal[Normal[dataset]]]       but that seems merely a workaround. Is there anyone here who knows a neat solution?


Median of Dataset in Mathematica 10

I'm having trouble calculating the median of a `Dataset[]` in Mathematica 10. The situation is as follows. Consider a dataset that was defined as follows:               dataset = Dataset[{<|"a"->1,"b"->2|>,<|"a"->3,"b"->4|>}];      The mean and variance of columns `a` and `b` can now be calculated by               mean = dataset[Mean, {"a","b"}]     var = dataset[Variance, {"a","b"}]      That works pefectly, but               med = dataset[Median, {"a","b"}]      returns a `Failure[]`! Somehow, `Median[]` is not compatible with a list of associations as its argument and the other functions are. Can someone explain why this happens and maybe help with a solution?


Is it possible to save an interrupted computation?

I've got this really time consuming factoring problem. To decouple things a bit, I decided to start _Mathematica_ using the command line interface (under screen).               $ math      So my code is running, and I know that I can interrupt it with `Ctrl`-`C`, but what I want to do is interrupt it, and then write the state of the process to disk, so that I can reboot. On Linux, there is a program called CryoPID which might work. Unfortunately, my computation is running on OS X. I can detach from the screen session and re-attach to it, but if I reboot the machine I know it'll lose memory and the computation progress so far. My question is: can you save the state of a _Mathematica_ computation that you interrupt (to disk and reloadable after a restart). Thanks.


Solving a two point boundary problem for a piecewise system of equations

I'm trying to solve a two point boundary value problem with a piecewise system of equations like:               dx[t_] := Piecewise[{{0, y[t] <= 0}, {x[t]^(3/4) - x[t], y[t] > 0}}]     dy[t_] := Piecewise[{{0, y[t] <= 0}, {(1 - y[t])/x[t]^(1/4) + y[t], y[t] > 0}}]          NDSolve[{x'[t] == dx[t], y'[t] == dy[t], x[0] == 1, y[10] == 2}, {x, y}, {t, 0, 10}]      which produces the error                NDSolve::bvdisc: NDSolve is not currently able to solve boundary value problems with discrete variables.      I tried the answers here by entering               funs = ParametricNDSolveValue[{x'[t] == dx[t], y'[t] == dy[t], x[0] == 1, y[10] == yt}, {x, y}, {t, 0, end}, yt]          FindRoot[funs[yt][end], {yt, 2}]      which yields the same error. Is there any way to solve this system? Thanks for the help.


Clear inside a loop

I want to solve a system of differential equations and each time I want to change two parameters. To prevent wrong result I want to clear every assignment after solving the equations in each iteration. I have a `Do`-loop with two iterator. The problem is that if I use `Clear["Global`*"]` then the outer iterator will not be accessible to the code inside the loop. Here is an example:               Do[{Print[a]; Clear["Global`*"];}, {a, 1, 2}, {b, 1, 2}]      Result: > >     1 >   >     a >   >     2 >   >     a >   As you can see the iterator `a` is erased for the inner iterator `b`. How can I resolve this issue? I expect the outer iterator to be printed each time. There are 4 iteration in total, so I expect to get: > >     1 >     1 >     2 >     2 >   I want both iterators, a and b, in spite of using Clear command to be accessible to the code inside loop. I want to clear everything after each iteration except iterators a and b.


How do I union graph properties?

I have two graphs               g1 = Graph[{"1", "2", "3"}, {{2, 1}, {3, 1}},VertexLabels -> {"1" -> Placed["One", Tooltip], "2" -> Placed["Two", Tooltip], "3" -> Placed["Three", Tooltip]}]      and               g2 = Graph[{"5", "2", "3"}, {{2, 1}, {3, 1}}, VertexLabels -> {"5" -> Placed["Five", Tooltip], "2" -> Placed["Two", Tooltip], "3" -> Placed["Three", Tooltip]}]      Each of which displays the appropriate label when doing a mouseover. Then I do               GraphUnion[g1,g2]      and get the desired graph, but the tooltips for the vertex names are gone. If I do               GraphUnion[g1,g2,Options[g1]]       then as expected I get the tooltips for the vertices of g1. But how can I get the tooltips for ALL the vertices (i.e. vertices for both graphs)? Thanks much!


Problem with ContourPlot3D

The following line works fine:               ContourPlot3D[2 x - y == 0, {x, -10, 10}, {y, -10, 10}, {z, -10, 10},                   ContourStyle -> Opacity[0.5], Mesh -> False]      But when I bind the equation `2 x - y == 0` to a variable `eq`:               eq = 2 x - y == 0     ContourPlot3D[eq, {x, -10, 10}, {y, -10, 10}, {z, -10, 10},                    ContourStyle -> Opacity[0.5], Mesh -> False]      it fails. I also noticed that values are assigned to variables x and y after executing ContourPlot3D. There's something that I don't understand about workings of `ContourPlot`. Could anyone explain what's going on and how should I pass the equation in a variable? **UPDATE** As **m_goldberg** wrote in his answer, in a bug-free Mathematica it is not necessary to defer evaluation so `eq = 2 x - y == 0` works fine. The call to `Evaluate` is still required. But it seems to me that `eq` and `2x - y == 0` should evaluate to the same expression:               In[33]:= eq === 1 + 2 x == 0     Out[33]= True      So what's difference between these two expressions, which causes them to behave differently in `ContourPlot3D`? How can I see this difference in Mathematica environment?


Use different ColorFunction for each function plotted

When plotting two curves on one plot, you can specify different colors for each function:               Plot[{Sin@x, Cos@x}, {x, 0, 4π},       PlotStyle -> {Red, Blue}]      ![Mathematica graphics](http://i.stack.imgur.com/S9XKP.png) To plot the curves using different `ColorFunction`s, you can manually combine the plots:               Show[      Plot[Sin@x, {x, 0, 4 \[Pi]},       ColorFunction -> ({x, y} \[Function] Opacity[y, Red])],      Plot[Cos@x, {x, 0, 4 \[Pi]},       ColorFunction -> ({x, y} \[Function] Opacity[y, Blue])]      ]      ![Mathematica graphics](http://i.stack.imgur.com/ZZeIM.png) But if you try to combine them into one `Plot[]` expression, it doesn't work:               Plot[{Sin@x, Cos@x}, {x, 0, 4 \[Pi]},      ColorFunction -> {({x, y} \[Function]           Opacity[y, Red]), ({x, y} \[Function] Opacity[y, Blue])}]      ![Mathematica graphics](http://i.stack.imgur.com/hN4mF.png) How can you easily plot multiple curves, specifying the `ColorFunction` to use for each?


Implementing local complements of graphs

I'm trying to write a routine which generates the local complement of a graph at a vertex. For those who don't know, the local complement for a singly- connected, undirected graph is defined as the graph where for all vertices adjacent to the selected one, two of them have an edge exactly if they don't have in the original one (in other words, the subgraph containing only the adjacent edges). All other edges, including those connecting the selected vertex with its adjacent vertices, are unchanged. For example,               LocalComplement[Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1}], 1]      should give > >     Graph[{1 <-> 2, 3 <-> 1}] >   and               LocalComplement[Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 1}], 1]      should give > >     Graph[{1 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 1, 2 <-> 4}] >   Here's what I've tried:               LocalComplement[g_,v_]:=Module[{h=VertexDelete[NeighborhoodGraph[g,v],v]},       GraphUnion[GraphDifference[g,h],GraphComplement[h]]]      The idea is simple: First I determine the neighbourhood of the selected vertex. Since Mathematica includes the vertex in the NeighborhoodGraph, I remove that. Then I remove the original subgraph `h` from `g` and add the complement of `h`. This works well with the first example above, but for the second example, the same graph is returned, without the additional edge. Therefore I'd like to know:   * Why does my code not work as expected?   * And of course: How can I fix it?


Easiest Way to Use ShowGroupOpener in Mathematica

I currently edit manually the cell contents of a notebook (Ctrl+Shift+A or Cmd+Shift+A) to "recycle" cells containing the ShowGroupOpener option. Is there an easier way to create documents hiding contents under that type of icon?


Export different simulation parameters and results to same file

I have a simulation, and I would like to export the parameters and results to a same spreadsheet without overwriting the previous values. if I have:               parameter1 = {0.1};     parameter2 = {0.2};     result1 = {10};     result2 = {20};      And if I export it I get that. But then if I change the parameters and run the simulation again, I would like these new values to go right after the ones I had previously exported.               parameter1 = {0.1,0.3};     parameter2 = {0.2,0.2};     result1 = {10,25};     result2 = {20,30};      As a spreadsheet or a list with headings would be best. I saw an answer to a similar question recommended creating a spreadsheet beforehand and then defining the cells where the values should be exported to, but this would still rewrite the cells. I guess I could always manually change the location after each simulation. Maybe mathematica has some built-in function to do something like this? I am still very new, I apologize if this question is elementary or doesn't make sense. Any help is much appreciated!


Efficient export of complex graphics to PDF

So I have 2D plot, made with DensityListPlot. Mathematica just cannot export them properly to PDF, so what I want to do is 1) export the plot itself, without axes, labels, etc, as a jpg image, and 2) Inset this image in an empty graphics containing only axes, labels etc. So far so good. The problem is that when I export the final graphics to PDF, the image are not compressed at all -- and the file end up weighing 400k instead of 30k. The question is: how do I specify the format and compression factor of images embedded in a pdf?


How to calculate partial derivative of an unknown function

How can I force Mathematica to calculate symbolically the partial derivative of a function `u[x,y]` with respect to a variable `z = f(x, y)`, where f(x, y) is known? `u` is a function, defined on reals, taking real values. Same thing holds for `f`. I want to try different changes of variables in PDEs. An example of what I'm trying to achieve and why it's failing:               z = 2*x + y       > 2 x + y               D[u[x, y], z]      > General::ivar: 2 x+y is not a valid variable. >> > > D[u[x, y], 2*x + y] **EDIT** : It appears I have failed to convey the essence of the question. I am not asking _how_ to solve a PDE with Mathematica. I am asking how, given a transformation of the original variables, to calculate the partial derivatives with respect to the new variables. The PDE part is merely some context as to why I want to do this.


Why does NSum fail here?

I want to evaluate a sum of integrals; each integral has a pole on the real axis and I handle this via the Cauchy Principal Value $ f(E)=-\frac{a^2}{2q}\sum^{\infty}_{n=-\infty}\int^{\infty}_{-\infty}dr \exp{(-2iEr/q)}\frac{1}{\left[\sinh^2{(r)}-(\frac{rp}{q}+\frac{npP}{2})^2\right]} $ $a,p,q, E$ are constants. I should say first of all the following applies for $n\neq 0$, for zero $n$ I handle differently. For each $n$ and $E$ the denominator of the integrand has two poles on the real axis (amongst others in the complex plane I shall not be concerned with). I will use Mathematica's `FindRoot` to get the locations of these poles, since the equation whose root we need is transcendental. I will then use `NIntegrate` with the `CauchyPrincipalValue` method to evaluate the principle parts of my integral. To get the additional contribution from the $i\pi \times \text{residue}$ at each pole, I first use partial fractions on my integrand to obtain $ f(E)=-\frac{a^2}{4q}\sum^{\infty}_{n=-\infty}\int^{\infty}_{-\infty}dr \frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\left(\frac{1}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}-\frac{1}{\left[\sinh{(r)}+(\frac{rp}{q}+\frac{npP}{2})\right]}\right). $ Now the two poles for each $n,E$ are simple poles and providing we know their location (numerically via `FindRoot`) the residue is easy to compute for each. For example, considering the first term in the integrand $-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{1}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}$ and say we have numerically found the root to be at $r_0$ for this piece, then $\text{Res}=\lim_{r\to r0}\left[-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{(r-r_0)}{\left[\sinh{(r)}-(\frac{rp}{q}+\frac{npP}{2})\right]}\right]$ $\text{Res}=\lim_{r\to r0}\left[-\frac{a^2}{4q}\frac{\exp{(-2iEr/q)}}{\left(\frac{rp}{q}+\frac{npP}{2}\right)}\frac{1}{\left[\cosh{(r)}-\frac{p}{q}\right]}\right]$ the second equality following from L'Hopital's rule. Note the zeroes of $\left(\frac{rp}{q}+\frac{npP}{2}\right)$ are not really poles when the full expression is considered together as further above. There will be a similar residue from the other piece, and we must add $i\pi\times$ both of these residues to our PV. **Mathematica Implementation**               (*some constants and definitions*)     M = 1;     R = 10 M;     wp = 40;     ag = wp - 8;     pg = wp/2;     a = 1/(4 M) Sqrt[R/(R - 2 M)];     p = 1/(4 M) Sqrt[(M R)/((R - 2 M) (R - 3 M))];     q = 1/(4 M) Sqrt[R/(R - 3 M)];     P = 2 Pi Sqrt[(R^2 (R - 2 M))/M];          (*find the poles for each n,E*)          findNroots[n_?IntegerQ, x0_?NumericQ] := Block[{rM, rP, roots},      rP = r /. FindRoot[Sinh[r] + ((r p)/q + (n p P)/2) == 0, {r, x0}, PrecisionGoal -> pg, WorkingPrecision -> wp][[1]];     rM = r /. FindRoot[Sinh[r] - ((r p)/q + (n p P)/2) == 0, {r, x0}, PrecisionGoal -> pg, WorkingPrecision -> wp][[1]];     roots = {rP, rM};     roots       ]          (*integrate for given n, E, summing PVs and residues*)           integrator[n_ /; n != 0, En_?NumericQ] := Block[{rtM, rtP, lowRoot, highRoot, mid, tmp1, tmp2, tmp3, tmp4, sum},           rtP = findNroots[n, 0][[1]];      rtM = findNroots[n, 0][[2]];      lowRoot = Sort[{rtM, rtP}][[1]];      highRoot = Sort[{rtM, rtP}][[2]];      mid = (highRoot + lowRoot)/2;  (*const somewhere in middle of two poles on real line*)           tmp1 = -a^2/(2 q) NIntegrate[ Exp[-2 I En r /q] (1/((Sinh[r])^2 - ((r p)/q + (n p P)/2)^2)), {r, -Infinity, lowRoot, mid}, Method -> {"PrincipalValue"}];      tmp3 = -a^2/(2 q) NIntegrate[Exp[-2 I En r /q] (1/((Sinh[r])^2 - ((r p)/q+ (n p P)/2)^2)), {r, mid, highRoot, Infinity}, Method -> {"PrincipalValue"}];           (*add residues too:*)      tmp2 = I Pi ( -a^2/(4 q) Exp[-2 I En rtM /q] 1/((rtM p)/q + (n p P)/2) ) Limit[1/( Cosh[r] -  p/q), r -> rtM];      tmp4 = I Pi ( -a^2/(4 q) Exp[-2 I En rtP /q] 1/((rtP p)/q + (n p P)/2) ) Limit[-1/( Cosh[r] +  p/q), r -> rtP];           sum = tmp1 + tmp2 + tmp3 + tmp4;      {sum}      ]      This seems to work OK, I can do `Table[integrator[n,1],{n,1,100}]` and Mathematica seems to compute this list just fine. However if I do just`NSum[integrator[n,1],{n,1,2}]` then Mathematica will give all manner of complaints such as `NIntegrate::deorela`. Why is this when it is perfectly happy to compute the values of `integrator` in a list individually? Is there another way I should be performing this sum? A separate issue: I also find that at certain values of $n,E$ for example `integrator[1, 24]` I also get errors like `NIntegrate::deodiv: DoubleExponentialOscillatory returns a finite integral estimate, but the integral might be divergent` and I can't even compute the result individually let alone in `NSum`. I suspect this is because things become too oscillatory at higher values of $E$.


Simplify with Assumptions Sqrt[(expr)^2]

While trying to simplify expressions in the form `Sqrt[(expr)^2]` when `expr>0` I noticed a peculiar behavior that was not resolved with code from this Q&A.               Simplify[Sqrt[(x - y + a b c)^2], x - y + a b c > 0]      > >     Abs[a b c + x - y] >   When I remove any of the `a`, `b`, `c`, `x` or `y` it returns the result without the `Abs`:               Simplify[Sqrt[(x - y + b c)^2], x - y + b c > 0]      > >     b d + x - y >   I loose faith when I meet such behavior with Mathematica :-( Even though               Simplify[Sqrt[expr^2], expr > 0] /. expr -> (x - y + a b c)      does fix the first issue how could I simplify this:               Simplify[Sqrt[(x - y + a ^2 b^2 c^2)^2], x > y]      Anyway, can anybody explain why this happens and propose a way to fix it for general expressions?


Noticeable slowdown in graphical performance when using manipulate

I have been making these mathematica 3D objects that involve a molecule with some sort of surface displayed above them. This is done fairly easily by:               Molecule=Graphics3D[{{x,y,z},...},Sphere[1, .24]...,Cylinder[{1, 2}, .15]]     PES=ListPlot3D[{{x,y,z},...}]     Show[Molecule,PES]      A python script was pretty easy to whip this up for molecules; for me its better then the wolfram chemistry database because it is in better units (angstroms) and can be oriented easier. It works great, the objects manipulate smoothly. Now I wanted to do something that would have a very nice end product. Following the work of an online demonstration I started with the initialization code:               Molecule[coord_, conf_, col_, rad_, bondstyle_] :=        Module[{intconf, atomplot, tuples, bonds, bondplot},         intconf =          ReplacePart[conf,           Flatten@Table[# -> ii & /@ (Flatten@               Position[conf, DeleteDuplicates[conf][[ii]]]), {ii, 1,              Length@DeleteDuplicates[conf]}]];        atomplot = {col[[intconf[[#]]]],             Sphere[coord[[#]], rad[[intconf[[#]]]]]} & /@           Range[Length[intconf]];        tuples =          Select[Subsets[           Range[Length[             coord]], {2}], ((conf[[#[[1]]]] =!= "H" ||                conf[[#[[2]]]] =!= "H") &&              Norm[coord[[#[[1]]]] - coord[[#[[2]]]]] <=               bondstyle[[1]]) &];        bonds = coord[[#]] & /@ tuples;        bondplot =          Table[{col[[intconf[[tuples[[#, ii]]]]]],              Tube[{bonds[[#, ii]], .5*Total[bonds[[#]]]},               bondstyle[[2]]]} & /@ Range[Length[bonds]], {ii, 1, 2}];        {atomplot, bondplot}];     coord["Acrolein"] := {{-1.4373, -1.1224, 0.4127}, {0.1565,          0.3728, -0.3457}, {-1.1456, -0.2881, -0.399}, {1.0519, 0.0649,          0.6058}, {0.4003,          1.1146, -1.0773}, {-1.8435, -0.0263, -1.1667}, {0.8173, -0.6754,          1.3418}, {2.0003, 0.5599, 0.6283}};     conf["Acrolein"] := {"O", "C", "C", "C", "H", "H", "H", "H"};      I decided to use this since I can use Map to manipulate the position and scale of the object. Its really just a way to replace my python script. Surfaces were again easy to create with the Map just used to duplicate quadrants:               AcrWater=Import["xyzlist.csv"     surface["Acrolein", "Water"] =        ListPlot3D[Union[AcrWater, Map[#*{1, -1, 1} &, AcrWater]],         Mesh -> 3, ColorFunction -> "Rainbow", PlotStyle -> Opacity[0.9]];      This next part was just done in my experiments to make the graphics smoother:               graphic["Acrolein", "Water"] =        Show[          Graphics3D[{Specularity[White, 100],           Molecule[coord["Acrolein"], conf["Acrolein"],            ColorData["Atoms", #] & /@             DeleteDuplicates[             conf["Acrolein"]], {.4, .4, .4, .4}, {1.5, .193}]}],             surface["Acrolein", "Water"],             ImageSize -> {600, 600}, Background -> White, ViewPoint -> Top,         Axes -> True, Lighting -> "Neutral"];      Finally the manipulate argument:               Manipulate[      graphic[substance,        solvent], {{substance, "Acrolein", "Molecule"}, {"Acrolein"}},      {{solvent, "1C", "Solvent"}, {"Water"}}]      All of this works great together! The only problem is that manipulating the final product is incredibly slow even on a new, well equipped machine with the antialiasing all the way down. There in total will be about 30 different combinations and only implementing a single one shows significant degradation in the overall feel of the demonstration; adding more is even worse. This seems strange when it is done the previous way there is no noticeable lag even with much larger systems. My question is where is the major slowdown in this. It was my understanding that the vector objects were first evaluated then simply displayed by the manipulate command. If there is not an easy workaround is there another way to do this that can avoid the slowdown problem. Edit: Thank you for the tips so far dynamic and tracked symbols certainly made marked improvements. Here is a chunk of working code that will mimic what I am trying to do. This is a single example with with only 25 points for the surface (real surfaces will have 1000-2000). I am not entirely sure how to do it but a better way to recreate the surface using the proper notation of the data is [x,y,sin[x+y]] where and x and y run from 0-3 in steps of .1. Instead of Dynamic I also tried the Refresh command to no avail.:               Molecule[coord_, conf_, col_, rad_, bondstyle_] :=        Module[{intconf, atomplot, tuples, bonds, bondplot},         intconf =          ReplacePart[conf,           Flatten@Table[# -> ii & /@ (Flatten@               Position[conf, DeleteDuplicates[conf][[ii]]]), {ii, 1,              Length@DeleteDuplicates[conf]}]];        atomplot = {col[[intconf[[#]]]],             Sphere[coord[[#]], rad[[intconf[[#]]]]]} & /@           Range[Length[intconf]];        tuples =          Select[Subsets[           Range[Length[             coord]], {2}], ((conf[[#[[1]]]] =!= "H" ||                conf[[#[[2]]]] =!= "H") &&              Norm[coord[[#[[1]]]] - coord[[#[[2]]]]] <=               bondstyle[[1]]) &];        bonds = coord[[#]] & /@ tuples;        bondplot =          Table[{col[[intconf[[tuples[[#, ii]]]]]],              Tube[{bonds[[#, ii]], .5*Total[bonds[[#]]]},               bondstyle[[2]]]} & /@ Range[Length[bonds]], {ii, 1, 2}];        {atomplot, bondplot}];     coord["Acrolein"] := {{-1.4373, -1.1224, 0.4127}, {0.1565,          0.3728, -0.3457}, {-1.1456, -0.2881, -0.399}, {1.0519, 0.0649,          0.6058}, {0.4003,          1.1146, -1.0773}, {-1.8435, -0.0263, -1.1667}, {0.8173, -0.6754,          1.3418}, {2.0003, 0.5599, 0.6283}};     conf["Acrolein"] := {"O", "C", "C", "C", "H", "H", "H", "H"};          AcrWater :=       Table[Sin[j + i] + 2, {i, 0, 2 Pi, Pi/4}, {j, 0, 2 Pi, Pi/4}]          surface["Acrolein", "Water"] :=        ListPlot3D[AcrWater, Mesh -> 3, ColorFunction -> "Rainbow",         PlotStyle -> Opacity[0.9]];          graphic["Acrolein", "Water"] :=        Dynamic[Show[         Graphics3D[{Specularity[White, 100],            Molecule[coord["Acrolein"], conf["Acrolein"],             ColorData["Atoms", #] & /@              DeleteDuplicates[              conf["Acrolein"]], {.4, .4, .4, .4}, {1.5, .193}]}],          surface["Acrolein", "Water"], ImageSize -> {600, 600},          Background -> White, ViewPoint -> Top, Axes -> True,          Lighting -> "Neutral"], None];          Manipulate[      graphic[substance,        solvent], {{substance, "Acrolein",         "Molecule"}, {"Acrolein"}}, {{solvent, "Water",         "Solvent"}, {"Water"}}, TrackedSymbols :> {substance, solvent}]


Making cells group

After reading rcollyer's post I'm still not able to understand how grouping rules work. Here is a problem I'm facing. What I want is to create a new title, section and subsection styles. I want the title to group everything below till the next title. The section should group everything below till the next section. To see what I mean, open up a new notebook. Go to `Format > Edit Stylesheet...`. On this stylesheet make a new cell. Then select this cell and go to `Cell > Show Expression`. Here enter the following:               Cell[StyleData["MyTitle"],      CellGroupingRules->{"MyTitleGrouping", 0},      CounterIncrements->"MyTitle",      CounterAssignments->{{"MySection", 0}, {"MySubsection", 0}},      FontSize->26,     ]       Once this has been entered now go to `Cell > Show Expression` to revert back. Let us create two more cells in the same fashion, one for the section and subsection.               Cell[StyleData["MySection"],      CellGroupingRules->{"MyTitleGrouping", 10},      CounterIncrements->"MySection",      CounterAssignments->{{"MySubsection", 0}},      CellFrameLabels->{{         Cell[          TextData[           CounterBox["MySection"], " -"], CellBaseline -> Baseline], Inherited}, {        Inherited, Inherited}},      FontSize->20,     ]      Finally, the subsection:               Cell[StyleData["MySubsection"],      CellGroupingRules->{"MyTitleGrouping", 20},      CellFrameLabels->{{         Cell[          TextData[           CounterBox["MySection"], ".",            CounterBox["MySubsection"], " -"], CellBaseline -> Baseline],          Inherited}, {Inherited, Inherited}},      CounterIncrements->"MySubsection",      FontSize->16,     ]      After creating those new styles, now we can use them, here is a screenshot of what I obtained if I use the "MyTitle", "MySection" and "MySubsection" styles. ![enter image description here](http://i.stack.imgur.com/zh8fg.png) Don't mind the text I entered there. The main point here is that there is no grouping. How can I make it behave as the regular "Title", "Section" and "Subsection" styles? ![enter image description here](http://i.stack.imgur.com/t7Rxh.png)


How to Export Data from Mathematica into Excel specific cell

for import,we can do like this Import["XXX.xlsx", {"Data",1,2,3}],Mathematica will get the cell {2,3} of the "sheet1" in "XXX.xlsx". But if we want to export data from Mathematica to one Excel specific cell,How to realize?


Define a function with a function for an input

I want to create the functions $even[f]$ and $odd[f]$ which will apply the formula $even[f(x)] = \frac{f(x)+f(-x)}{2}$ and $odd[f(x)]=\frac{f(x)-f(-x)}{2}$ for an arbitrary $f$. I tried using               even[ff, x_] := (ff[x] + ff[-x])/2      But that doesn't seem to work. What would the correct approach to this be?


How do I get a MeshRegion from an obj file, or from Geometry3D

How do I read in an obj file as a `MeshRegion` so I can e.g. compute its area? If I just import the object and try `Area[O]` it tells me it is not a correctly specified region, even for e.g. the StanfordBunny. Also, how do I turn `Geometry3D` into a `MeshRegion`? For example `Area[ExampleData[{"Geometry3D", "SpaceShuttle"}]]` does not work either. It seems that geometry has more than one representation in different parts of _Mathematica_ \- bad.


When I use Rule, why doesn't this work?

k.k.k //. {k.k -> k}      works perfectly, so the output is just `k`. But, when I use `Esc`.`Esc` (center dot, CenterDot[k,k]) instead of . (comma),               k Esc.Esc k Esc.Esc k //. {k Esc.Esc k -> k}      does not work while               k Esc.Esc k //. {k Esc.Esc k -> k}      works. How can I fix this problem?


How to make a CDF document with dynamic content?

I would like to create a CDF document that uses dynamic content. The example code is:               fun=x^2-1;     InputField[Dynamic[fun]]      And what I get is $Aborted instead of interactive document. How to make a useful document? EDIT: What I am really trying to do is to make a CDF document in which the given function is plotted. Initially the function is x^2-1, but the user should be able do input any function.


Export a simple DataSet with key-value associations to CSV in Mathematica 10

I'm trying to Export a simple dataset with key-value pairs to a CSV               Export["n.csv", MyDataset, "CSV"]      This results in a single-line serialization:               Dataset[<|"A" -> 3757, "B" -> 426, "C" -> 193, ...."D" -> 1|>, TypeSystem`Assoc[TypeSystem`Atom[String], TypeSystem`Atom[Integer], 15], <|"Origin" -> HoldComplete[Sort[Dataset`DatasetHandle[265575026537634], Greater]], "ID" -> 109770792907938|>]      The desired result is:               A,3757     B,426     C,193     ...     D,1


Why are the attributes of Plot changing?

In version 9, with a newly started _Mathematica_ session, try the following code:               plotAttributes = Attributes[Plot]          Plot[Sin[x], {x, 0, 1}];          Attributes[Plot]          % == plotAttributes      > `{Protected, ReadProtected}` > > `{HoldAll, Protected, ReadProtected}` > > `False` Is there any explanation why `Plot` doesn't have `HoldAll` as one of its attributes when a fresh _Mathematica_ session is started, and acquires this attribute only after I call `Plot` once?


How can I get every distinct size-n combination of a list?

Let's say I have a list:               {a, b, c}      I would like to, for say $n=2$ get every distinct pair from that list. That is, the expected result should be, for some function `choose`:               choose[{a, b, c}, 2]     (* {{a, b}, {a, c}, {b, c}} *)      My attempt at this was like so:               choose[list_, n_] :=         DeleteDuplicates[Permutations[list, {n}], Union[#1, #2] == #1 &]      And it does give the expected result for this example. There are, however, some problems in which I would like some help addressing:   1. `Permutations` creates more combinations that I need, which forces me to use `DeleteDuplicates`. Is there away to directly arrive at all combinations?   2. The `DeleteDuplicates` operation is very costly. Is there a way I could use the structure of the `Permutations` result to my advantage to get rid of the unwanted repeats?   3. My function DOES make an error when there are supposed to be _intended_ repeats. For instance, `choose[{b, b, c}, 2]` should give `{{b,b}, {b, c}, {c, b}}` \- as every element in the list is considered "distinct" even though the values could be equal - but instead, the duplicate deletion removes the `{c, b}`. **EDIT** I have figured out a way to address #3. If I create a symbolic list `tempList` in which every element is unique, then replace that with the list, I am able to preserve "distinct" combinations even though they have the same value:               choose[list_, n_] :=         With[{tempList = Array[Unique[] &, Length@list]},              DeleteDuplicates[             Permutations[tempList, {n}],              Union[#1, #2] == #1 &] /. Thread[tempList -> list]]      However, there's still room for improvement as having to use the replacement is not great for larger `list` lengths and values of $n$.


Triangle that collapse cells

I'm not very good in English , so is hard to explain but how put the triangle in the left that deploy or collapse a group of cells ?


Series expansion with irrational power

I need the series expansion of a fairly nasty function and its derivative:               f = (x - a) (1 + b (1/(x - a))^((5 + Sqrt[73])/12) *        Hypergeometric2F1[(-7 + Sqrt[73])/12, (1 + Sqrt[73])/12, (        6 + Sqrt[73])/6, -(a/4)/(x - a)]) + a/2      $f\left(x\right) = (x-a) \left(1+b \left(\frac{1}{x-a}\right)^{\frac{1}{12} \left(5+\sqrt{73}\right)} \, _2F_1\left(\frac{-7+\sqrt{73}}{12} ,\frac{1+\sqrt{73}}{12} ;\frac{6+\sqrt{73}}{6} ;-\frac{a}{4 (x-a)}\right)\right)+\frac{a}{2}$ where $x$, $a$ and $b$ are positive real numbers and I know $x \gg a$. I'm interested in the series expansion of $f$ and $f'$ in inverse powers of $x$:               Series[f, {x, \[Infinity], 1}] // Normal      $\dfrac{b \left(\dfrac{1}{x-a}\right)^{\dfrac{\sqrt{73}}{12}}}{\left(\dfrac{1}{x}\right)^{7/12}}-\dfrac{a}{2}+x$               Series[D[f, x], {x, \[Infinity], 1}] // Normal      $b \left(\dfrac{1}{x}\right)^{5/12} \left(\dfrac{1}{x-a}\right)^{\dfrac{\sqrt{73}}{12}}+1$ The problem is I can't figure out how to get this to simplify any further. I need to get these in the form $ c_1 x + c_0 + \dfrac{c_{-1}}{x^{p}} $ for some constants $c_i$ and $p$, but `Series` doesn't expand the term with $x-a$ in the denominator. I guess because the power is irrational? How can I get the answer in the desired form? I could do it by pen and paper of course, but I would love to have it in code. Using `Assumptions -> {x > a > 0, b > 0}` doesn't seem to make any difference. Any help is appreciated.


Evaluation of second argument to NIntegrate

Apologies if this is a duplicate, but I couldn't find it. The expression               Integrate[x^2, Flatten[{{x},{1,2}}]]      evaluates properly, to $\frac{7}{3}$. However,               NIntegrate[x^2, Flatten[{{x},{1,2}}]]      returns               NIntegrate::vars: Integration range specification Flatten[{{x},{1,2}}] is not of the form {x, xmin, ..., xmax}. >>      An explicit `Evaluate` is required on the second parameter to make this work. So I assume that NIntegrate has a `HoldAll` on its second parameter. Did I have any way of knowing this before hand? That is, is this behavior documented? And, if it is (or even if it is not), why do the two functions behave differently?


Numerically solving a system of PDEs where one function is composed with the other

I'm trying to solve the following system using `NDSolve`: $$ \begin{align} u_t(x,t) &= u_{xx}(x,t) - v(x,t) \\\ v_t(x,t) &= u(v(x,t),t) \end{align} $$ with $$ u_x(-1,t) = 0, \quad u_x(1,t) = 0, \quad u(x,0) = \tanh(10x), \quad v(x,0) = 1/3. $$ I tried the following code in Mathematica 7.               NDSolve[{         Derivative[0, 1][u][x, t] == Derivative[2, 0][u][x, t] - v[x, t],         Derivative[0, 1][v][x, t] == u[v[x, t], t],              Derivative[1, 0][u][-1, t] == 0,         Derivative[1, 0][u][1, t] == 0,              u[x, 0] == Tanh[10 x],         v[x, 0] == 1/3       }, {u, v}, {x, -1, 1}, {t, 0, 5}]      This produces an error: `NDSolve::delpde: Delay partial differential equations are not currently supported by NDSolve.` I think this is coming from the second differential equation, because if it doesn't have a composition, for example if I change the second equation to $$ v_t(x,t) = u(x,t)+v(x,t), $$ and try the code               NDSolve[{         Derivative[0, 1][u][x, t] == Derivative[2, 0][u][x, t] - v[x, t],         Derivative[0, 1][v][x, t] == u[x, t] + v[x, t],              Derivative[1, 0][u][-1, t] == 0,         Derivative[1, 0][u][1, t] == 0,              u[x, 0] == Tanh[10 x],         v[x, 0] == 1/3       }, {u, v}, {x, -1, 1}, {t, 0, 5}]      then I get a result. Is there anything I can do to help `NDSolve` solve the original system (with the composition)?


EquationTrekker-like behavior for state space?

`EquationTrekker` is great for phase space plots, however I want to plot the results of $$\phi '(t)=-b \sin (\phi (t))+g \sin (\Phi (t)-\phi (t))+1\\\\\Phi '(t)=g y \sin (\phi (t)-\Phi (t))-J (\Phi (t)-\phi (t))$$ I modified this to create this:               Manipulate[      Show[ParametricPlot[        Evaluate[         First[{ϕ[t] , Φ[t]} /.            NDSolve[{ϕ'[t] ==                1 - b Sin[ϕ[t]] +                g Sin[Φ[t] - ϕ[t]], Φ'[t] ==                y g Sin[ϕ[t] - Φ[t]] -                J (Φ[t] - ϕ[t]),              Thread[{ϕ[0] , Φ[0]} ==                point]}, {ϕ, Φ}, {t, 0, T}]]], {t, 0, T},         PlotStyle -> Red, PlotRange -> R]], {{T, 20}, 1, 100}, {{R, 2}, 0,        10}, {{b, 1.79}, -1, 4}, {{g, 0.32}, -1, 4}, {{y, 0.26}, -1,        4}, {{J, 0.51}, -1, 4}, {{point, {1.3, 0.2}}, Locator},       SaveDefinitions -> True]      which lets me click on various portions of the graph and have a look at the time evolution in state space. I'd like to get similar behavior in EquationTrekker, where it shows me the solution of a two-dimensional system in state space. The main thing I need is the "memory" bit, that previously drawn curves stay put instead of getting erased. Is there any way I can get this to work with `EquationTrekker`? If not, is there any way to modify my example so that it "imprints" a line wherever the `Locator` is put? Additionally: A way to `StreamPlot` the gradient in the same graph would be nice.


Can one force a linear regression fit to go through the origin?

As the question says, can one force a fit through the origin $(0,0)$ as one can when fitting a trendline to your data in MS Excel? If so, how do you do that?


How to find pieces of code responsible for syntax errors?

_Especially: How to find the piece of code responsible for a missing parenthesis problem caused by a misplaced_ `SuperScriptBox`    For last 30 minutes (and I was lucky today, sometimes I spend 5 times as much time) I have been removing code little by little from my large one cell, (have to be one cell, it is `Manipulate` demo stylesheet) in order to find where the syntax error is (since _Mathematica_ , with all its might and power, can't tell the user which line number the syntax error is located at). Each time I see the red line show up on the right side of the notebook, indicating a syntax error, I know that I will now waste another hour at least looking for the syntax error. Why is it that hard for _Mathematica_ to tell the user where the syntax error is? I zoomed down to this little 5 character code, and I copy it to new notebook to examine it: ![enter image description here](http://i.stack.imgur.com/w6Opn.png) So, there is a hidden bad character there. Sometimes, with my big fingers and my small keyboard (can't find big keyboards any more, everything is so tiny), I must have hit wrong key combination, which must have injected some bad character to the notebook, and this happens. I will keep this cell on its own in order to find what the problem is. I tried to select the cell, and do convert to input form, but nothing happened. no output came of it. Then I did `cell->ShowExpression`, and this came up               Cell[BoxData[      RowBox[{"(",        RowBox[{"k", "h"}],        SuperscriptBox[")", "2"]}]], "Input",      CellChangeTimes->{3.536893041212217*^9},      EmphasizeSyntaxErrors->True]      ![enter image description here](http://i.stack.imgur.com/N8h1r.png) So, what does all this mean? Do you see from the above what is the problem? I think I entered the superscript as I always do, using `Ctrl+^` then `2`. I think the notebook interface is powerful and allows many things not possible otherwise, but because of problems such the above, I wish sometimes I am using plain text editor like emacs, where I can see what I have and not worry about hidden things I do not see, but I tried that once, and it is not practical overall setup to work with. Btw, originally, I had lots of code like the above inside strings, i.e. inside `" "` for formatting, and now I am removing all the strings to do some other way of formatting. I do not know if this has anything to do with it. But as you can see, now there is no string around the expression. Here is a screen shot of the earlier version of the notebook, from the same location of the code, showing how the above was inside a string, and I simply was removing the outside string quotes, that is all: ![enter image description here](http://i.stack.imgur.com/Fufj0.png)


Automating FTP upload within Mathematica?

I have MMA-generated html and would like to automate uploading to a named directory to a web host via SFTP or HTTP POST, ideally without creating local temp files. The closest question I could find on MMA.SE is this question which doesn't really address this issue. Based on this "minimal http upload gci" in Python, and HTTP Request- Authentication flow-chart, it seems that uploading by FTP may be relatively easier. Sjoerd C. de Vries suggested this question may answer the POST part. Others have found FTP in non-interactive mode to be difficult. But one would think authentication, put and closing the session in interactive mode could be managed within MMA. However, Run is not meant to capture output from the external program. From the sparse documentation, I think `RunThrough` is meant to capture external program output, but I can only manage to capture an exit condition code:               RunThrough["sftp", "####@understars.org:temp.understars.org"]      Doesn't output to the front end, but does set the Out[] to 256. So how can an interactive FTP session be automated? (Note I've tagged this "html" as well since ultimately that is what I want to export.)


What is the purpose of Dump contexts?

## Motivation I've been trolling through some internal code, trying to glean design practices WRI developers employ when extending Mathematica using top-level code. During my `??...`\-- type searches, I've encountered a number of contexts named either like `SomePackageDump` or with `Dump` appended as a subcontext of `SomePackage`. ## Question What is the designed purpose of these `Dump` contexts and how exactly are they employed (in the overall scheme of evaluation)? Note: I understand the use of `Private` subcontexts. :)


How to find out available fonts from within Mathematica?

How to find out available fonts on the system from within Mathematica? When I do               Style["foobar", FontFamily -> "Foobar"]      how do I know which font the displayed output is using/falling back to use?


Changing scroll rate for page down key?

I have a presentation remote that allows me to advance Mathematica slides when in the SlideShow environment. The control sends a `page down` key. Some of my slides extend below the screen window, and `page down` scrolls a page at a time. Is there a way to change the scroll rate associated with a `page down` key- stroke? I'd like to advance the slides by half a page at a time, or a quarter, for example, or even cell-by-cell. The notebook options associated with `ScrollingOptions` seem not to control what I need. My system is MacOSX, running Mathematica 8.0.4.


calling a batch or executable application on Windows

How to run a batch file, send commands and collects output on windows               Run["!C:\\runme.bat"]      it outputs 1 and a window appears and then disappears. I also want to send my script file to python shell and collect its output in mathematica. How to do on Windows?               ReadList["!C:\\Python27\\python.exe", "my_script_file.txt"]


How to adjust the correct ImageSize between two plots

Let's consider the following simple plot               P0 = Plot[Sin[x], {x, -7, 7}, Frame -> True, Axes -> False, PlotLabel ->           Style["Test 1", FontSize -> 20, Black, FontFamily -> "Helvetica"],          AspectRatio -> 1, ImageSize -> 550];      The second one is much more complicated ad we need to create some data in order to replicate the situation               n = 5000;     data = Table[{RandomReal[], RandomReal[], RandomReal[{10^-2, 10^4}],      RandomInteger[{0, 2}]}, {i, 1, n}];      Define a color function               valrange = {-2, 4};     data[[All, 3]] = Rescale[Log10[data[[All, 3]]], valrange];     colfunc[x_, cf_] := If[x[[4]] == 0, Gray, ColorData[cf][1 - x[[3]]]];      Create a colrbar               Clear[colorbar]     colorbar[{min_, max_}, colorFunction_: Automatic, divs_: 150] :=        DensityPlot[y, {x, 0, 0.1}, {y, min, max}, AspectRatio -> 10,        PlotRangePadding -> 0, PlotPoints -> {2, divs}, MaxRecursion -> 0,        Frame -> True, FrameLabel -> {{None, "test"}, {None, None}},        LabelStyle -> Directive[FontFamily -> "Helvetica", 17],        FrameTicks -> {{None, All}, {None, None}},        FrameTicksStyle -> Directive[FontFamily -> "Helvetica", 15, Plain],        ColorFunction -> colorFunction]      A simple contour               C0 = ContourPlot[x^2 + y^2, {x, -1, 1}, {y, -1, 1}, Contours -> {0.5},          ContourStyle -> {{Black, Thickness[0.005]}}, AspectRatio -> 1,           ContourShading -> False, PlotPoints -> 200,           PerformanceGoal -> "Quality"];      and finally the modified density plot               With[{opts = {ImageSize -> {Automatic, 550}}, cf = "Rainbow"},          Row[{Show[          ListPlot[List /@ data[[All, {1, 2}]],           PlotStyle -> ({PointSize[0.005], colfunc[#, cf]} & /@ data),           AspectRatio -> 1, Frame -> True, RotateLabel -> False,           Axes -> None, FrameTicks -> True, FrameLabel -> {"x", "y"},           LabelStyle -> Directive[FontFamily -> "Helvetica", 20],           ImagePadding -> {{60, 20}, {60, 20}}, opts,           PlotLabel -> Style["Test 2", FontSize -> 20, Black,           FontFamily -> "Helvetica"]], C0, PlotRange -> 0.9,           PlotRangeClipping -> True],           Show[colorbar[valrange, ColorData[cf][1 - #] &],           ImagePadding -> {{20, 60}, {60, 40}}, opts]}]]      There are two issues regarding this second complicated plot: (a). For large data sets, (`n` > 10000) the programs needs more than 10 minutes so as to create the plot! Is there any way to speed up the process? (b). Even though I set `PlotRange -> 0.9, PlotRangeClipping -> True`, we see that the frame in all directions does not end at exactly 0.9 but in 0.9 + dx. Why? Now, if we put together the two plot ![plot](http://i.stack.imgur.com/8QyBW.jpg) it becomes evident that size of them do not match. For both plots I used `ImageSize -> 550` but it seems that the second one (the complicated) is smaller. I suspect, that this has to so with the colorbar it carries together. So, my question is: how can I get the second plot match in size with the first? **EDIT** Apparently, each (x,y) point should be treated as a separate list by using `List /@ data[[All, {1, 2}]]`. That's the reason why the code is very slow when we have many points. Unfortunately and strangely enough I cannot use `ListDensityPlot` simply because stupidly it joins by default the points without giving you an option for that!


Understanding `Paste` and how to get a string from the Clipboard to use with `ImportString`

Trying to work on this question I got distracted by my first naive attempt of copying the data and then typing               dat = ImportString[Paste[], "Table"]      > ImportString::string: First argument Null is not a string. >> >   >   >     ImportString[Null, "Table"] >   I do know that typing `dat = ""` and then pasting within the quotation marks does work. Particularly nice is this other solution that unfortunately is limited to MS Windows .NET. But what I want is to understand what is going on, what is `Paste` giving if not a string, and how can I find out what the object is. As a bonus, making the output of `Paste[]` work within `ImportString` would be nice.


how to Export raster data as a tiff unmolested

I feel certain there is a simple answere here.. how do I export image data to a tiff without any scaling? I want to read back in the exact data.               g = Show[Graphics[{Black, Disk[#, 1]}] & /@ Table[RandomReal[{-10, 10}, 2], {50}]];     datain = ImageData[Rasterize[Style[g, Antialiasing -> False], "ColorSpace"-> "Grayscale"]];      as a more simple example just use:               datain = Table[0, {300}, {400}];          Export["test.tiff", Raster[datain], "BitDepth" -> 1, "ColorSpace" -> "Grayscale" ,            ImageSize -> Reverse[Dimensions[datain]]];     dataout = Reverse[ImageData[Import["test.tiff"]]];     datain == dataout    ->> False     GraphicsGrid[{{        Graphics[Raster[datain]],        Graphics[Raster[dataout]],         Graphics[Raster[(1 + datain - dataout)/2]]}}]      ![enter image description here](http://i.stack.imgur.com/kZ4ft.jpg) What you see is the image has been shrunk to accomodate an white margin of about 10 pixels. (Most annoying you wouldn't notice this if you didn't look carefull..) example 2.. ![enter image description here](http://i.stack.imgur.com/ozzFS.jpg) Edit Bill S has the solution.. Either `Image[datain]` or `Image[Raster[datain]]` or this mess:               Graphics[Raster[datain],            PlotRange -> {{0, Dimensions[datain][[2]]}, {0,Dimensions[datain][[1]]}}]      does the job. The last form I guess gives a clue, presumably Export calls Graphics which is padding by default. None of the documented options ImagePadding, ImageMargins, etc turn this off though. Edit 2.. need BOTH of these options...go figure               Graphics[Raster[datain], ImagePadding -> None,  PlotRangePadding -> None]


Use NotebookWrite with Graphics?

I am trying to use NotebookWrite to paste a plot into another notebook. The code looks something like: `ptemp = Show[Plot[x^2,{x,-2,2}],Plot[x^3,{x,-2,2}]]; nb = CreateDocument[]; NotebookWrite[nb,ptemp];` But when I run the code I get an error message: `An unknown box name (Graphics) was sent as the BoxForm for the expression.` Is there any way to use NotebookWrite to insert a graphic? Does there exist any sort of wrapper for Graphics that would make it NotebookWrite-able?


How can preserve my manual edit of an expression when exporting to LaTeX?

**Context** I would like to use the _Mathematica_ front end to pre-process expressions before exporting them to LateX, for the sake of readability. **Example** Say I have this expression                  (16*((-3 + r^2)*BesselI[0, r^2/8]^2 - ((-48 + 16*r^2 + r^4)*BesselI[0, r^2/8]*        BesselI[1, r^2/8])/r^2 +         15*BesselI[1, r^2/8]^2)*Cos[2*\[Theta]])/(3*Sqrt[3]*E^(r^2/4))      which looks like this in _Mathematica_ ![Mathematica graphics](http://i.stack.imgur.com/uriYq.png) Once I edit it by hand within _Mathematica_ , it might look like this: (notice that its more publishable in that form) ![Mathematica graphics](http://i.stack.imgur.com/05BZq.png) (This is a great feature of the Front-End by the way!). If I then select the expression and choose the export to latex menu, _Mathematica_ exports the original (unedited) equation. **Question** How do I tell _Mathematica_ to mind its own business and export to LaTeX the result of my edit, not its re-processing of it? **EDIT** Following the suggestion of @Nasser, I tried ![Mathematica graphics](http://i.stack.imgur.com/fzLvV.png) So it does not really preserve the original expression?


Parallelizing sparse array construction

I have a very large sparse array, and the computation of individual matrix elements is fairly expensive. The Matrix is Hermitian and traceless, so I would like to construct only the sub-diagonal elements explicitly. A sketch of my attempt:               M = SparseArray[{}, {imax, imax}];     SetSharedVariable[M];     ParallelDo[       If[j < i, M[[i, j]] = f[i, j]],       {i, 1, imax}, {j, 1, imax}];      My understanding is that setting M as a shared variable this way is very expensive. Is there a good way to parallelize this process? Note: I have seen examples where people calculate dense matrices by constructing the submatrices on separate kernels, but for my matrix the computation time of a submatrix is difficult to estimate so trying to distribute the computation time manually is difficult.


Constructible numbers

Can Mathematica detect constructible numbers? I know it has `MinimalPolynomial` but for degrees higher than 4 it's not obvious whether a given polynomial yields a constructible number or not. See, e.g., http://en.wikipedia.org/wiki/Constructible_number#Transformation_into_algebra or http://mathworld.wolfram.com/ConstructibleNumber.html


How to set path of IMPORT from excel into Mathematica?

I was able to IMPORT from excel data at the start of my project when both the .nb and EXCEL XLS files were sitting in MyDocument (or some other location), but upon moving both files into my Dropbox location, when I opened my .nb file again, IMPORT fails with 'File not found during Import'? I assume having both in the same directory is not suffice, but rather IMPORT only looks for file as defined by path setting within Mathematica? If so how to change it so that regardless of where I put the .nb and excel files, as long as they are both in the same directory I can do IMPORT?


Changing the x-axis data range

I have a series of data and Ive ploted them by mathematica.how can I change the x-axis scale?for example instead of "x" being between 0-300, I want to plot my data between 0-2 scale. this is my code:               data = Import["Desktop/kmc final result.txt", "List"];     bb = SmoothKernelDistribution[data];     cc = SmoothKernelDistribution[data];     h[y_] = ((1/207) PDF[bb, y])*(PDF[cc, y]);     time = 100;     J[y_] := -1/time Log[h[y]];     plt1 = Plot[J[y], {y, 0, 300}, Frame -> True,        PlotStyle -> {Blue, PointSize[0.004]}, PlotRange -> All]


Adapting old Arrow expressions

I have an old notebook that uses the now obsolete `Arrow` package. For example, I have an expression containing               Arrow[{1,2}, {6,7}, HeadLength -> 0.005, HeadCenter -> 0.5]      I suppose I know how to translate this in absence of options. I should have               Arrow[{{1,2}, {6,7}}]      but how can I obtain the same arrow shape as given by the old-style options using `Arrowheads`?


Indicating the probability that a weather datum is above/below some given value on a geographic map

With help of the previous questions here, I am analyzing weather data as daily `MeanWindSpeed` of some cities with the following code:                 {date, year, month, day, wind} = {1, 1, 2, 3, 2}            cityWind1 = WeatherData["Bodo", "MeanWindSpeed", {{1973, 1, 1}, {2013, 5, 1},"Day"}];       cityWind1[[All, date, year]] = 0            slowWinddays1 = Select[cityWind1, #[[wind]] < 21 &];       DateListPlot[{cityWind1, slowWinddays1}, ImageSize -> 600]      I have two problems.   1. I want to calculate the probability of the days that mean wind speeds higher than 21 km/hr and show it in the plot. It could be monthly or weekly outlet. I know the algorithm is too easy, but sorry guys I am new in town!    2. Most important, how can I show this probability in different geographic regions based on data from the available stations of that region. For example, assign a color to Norway and vary intensity to indicate the probability on the geographic map. That is to say, the more intense the color, the higher the probability.


Put random points into a specific 2D subregion

I want to cover a particular subregion of the x-y plane with a random distribution. As this particular region is not a circle I encounter some problems declaring the permitted zone where to put points. The points must NOT be drawn in the blue zone. As in the graph![enter image description here](http://i.stack.imgur.com/R1IsX.png) And I use the following code to drawing the graph:               mu = 0.000954;     h = x^2 - y^2 + 2 (1 - mu)/Norm[x + mu] + 2 mu/Norm[1 - x - mu];     S =        RegionPlot[h < 3.07, {x, -2, 2}, {y, -2, 2},          Mesh -> None, PlotPoints -> 200, Axes -> True, Frame -> False]      Where `h` is the function. **P.s.:** the drawing process is a bit long if you use more then 200 points, so keep this not so high.


Anti-aliasing a fractal-like bitmap image

I have a .bmp image 9600x5400 that shows a lot of points at various intensities. There are no lines inside this picture - only a lot of points. I would like to apply anti-aliasing on the image to make it smoother (and more beautiful). Can Mathematica help me on that? ![enter image description here](http://i.stack.imgur.com/FzHKm.jpg)


Binomial Distribution (binomial model inspired by Merton) Hi I want to do the following and I hope that anyone of you can help me out. In short, I have a portfolio consisting of 10 companies, whereas their asset values are driven by a common economic background factor u and the assets in question are correlated. Now I want to calculate the probability that e.g. **3 of 10 companies default simultaneously**. In order to do so, I choose a mixed binomial Merton model. whereas the probability that a given number of companies default is given by: ![enter image description here](http://i.stack.imgur.com/H6bht.png) whereas u is the common economic background factor and a standard normal random variable. C(i) is given by: ![enter image description here](http://i.stack.imgur.com/J3Tuz.png) whereas I substituted r with μ Then I entered the following definitions:               V1 = 100; D1 = 70; μ1 = 0.2; σ1 = 0.1;     V2 = 110; D2 = 75; μ2 = 0.25; σ2 = 0.2;     V3 = 95; D3 = 72; μ3 = 0.1; σ3 = 0.2;     V4 = 120; D4 = 100; μ4 = 0.4; σ4 = 0.3;     V5 = 120; D5 = 110; μ5 = 0.2; σ5 = 0.2;     V6 = 100; D6 = 65; μ6 = 0.25; σ6 = 0.12;     V7 = 99; D7 = 85; μ7 = 0.3; σ7 = 0.05;     V8 = 125; D8 = 76; μ8 = 0.2; σ8 = 0.3;     V9 = 105; D9 = 100; μ9 = 0.23; σ9 = 0.02;     V10 = 100; D10 = 75; μ10 = 0.2 ; σ10 = 0.2;          T = 5; ρ = 0.5; \[ScriptU] = 0.25;          Evaluating Subscript[C, i]          C1 = (Log[V1/D1] + (μ1 - 0.5*σ1^2)*T)/(σ1*Sqrt[T]);          C2 = (Log[V2/D2] + (μ2 - 0.5*σ2^2)*T)/(σ2*Sqrt[T]);          C3 = (Log[V3/D3] + (μ3 - 0.5*σ3^2)*T)/(σ3*Sqrt[T]);          C4 = (Log[V4/D4] + (μ4 - 0.5*σ4^2)*T)/(σ4*Sqrt[T]);          C5 = (Log[V5/D5] + (μ5 - 0.5*σ5^2)*T)/(σ5*Sqrt[T]);          C6 = (Log[V6/D6] + (μ6 - 0.5*σ6^2)*T)/(σ6*Sqrt[T]);          C7 = (Log[V7/D7] + (μ7 - 0.5*σ7^2)*T)/(σ7*Sqrt[T]);          C8 = (Log[V8/D8] + (μ8 - 0.5*σ8^2)*T)/(σ8*Sqrt[T]);          C9 = (Log[V9/D9] + (μ9 - 0.5*σ9^2)*T)/(σ9*Sqrt[T]);          C10 = (Log[V10/D10] + (μ10 - 0.5*σ10^2)*T)/(σ10*Sqrt[T]);      Now i am not sure How to calculate the individual probabilities and add them up. Would you suggest first to integrate the terms on the right hand side of the integral or is it possible to enter the whole function in Mathematica considering both the Normaldistribution and the Binomialdistribution? I would be very thankful for any advise. Thanks.


Function that puts zero after a certain decimal in every element of the matrix

We know that in Mathematica there is some default precision, which you can also change. This means, that after a certain decimal(fixed by the precision), the computer puts pseudo random numbers. I am looking for a function F that would put everything zero after a certain decimal. Let us say I want this to be the fourth decimal, then F[0.12345678]=0.12340000 Does such function exist? Thank you


Multiple scripts run using same kernel

I have an external program that calls Mathematica scripts upon certain events. Each script requires a large Mathematica library to load (takes a while). Is there some way to run an initial script that loads the library, then each following script call uses the same Kernel?


Front End - Bug in Edit->Find?

As a beginner I make notes in my notebooks on what I am learning as I go along, and I have also referenced the help files by pasting hyperlinks from them - this seems to break the Find function. Is it really a bug (in V9), and if so is it likely to have any other effects? To reproduce the issue, try this... Create a blank notebook, enter some text including a keyword (e.g. MinValue) in a text cell. Select the keyword and press F1. Right click the target word in the help windw where it first appears in blue beneath the heading and select copy hyperlink. Paste the clipboard content at the beginning of the text cell, which now contains the pasted hyperlink (1st) and original typing 2nd. Go to the beginning of the notebook, invoke Find, enter e.g. MinValue. Find next will find the pasted hyperlink. Pressing Find Next again will not move the found location. **Update - Bug Confirmation** WRI Case 652039: they confirmed by email 20/03/2014 that they had reproduced it and had passed it to development to fix, they hope to fix it in the next release.


Chain rule while differentiating

I am trying to find the derivative of a function defined in polar coordinates with respect to $x$ and $y$. My function is defined as follows: $ v_x(r, \theta ) = v_r \cos (\theta ) - v_{\theta }\sin (\theta ) $ To do this, I start by defining the relation between Cartesian and Polar coordinates:               (* Define the mapping between Cartesian and Polar coordinate systems. *)     x[r_, θ_] = r Cos[θ];     y[r_, θ_] = r Sin[θ];      Then I define the function and find its derivative with respect to $x$:               Subscript[v, r][r_, θ_] = Subscript[v, r][r, θ] Cos[θ] - Subscript[v, θ][r, θ] Sin[θ];     D[Subscript[v, r][r, θ], x]      I am getting 0 because _Mathematica_ is not considering the relation between $r$ and $x$. Is there anyway to tell _Mathematica_ to use the chain rule to find the derivative of $v_x$ with respect to $x$? The other problem is that _Mathematica_ is considering the subscripts to be variables (which is reasonable), is there anyway to tell it that the subscripts are only notational symbols? **EDIT** : The function is better defined as:               vx[r_, θ_] = vr[r, θ] Cos[θ] - vtheta[r, θ] Sin[θ];      to avoid evaluating subscripts and possibly having recursion.


Creating a list of PopupMenus that dynamically update an element in a list

So as the title says I am trying to make a list where each element is determined by a users choice of an element in a PopupMenu. My first attempt:               test = Table["A", {5}];     Table[PopupMenu[Dynamic[test[[n]]], {"A", "B", "C"}], {n, 5}]      Returned the following error               Part::pspec: Part specification n is neither an integer nor a list of integers.      For some reason the dynamic(?) would not allow me to refer to specific elements in the list. I then tried to circumvent this issue by introducing an extra variable _temp_ :               Table[temp = n;PopupMenu[Dynamic[test[[temp]]], {"A", "B", "C"}], {n, 5}]      However, all this did was create 5 PopupMenus that all referred to the $5^{\text{th}}$ element of the list _test_. I tried to put a `Setting[]` around the `Dynamic[]`, but since that removes that effect of `Dynamic[]` nothing happened at all. Any suggestions would be greatly appreciated.


How to draw a network from a dataset reporting the labels of nodes of every link?

I have a dataset in format `.txt` of a directed network, containing a matrix `A` of dimension `m x 2`, where each row gives the labels of two nodes showing a direct link. For example, when the network has $4$ nodes, the matrix `A` could be               A = [1 2; 1 3; 2 1; 2 4; 3 2; 4 1; 4 2]      where the first row means that there is a link from `1` to `2`, the second row means that there is a link from `1` to `3`, etc. Could you suggest me a way to draw the network specified by `A` in _Mathematica_?


Plot 3D density

I have data that is in four columns. The x y and z are just the coordinates and the fourth is my data. This is not a function. This is electron density in a copper cell and I'm trying to display it in a way that makes sense. Any help would be appreciated. I was semi-successful in gnuplot but it was hard to see and I could only specify certain boundaries. using `($1:$2:($4>0 && $4<2 ? $3/0)` This might be slightly wrong, but you get the picture. I was saying to only plot z if the data was between certain bounds. There must be a better way and I need your help. Thanks. Here is the structure. ![enter image description here](http://i.stack.imgur.com/f2m3U.png)


MathLink wrapper for NIntegrate

I wonder if I can benefit from the Mathematica numerical quadrature routines in a way which integrates completely into an existing C-program. To be more specific I have C-program which does numerical quadrature using C-libraries like GSL (Gnu Scientific Library). These library functions are used by initializing data structures and running quadrature routines which take pointers to C-functions representing the the integrand and a pointer to a parameter structure which is fed to the integrand function as second parameter. Finally the data structures are freed. There is a set of functions for various kinds of integrands, but obviously there are some routines in Mathematica which are not implemented in the GSL. I wonder now if it is worth attempting to write wrapper functions for `NIntegrate` using MathLink such that I can use Mathematicas integration routines in just the same way as I would use C-library functions. Maybe there are MathLink examples out there which come close to what I want to achieve?