Can Table be used inside Manipulate?

**EDIT: CHanged the code. Please try again t see if it works well on our PCs.** I am creating a simple Manipulate[] notebook. However when I place Table[] in the code, like:               Manipulate[       OK = True;                ai = ConstantArray[0, MaxIter + 1];       bi = ConstantArray[0, MaxIter + 1];       ci = ConstantArray[0, MaxIter + 1];      ai[[1]] = a0; bi[[1]] = b0; ci[[1]] = (ai[[1]] + bi[[1]])/2;      Table[ (*This instruction causes problems*)       a = ai[[j - 1]]; b = bi[[j - 1]]; c = ci[[j - 1]];       If[(f /. x -> a) (f /. x -> c) <= 0, ai[[j]] = ai[[j - 1]];         bi[[j]] = ci[[j - 1]];,         If[(f /. x -> b) (f /. x -> c) <= 0, ai[[j]] = ci[[j - 1]];           bi[[j]] = bi[[j - 1]];, OK = False; break;];];       ci[[j]] = (ai[[j]] + bi[[j]])/2;       , {j, 2, i}];           If[OK, Show[Plot[f, {x, a0, b0}, PlotStyle -> Thick],         PlotLabel -> "Metoda bisekcji", ImageSize -> Large]]      ,       (*controls*)           Dynamic@Column@{         Control[{{f, x^2 - 1, "f(x)="}, {x^2 - 1, Cos[x] - x}}],         Control[{{method, "Bisekcji", "Metoda:"}, {"Bisekcji", "Newtona",             "Iteracji prostej", "Siecznych"}}],         Sequence @@           If[method == "Bisekcji" ||             method ==              "Siecznych" , {Control[{{a0, 1/2,                "\!\(\*SubscriptBox[\(a\), \(0\)]\)="}}],             Control[{{b0, 2,                "\!\(\*SubscriptBox[\(b\), \(0\)]\)="}}]}, {Control[{{x0, 2,                "\!\(\*SubscriptBox[\(x\), \(0\)]\)="}}]}],         Control[{{i, 1, "Iteracja"}, 1, 5, 1}]         },      (*Initialization*)      Initialization :> (        MaxIter = 5;        )       ]      The cell containing the GUI keeps evaluating all the time and the displayed content keeps being refreshed and looks like shaking. Is it normal?


How to use Mathematica in my Problem as I would use it in Matlab

I would like to calculate the convolution of a function with itself for $n$ times. Let $n$ be $10$. For $n=1$, I wont make any calculation and $f0$ is my function, when $n=2$, I will convolve $f0$ with itself and get $g=f0*f0$ when $n=3$ I will get $gg=g*f0$ etc.. As it can be seen the total number of convolutions that I need to make is $9$. At each iteration I will compute some other functions. In Matlab I do it as follows               h=f0;     for n=1:9     some computations related to "f0"     h=conv(h,f0);     some computations related to "h"     end      I would like to do the same in Mathematica and below is the code that I typed:               f0[x_] := PDF[NormalDistribution[-2, 2], x]     f1[x_] := PDF[NormalDistribution[2, 2], x]               q[1, B_, A_, f_] := f          q[n_ /; n > 1, B_, A_, f_] :=Block[{\[Omega]},q[n, B, A, f] =Function[x,Evaluate[Integrate[q[n - 1, B, A, f][\[Omega]] f[x - \[Omega]],{\[Omega], B, A}]]]]          p[n_, B_, A_, f_] :=Integrate[q[n, B, A, f][x], {x, -\[Infinity], B}] +Integrate[q[n, B, A, f][x], {x, A, \[Infinity]}]      In short $q$ is calculating the convolution and $p$ some integrals over a given $q$. If I want to calculate for example               Sum[p[n, B, A, f0]*(k3*n + k2*p[n, B, A, f1]), {n, 1, 10}]      where $k2$ and $k3$ are some constants. Then Mathematica will make 108 convolutions and the following calculations. Instead I can make the same thing in Matlab with 9 convolutions and the following calculations. As a result of this I decided to change my code parts as follows               q0[1] := PDF[NormalDistribution[-2, 2], x]     For[n = 2, n < 10, n++,q0[n][B_, A_] :=Convolve[q0[n - 1][B, A], f0(UnitStep[x - B] - UnitStep[x - A]), x,y]]      this code shows what I want to do but It is incorrect. I want to calculate q0[1][x], q0[2][x], q0[3][x],.. which are simply the one time, 2 times, and 3 times convolutions of $f0$ with itself (in the range from $B$ to $A$ ). $$q_n(x)=\int_{B}^A q_{n-1} (\omega)f(x-\omega)\mathrm{d} \omega,\quad q_1=f,\quad n\geq 1.$$ I would like to do some other operations for example               Sum[p[n, B, A, f0]*(k3*n + k2*p[n, B, A, f1]), {n, 1, 10}]      Thank you very much. Please let me know if something is unclear in the same for loop. How I can manage it?


Double series over primes

I'm very curious if the following double series over primes has a closed form: $$\sum_{k \in \mathcal{P}}\sum_{n \in \mathcal{P}}\frac{1}{k\;n(k+n)^2}$$ where $\mathcal{P}$ denotes the set of all prime numbers.   Could you help here with `Mathematica` coding?


Partial products in prime steps

I am trying to find out partial products going up in prime steps for Euler's product formula $$\prod_{p} \frac{1}{1-p^{-s}}$$ Trying things like               s=10;     Product[1/(1-p^(-s)), {i, p, 100p, Prime[p]}]      I am clearly a little lost!


Modeling neural excitation with a non-linear differential equation

I think I have a special problem and I am not sure how to search for an answer, so I thought I would try here. I am working with the so called FitzHugh-Nagumo model which describes very simple neurons by the following equations:               u' = v - 1/3*v^3 - u     v' = u + a      where `a` is the excitation threshold. If `a` is greater than 1, the system is in the so called excited state. So there is one fix point in which all trajectories will lead for `t -> ∞`. With the `NDSolve` function there is no problem computing this for every initial condition I want, e.g., the following:               s = NDSolve[{ε*u'[t] == u[t] - 1/3*u[t]^3 - v[t], v'[t] == u[t] + a,        u[0] == 0.5, v[0] == 0.5}, {u, v}, {t, 200}, MaxSteps -> 10^6]      If the system now is excited a little, nothing special happens, it just relaxes back to the fixpoint again. But if the excitation is large, the system can make a loop before it relaxes. And that would be exactly a neural pulse. So my problem is how to tell _Mathematica_ that it should excite the system again after it reaches its fix point. I already found the `EvenLocator` function, which gives me the `t` value, when `u` or `v` is close to the fixed point:               Method -> {"EventLocator", "Event" -> u'[t] - 0.00001, "EventAction" -> ?}      with the value in `Event` I can control how close my system is at a fix point. Now I want the dynamic variables `u` and `v` to jump to a new point above the threshold and start to move through the dynamics again. So here are the questions:   * Can I use the `EventLocator` for what I want and is `EventAction` the right instrument?   * What possibilities do I have to simulate such excitation (something continuous would be nice)?   * Or am I totally on wrong direction? Maybe it is important to state that I use Mathematica 6.0 at the moment. * * * Update: thanks for your help! Your solution is very interesting for me because I also want to solve the problem in more Dimensions, but in my special case in 0D I have another problem: There is no travelling pulse that excitates element by element. So I need another trick to simulate something like this. But studying your solution I had an idea: because there is no diffusion (of course!) I need something like a virtual excitation from the neighbors to restart the pulse. So maybe it is possible to simulate just two neighbors and have something like very small 1D model. So the more dimensional approach maybe can help me in terms of simulating such a "virtual diffusion". Do you know what I mean? The point is, that this is only interesting if it would save resources well compared to a full 1D model. Otherwise it probably would not make sense to have a 0D model ... What do you think?


Avoiding grid lines inside filled area in RegionPlot exported as PDF

Basically the same question as here, but now with regions which have opacity.               RegionPlot[x^2 + y^2 < 1, {x, -1, 1}, {y, -1, 1},        PlotStyle -> Opacity[0.5, Black]];     Export["tmp/region.pdf", %]      How do I remove the black lines when exporting to pdf?


Operations perform differently in notebook and terminal interfaces

The following command executed on a Raspberry Pi equipped with a RaspiCam behaves differently depending on whether the command is run from the terminal (via `wolfram`) or a notebook (via `mathematica`):               <<"!raspistill -t 5 -k -o image.jpg"      In the terminal, the function behaves as expected: a preview window appears and raspistill maintains control until the user presses Enter twice. In the notebook interface, however, raspistill behaves _as if_ it is receiving keypresses and eventually exits. It is possible to work around this issue to execute a terminal which calls raspistill, e.g.:               <<"!lxterminal -e \"raspistill -t 5 -k -o image.jpg\""      Does anyone know why the behavior of executing external commands would differ between the two flavors (?) of Mathematica, or how I might go about debugging this issue further?


mathematica startup time

I have Mathematica 7 and 8 installed on my laptop. Mathematica 7 starts quite fast, but Mathematica 8 is extremely slow to start. In the Option Inspector I canceled the "welcome screen" option at startup, and I tried canceling "opening a new notebook" at startup so that only the front end opens without any blank notebook, but as soon as I open a notebook, the whole front end freezes for about half a minute before opening it. As I said I do not experience this problem with M7. In this forum I have already found something related to my problem here but it doesn't answer it. I ran the command shown there which shows the time M8 spends to start and I got the following output :               {      {"Initializing kernel connections..." -> 0.265},      {"Initializing cell styles..." -> 0.764},      {"Initializing fonts..." -> 1.076},      {"Initializing menus..." -> 1.108},      {"Initializing defaults notebook..." -> 1.654},      {"Initializing defaults clipboards..." -> 2.278},      {"Initializing internal preferences..." -> 2.418},      {"Initializing kernels..." -> 3.619},      {"Opening Welcome Screen..." -> 12.059},      {"Closing Splash Screen..." -> 12.09},      {"Preloading Favorites..." -> 12.137},      {"Handling CommandLineOptions..." -> 12.137},      {"Opening Files..." -> 12.137},      {"Do Startup Action..." -> 12.137},      {"Finished" -> 12.137}     }      and as you can see it seems that most of the time is spent on opening the splash screen just to close it 20 ms later !!!!!!! Do you guys have any idea how to overcome this. I have asked support for this but ... well ... extremely poor assistance. So I am asking here. Thank you in advance :)


I'm relatively new to _Mathematica_ programming, so forgive my rather unsophisticated question: I'm trying to do a Monte Carlo simulation using geometric Brownian motion (GBM). I want to write a indicator function which produces is 1 if my GBM stays within a certain corridor `[L, U]`. I found a function which produces the paths of my GBM:               data = RandomFunction[       GeometricBrownianMotionProcess[0.01, .15, 100], {0, 1, .01}, 100]      How can I access `data` so that I can write the indicator function? EDIT: Ive got a follow up question: Let's say one sample path is the following list               pts=data["Paths"]            pts         {{0,100},{0.01,98}...}      How can I select from all my pahts only those values where the x-variable is >=1? I tried `Select[pts,#1.0&]`, but this gives me an empty list.


Another Sort with multiple criterion

I have a list               list={{ω->0.538826+1.31221 I},{ω->-0.538826+1.31221 I},{ω->-1.2444-0.68023 I},{ω->1.2444-0.68023 I},{ω->0.496864+1.32811 I},{ω->-0.496864+1.32811 I},{ω->1.22187-0.719147 I},{ω->-1.22187-0.719147 I},{ω->0.454442+1.34261 I},{ω->-0.454442+1.34261 I},{ω->1.19811-0.757303 I},{ω->-1.19811-0.757303 I},{ω->1.17316-0.794657 I},{ω->-1.17316-0.794657 I},{ω->0.411617+1.35568 I},{ω->-0.411617+1.35568 I},{ω->-1.14704-0.831174 I},{ω->1.14704-0.831174 I}}      and I would like to sort it by ascending positive. I tried with the Sort command               Sort[list, (Re[#1[[1, 2]]] < Re[#2[[1, 2]]] && Re[#1[[1, 2]]] > 0) &]      but it does not sort them in desired order:               {{ω->1.14704-0.831174 I},{ω->-1.14704-0.831174 I},{ω->-0.411617+1.35568 I},{ω->0.411617+1.35568 I},{ω->-1.17316-0.794657 I},{ω->1.17316-0.794657 I},{ω->-1.19811-0.757303 I},{ω->1.19811-0.757303 I},{ω->-0.454442+1.34261 I},{ω->0.454442+1.34261 I},{ω->-1.22187-0.719147 I},{ω->1.22187-0.719147 I},{ω->-0.496864+1.32811 I},{ω->0.496864+1.32811 I},{ω->1.2444-0.68023 I},{ω->-1.2444-0.68023 I},{ω->-0.538826+1.31221 I},{ω->0.538826+1.31221 I}}      How am I wrong? Thanks in advance


Using a table to format a grid

Ok, I can't wrap my head around this because I don't know Mathematica well enough yet, so I'm asking for help, at least a direction to explore in. I have a Grid: `positionsDisp = Grid [{ {1, 4, 7, 10, 13}, {2, 5, 8, 11, 14}, {3, 6, 9, 12, 15} }];` And I have a list of lists, each 5 numbers, one for each column of the positionsDisp grid, such as {1,4,7,10,13}, or in aggregate: `{{1, 4, 7, 10, 13}, {1, 4, 7, 10, 14}, {1, 4, 7, 11, 13}, {1, 4, 7, 11, 14}, {1, 4, 7, 11, 15}, ...}` Finally, I have a grid of positionsDisp grids: `Grid[Table[reelPositionsDisp, {9}, {11}], Frame -> All]` Now, here is the issue: I want to highlight the positions in the final grid according to the quintuples in my list of lists, so that for the first element of the list, the grid would be highlighted or framed at positions 1, 4, 7, 10, 13 in the first grid, positions 1,4,7,10,14, etc. The goal is for the final grid to show all paths across the columns traversing only adjacent positions (for example, 1,6,7,12,13 is not a valid path). I've tried Map to map a function over the final grid, but that requires a table iterator, and I'm not sure what function I would use anyway. I've seen a lot of formatting examples, but they seem to be rather "hardcoded". I thought about addressing each column/row, but that would require table iteration again. What approach is best? Or even better, what is a workable solution? It's purely a cosmetic thing, but my audience is more visual than mathematical.


What is going wrong when I save an animation as a SWF-file?

The first I am trying to export animations from _Mathematica_ to a file and then to LaTeX. Don't assume I know anything about what I'm doing. The following definitions defines the still image of a single frame. It is a stick of length $k$ that has two pivot points: one sliding along $x$-axis, $\{\cos u,0\}$, and the other, along the $y$-axis. $\{0,\sin u\}$, so the distance between the two pivots is always equal to $1$ irrespective of the value of the parameter $u$. One end of the stick is at the $y$-axis pivot, and the other is determined by the length of the stick. That other endpoint draws an ellipse, as $u$ increases from $0$ to $2\pi$.               tikku[u_, k_] :=       Show[{ParametricPlot[{k Cos[x], (1 - k) Sin[x]}, {x, 0, u}],         Graphics[{Line[{{k Cos[u] + 0.05 Sin[u], (1 - k) Sin[u] +               0.05 Cos[u]}, {0.05 Sin[u],              Sin[u] + 0.05 Cos[u]}, {-0.05 Sin[u],              Sin[u] - 0.05 Cos[u]}, {k Cos[u] -               0.05 Sin[u], (1 - k) Sin[u] - 0.05 Cos[u]}, {k Cos[u] +               0.05 Sin[u], (1 - k) Sin[u] + 0.05 Cos[u]}}]}],         Graphics[{PointSize[0.02], {Point[{Cos[u], 0}],            Point[{0, Sin[u]}]}}]}, PlotRange -> {{-2.2, 2.2}, {-1.2, 1.2}},        AspectRatio -> Automatic, AxesOrigin -> {0, 0}, Axes -> True]      Then I create an animation with               movie = Animate[tikku[u, 1.8], {u, 0, 2 Pi}, Alignment -> Center]      That is displayed as expected. But when I export that file with the command               Export["Analyysi I/2013/ellipsi.swf", movie]      and open the resulting `.swf` file with _Adobe Reader_ I get the following error message (my translation from Finnish): `"Adobe Reader couldn't open the file "ellipsi.swf", because it is of an unsupported type...."` I can open the `.swf`-file in IE. If I export the animation as an .avi-file instead, then I can also view it in _Windows Media Player_. However, something seems to have gone wrong while exporting, because at the beginning (and also at the end) a frame with _Mathematica_ code is shown instead of the first frame of the animation. Questions:   1. What should I do to make it viewable in _Adobe Reader_? (I just installed flashplayer, but that didn't help) This is kinda crucial for including the animation to a slide set produced by _LaTeX_.   2. What should I do to get rid of that extraneous first frame?


ParallelTable and plotting result of own define funtion

I define function which return a list of numbers               KSmoothTest[vy_, b_] := Block[{n, res, i, j, weights},        n = Length[vy];        weights = Table[K[i/b], {i, 0, Length[vy] - 1}];        Table[Sum[weights[[Abs[i - j] + 1]]*vy[[j]], {j, 1, n}]/          Sum[weights[[Abs[i - j] + 1]], {j, 1, n}], {i, 1, n}]        ];      I want run this code               Table[ListLinePlot[KSmoothTest[RandomReal[{-10, 10}, 10], 9]], {i, 1, 10}]      in parallel using ParallelTable. I try this               ParallelTable[ListLinePlot[KSmoothTest[RandomReal[{-10, 10}, 10], 9]], {i, 1, 10}]      but Mathematica return graphics like this: ![](http://i.stack.imgur.com/Tbpat.gif) What is wrong? Why Mathematica return empty graphic? PS: sory for my english, i am not strong in it **EDIT:** K[t_]:=1.078222*Exp[-(t^2/0.273800)];


How can I set an image to be the Notebook's background?

Is it possible to set a notebook's background to a nonscrolling image?


Position function not always retuning an answer even with no apparent problems

I'm having some problems with `Position`. Sometimes it will give an empty list instead of the actual position of the element I am looking for when that element is specified through some other code but will return the correct position when the element is specified directly as a number as in the minimum working example below.               data = {{0.1, 0.0001683}, {0.2, 0.00035754}, {0.3, 0.00056711}, {0.4,         0.00078986}, {0.5, 0.0010333}, {0.6, 0.0010333}, {0.7,         0.0015758}, {0.8, 0.0018738}, {0.9, 0.0022054}, {1.,         0.0025706}, {1.1, 0.0029788}, {1.2, 0.0034366}, {1.3,         0.0039831}, {1.4, 0.0046433}, {1.5, 0.0055203}, {1.6,         0.0068061}, {1.7, 0.010939}, {1.8, 0.031246}, {1.9, 0.054948}, {2.,         0.076556}, {2.1, 0.098521}, {2.2, 0.12551}, {2.3, 0.1585}, {2.4,         0.1921}, {2.5, 0.22544}, {2.6, 0.25798}, {2.7, 0.28992}, {2.8,         0.32051}, {2.9, 0.35095}, {3., 0.38104}}          interpol = Interpolation[data];          q = FindRoot[interpol[x] == 0.159, {x, 2.9}][[1, 2]]     (*2.3015*)          xlow = Floor[q, 0.1]     (*2.3*)          Position[data[[All, 1]], xlow]     (*{}*)          Position[data[[All, 1]], 2.3]     (*{{23}}*)      When running v8 on xP this code gives `{}` for the first output and `{{23}}` for the second. This type of error is referenced in the Possible Issues section of the documentation for `Position` in v8 and v9 but no advice is given.               In[1] := Position[Range[-1, 1, 0.05], 0.1]     Out[1] = {}      I've tried putting `N` everywhere I can to solve it as I thought it could just be a precision or representation issue ( i.e. 2.3 vs 23/10 ) but with no success. Does anyone have nifty work around or solution to this that I am missing please?


Use of own unit abbreviations

I have been using AutomaticUnits in my calculations. In this package all I had to do was to declare the units I wanted e.g. mm, kN, sec, kPa, litres etc. in terms of existing units, and then use them in my calculations. To get an answer in the units I needed I could use `Convert[expression,unit]` eg. `Convert[100kNm/(1000cm3,MPa)]`. This seemed simple and allowed me to write my calculations down in the way I would if I were doing the calcs by hand. I have looked at `Quantity` and the information on units in v. 9 and cannot understand how I can achieve the same results. By the way, the use of Wolfram Alpha is not desirable except as an occasional reference source. I do not always have an internet connection and could not include the verbosity that results. Any thoughts?


Combined fitting via NonlinearModelFit

I am trying to fit my data to a combined function model. Say I have two functions with some common parameter(s)               f[x_]:= a*x^2 + b*x + c     g[x_]:= d*x^2 + e*x + c      Also, I have separate data and errors for these two functions. Performing the fit is easy: I create the chi-squared function manually and minimize via `NMinimize`. In my work the code is rather lengthy, but looks similar to               Chi2[data_, errors_, dataprime_, errorsprime] :=      Sum[((data[[i, 2]] - f[data[[i, 1]]])/errors[[i]])^2,{i, 1, Length[data]}] +      Sum[((data[[i, 2]] - g[data[[i, 1]]])/errors[[i]])^2,{i, 1, Length[data]}];      where `data` and `dataprime` are the different datasets for the functions `f[x]` and `g[x]` respectively (`data[[i,1]]` represents, say, the i-th x value while `data[[i,2]]` represents what `f[data[[i,1]]]` should be, say, y). However, I would like to perform, using the values obtained from `NMinimize`, a NonlinearModelFit. This would give me error estimation for parameters (which are hard to get with my current technique) and also provides confidence band levels and other features which are quite useful to me. However, I haven't been able to find the way to implement a NonlinearModelFit ... any suggestion? (I already did a search and found some links related to calculating the errrors through the Hessian. However, this is not convenien for me due to errors in calculating the inverse of the Hessian.) Thanks in advance!


Version 9 Blue Screen or Self-Test Error on Windows 7 64-bit

**Update** There is now an official response from Wolfram Support on this issue. Having recently installed _Mathematica_ version 9 64-bit on Windows 7, I keep running into Self-Test Errors evaluating certain expressions. For example, if I evaluate:               Piecewise[{{0, x < 10}, {1, True}}]      then this message pops up: > INTERNAL SELF-TEST ERROR: NoteFont2|c|1982 The output cell did not render properly and, when I hover over the cell, the following additional message pops up: > The stretchable character 0xf361 in the Mathematica5Mono font (size 13) has > a repeating piece (0xb2) that is zero size. The same SELF-TEST error pops up if I type `ESC`pw`ESC` in an input cell. This error occurrs on two different Windows 7 machines, installing the Standard Edition on one and the Home Edition on the other. Both machines also have versions 7 and 8 installed. On the Standard Edition machine, it is very likely that _Mathematica_ had been run many times before installation after the last reboot. But on the Home Edition machine the installation was the first thing done after power-on. Interestingly, my pre-existing installations of version 7 and version 8 both exhibit this behaviour now. They worked prior to installing version 9. How can I fix this? **Update** Some users report getting a Windows "Blue Screen of Death" (BSOD) performing these or similar operations.


How Do I Upgrade a Show to a Manipulate?

I'm trying to ilustrate the difficulties in assigning bins to a data set and then running a comparison of the bins against a binomial distribution for all values- n, p. The code I have so far is (mostly thanks to Nasser):               Manipulate[Show[Histogram[dataB, {-0.5, 7.5, c}, "PDF"],        DiscretePlot[PDF[BinomialDistribution[n, p], x], {x, 0, 20},         PlotStyle -> PointSize[Large]], ImagePadding -> All],       {{c, 8, "Column Width"}, 0, 4, .1, Appearance -> "Labeled"},       {{n, 7, "Number Of Quarters"}, 1, 20, 1, Appearance -> "Labeled"},       {{p, 0.5, "Fair Coin Toss"}, 0, 1, 0.01, Appearance -> "Labeled"}]      The remaining problem, scaling the number of quarters in the binomial to the width of the X axis. Right now my X axis ranges from 0 to 7.5 in agreement with the range of the numbers in my data set. I think I need two X axes. One to illustrate the range of the numbers in my data set. And a second X axis to illustrate the number of quarters in the binomial ensemble (1 to 20). That's what I think. @Nasser


What is the equivalent of MATLAB's "timealign" function? Given two sequences (lists of values) and offsets, timealign will insert 0's into sequences to align them so they have the same number of elements and are thus aligned for the purpose of doing operations across both sequences in parallel.


Proper way to handle free variables in manipulate/plot?

It took me a while today to figure out that `Manipulate` (used with `Plot`) requires that the variable I'm manipulating be an actual parameter of the thing that I'm manipulating. That is, if I have something like:               foo = Exp[2 x+y]     Manipulate[Plot[foo, {x, 0, 10}], {y, 0, 10}]      It will not work as desired, but if I have:               ffoo[x_, y_] := Exp[2 x+y]     Manipulate[Plot[ffoo[x, y], {x, 0, 10}], {y, 0, 10}]      It will. I can't help but wonder; what is the general correct approach here? To me it feels slightly "wrong" that I should need to declare all the free variables for my statements as arguments. But maybe this is just something I should get over. In my case, it means I need to change, say, an arbitrary amount of places where I might call these to get various things (like eigenvectors with free parameters) and do a bunch of work converting them into function calls? Just because I want to use them in plots? My actual approach was to write little "plot functions" for the particular bits I wanted to plot, and I then I did a little probably-inappropriate trick of just sneaking them into functions:               foofunc[a_, b_, c_] := Evalulate[foo]      (Knowing that `foo` contains free variables named as "a", "b", etc...). It seems, though, that there must be a better way of just asking Manipulate to consider implicit parameters (or whatever their formal name is; I tried a bit of searching and wasn't able to find anything about this; though I imagine it's fairly common). Thanks for any advice.


How to select minimal subsets?

I am a newbie, so please point me in the right direction if you feel this question has been answered somewhere else before. Here goes: Suppose I have a list like this:               {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}, {a, e, d, f}}       I want to strip this list of all its non-minimal sublists, by which I mean that I want to check whether each set contains a subset that's already somewhere else in the set. So, in this case, the output would need to be:               {{a,b},{b,c},{a,c,e},{a,e,d,f}}      Where {a,b,c} is dropped either because it contains {a,b} or {b,c} and {a,b,e} is dropped because it contains because it contains {a,b} **Edited to add:** I have found one solution so far which works like this:               list = {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}, {a, e, d, f}}     Intersection[DeleteDuplicates[Apply[Intersection, Tuples[list, 2], {1}]], list]      which generates the desired result:               {{a, b}, {b, c}, {a, b, c}, {a, b, e}, {a, c, e}}      What this does: It generates all 2-tuple subsets of the list with itself. Then, the intersection of all these tuples are calculated and all duplicates are deleted. Finally, the resulting list is compared with the original list: the intersection is than the desired result. But: this list has length 6, so the tuple-list is 6^2 = 36. I would like this formula to also work on lists of lengths around 500 to 1000, which would mean the tuple-list is between 250 000 and 1 000 000. If anyone is able to point me to an easier way to do this calculation, I would be very much obliged.


Mouse motion heat map - live visualization and analysis

Mouse motion heat map is an great way to study spatial attention distribution, styles of movement, reaction, etc. I am trying to design a code that visualizes such heat map. The requirements: 1) It must be real fast and 2) it must run for long time - no memory overload, etc. Simply collecting data points from 'MousePosition' in a list would probably run into a memory and slow interpolating graphics problems (unless you guys can prove otherwise ;-) ). So I came up with the idea of collecting data in an 'ArrayPlot'. This is pretty fast:               Manipulate[      IC = If[MousePosition["Graphics"] == None, IC, "fake",        Chop@Mod[IC + splash[100, 20] @@             Floor[{100 - #2, #1} & @@ MousePosition["Graphics"]], 10^6]];      ArrayPlot[IC, PlotRange -> All, PlotRangePadding -> 0,        Frame -> False, ImageSize -> 400, ColorFunction -> "TemperatureMap"]      , FrameMargins -> 0, AppearanceElements -> None      , Initialization :> (        IC = SparseArray[{{1, 1} -> 0., 100 {1, 1} -> 0.}];        splash[n_, r_][x_, y_] :=          SparseArray[Flatten[Table[{1 + Mod[i, n], 1 + Mod[j, n]} ->               1. Exp[-((i - x)^2 + (j - y)^2)/(n/10.)], {i, x - r,               x + r}, {j, y - r, y + r}]~            Join~{{1, 1} -> 0., n {1, 1} -> 0.}, 1]])]      This is an insight into how handwriting proceeds through time, where the hand spends more time, which part are more difficult to draw: ![enter image description here](http://i.stack.imgur.com/Ol80G.png) And here some very basic type of further analysis or visualization:               Column[ListPlot[#, PlotRange -> All, PlotRangePadding -> 0,          Frame -> True, ImageSize -> 600, ColorFunction -> "DarkRainbow",          Joined -> True, PlotStyle -> Opacity[.3],          AspectRatio -> 1/5] & /@ {IC, Transpose@IC}, Spacings -> .05]      ![enter image description here](http://i.stack.imgur.com/Swsu1.png) **My questions are: is there more efficient and fast approach? what interesting Mathematica stats we could try? what cool apps we can make (games, writing, etc.)?** All approaches are welcome.


How to generate table without comma and bracket or get rid of those?

I want just data without comma and brackets. Even `TableForm` is not working for me. For example, the general pattern of my table is               t = Table[Table[{m, n}, {m, 1, 10}], {n, 1, 9}]      which gives output in the for `{x1,y1},{x2,y2}.....` . If I use `TableForm` it will show output as:               1 2 3  ... 10     1...........      ...............     2...Numbers......     ..............     9............9      But I want output of just two columns for the values of m and n ({m,n}) like               m1 m2     m3 m4     .....      How to do that? Or suggest me how convert the data in the form {{x1,y1},{x2,y2}} in just two columns?


Why doesn't Mathematica divide out the Kelvins?

I thought I understood _Mathematica_ V9 units. However, I can't get these numbers to plot, or even to come out to a nice clean unit of mass (say grams). The `Kelvin's` always stick around: even though they should cancel. Note that the `UnitConvert` with `"gram"` does work at all... But `"Convert to SI unit"` seems to get me close with `"kg K^(3/2)/K^(3/2)"`. Same for `UnitSimplify` ... ![\[PNG of math notebook with problem\]\(https://dl.dropboxusercontent.com/u/5614270/Eqn.png\)](http://i.stack.imgur.com/AHRKd.png) Why doesn't _Mathematica_ divide out the `Kelvins`? Is this somehting to do with the `Kelvin` vs `KelvinDifference` unit thing? I can't seem to find the right way to do this. I just want to plot grams... This is the Jean's mass eqn from Astrophysics.. I would have included a picture of the notebook, but this thing won't let me link/embed pictures.


Problems with WhenEvent

Any help/explanations will be highly appreciated: * * * This works:               sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,          WhenEvent[Abs[t x[t]] > 1, {x'[t] -> -x'[t]}]},          x, {t, 0, 8}][[1]];          xt = x /. sol;          Plot[xt[t], {t, 0, 8}];      * * * This does not:               TT = t;          sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,          WhenEvent[Abs[TT x[t]] > 1, {x'[t] -> -x'[t]}]},          x, {t, 0, 8}][[1]];          xt = x /. sol;          Plot[xt[t], {t, 0, 8}]      * * * This crashes the Kernel:               sol = NDSolve[{x''[t] + x[t] == Sin[t], x[0] == 0, x'[0] == 1,          WhenEvent[(Abs[x[t]] > 1) && (x[t] > 5), {x'[t] -> -x'[t]}]},          x, {t, 0, 8}][[1]];          xt = x /. sol;          Plot[xt[t], {t, 0, 8}]


How to simplify expressions

I read several similar posts but I have not found a solution yet. However, I think that my problem should be quite easy. So here we are. Relations               Mt = M1 + M2;     x1 = -(M2/Mt)*R;     x2 = R*(1 - M2/Mt);     r1 = (x - x1)^2 + y^2;     r2 = (x - x2)^2 + y^2;     Ω = Sqrt[Mt/R^3];      * * *               V1 = -M1/(b1^2 + Sqrt[b1^2 + r1]);     V2 = -M2/(b2^2 + Sqrt[b2^2 + r2]);     Vt = V1 + V2;          Vx = D[Vt, x];     Vy = D[Vt, y];     Print["Vx = ", Simplify[Vx]]     Print["Vy = ", Simplify[Vy]]      My question is how to simplify the expressions `Vx` and `Vy`. Mathematica computes them correctly but I want to take into account the above relations, in other words, `Vx` and `Vy` should contain `Mt`, `r1`, `r2` and `Ω` in order to get the most simplified output. Any ideas? **EDIT** It seems that rules do not work in this case. For example if I set               rule1 = {Mt -> M1 + M2};      and apply it to `Vx`               Vx/.rule1      the output still contains `M1 + M2` instead of `Mt`. Same goes for `r1`, `r2` and omega.


Way to input caligraphic letter as a axis label in Mathematica plot

In my paper written in LATEX, I used a symbol $\mathcal{T}$ and I want to put it in the axis label of my plot. However I could not find such functionality in Mathematica. Is it possible?


Complex limit gives wrong answer

I'm evaluating $$\lim_{z\to e^{i \pi/2 n}} \frac{z-e^{i \pi/2 n}}{z^{2 n}+1}$$ with Mathematica 9.0.1:               In[139]:= Limit[(z - Exp[(I π)/(2 n)])*1/(1 + z^(2 n)),      z -> Exp[(I π)/(2 n)]]     Out[139]:= 0      Mathematica returns 0, but this is not correct. For example, setting n=4, we get a nonzero result:               In[140]:= With[{n = 4},       Limit[1/(1 + z^(2 n)) (z - Exp[I π/(2 n)]),        z -> Exp[I π/(2 n)]]     ]     Out[140]:= -(1/8) (-1)^(1/8)      What went wrong? Is Mathematica assuming something about the value of $n$?


Recurrence Relation construction

How can I go about setting up a recurrence relation where the first 10 values are a constant and the second 10 values are another constant? Ideally, I'd like an efficient way to set               a[1] = 200     a[2] = 200     a[3] = 200     a[4] = 100     a[5] = 100      And so on, without having to type each term out explicitly.


Skip header lines on import

When importing a data file what are the comment symbols for _Mathematica_? That is, given a file like this               blabla     bulbul          1 2 6 54 7 ...     ..      what symbol do I have to put in front of header lines so _Mathematica_ skips them and starts reading at the line `1 2 6 54 7 ...`. I tried `#`, which works in gnuplot, but that did not work. I know that I could just tell _Mathematica_ to skip the lines, but as I can control the file output, it would be nicer to use some kind of a tag.


How can I automatically name files being exported based on input parameters

I have mathematica notebook that performs some operation say a=2 b=3 c=5 d=4 how do I set the output file after evaluation to be named using the values 2,3,5,.. like "2_3_5_4_" such that the the naming automatically takes the values assigned to a,b,c d


Manipulating and plotting two interdependent functions:

I want to plot two functions. Function G8 and G9. Both should be manipulable. Function G9 should dependent on Function G8. Function G8 has a bigger starting value. If function G8 increases by δ function G9 should also increase by δ. And I want to manipulate δ.               Manipulate[G8 := Plot[a, {x, 0, 8}];       G9 := Plot[d, {x, 0, 8}, PlotStyle -> Red];      Show[G8, G9],      {a, 4, 20, Appearance -> "Labeled"}, {d, a - δ, 20,        Appearance -> "Labeled"}, {δ, 1, 20, 0.1,        Appearance -> "Labeled"}]          Can anybody help me? Thak you!


How to make slider in/visible in Manipulate?

I need your help with making a slider invisible and visible in a `Manipulate`. Here is my code:               Manipulate[{},        {x, 0, 1},        {y, 0, 1},        {visible,          {"only x-slider visible", "only y-slider visible", "both visible"},          ControlType -> PopupMenu}]      The `PopupMenu` shows how I want it to function.


Fibonacci Sequence Generator

I'm trying to write a function in Workbench which will generate a Fibonacci sequence starting with `F0 = 0` and `F1 = 1`. So far I have this written               fibonacciSequence[n_] :=      Module[{fPrev = 0, fNext = 1, i = 0},      While[i++ < n, {fPrev, fNext} = {fNext, fPrev + fNext}];     fNext]      How do I modify the function to make it print out a list like the one below when `fibonacciSequence[15]` is called?               {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}      Sorry, but I am very new to _Mathematica_ and my professor didn't give us much instructions or examples of similar functions.


Finding the root of a nested function with small values

I have reduced an error in my program to this line of code:               FindRoot[Nest[# (1 - #) k &, 1/2, 2^4] - 1/2, {k, 3.5}]      It works for $2^1, 2^2, 2^3, 2^4,$ but then for $2^n, n\ge5,$ it stops. Nothing happens. _Mathematica_ is "thinking" forever. `FindRoot` is not doing a single iteration. Why does this happen? I have some ideas of my own, none of which have gotten me anywhere:   1. The values are very small, is it a precision problem?   2. Maybe I'm not using `Nest` properly?


Style of Slideshow

So I am giving my first shot at making a Mma slideshow. But I am finding difficult to change the formatting of Sections and others in the slideshow. I can change the style of Sections in the Working environment through the Format > Edit Stylesheet menu. Yet, even when I change the environment to Slideshow (via Format > Screen Environment > Slideshow), and then edit the stylesheet I see no results. Here is what I see in the stylesheet editor when trying to change the style of the slideshow:               Cell[StyleData[StyleDefinitions -> FrontEnd`FileName[{"SlideShow"}, "Sapphire.nb",        CharacterEncoding -> "WindowsANSI"]]]          Cell[StyleData["Section"],      FontFamily->"Calibri",      FontSize->48,      FontWeight->"Bold",      FontSlant->"Plain",      FontVariations->{"StrikeThrough"->False,      "Underline"->False}]      Could you tell me what I am doing wrong? I tried changing the Font to Calibri and make it Bold, but when I start the presentation, none of this shows up. Thanks in advance


Label x-axis of Plot with power of two values

I want to make a plot similar to LogLinearPlot, but with power of 2 ticks instead of 10 on x axis.               values = {n -> 2^x}     Plot[{Evaluate[f[n] /. values]}, {x, 2, 10}]      How to mark x axis with 2^2, 2^3, ... , 2^10 instead of default 2, 3, ..., 10 ?


Contourplot of Binomial Distribution

Ok, so before anything else, I have no idea what I'm doing. Not in mathematica and maybe not in the maths either. My question is basically if I can contour-plot `f=BinomialDistribution[100, p]`, with the distribution f (in colour) along the y-axis, and the chance p for the distribution along the x-axis. I would give some MWE if I got anything to work, but sadly I don't. I did create an image of how I somewhat expect it to look. ![Example of my proposed image](http://i.stack.imgur.com/yHq9K.png) So what I can do is explain the rationale. I'm working on grain count samples, which are usually expressed in concentrations (5% Garnet, 10% Zircon, etc.). One usually counts 100 grains, so every grain turns into 1%. This of course introduces a representation error, due to the difference in _actually present_ concentration and _measured_ concentration. As far as I know, the Binomial Distribution like `BinomialDistribution[100, 0.2]` gives you the chance of finding the correct concentration (f=0.1 at 20%) as well as the chances for near integers. The distribution obviously peaks at a low percentage and spreads out greatest along the middle 50%. Thus along the X-axis I have the 'actual concentration', and along the y-axis I have the '(chance of) measured concentration'. given by `BinomialDistribution[100, x/100]` I hope you understand my question :)


How does Accumulate work?

`Accumulate` can be used to compute the partial sums of a list. The partial sums can also be computed using a `For` loop but this method should not be used according to following answer. I have the following questions:   * Why is `Accumulate` much faster than using a `For` loop? Please give a more elaborate answer than the fact that Mathematica is inherently a functional programming language.   * What is the exact algorithm for `Accumulate`?    * Can this algorithm be used in object-oriented languages (I am familiar with C++) to compute partial sums of an array faster than a `for` loop? If no, then why not? If yes, then how much will the performance gain (big- _O_ notation is preferable) in C++ be compared to Mathematica? P.S. I am not very familiar with algorithm stability so if that is a part of your answer, please provide links/details on the same.


How should my data be formatted for use with BetweennessCentrality?

A few weeks ago I asked this question. I am trying to upload my data which is an adjacency list for an undirected, unweighed graph and find the betweenness centrality. At the time I tried to use the answer given by user halmir but the output data I got was not right. I have since examined his steps more closely and realized that his data was formatted differently from mine at the start. This is an excerpt of my data showing how it is formatted:               45171 60598     60598 61940     61940 21435     21435      14914      4502 61344 40355 3656 22250 28859      The first number of each row is a node ID and any numbers after are the node IDs of nodes adjacent to the first node. As you can see, node 60598 is adjacent to nodes 45171 and 61940. Only node 61940 is after 60598 though because the adjacency between nodes 60598 and 45171 is already expressed in node 45171's row. This is how I believe user halmir's data was formatted before using `adjlist = ImportString["data.txt", "Table"]`:               2 10     1 8 9     6 7 8 9     5 8     4 9     3 8 9     3 10     2 3 4 6     2 3 5 6 10     1 7 9      There are two differences between his formatting and mine:   1. His data uses the line number as the node id for each row.   2. Each adjacency in his data is expressed twice, once in each node's row.  I am about to whip up some Python code to format my data to take care of the first difference. It's going to be a little tricky since the node IDs in my data don't start from one and when in order are not consecutive. I'll probably change all the node IDs to start from one and increment and I will have to manually refer to a key to figure out which node is which. Will this even work since the second difference isn't addressed? Is there another way I can make my data work with `BetweennessCentrality` in Mathematica?


Efficient Generation of Subgraphs (or, unfriend a friend a day)

_NB: If you're not interested in the back-story, you could simply jump forward to the code which I'm seeking to optimize. Also, I believe this code would only work for MMA 8.0 and above._ My friends and I were discussing the issue of social networks when one of us mentioned what the effect of each person removing a friend a day would be. As we made some calculations (on some rather artificial situations), we realized that it would be interesting to find out the average number of days that would be required before everyone would be left with no friends. The rules that were decided upon were as follows.   1. A set of $n$ people are considered, each pair of whom are either friends or not.    2. Before the start of each day, anyone who no longer has any friends are removed.    3. During each day, each of the remaining people picks one of his friends to unfriend.    4. Consider two people who are initially friends - Alice and Bob. If Alice decides to unfriend Bob or vice versa, then their friendship will be eliminated; if both happen to decide to unfriend each other on the same day, the same occurs.   5. No additional friendships are made on any of the days.  While the maximum and minimum number of days before everyone would be left with no friends is quite easy to analyze, the average number of days wasn't so easy to analyze mathematically. Seeing as I had Mathematica, I decided to try the following code...               isolatedVertexRemover = Function[{inputGraph},        degreeList = VertexDegree[inputGraph];        IndexGraph@VertexDelete[inputGraph, _?(degreeList[[#]] == 0 &)]];          Clear[func];     func[System`Graph[List[], List[]]] = 0;     func[testGraph_] := func[testGraph] =          (testAdjacencyList =               AdjacencyList[testGraph, #] & /@ VertexList[testGraph];            daughterGraphs =               EdgeDelete[testGraph,                 MapThread[UndirectedEdge,                   Transpose@                    Union[Sort /@ Transpose@{VertexList[testGraph], #}]]] & /@                 Tuples[testAdjacencyList];            daughterTally =               Transpose@{isolatedVertexRemover /@                IndexGraph /@ #[[1]], #[[2]]/                        Total@#[[2]]} &@                Transpose@Tally[daughterGraphs, IsomorphicGraphQ];            (1 + Total[(Map[func, #[[1]]]*#[[2]])]) &@          Transpose@daughterTally);      Then, to find out the average number of days before all people are left with no friends, one can simply run the code as follows (the example graph given is for a set of 5 people all of whom are initially friends with each other).               func[CompleteGraph[5]]      The problem with this function is that, even thought it is defined recursively, it nevertheless still takes a very long time to run. For a complete graph of size 6, the function takes only 17 seconds to run on my system, but I have not been able to obtain a result for a complete graph of size 7 and above. In fact, most graphs larger than size 10 simply cause the system to abort during the first step of the generation of the daughter graphs. > My question, therefore, is: How can we optimize the above code? The area to > focus on, in my opinion, would be in the generation of the `daughterGraphs`. > Currently, I am simply considering all possible ways in which people can > unfriend each other without taking into account the possible symmetries in > the graph (for example, a case where two people are friends with exactly the > same set of friends). This is a rather brute-force method which I'm sure can > be improved. Thank you for reading until here - hope you enjoyed the question, and any mathematical insight into this specific issue or perhaps the problem in general would be appreciated.


How do you create a tangent line that will move along the curve of a line?

Other people have answered this question, but I'm new to _Mathematica_. We're supposed to use the `Manipulate` and `Show` commands to produce two functions: one that is sin(x), and the other a line that moves tangent along f(x)=sin(x). I have no idea if this makes any sense, but the other pages don't. This equation was given as a hint:               Manipulate[Plot[Sin[t], {t, 0, 2π},      Ticks -> {Range[0, 2π, π/6], Sin[Range[-(π/2), π/2, π/6]]},          Epilog -> {{Dashed, Line[{{x, 0}, {x, Sin[x]}, {0, Sin[x]}}]},           {Red, PointSize[.015], Point[{x, Sin[x]}]}}],       {{x, (2π/3}, 0,2π}]      Anything helps. Thank you. :)


Manipulate flickering and consuming lots of CPU

I am new to _Mathematica_ and was experimenting with a simply problem of plotting a tangent to a curve and being able to move the point at which the tangent is drawn using `Manipulate`. When I run the following, the cell flickers a lot and it also seems to consume a lot of CPU? Is there a way to avoid this?               Manipulate[       Module[{f, x, y, dx, dy},         dx = dy = 1;         f[x_] := x^2;         tangent[x_, y_] := {{x - dx, y - f'[x] dy}, {x + dx, y + f'[x] dy}};         g = Graphics[Line @ tangent[x0, f[x0]], PlotRange -> {{-5, 5}, {-5, 5}}];         p = Plot[f[x], {x, -5, 5}];         Show[p, g]],       {{x0, 2}, -4, 4}]


Efficiently initialize list of consecutively named variables for file import

Let's say I have the code:                    $runningLogFile0 = "m0.txt";          $runningLogFile1 = "m1.txt";          $runningLogFile2 = "m2.txt";               If[FileExistsQ[$runningLogFile0], Get[$runningLogFile0], Print["Error: Noexist"];];          If[FileExistsQ[$runningLogFile1], Get[$runningLogFile1], Print["Error: Noexist"];];          If[FileExistsQ[$runningLogFile2], Get[$runningLogFile2], Print["Error: Noexist"];];      that I use to read in a list of consecutively named files, `m0.txt,m1.txt, m2.txt`. I want to make this code more efficient for reading in a large number of such files, for which it would be very tiresome to do in the above way. Can I automate this with a `Do` or `Table`? I thought something like                Do["$runningLogFile" <> ToString[i] = "m"<>ToString[i]<>".txt";, {i, 1, 100}];      might work but apparently not.


Different integral when used with assumptions

I want to calculate an integral, but Mathematica gives me different results if I am more specific with the `Assumptions` option of `Integrate`. I have :               Integrate[(1 - Cos[x])/x^2 Exp[I t x], {x, -∞, ∞}]      that returns :               ConditionalExpression[π - π Abs[t], -1 < Re[t] < 1 && Im[t] == 0]      and :               Integrate[(1 - Cos[x])/x^2 Exp[I t x], {x, -∞, ∞}, Assumptions :> t ∈ Reals]      that returns :               1/2 π (Abs[-1 + t] - 2 Abs[t] + Abs[1 + t])      How to explain the difference between the two results ?


Does Mathematica have Month Range and Day range?

It is known that `CharacterRange["a", "z"]` gives list of characters from a to z. Does _Mathematica_ have something similar for weekdays and months of the year? Something like:               Somefunction["Saturday", "Friday"]     (* {"Saturday", "Sunday", ...} *)          Somefunction["January", "December"]         (* {"January ", "February ", ...} *)


How to make the Mathematica icon flash in the taskbar?

I have a somewhat long computation running in the background. I would like the Mathematica icon on the taskbar to flash once the computation is done. For example, Microsoft Outlook reminders make the taskbar flash: ![enter image description here](http://i.stack.imgur.com/cZXRE.png) How can I achieve the same effect in Mathematica? Is there a Mathematica command that makes the Mathematica icon in the taskbar flash? **What I've tried:** `Beep[]` can be useful, but if you leave the computer for a while, you can miss the beep. The advantage of flashing is that it remains flashing indefinitely. Another alternative is `MessageDialog[]`, but you have no way of knowing that a message is up if Mathematica is minimized. It would be useful if `MessageDialog[]` produced the flashing in the taskbar, but that doesn't happen.


Math cell symbols not in italics

If I type $y(x)=ax+b$ in a math cell, y, x, and b are italicized, but a and x are not. How do I make them italicized? I tried adding an \[InvisibleSpace] or a \[VeryThinSpace] in between, and it makes the symbols italicized. Is that the right way to do it? It feels like a workaround, as if I'm not supposed to do this.


Learning from Michael Trott's Guidebook with V8 or later

I am not sure this question is suitable for this site. Please let me know if my question is too vague or if it is hard to give a clear anwser. I'm a new user of _Mathematica_. My _Mathematica_ use began with version 8. I think I'm reasonably familiar with the core language of _Mathematica_ , but I want to get better acquainted with it's applications to various fields such as visualization. I find Michael Trott's four big volumes, _The Mathematica Guidebook_ , a very good resource, but find it a problem that the books are written for V4 and V5. As I stated above, I am a user of a later version of _Mathematica_ , so I have little knowledge of versions before V6. The core language of _Mathematica_ hasn't changed a lot since V5, but other parts did (the graphics capabilities for example). So, my question are:   * Are there any tips/suggestions/references for making the best use of this rather old book?   * How do I deal with the code compatibility issues?


How to handle NDSolve::ndsz problem (singularity problem)

I have 2 second order differential equations (non-linear). The physics behind them is correct. I verified the equations many times. It is a solid pendulum with a mass-spring at the end of it. Now, assuming the mathematical model is correct and that the 2 differential equations are derived correctly based on the physics, I found that under some specific initial conditions, I get the dreaded `NDSolve::ndsz` error               NDSolve::ndsz: At t == 0.09571750107721341`, step size is effectively zero;      singularity or stiff system suspected      Here is an example, where a tiny change in initial conditions causes this error:               Clear[theta,x,t];     eq1 = 98  Sin[theta[t]]+x[t]-10 x[t] theta'[t]^2+10 (x''[t]+0.5  theta''[t])==0;     eq2 =-98 (-0.5  Sin[theta[t]]-Cos[theta[t]] x[t])+5 (4 x[t] x'[t] theta'[t]+              (x''[t]+0.5 theta''[t])+2 x[t]^2 theta''[t])==0;      Now depending on the IC, this problem shows up. This one gives the above `ndsz` error               ic={x[0]==0.23,x'[0]==-2,theta[0]==5,theta'[0]==3};     NDSolve[Flatten[{eq1,eq2,ic}],{x,theta,x',theta'},{t,0,0.1},            Method->{"StiffnessSwitching"}]      While if I changed `x[0]` above to be `0.24` instead of `0.23`, now it works               ic={x[0]==0.24,x'[0]==-2,theta[0]==5,theta'[0]==3};     sol=NDSolve[Flatten[{eq1,eq2,ic}],{x,theta,x',theta'},{t,0,0.1},                 Method->{"StiffnessSwitching"}]      I tried many of the tricks for stiffness gives here http://reference.wolfram.com/mathematica/tutorial/NDSolveOverview.html but none has helped so far. I am actually not sure if it is stiffness issue or singularity issue. Singularity means to me that equations are wrong, right? and that should not really happen if the physics is correct, or may be I do not understand exactly what this means. The error seems to say it is singularity. Either way, I tried all the tricks I know about relating to stiffness methods. My question is really this: Assuming the equations are correct (and I am almost sure they are). How does one handle such a problem? If I trap this error, what should I do next? Could a valid and correct differential equations (i.e. derived from a correct mathematical model) generate a singularity error for specific initial conditions? and if so, how to handle this using `NDSolve`? Looking to see if there are options for `NDSOlve` that I overlooked to help handle this. Feel free to try any other options above to see if you can get rid of this error for this specific case of initial conditions. Here is the CDF itself in case you want to see the actual demo http://12000.org/my_notes/mma_demos/solid_pendulum_with_spring_mass/ **update:** fyi, I just uploaded to the above link a small report showing the derivation of the differential equations from the model. The links are there for the report.pdf and html version, as well as the Mathematica notebook itself `report.nb` which shows the derivations using the Lagrangian method. The case described here is in `report.nb`, the last one at the end. This problem again shows up only under very specific initial conditions. This problem shows up when I model the pendulum arm as mass-less instead of solid pendulum. I think I did the model correctly in this case as well. So, right now, for the demo itself, I force the pendulum to be a solid pendulum only to avoid this problem. thanks


Extruding along a path

I'm trying to render a 3D image of a path by extruding a circular cross- section along the path, creating a "snake-like" path. Here is an image I found to illustrate: ![tube](http://i.stack.imgur.com/W47t1.jpg) I can't seem to figure out if there is a way to do this? I just found the `Tube` command; now I need to find a way to turn a set of points into a `Curve`. Basically, I need to find the necessary control points for a `BezierCurve` or a `BSpline` to fit a set of {x,y} coordinates. Can the `Interpolation` with the `Spline` method be used to generate a spline from a set of points?


How to output from a .NET console app to an existing Notebook in Mathematica?

I'm wondering if its possible push output from a .NET console application to an existing Notebook that is open in Mathematica. The reason I'd like this is that I want to use Mathematica as a "debugging console" for intermediate calculations that I am performing in .NET, by pushing out text, graphics, etc. p.s. I'm fairly familiar with C# and Mathematica, so all I want to know is if this is possible, or not.


Extracting Coefficient Matrices from partial differential equations

I have a system of differential equations which are in the form               Dt[a01,t] + u*Dt[a01,x] + v*Dt[a01,y] + w*Dt[a01,z]      I have ten of these equations and my variables inside the derivatives are a01 through a10 (with some exceptions). In general, in any equation, I have all four derivatives (t, x, y, and z). I'd like to be able to extract the coefficient matrices so that I can write my system of equations in the form $$ \delta a/\delta t + A_x \delta a /\delta x + A_y \delta a/\delta y + A_z \delta a/\delta z $$ where "a" is my vector of variables. Any help would be greatly appreciated!


Combining and aligning "chart" type graphics with regular plots

Is there an easy (recommended) way to align regular plots (e.g. `ListPlot` or `Plot`) with chart type graphics (`BarChart` or `DistributionChart`)? For example:               Show[        DistributionChart[Table[RandomReal[NormalDistribution[i, .2], 1000], {i, 1, 10}]],         ListPlot[Range[1, 10]]     ]      ![Not aligned!](http://i.stack.imgur.com/KSVDe.jpg) I would like the points of the `ListPlot` to reside exactly on top of the `DistributionChart` elements. Furthermore, the coordinate positioning of chart elements seems to vary with the number of elements (which is ridiculous).               Show[         DistributionChart[Table[RandomReal[NormalDistribution[i, .2], 1000], {i, 1, 3}]],          ListPlot[Range[1, 3]]     ]      ![Not aligned 2](http://i.stack.imgur.com/M0MV8.jpg)


Inconsistent boundary and initial conditions: BC ignored altogether

Consider the following diffusion-decay equation with von Neumann b/c in the origin and Dirichlet at the other boundary:               pde = D[u[x, t], t] == d*D[u[x, t], x, x] - \[Delta]*u[x, t]     bc = {D[u[x, t], x] == -j0 /. x -> 0, u[x, t] == 0 /. x -> length}     ic = u[x, t] == u0 /. t -> 0     params = {d -> 10, \[Delta] -> 1, length -> 600, u0 -> 200, j0 -> 4000}     tFinal = 150;     soln = NDSolve[Flatten@{pde, bc, ic} /. params, u, {t, 0, tFinal}, {x, 0, length /. params}]      Running NDSolve as above generates this Warning:               NDSolve::ibcinc: Warning: Boundary and initial conditions are inconsistent.       I understand that the boundary and initial conditions are inconsistent. To solve this problem I looked through this webpage: http://reference.wolfram.com/mathematica/tutorial/NDSolvePDE.html#51169332 I noticed, however, that changing **j0** had no effect on the attained numerical solution and, in fact, leaving the symbol **j0** undefined does not lead NDSolve to complain about non-numerical derivatives and such. This leads me to believe that NDSolve ignores somehow the boundary condition in the origin altogether, making it somewhat hard to debug the warning message about inconsistent boundary and initial conditions. **To clarify my point about j0:** I don't understand how NDSolve manages to ignore the boundary condition in the origin altogether without running into trouble. If I comment out the left b/c, NDSolve complains:               NDSolve::bcart: Warning: An insufficient number of boundary conditions have been specified for the direction of independent variable x. Artificial boundary effects may be present in the solution.      **Edit:** One solution I found is to turn j0 into a Michaelis-Menten type of function of time. Here, I also incorporate a valid point made in the comments: the Dirichlet b/c on the right of the domain was also inconsistent with the initial condition.               pde = D[u[x, t], t] == d*D[u[x, t], x, x] - \[Delta]*u[x, t]     bc = {D[u[x, t], x] == -((j0*t)/(1 + t)) /. x -> 0, u[x, t] == 0 /. x -> length}     ic = u[x, t] == u0 /. t -> 0     params = {d -> 100, \[Delta] -> 1, length -> 600, u0 -> 0, j0 -> 40}     tFinal = 150;     soln = NDSolve[Flatten@{pde, bc, ic} /. params, u, {t, 0, tFinal}, {x, 0, length /. params}, Method -> {"MethodOfLines",      "SpatialDiscretization" -> {"TensorProductGrid",        "MinPoints" -> 1000}}]      Your help and suggestions are greatly appreciated!


Ticks don't display on Y-Axis of Histogram when using PlotRange

I have a histogram, if I create it without specifying the `PlotRange` it works fine and the ticks on the Y-Axis are displayed               Histogram[{myData}, {10000}, PlotRange -> {Automatic, Automatic}]      ![](https://dl.dropboxusercontent.com/u/49254507/histogramwlabels.jpg) However if I indicate the `PlotRange` they vanish               Histogram[{myData}, {10000}, PlotRange -> {{0, 200000}, Automatic}]      ![](https://dl.dropboxusercontent.com/u/49254507/noLabels.jpg) I tried setting the `Ticks` manually:               Histogram[{myData}, {10000}, PlotRange -> {{0, 200000}, Automatic},                Ticks -> {{0, 50000, 100000, 150000, 200000},                          {0, 100, 200, 300, 400, 500, 600, 700}}]      but _Mathematica_ stubbornly refused to display them.   Does anyone know how fix this?


NIntegrate error bound

I am trying to evaluate a highly oscillatory integral using **NIntegrate**. I fear that due to limited resources (time and/or memory), I will not be able to evaluate the integral to the desired precision. Thus, I would like to **programmatically access the error estimates** that are e.g. reported by the messages **NIntegrate::maxp** , **NIntegrate::ncvb** , or **NIntegrate::eincr**. I could not find an option of NIntegrate that would directly make these error estimates available. However, given that I have to evaluate a multitude of integrals, it is impractical to obtain the errors from the warnings by hand. The following example generates the NIntegrate::maxp message (obviously this very integral has an analytical solution):               NIntegrate[Sin[x]/Sqrt[x], {x, 0, 100}, Method -> "MonteCarlo",PrecisionGoal -> 6]      > NIntegrate::maxp: The integral failed to converge after 50100 integrand > evaluations. NIntegrate obtained 1.1787733508261242`and 0.07678430788995934` > for the integral and error estimates. How to get (if necessary, extract) the error estimate (0.07678430788995934`)? Remark: The example from the help of NIntegrate::eincr, i.e. ref/message/NIntegrate/eincr, does not produce the expected message in version 8.0; unfortunate my integrals still do.


Alternative closed forms for digamma expressions

What commands should I use such that Mathematica / W|A express $$\psi(1+i)+\psi(1-i)$$ exclusively in terms of trigonometric functions?


can a ColorFunction have side effects?

Can anyone explain this (to me) odd behavior. If I run this code once (fresh kernel) it works as intended.               data = Table[Random[Real], {i, 5}, {j, 5}];     mycf[x_] := (AppendTo[hdat, x]; Hue[x])     hdat = {};     Show[Graphics[Raster[data, ColorFunction -> mycf]]]     Print["hdat len", Length[hdat]]     Histogram[hdat]      If I execute the same thing a second time the plot is generated but the `hdat` array is left empty. It seems some sort of caching is happening?? Edit - an even smaller example to illustrate the issue:               mycf[x_] := (value = 1; Hue[0])     value = 0     Show[Graphics[Raster[{{0}}, ColorFunction -> mycf]]]     value         ------------next cell     value      Further clue... it turns out that any `ColorFunction` specified gets wrapped in `Dynamic[]`: If you do:               Graphics[Raster[{{0}}]]     Graphics[Raster[{{0}}, ColorFunction -> (Black &)]]      with dynamic updating disabled the first form works while the second does not. With that in mind, following `Show[]` in my example with `FinishDynamic[]` seems to do the trick.


Matrix conditional operation

Say I have a matrix of:               tmp1 = 5;     tmp2 = 5;     tmp3 = RandomChoice[{0, 1, 2, 3, 4, 5}, {tmp1, tmp2}];     MatrixForm[tmp3]      How to do a conditional operation of elements - 1 if non-zero, else do nothing, as in the attached:![enter image description here](http://i.stack.imgur.com/Q94EO.png). Maybe using Positive?


Remove variable from autocomplete - version 10 issue?

I've got a program that's fairly long. Occasionally I ClearAll some lists that I created. That works fine, but those lists continue to show up in the autocomplete. Is there anyway to remove them from the autocomplete?


Import specific data from Excel to make a plot

I need some help with this: I have imported data from an Excel file and I need to make a contour plot of it. The data are in table-like form. Here is a sample of the first few 'rows':               {{{"",  0.4,      0.5,      0.6,     0.7,     0.8,     0.9,     1.},        {0.3, 0.00122,  0.00182,  0.00247, 0.00311, 0.00382, 0.00453, 0.00524},        {0.4, 0.000949, 0.00149,  0.0021,  0.00272, 0.00337, 0.00406, 0.00477},        {0.5, 0.000714, 0.00123,  0.00176, 0.00233, 0.00295, 0.00361, 0.00425},        {0.6, 0.000519, 0.000982, 0.00147, 0.002,   0.00257, 0.00317, 0.00382},      ...}}      In the first row I have values for one metric in each cell, let’s say from 0.2, 0.3,…,1. In the first column I have values for the second metric, with values 0.3,0.4,….1. The upper corner is blank, if we consider it as table. I need triplets of numbers created like this: I take a value from the first/main row, a value from the first/main column, and the value at their intersection. So the first triplet would be `{0.4, 0.3, 0.00122}`... If I insert the data manually, I get exactly what I want with `ListContourPlot[{x1,y1,f1},{x2,y2,f2},...]`. But it takes a lot of time and seems rather nonsense! At a second level, I would like to transpose the axes and make a second contour plot. So the first triplet would now be `{0.3, 0.4, 0.00122}` etc. Since I’m new to _Mathematica_ and with no knowledge of programming I am not sure how to get what I want. Some attempts I made were in vain.


replacement rule to pull independent expression outside of Integrate

I'm trying to write a fairly general replacement rule that will pull expressions independent of the variable of integration outside of Integrate, since `Simplify` and `FullSimplify` do not seem to do this. So as an example I try               Integrate[f[x] Log[y], {x, r, s}] /.      Integrate[q_*r_, {v_, l_, h_}] /; FreeQ[r, v] ->        r*Integrate[q, {v, l, h}]      and that returns               (* (-r f[x] + s f[x]) Log[y] *)      Trace shows it correctly recognized the Log as independent of z and pulled it outside but then, even though it recognizes that f[x] depends on x, it incorrectly does the integration and finally assembles the result. If `f[x]` is previously defined, say `Sin[x]`, then this problem does not appear. Is there a way to write this rule that would be correct in all circumstances?


How to change default notebook background color?

How does one change the default notebook background color?


Series expansions

I am not a very experienced user. My problem is that I have a polynomial equation F[Z,a,b,c]=0 in which parameters a, b and c are series of another variable x. What I look for is how to generate the coefficients of the series for Z as functions of x. I used brutal force but it is just a nightmare. Thank for your help


Problems with BarLegend in MatrixPlot

I have the following data:               TableA = {{5.72, 5.81, 1.13}, {4.81, 5.25, 0.86}, {4.31, 2.88,      0.73}, {3.98, 2.38, 0.71}, {3.81, 2.33, 0.84}, {2.37, 0.97, 0.74}};     TableB = {{20.2, 5.91, 2.00}, {15.0, 4.37, 1.41}, {12.1, 3.14,      1.13}, {10.2, 2.59, 1.02}, {9.19, 2.29, 1.08}, {4.90, 1.22,      0.88}};      And I want to create a `MatrixPlot` of these:               PlotA3k =      MatrixPlot[TableA,      FrameLabel -> {Style["\!\(\*SubscriptBox[\(z\), \(i\)]\)", 20],       Style["\!\(\*SubscriptBox[\(k\), \(i\)]\)", 20]},      PlotLabel ->      Style["\[CapitalDelta]\!\(\*OverscriptBox[\(A\), \(_\)]\)", 22],      LabelStyle -> Directive[12],      PlotLegends -> Placed[BarLegend[Automatic], {After, Center}],      ColorFunction -> "Rainbow",      FrameTicks -> {{1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3}},      DataReversed -> {True, False}];     PlotR3k =      MatrixPlot[TableB,      FrameLabel -> {Style["\!\(\*SubscriptBox[\(z\), \(i\)]\)", 20],       Style["\!\(\*SubscriptBox[\(k\), \(i\)]\)", 20]},      PlotLabel ->      Style["\[CapitalDelta]\!\(\*OverscriptBox[\(R\), \(_\)]\)", 22],      LabelStyle -> Directive[12],      PlotLegends -> Placed[BarLegend[Automatic], {After, Center}],      ColorFunction -> "Rainbow",      FrameTicks -> {{1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3}},      DataReversed -> {True, False}];      I have problems with the numbers in the BarLegend. ![matrix plots](http://i.stack.imgur.com/VHM24.png) I want to have kind of percentage bar, running from the lowest to the maximum value of the data. Also I notice that numbers doesn't appear as decimals.


Function that takes another function inside

Looking at this QA, I'm trying the following - 2 functions (r in vector format) using Theta { A, 2 } functions (sorry for the inconsistent names...).               ihat = {1, 0, 0}     jhat = {0, 1, 0}     khat = {0, 0, 1}     ThetaA[t_] := 0.2 Pi Cos[50 t];     Theta2[t_] := 0.2 Pi Sin[50 t - Pi/3];     L1 = L2 = 5.0;     rAO[ThetaA_, t_] := L1 Sin[ThetaA[t]] ihat + L1 Cos[ThetaA[t]] jhat     rBA[t_] := (L2 Sin[Theta2[t]] + rAO[[1]]) ihat               + (L2 Cos[Theta2[t]] + rAO[[2]]) jhat      which gives me the following errors: ![enter image description here](http://i.stack.imgur.com/YaJwr.png) Could anyone tell me what's wrong with my functions. Thank you.


Drawing normals to a curve

I want to draw a series of normals to a curve, where the curve has been parametrized by a single angle, i.e., the polar angle. The curve is actually sinusoidal perturbation of a circle of radius 1/2, and the magnitude of the perturbation is given by `amp`. I have the `normal` function calculated in the code below already. I want to be able to draw normals to the curve at different points on the curve. How do I do this?               orad       = 1/2;     amp        = 0.05;     numpetals  = 7;           (*Polar information of interface*)     r[th_]  := orad + amp * Sin[numpetals*th];     rp[th_] := amp*numpetals*Cos[numpetals*th];          (*Cartesian information of interface*)     x[th_]  := r[th]*Cos[th]; (*X-coordinate of the interface/*)     y[th_]  := r[th]*Sin[th]; (*Y-coordinate of the interface*)          (*Speeds of traveral*)     xp[th_] := rp[th]*Cos[th] - r[th]*Sin[th];     yp[th_] := rp[th]*Sin[th] + r[th]*Cos[th];          (*Outward unit normal to the curve*)     normal[th_] := {yp[th], -xp[th]}/Sqrt[xp[th]^2 + yp[th]^2];


Using Product for different variables

when using product in mathematica the initial and maximum value of the product will be the variable itself that will be maupulated. what I need is to make these initial and maximum of the product as an index for several variables. for example if I have the following series product: $$\text{y}=\prod _{i=1}^M \left(1-\exp \left(-\frac{z}{\bar{\gamma }_{\text{RD}_i}}\right) \left(\frac{\bar{\gamma }_{\text{SR}_i}}{z \bar{\gamma }_{\text{IR}_i}+\bar{\gamma }_{\text{SR}_i}}\right){}^L\right);$$ So here $i$ is the index for variables $\bar{\gamma }_{\text{RD}}$, $\bar{\gamma }_{\text{IR}}$, and $\bar{\gamma }_{\text{SR}}$ How I can perform this product? Note: L is Positive Integer; L=1,2,...


How to delete the current group-cell using the keyboard?

Related to Delete the current notebook cell using the keyboard. Difference is that here I want to delete the whole group of cells, including the original Input cell and all Print, Output, Message etc. cells it generated (or belong to the same group). However in the case when several Input cells are grouped it will not delete the whole group, but only the subgroup that belongs to that one Input cell.


How do I prevent auto loading of blank notebook at startup?

I'm using Mathematica 8 with operating system Mac OS X Lion. When I open Mathematica it always loads a blank notebook. I don't want it to load anything by default. In the Preferences pane there is a tab for Appearance. Near the bottom of the tabview there is an option "Show at startup" with a drop down menu. There is no option for not showing anything at startup. Is there a way around this?


Social Media Data, specifying the time interval

I am facing a problem concerning the SocialMediaData function built in Mathematica. I am trying to investigate the WallMostLikedPost over time, i.e I want get the most liked post for the last few years for various fan pages. The built in function               SocialMediaData[{"Facebook", "BMW"}, "WallMostLikedPost"]      does not give me the possibility to state a time interval which I want to analyze. Does anybody have an idea how I should tackle this problem. Thanks a lot!


Max of a table/list with indeterminate values

Suppose I have a Table:               tab = {1., 2., 3., Indeterminate}      When I type `Max[tab]` I get `Indeterminate`, I would like instead to get Max of all points except the `Indeterminate` (i.e. `Max_new_version[tab] = 3`). NB: As a secondary case the answer should also provide a method to do a conditional replacement such that `tab` will end up looking like (i.e. `Indeterminate` is replaced by zero).               tab = {1., 2., 3., 0.0}


Problems with Manipulate (indicated by blinking output cell)

The following code produces the error message when exported to CDF in the title of this question. Although I have seen similar issues on SE, the problem is manifest by the "blinking" of the plot output's cell bracket. My goal is to export this code to CDF but am stymied now.               Manipulate[If[s = 20, s = 0];      y1[t_] := y[t, 2];      Plot[y1[t], {t, 0, 20}, PlotRange -> {0, 2},        Epilog -> {PointSize[0.02], Red, Point[{s, y1[s]}]}],      {{s, 0, "GO"}, 0, 20, .01, ControlType -> Trigger, AnimationRate -> 4,        SaveDefinitions -> True},           Initialization -> (y[t_, x0_] := 1/(1 + (1/x0 - 1) Exp[-0.2 t]))      ]


Alternatives to indexed variables in Compile

According to the excellent answer given here by @Leonid Shifrin: How to compile effectively?, > You can not really use indexed variables in `Compile`, although it may > appear that you can. Separately, @Szabolcs writes in When to use indexed variables > Indexed variables can be used in symbolic calculations. They're useful when > the number of variables used needs to be changed programmatically. Back to me now - I've recently been learning about indexed variables and getting my head around them. Here I'm generating a formula programmatically. For a simple example, it's a sum of sines,               f[x]=a[1]*Sin[x + b[1]] + a[2]*Sin[x + b[2]] + ...      The number of terms in the function is variable, which is why I'm generating the function programmatically. To generate a function with two terms, I run               sinfunction[a_, b_] := a*Sin[x + b];     variables = {a[#], b[#]} & /@ Range[2];     Total[sinfunction @@@ variables]     **Out=a[1]*Sin[x + b[1]] + a[2]*Sin[x + b[2]]**      Once I've generated a formula with _n_ terms, it stays that size, but I then call the function many times with different parameters, and I'm looking to see if `Compile` can offer me any advantage. I'd like to be able to compile my function and run various benchmarks to see what happens compared to an uncompiled case. Obviously for small expressions such as this there probably isn't any benefit to compiling (documentation), but I'm using this as an exercise to improve my knowledge of Mathematica for the future! This hardcoded effort is impractical and probably somewhat redundant:               complexformula = a[1]*Sin[x + b[1]] + a[2]*Sin[x + b[2]];     complexcompiledFunction = With[{function = complexformula},          Compile[{{a[1], _Real}, {b[1], _Real}, {a[2], _Real}, {b[2], _Real}, {x, _Real}},             function         ]     ];     complexcompiledFunction[2, 3, 1, 1, 5]     **Out=1.6993**      Are there any alternatives? Or do I need to rethink my approach altogether?


Floating point addition not associative

Can anybody explain the following behavior?               x = 0.2 + (0.3 + 0.1);     y = (0.2 + 0.3) + 0.1;     x == y (* -> True *)      But actually the variables do not exactly contain the same values:               x // FullForm (* -> 0.6000000000000001` *)     y // FullForm (* -> 0.6` *)      The example was taken from Mike Croucher's blog entry.


Extract information from functions that returns nested structures with DefineDLLFunction

Where can I find examples devoted to extracting information from functions that returns nested structures with DefineDLLFunction in Mathematica? The only example I found and understood, was given by Todd Gayley in “calling a dll- function that returns a structure ”, but this concern a function with only one structure. How to pass a nested structure in DefineDLLFunction and how to extract the information concerning the nested records from it?


NDSolve with varying PrecisionGoal and WorkingPrecision

Sometimes we need higher numerical precision to deal with large number cancellation in an equation. But if this cancellation happens only in a small (and known) parameter space, would it be possible to only use high precision calculation in that small part of the parameter space? For example, something like               NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30},        WorkingPrecision -> If[x < 5, $MachinePrecision, 50],            PrecisionGoal -> If[x < 5, $MachinePrecision, 50]]      This code doesn't work, because _Mathematica_ doesn't relate the `x` in the two `If` expressions to the `x` in the ODE. Is there any way to make the above idea work?


How to solve this FindFit::nrlnum:

the following code show error message > FindFit::nrlnum: "The function value {6.71759 -9.36268*10^-8\ I,6.51797 > -8.42641*10^-8\ I,6.31789 -7.49014*10^-8\ I,6.1179 -6.55387*10^-8\ I,5.91794 > -5.61761*10^-8\ I,5.71797 -4.68134*10^-8\ I,<<5>>,4.53457 +0.\ I,4.35846 > +0.\ I,4.21276 +0.\ I,4.12436 +0.\ I,4.12268 +0.\ I}\n is not a list of real > numbers with dimensions {16} at {a,b} = {1.,1.}. "               FindFit[{{-1.9999999999999993`, -8.71758682396597`}, \         {-1.7999999999999994`, -8.317969980679658`}, {-1.5999999999999996`, \         -7.9178913932701125`}, {-1.3999999999999995`, -7.517895681098703`}, \         {-1.1999999999999997`, -7.117935726160363`}, {-0.9999999999999997`, \         -6.717970679612214`}, {-0.7999999999999997`, -6.318075235251766`}, \         {-0.5999999999999999`, -5.918333526484718`}, {-0.3999999999999999`, \         -5.518978976322539`}, {-0.1999999999999999`, -5.120597037968602`}, \         {0.`, -4.724630562634576`}, {0.1999999999999997`, \         -4.334574650968856`}, {0.3999999999999999`, -3.9584626158001357`}, \         {0.6000000000000001`, -3.6127563661613884`}, {0.7999999999999998`, \         -3.324357131929245`}, {0.9999999999999994`, -3.1226771789912595`}},           a x^b, {a, b}, x]      I tried the method here, but all didn't work.


Font changes once Exported for Text inside a Grid

I am trying to work with Mathematica 10's new font and have found a simple way to revert the font family to Times New Roman for all my figure. I enter the following command in the `Private Style Definitions`, under 'Format' > 'Edit Stylesheet'.               Cell[StyleData["Graphics"],FontFamily->"Times"]      However, if a `Graphics` is inside a `Grid`, the font may look like Times in the FrontEnd of Mathematica, but it goes back to the Sans font family once exported.               myFigure=Grid[{{Show[RegionPlot[1<0,{x,0,1},{y,0,1},FrameLabel->{"Text","Text"},ImageSize->400]]}}]     Button["Export Figure",Export["C:\\Figure.pdf",myFigure];]     myFigure2=Show[RegionPlot[1<0,{x,0,1},{y,0,1},FrameLabel->{"Text","Text"},ImageSize->400]]     Button["Export Figure 2",Export["C:\\Figure 2.pdf",myFigure2];]      Any thought why? Any ideas how to get Times in my final output?


Detecting edge/region in contour plot

I am interested in improving this plot: ![contour plot](http://i.stack.imgur.com/qvPAJ.png) which I produced with the following command:               dat // ListContourPlot[#, ContourShading -> False,         ContourStyle -> ColorData[10] /@ Range[10], Contours -> Range[21]/8,        ContourLabels -> None, FrameLabel -> {x, y},         DataRange -> {{-7, 2}, {-15, 15}}, PlotLabel -> "Contour plot of ϕ(x,y)"] &      The actual `dat` is available here; the edge corresponds to zero values (though, it could be set to something else). **Question** > I would like _Mathematica_ to identify the edge of the contours and do a > region plot to avoid the ragged line, or alternatively, to draw a thick line > over it to make it publication-friendly. **Attempt** I guess I know how to find the edge:               dat2 = dat // Image // EdgeDetect // ImageData // Position[#, 1] & // Sort;      On the other hand, these points are not sorted correctly: ![badly-sorted points](http://i.stack.imgur.com/oODeH.png) I supposed I could use 2D neighbours as a criterion for sorting, but I feel there is a smarter way to achieve my overall goal(?)


Download xkcd Click and Drag comic

Inspired by the recent question about xkcd styled plots I started looking at xkcd again and I came across a comic titled Click and Drag. And if you do that, you start exploring a larger drawing. A _much_ larger drawing. How large? I don't know, but I spent about half and hour exploring it before my arm wore out. Now I want to see all the comic but I don't want to give myself RSI in the process. That leads me, finally, to my questions:   * How can I use _Mathematica_ to download the entire scrollable drawing?   * How can it be assembled and stored? This will surely be a tremendously large image; what data formats does _Mathematica_ support that can handle it?   * Is it possible to navigate the image from within _Mathematica_? In fairness people may ask "what have you tried" and I must say: nothing. Not long after posting I realized that the tiles are stored as PNG files with names that describe the location. This was also mentioned in the comments. This makes acquisition easier than I anticipated, and shifts the emphasis of this question to the second and third points.


ArcTan[0,0] numeric approximation

I've noticed that the numeric approximation of `ArcTan` is a bit different from the symbolic one. If I write               ArcTan[0,0]      I obtain               ArcTan::indet: "Indeterminate expression ArcTan[0,0] encountered.      While if I write               ArcTan[0.0, 0]      I obtain               0      Instead I expect to obtain also in this case an indeterminate result. Is there some specific reason for this behavior? === EDIT === J. M. has noticed also this:               ArcTan[0, 0.0]      gives               Pi/2      === EDIT 2 === celtschk also noticed that               ArcTan[0.0, 0.0]      gives               ArcTan::indet: "Indeterminate expression ArcTan[0.,0.] encountered.      but it _does_ generate an output:               Interval[{-Pi, Pi}]


How to solve this integral

I'm trying to deal with this article, but I don't understand how equations 5.9 and 5.10 were obtained. I tried to use _Mathematica_ 8 to solve it, but the answer was different. I have a problem with this integral $$ \int _0^{\tau }\int _{\sigma -(\tau -\tau_1)}^{\sigma +(\tau-\tau_1)} \frac{M\ y_0\ \sinh^2(\beta)} {\left(\sigma_1^2+ (\tau_1 \sinh(\beta)+x_0)^2+y_0^2\right)^{3/2}} \ d\sigma_1\ d\tau_1 $$ where $\tau, M, y_0, \beta$ are constants. I used only a simple `Integrate` function with `GenerateConditions -> False`. Maybe I'm doing something wrong in _Mathematica_. If you know; tell me _Mathematica_ code, please. Otherwise, if there is some kind of algorithm to solve integrals like this, please tell me too.


How do I find all the solutions of three simultaneous equations within a given box?

Sometimes, one needs to find all the solutions of three simultaneous nonlinear equations in three unknowns $$\begin{align*}f(x,y,z)&=0\\g(x,y,z)&=0\\h(x,y,z)&=0\end{align*}$$ within a given cuboidal domain; that is, all triples $(x,y,z)$ satisfying the three equations given above, and within the region defined by $x_{\min}\leq x\leq x_{\max}$, $y_{\min}\leq y\leq y_{\max}$, $z_{\min}\leq z\leq z_{\max}$. (I restrict the discussion here to _transcendental_ equations; algebraic equations are not too problematic for _Mathematica_ (`Solve[]`/`NSolve[]`, `Resultant[]`, `GroebnerBasis[]`...)) **How can I use _Mathematica_ to find these solutions?** `FindRoot[]` can only find one solution, and you still need an approximate location as a starting point for `FindRoot[]`. `NSolve[]` works (sometimes), but it takes long.


Replicating a discontinuous graph

I'm trying to replicate a graph from my math book for my notes as well as to learn Mathematica. I was hoping someone would be able to help me figure out how to add the open points to the graph, and possibly add a slight curve to the lines as shown in the real graph. My lines are straight. The Graph from the book: ![](http://i.imgur.com/tRcRM.jpg) What I've been able to come up with:                  g[x_] := \[Piecewise] {        {x + 1, x < 1},        {-x + 3, x < 2},        {(x + 2) - 2, x < 3},        {-x + 6, x < 4}       }          Plot[g[x], {x, 0, 5},       PlotStyle -> {Thick}, PlotRange -> {0, 5},      Ticks -> {{0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4, 5}, Automatic},      GridLines -> {{0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4, 5}},      GridLinesStyle -> Directive[LightGray, Dashed],      Epilog -> {Red, Dashed, PointSize[Large],        Point[{{0, 1}, {1, 3}, {2, 1}, {4, 2}}]        }      ]


Why doesn't Roots work on a certain quartic polynomial equation?

In everything that follows I am using `Roots` to get the solutions to the equations. I start off with this equation: $$ \frac{A}{3}x^4 - x^2 + 2ax - b^2 = 0$$ Now `Roots` gives me back $4$ complicated looking solutions to this. Now if one stares at the solutions it appears that if one tunes to $a =b = \sqrt{\frac{3}{16 A}}$ then these 4 solutions collapse to $3$ namely, $ x = \frac{1}{2}\sqrt{\frac{3}{A}}, -\frac{1}{2}\sqrt{\frac{3}{A}} \pm \sqrt{\frac{6}{A} }$ **however**   * when I from the beginning itself set $a = b = \sqrt{\frac{3}{16 A}}$ and run `Roots` on the equation the system just hangs!   * And of these $3$ solutions the "$\pm$" _doesn't_ seem to satisfy the original equation. (with $a = b = \sqrt{\frac{3}{16 A}}$)  Can someone kindly explain what is happening?


What is the maximum real value for Compile?

Can one be found programmatically? The function I'm compiling, `indicesOfMin`, gives the indices of the minimum value(s) of a real-valued list, the parameter, in a single traversal (which is why I'm using this instead of `Ordering` or `Sort`).               indicesOfMin = Compile[{{list, _Real, 1}},       Module[{bag = Internal`Bag[Most[{0}]], min = 1.7976931348623157*^308, sub = 0.},         Do[If[(sub = list[[i]] - min) < 0, min = list[[i]]; bag = Internal`Bag[Most[{0}]]; Internal`StuffBag[bag, i];,           If[sub == 0, Internal`StuffBag[bag, i]]],           {i, 1, Length[list], 1}];         Internal`BagPart[bag, All]       ]];      As you can see, I'm using `C++`'s positive infinity value for my first setting of `min`, but I don't even know if that's the language this will be compiled to. Potential issues:   1. I understand I can use the first value in `list` for `min`, but that takes extra code and I would like to avoid doing so because it also creates a precondition that the list is at least one element long.   2. I don't know what language this will be compiled to in advance (the function is part of a package, and the person running it may not have a `C` compiler, so the maximum field value might be wrong.


Has anyone implemented cohomology for complex manifolds?

I'm investigating the cohomology of complex manifolds, and need to construct chain complexes, Mayer-Vietoris sequences etc. I use Mathematica for numerically tracing manifolds with geodesics, but haven't implemented any representation of cohomological classes, differentials and complexes. Has anyone used Mathematica in this area, or anything related to this (eg multidimensional topology)?


Cursor disappears in Mathematica 9.01

When using the template blocks from the Pallets to enter equations, the mouse cursor disappears. It also becomes difficult to set the focus to a block in a template by clicking it. This was also an issue in earlier versions of Mathematica for Windows. Is there an alternative way to enter formulas or is it possible to use a third- party equation editor?


All possible pairs of two items

I have 4 different items `{1, 2, 3, 4}`. I want to obtain all possible pairs of two of the items. I have written:               n = 4;     x1 = Tuples[Range@n, n];          Cases[x1, {a_, a_, b_, b_} /; a != b]      gives the desired result: > {{1, 1, 2, 2}, {1, 1, 3, 3}, {1, 1, 4, 4}, {2, 2, 1, 1}, {2, 2, 3, 3}, {2, > 2, 4, 4}, {3, 3, 1, 1}, {3, 3, 2, 2}, {3, 3, 4, 4}, {4, 4, 1, 1}, {4, 4, 2, > 2}, {4, 4, 3, 3}} Now I choose               n = 6;     x2 = Tuples[Range@n, n];          Cases[x2, {a_, a_, b_, b_, c_, c_} /; a != b && a != c && b != c];     % // Short      > {{1,1,2,2,3,3},{1,1,2,2,4,4},<<116>>,{6,6,5,5,3,3},{6,6,5,5,4,4}} again gives the desired result. How would you automate this (for even `n`)? Are there better alternatives?


how to find intersection between a parametric trajectoy and a point

I'have a 2d-system of differential equations, analitycally solved, depending on a parameter. I know that, by continuity, there exist a minimum value of the parameter such that trajectory passes through a specific point. My problem is to find such value (also approximatively). This is the system-equation:               ti = 0;     yi = 0;     zi = -.75;     zf = -.5;     eps=.01;          sol = FullSimplify[DSolve[{y'[t] == 1/(2 zf) y[t] - u z[t],      z'[t] == -1 + 1/zf z[t] + u y[t], y[ti] == yi, z[ti] == zi},{y[t],z[t]},t]];      The parameter is u. I have to find the first u such that trajectorie intersect the point: z=zf; y=Sqrt[-2*(zf)*eps + eps^2] Note that this point is done by the intersection between `z=zf` and the circle of radius `|zf|+eps`. In the following, you can see an animation of the system:               Manipulate[      Module[{sol, y, z, t},        sol = First@DSolve[{y'[t] == 1/(2 zf) y[t] - u z[t],        z'[t] == -1 + 1/zf z[t] + u y[t], y[ti] == yi,        z[ti] == zi}, {y[t], z[t]}, t];     Show[p1, p2, Graphics[{Red, Line[{{0, -1}, {0, 1}}]}],     Graphics[{DotDashed, Red, Thickness[.006],       Line[{{-1, zf}, {1, zf}}]}],     ParametricPlot[{y[t] /. sol, z[t] /. sol}, {t, 0, tend},      PlotStyle -> Thickness[.004]]]],           {{tend, .1, "t"}, .01, 20, .1, Appearance -> "Labeled"},           {{u, 10, "u"}, -300, 300, .5, Appearance -> "Labeled"},           {{zi, -.75, "zi"}, -1, 1, Appearance -> "Labeled"},           {{yi, 0, "yi"}, -1, 1, Appearance -> "Labeled"},     Initialization :>     (deltaA[y_, z_] := 1/(2 zf) y^2 - z + 1/zf z^2;     circ[y_, z_] := y^2 + z^2;     p2 = ContourPlot[{circ[y, z] == (-zf + eps)^2}, {y, -1,        1}, {z, -1, 1}, ContourStyle -> Yellow, GridLines -> Automatic,       Frame -> True, FrameLabel -> {"y", "z"}, RotateLabel -> False,       LabelStyle -> {FontSize -> 20}];     p1 = ContourPlot[{deltaA[y, z] == 0}, {y, -1, 1}, {z, -1,        1}, ContourStyle -> Green, GridLines -> Automatic,       Frame -> True, FrameLabel -> {"y", "z"}, RotateLabel -> False,       LabelStyle -> {FontSize -> 20}];)]