How to customize derivative behavior via upvalues?

I'm having trouble getting customized derivatives (defined using upvalues) to behave in sane ways. By this I mean that I'd like to define a derivative using an upvalue and then have Mathematica apply all derivative rules it normally would, delegating to the upvalues when appropriate. For example.               X /: D[X[x_], y_] := A KroneckerDelta[x,y]     Y /: D[Y[x_], y_] := B KroneckerDelta[x,y]     D[X[x], x]        (* Gives the Expected Answer:  A *)     D[X[x] + Y[x], x] (* Desired Output:   A + B  *)     D[X[x] Y[x], x]   (* Desired Output:   A Y[x] + X[x] B   *)      For the latter two, I get `X'[x] + Y'[x]` and `Y[x] X'[x] + X[x] Y'[x]`. I'm not understanding why the upvalues aren't kicking in. A similar question was asked here, but I couldn't adjust it for my problem. **Update:** It looks like I didn't specify my problem in enough detail. To give a better sense of the direction I'm looking, see this question. My (present) understanding of `Derivative` suggests it cannot achieve what I want since the arguments to my functions are abstract indices (e.g. multiple arguments are implicit). Consider a (discrete) joint probability $p_{XY}(i,j)$ where $i$ and $j$ are indexes (with unspecified ranges) that represent the possible values. Now, consider a marginal distribution $p_X(i) = \sum_j p_{XY}(i,j)$. Each $p_X(i)$ depends on all of the $p_{XY}(j,k)$ with $j = i$. I was hoping to declare the derivatives of $p_{XY}(i,j)$ and $p_X(i)$ with respect to $p_{XY}(k,l)$ (treating each $p_{XY}(i,j)$ as independent variables). Then, I wanted to be able to differentiate any generic expression involving those functions. Mathematically, this is the behavior: $$ \frac{\partial p_{XY}(i,j)}{\partial p_{XY}(k,l)} = \delta_{ij} \delta_{jk} \qquad\qquad \frac{\partial p_X(i)}{\partial p_{XY}(k,l)} = \delta_{ik} $$ Here is a toy expression I'd like to differentiate: $$\frac{\partial}{\partial p_{XY}(k,l)} \left[ p_{XY}(i,j) p_X(i)^2 \right] = \delta_{ik} \delta_{jl}\, p_X(i)^2 + 2 p_{XY}(i,j)\, p_X(i) \, \delta_{ik} $$ The above is just an application of the product rule, so it's pretty straight- forward to do these calculations by hand, once the derivatives of the primitives are specified. However, I don't want to re-specify all the rules of differentiation. Somehow I'd like to tell Mathematica to use its own system, while incorporating my primitives. Things I've tried...               pXY /: D[pXY[i_, j_], pXY[k_, l_]] := Simplify[KroneckerDelta[i, k] KroneckerDelta[j, l]]     pX /: D[pX[i_], pXY[j_, k_]] := KroneckerDelta[i, j]     D[pXY[i, j] pX[i]^2, pXY[k, l]]   (* Undesirably returns 0 *)      I think I understand why (via pattern matching) this gives 0. Another attempt:               pXY /: D[pXY[i_, j_], pXY[k_, l_]] := Simplify[KroneckerDelta[i, k] KroneckerDelta[j, l]]     pX[i_] := MySumX[pXY[i, j], {i, j}]     MySum /: D[MySum[s_, {i_, j_}], pXY[k_, l_]] := D[s /. {i -> k, j -> l}, pXY[k, l]]     MySumX /: D[MySumX[s_, {i_, j_}], pXY[k_, l_]] := D[s /. {i -> k}, pXY[k, l]]          D[pX[i], pXY[i, k]]  (* Result is correct *)     D[pXY[i, j] + pX[i], pXY[k, l]] (* Result is not correct *)      Hopefully its clearer now how the original question relates to what I'm truly after. Just to keep it fun, here is another expression I'd like to differentiate: $$ \frac{\partial}{\partial p_{XY}(k,l)} \sum_{i,j} p_{XY}(i,j)\log \frac{ p_{XY}(i,j)}{p_X(i) p_Y(j)}$$


Color ramp banding in PDFKit when exporting Raster image Inset to PDF

Here I produce a `Raster` image with large uniformly colored rectangles and put it in an `Inset`:               With[{n = 5},      Graphics[Inset[        Graphics[Raster[          {Map[            List @@ ColorConvert[ColorData["LakeColors"][#],                RGBColor] &, (Range[n - 1] - 1)/(n - 2)]}          ]],        Automatic, Automatic, {.45, .5}        ]       ]      ]      ![Raster](http://i.stack.imgur.com/8Xe5C.png) Now export this to `PDF`:               Export["p.pdf", %]      ![ramp artefacts](http://i.stack.imgur.com/chkrn.png) The uniform regions have been replaced by a series of discrete bands that seem to try an interpolate between the rectangles. This happens if I choose fewer rectangles too (e.g., `n = 3`). If I generate the same thing _without_ using `Raster`, the exported `PDF` looks fine - e.g., try this:               With[{n = 5},      Graphics[Inset[        Graphics[         MapIndexed[{ColorData["LakeColors"][#],             Translate[Rectangle[], {#2[[1]], 0}]} &, (Range[n - 1] -              1)/(n - 2)]         ]        ,        Automatic, Automatic, {.45, .5}        ]       ]      ]      So it's the conversion of the rasterized image in `Export` that's responsible for this effect. Interestingly, one can work around this (on Mac) by selecting the graphic, going to `Edit > Copy As > PDF` and pasting the result into `Preview`. Although I have some workarounds now, it still seems mysterious to me why this banding effect happens with `Raster`. And it would of course be nice if someone knew **how to use`Raster` in an `Inset` inside a `Graphics` without triggering the effect** that causes the blocks of the raster to lose their uniform color. Also - the arguments to `Inset` can be left out (in particular the scaling `{.45, .5}`). But it seemed to me that this problem didn't always happen with `Raster`, and that it probably has something to do with the size of the bitmap being scaled up relative to some assumed coordinate system used in `Export`.


How to handle infeasible points in FindRoot?

I am calling               FindRoot[f[x,y],{{x,xInit,xMin,xMax},{y,yInit,yMin,yMax}}]      where for some points `{x,y}`, `f[x,y]` is undefined. I now wonder which value `f[x,y]` should return at `{x,y}` in order for `FindRoot` to neglect these points, and to continue searching. Should `f` maybe return `Null` or `Indeterminate` at the critical `{x,y}`? Note, that so far I have not added any domain restrictions on `f`. I also do not know whether adding domain restrictions would be a possibility? To give some more background: `f[x,y]` is a composite function of other functions of `x` and `y`. For some points `{x,y}`, bounds for integrals inside these functions become complex, which is nonsensical. Currently, I throw an error as far as possible down the tree of interdependent functions - call the function where I do this `l`. Points `{x,y}` are infeasible if `g[x,y]<h[x,y]`.               l[x_,y_]:=Module[{...},If[g[x,y]<h[x,y],Throw["Error"],Null],...]      However, I am not catching this error properly and `FindRoot` terminates.


Symbolic integration of elliptic functions

Is there some clever way to **integrate products of elliptic functions** $\wp(z;g_2,g_3)$ or $\zeta(z;g_2,g_3)$ in _Mathematica_? * * * _Mathematica_ seems to be able to integrate functions like               Integrate[WeierstrassP[z, {g2, g3}]^3, z]      However, not something like               Integrate[WeierstrassP[z, {g2, g3}] WeierstrassP[z + a, {g2, g3}]], z]      I have tried using the addition formulae for the $\wp(z)$, but _Mathematica_ is still unable to give the answer.


How to set tick label precision

When I make a plot like               Plot[Exp[x], {x, 1 - 10^-9, 1}]      The resulting plot looks like ![exp plot near 1](http://i.stack.imgur.com/7sKyb.png). Notice all the ticks on the x-axis are all labeled 1. Is there any way to increase the precision of the tick labels? So that the ticks are labeled something like 0.999999999, or 1-10^{-10} etc.


How do I prevent this precision exception?

I have the following as the first step to a sequence.               x = 2 - GoldenRatio;     Ceiling[x + x^(1/2)]      It gets a precision exception. The value is correct, but I would like to prevent the exception. (If we subtract 0.000001 from x, everything is fine.) Is there a way to limit the precision? For one step only? Edit: the sequence where 2-GoldenRatio is the seed.               x = 2 - GoldenRatio; t = Table[(x = Ceiling[x + x^(1/2)]), {2000}];      If ceiling is removed the first step works fine. However, I need the ceiling for alternate steps. Edit2: $0 < x \leq 2-\phi$ where $\phi$ is the golden ratio. $\textit{When x = 2 - $\phi$, the first step equals $1$}$.


Computation of parametric integral

I am trying to compute the integral               Integrate[(g^(u^(g - 1)))/(1 + u^g), {u, 0, t}]      but as an answer I get my input expression. There must be something wrong with parameters but even if I give values to `t` or `g` mathematica'a answer is the same: it just gives me back my input expression... My output is ![](http://i.imgur.com/5lACY.jpg) How can I compute this integral?


Mathematica 9 Linking with R

I would like to run a batch job from within the current Mathematica .m file using "R CMD BATCH &" (the job runs in the background when Mathematica proceeds with the current calculations. How can I do that in Mathematica 9?


How to define a large number of assumptions?

Please consider the following _simple_ and _larger_ example:               varSimple = ToExpression@CharacterRange["a", "b"];     fSimple = Total@Map[Sqrt[#^2] &, varSimple];     assumpSimple = And[Element[varSimple, Integers] , a >= 0 , b >= 0];     simpfSimple = Simplify[fSimple, assumpSimple]     (*a+b*)      When one defines a larger function such as `fLarge`, it is very inconvenient to type `character1>=0 && ... && character#>=0` for the whole `CharacterRange` to define the assumptions.               varLarge = ToExpression@CharacterRange["a", "z"];     fLarge = Total@Map[Sqrt[#^2] &, varLarge];     assumpLarge = And[Element[varLarge, Integers] , a >= 0 , ... , z=>0];     simpfSimple = Simplify[fSimple, assumpLarge]     (*a+...+z*)      **Question 1** Since `And` (as well as `Alternatives`) cannot cope with `List` as an argument, how can I combine a larger number of expressions with `And` (or `Alternatives`)? **Question 2** With `ToExpression@CharacterRange["a", "z"]` the number of variables is limited to 24. Is there another (easy) way to define a larger number of variables?


Can TextRecognize read digits?

While answering this question, I tried `TextRecognize` to read single digits. But it doesn't recognize a single digit, even though the digits are clearly readable. For example, this ![enter image description here](http://i.stack.imgur.com/EYX3I.png) is not recognized. This is my code:               digits = ImagePartition[Import["http://i.stack.imgur.com/cLncR.png"], 50];     Map[TextRecognize, digits, {2}]


Publishing quality graphs to Adobe Illustrator?

I am trying to produce publishing quality graphs. I would like to export graphs from a Notebook to Ai (Adobe Illustrator). How do I do this? Just started using Mathematica, very new! Thanks, Anousheh PS This is NOT a duplicate question!!! It has nothing to do with the FONTS!!! A simple question of how to export graphs into Ai. Can we attache files (Notebooks) for easiness? Thank you, Anousheh


Is there a keyboard shortcut for hiding the suggestion bar?

I see that there's a control I can click to hide or "minimize" version 9.0's "suggestion bar". Is there a keyboard shortcut to do this?


Mixing patterns with string patterns

I have imported an XML document into _Mathematica_. It is now represented as Symbolic XML expression in the variable `xml`:               XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0"]},       XMLElement[       "slideshow", {}, {XMLElement["title", {}, {"XML Tutorial"}],         XMLElement[         "slide", {}, {XMLElement["title", {}, {"Agenda"}],           XMLElement["item", {}, {"Introduction"}],           XMLElement["item", {}, {"XML technologies"}],           XMLElement["item", {}, {"Editors for XML documents"}]}]}], {}]      Using the `Cases` function I want to extract the `XMLElement` expressions whose plain text contents contain the word "XML":               Cases[xml, XMLElement["item", _, {___ ~~ "XML" ~~ ___}], Infinity]      This however returns the empty list, probably because it is mixing a _Mathematica_ expression pattern with a string expression pattern. How does one go about embedding a string pattern into a regular pattern?


Dynamic and LibraryLink: dynamic visualization of a simulation

I am asking this question to save some time and I am expecting answers only from people who have tried something like this before. (I realize that I could just try it and see if it works, but that takes a non-trivial amount of time.) Suppose you wrote a simulation in pure Mathematica. As the simulation progresses, a vector is being periodically updated changed. One could then have a `Dynamic@ListPlot[vector]` and watch the progress "live". Now the question is: is this possible when using LibraryLink? With LibraryLink it's possible to access a kernel variable (`vector`) directly. Is it possible to get the system to register the changes to that variable and to run the `Dynamic` when necessary? Or is there an alternative _simple_ (low effort) way to achieve the same, i.e. use Mathematica to visualize a simulation "live"? One way I see that certainly work is periodically calling back to the kernel through a MathLink connection and setting a variable through Mma code, which contains the information to be visualized. Is there a simpler/better way?


Generating unique random number lists

I am new in programming. I have an array containing, let's say 20 elements and first I want to randomly select two elements from it and record them. Then I will select two elements from the array of twenty elements again and record them. The process continues, let's say 10 times and in these 10 draws, I do not want to repeat any of the two elements that I have already drawn. I used `RandomSample` to generate random numbers.               j = 0;     For[i = 0, i < 2, i++,       Yarray[j] = RandomSample[Range[8], 2];       Print[Yarray[j]];       j++;]


How to connect Mathematica 9 to MS SQL 2012 using Windows 7 enterprise (64-bit)

I have used Microsoft Open Database Connectivity (ODBC) with _Mathematica_ 8.0 and MSSQL 2008 on Windows XP, but I can't get it to work on Windows 7 Enterprise (64-bit) with _Mathematica_ 9.0.1.0 and MS SQL server 2012 (64-bit). Has anyone had success in doing this?


FindShortestTour for charity (or: How can I optimize meal delivery with FindShortestTour?)

I've been wondering about this for a while - but never got around to asking - until I saw faleichik's incredible answer to _Mathematica_ Minecraft. I did some work at a not-for-profit a little while ago, which participated in a program called Meals On Wheels - wherein I helped to deliver food to those who are homebound. Myself and a partner would deliver meals to a daily list of addresses, sorted by name; not the most efficient route. The time to complete a route varied by as much as two hours because of it. `FindShortestTour`, however, is only one (possible) part of the solution. I'd need to parse addresses, read map data, and handle the slight irregularities of NYC streets. How can I use `FindShortestTour` to find the optimal meal delivery route, given a list of addresses?


Center of quadrangular

Having 4 points **A** `(ax, ay)`, **B** `(bx, by)`, **C** `(cx, cy)` and **D** `(dx, dy)` that describe any quadrangular in 2D, with `x` and `y` in range `[-100, 100]` I would like to calculate point **E** `(ex, ey)`, which would be a center of this quadrangular. What algorithm can be used for such calculation and why?


Why isn't autosave enabled by default?

While I've come across several ways to implement/enable autosave (see: Is there a notebook autosave frequency configuration?, Saving my code before cell evaluations: Insurance against front end hanging, How can I set up a versioning system within a notebook?), I've never found a reason why it isn't enabled by default. It seems incredibly useful to me - surely there must be some good reason why Wolfram chose to leave it unconfigured! Why isn't autosave enabled by default?


Faster Solve for Fermat 4n+1 conjecture

Assuming that Fermat `4n+1` conjecture (each prime of the form `4n+1` is the sum of two squares) is true then I like to solve the equation in the fastest possible form.               fermatQ[z_] :=       Length[Solve[x^2 + y^2 == z && x > 0 && y > 0 && x > y, {x, y},          Integers]] == 1      * * *               n = RandomPrime[10^1000]     7204820541697853265697482198302184350747317334028070603629009839116252110492095578256567601106541188796967599300930463571131759731713652353047579003939845222202423352007102653912639893572595606320600084613647266601717191253462990524380427645290376322143085916721648030108591154681102352260206273871572063237796538519461643983233381100630087701623080830334878529319816938438525254877567479353234371918939199585631244203057530334523235226572902803801085582846927846832856652925979381175382144232563160719058478946717172490138082439192330136929995648881640700486082783629709282614697667884919440294962926788805345569631546029257495702381802397055578335502287473342083514426712460325643772655909154310734572274430109077955105556789724468724642608390802045303940792665411216800131523990931511413428660061711347430190867360920645531069644270820680156683794692381221310012472305068130266122993566902672115038607482079495349772492239436104516688041844051770082711796572639884658459765037703578841572775761721          Divisible[(n - 1), 4]         True      * * *               Timing[fermatQ[n]]          {0.296875, True}          Timing[PrimeQ[n]]          {0.203125, True}          Timing[Length[PowersRepresentations[n, 2, 2]] == 1]          {0.687500, True}        1. Can we optimize `fermatQ` to solve it faster?   2. Can we say to `Solve` to halt and return upon finding the first `k` solutions ? (Not to compute them all and extract the first `k` solutions) **Updated** Added timing for MMA built-in `PowersRepresentations` which is slower than `Solve`. **Update 2** Based on @KennyColnago answer, we can write a one line formula but yet the timing is the same (everything behind the scene seems to be equal):               ModularRootPrimeQ[n_] := Length[PowerModList[-1, 1/2, n]] == 2          Select[Prime[Range[4, 1000000]],       Mod[#, 4] == 1 && ! ModularRootPrimeQ[#] &]          {} // Checked the first million primes and found no counterpart      If you run the same over all 4m+1 numbers, you'll get all 4m+1 primes with only prime powers:               Select[Range[1000000],       Mod[#, 4] == 1 && ! PrimePowerQ[#] &&         ModularRootPrimeQ[#] && ! PrimeQ[#] &]          {} // If you remove the condition !PrimePowerQ[#] , only prime powers will appear here.


Solving partial differential equation with DSolve does not give a result

I am trying to solve the equation: $-(d^2/dx^2+d^2/dy^2)\psi+(x^2+y^2-2)\psi=0$ Here, is my code:               Eq = -(D[ψ[x, y], {x,2}] + D[ψ[x, y], {y,2}]) + (x^2 + y^2 - 2) ψ[x, y] == 0;          DSolve[Eq, ψ, {x, y}]      The output returns an unevaluated expression. Why do I receive such a thing? The solution to the PDE is: $\psi=\exp(-1/2(x^2+y^2))$


Which ColorFunction should I use to get such a gradient of blue-cyan-green-yellow-orange-red?

![enter image description here](http://i.stack.imgur.com/fe3Fd.jpg) ## I want to get the effect in the above Figure. Here is my code:               Plot3D[Log[        4*((1 + x)^2)*(0.0065^2)*Log[y]/(3*((1 - 2 x))^2*(0.0267^2)) + 1]/       Log[y], {x, 0.315, 0.45}, {y, 0, 1}, Mesh -> 50, ImageSize -> 600,       AspectRatio -> 0.8, PlotRange -> {0, 20},       PerformanceGoal -> "Quality",       LabelStyle -> Directive[Bold, FontFamily -> "Times New Roman", 24],       AxesStyle -> {Thick, Thick, Thick}, AxesOrigin -> {0.315, 0, 0},       AxesLabel -> {\[Nu], n, l}, MaxRecursion -> 6, ClippingStyle -> None,       ColorFunction -> "Rainbow",       PlotLegends -> BarLegend[Automatic, LegendMarkerSize -> {20, 300}]]


Plotting a contour on a torus

There are two ways to consider a two-dimensional torus. One way is to take a parallelogram (let's say the square $[0, 1]^2$) and topologically glue the opposite edges. Another way is to look at the surface of a doughnut with one hole. I would like to draw the zero set of a doubly-periodic function as a contour on a torus. Here is how I do it when viewing the torus as a square: ![Contour on torus](http://i.stack.imgur.com/NDBZZ.png) However, I'd really like to see a contour on the surface of a doughnut. How can this be done? (Generally, I'd like to transplant the square $[0, 1]^2$ of any graphic onto the surface of a doughnut.)


new kernel for notebook

I know I can create a new kernel for my notebook from the evaluation menu but is there a command for this? I'd really like some of my notebooks to startup their own kernel as the first line of code.


Distance between two functions satisfying a constraint

My problem is that I have two functions that are described as follows:               x1 =        x[t] /. DSolve[{55 x''[t] + 100*n x'[t] + (5/22)*n x[t] == 5, x'[0] == 1/8, x[0] == 0},          x[t], t][[1]]     x2 =        x[t] /. DSolve[{x''[t] + 1 == 0, x'[0] == 1/8, x[0] == 0}, x[t], t][[1]]      Variable `n` in function `x1` ranges from 1 to 8. I want to find which `n` enables `x1` to come as close to `x2` as possible without falling below `x2`. Or stated otherwise, what is the highest `n` that ensures `x1 > x2` at all times. A plot of the functions reveals that most of the action takes place between `t = 0` and `t = 0.15`. However, the curves are too close to each other to read the right `n` from my screen. I have been trying ways to calculate the difference with integration, solving and all types of manners for hours now, but I'm certain there must be an easier way to achieve this within _Mathematica_.


Line Breaks in AxesLabel or PlotLabel?

Searching got me peripherally related threads, but not exactly what I was looking for. I'm making some graphs which I want to use on exams. Sometimes, labels (specifically in AxesLabel and PlotLabel) that are longish can be a hassle. Is there a way to introduce a line break in these labels to make them fit better in the space that I have? Thanks in advance.


Resizing palettes

My eyes are weary and my sight grows dim, so I used the zoom control bottom- right in the palette. Unfortunately, having zoomed in the palette window cannot be resized - so I can't see the rhs - _and_ there is no horizontal scrollbar. I'm also bemused by the fact that I can expand and collapse sections within palettes, but the overall palette size still doesn't change. What's the point of a "palette" in which everything you choose to be visible isn't? (screen limitations aside? Is there a way to resize palettes? (Mma 9 BTW) **Update & followup question to my own answer** Palettes can be made to respond as desired, but the Options dialog settings don't persist. How might I ensure that the options are reset each time I start Mma? **Update 2** I intended place copies of the relevant palette files in $USerBaseDirectory\SystemFiles\FrontEnd\Palettes and edit them in the hope that they would override the installed palettes. To check that the override works, I restarted without any mnodifications and found that lo-and-behold the zoom control works as it should do - and no editing seems to be required. The failure of the zoom control previously therefore _seems_ linked to the palette files' location. Hmmmmmm. **Eh?** And then it _doesn't_ work as I just described and I've edited all the relevant palette notebooks in $UserBaseDirector to make them editable, saveable, etc. Clearly I am missing something or this is very strange... probably the former, but palettes now come back where I left them (Screen 2) with the previous zoom (mostly, apart form Special Characters (?)


Drag & drop path info into front end?

On OSX at least, it's possible to quickly retrieve a folder/file path by dragging & dropping the folder/file into the terminal, eg: ![enter image description here](http://i.stack.imgur.com/1txfU.jpg) Is it possible to program _Mathematica_ 's front end enable similar drag & drop operation? I'm primarily interested in passing path info to `Import` and `Export`.


Text formatting with different wrappers

Formatting text in _Mathematica_ should be a punishment for serious crimes. I've face another frustrating feature, and I don't know how to get rid of it.               tekst = StringJoin @@ Array["tekst " &, 15];           Composition[        Grid[{{#, Graphics[Inset@#]}}, Frame -> All] &,          Panel[#, ImageSize -> {150, 100}] &,        Style[#, LineIndent -> 0] &                ][tekst]      ![enter image description here](http://i.stack.imgur.com/4BVds.png) Those texts should look the same imo. The only difference is that the one in `Graphics` is not formatted as it should be. * * * `Boxes` look well and I don't know what causes that:               ...     PanelBox[      StyleBox["\<\"tekst tekst ... tekst \"\>", StripOnInput->False, LineIndent->0],       ImageSize->{150, 100}],      GraphicsBox[InsetBox[     PanelBox[       StyleBox["\<\"tekst ... tekst \"\>", StripOnInput->False, LineIndent->0],     ...      I was trying to set `FormatType` for `Inset`or `BaseStyle` for `Graphics` or `ParagraphIndent -> 0`. But with no avail :/. Help me please :P


Mathlink works strangely

I have problem when using mathlink, the source code is quite simple:               void MAXF(char* ex1, char* ex2, char** result){        MLINK lp;        int pkt;        MLEnvironment env;        env = MLInitialize(NULL);        if (env == NULL) return;        int argcs = 4;        char *argvs[5] = {"-linkmode", "launch", "-linkname", "math -mathlink", NULL};        lp = MLOpen(argcs, argvs);        if (lp == NULL) return;             *result = malloc(100);        sprintf(*result, "0");             MLPutFunction(lp, "Exit", 0L);        MLClose(lp);        MLDeinitialize(env);     }      and in main, i call it by:               char* test;     MAXF("0", "0", &test);      However, after running, the terminal always shows this line:               In[2]:=       I believe that there is a problem, but I can't figure it out. Please help.


The third argument of the Root function

Consider the roots of an arbitrary indecomposable polynomial:               sol = Solve[x^5 + 2 x + 1 == 0, x]      The returned expression is               {{x -> Root[1 + 2 #1 + #1^5 &, 1]},      {x -> Root[1 + 2 #1 + #1^5 &, 2]},      {x -> Root[1 + 2 #1 + #1^5 &, 3]},      {x -> Root[1 + 2 #1 + #1^5 &, 4]},      {x -> Root[1 + 2 #1 + #1^5 &, 5]}}      Everything seems OK. But now let us evaluate the expression               InputForm[sol]      Now the returned expression is               {{x -> Root[1 + 2*#1 + #1^5 & , 1, 0]},      {x -> Root[1 + 2*#1 + #1^5 & , 2, 0]},       {x -> Root[1 + 2*#1 + #1^5 & , 3, 0]},      {x -> Root[1 + 2*#1 + #1^5 & , 4, 0]},       {x -> Root[1 + 2*#1 + #1^5 & , 5, 0]}}      Why has the extra argument `0` appeared ?   Is it a bug, mystery or some extremely smart property ? I use _Mathematica 9.0.1.0_ ( _64-bit Windows 7_ ).


Why does Manipulate execute the expression twice?

When I execute `Foobar[]` in the code below and move a slider, the variable `grad` is printed twice. Why is this? How can I make the `Manipulate` body only execute once on each update?               Foobar[] := Module[{f, vars, grad},        f = a x^3 - b x^2 + c y^2;        vars = {a, b, c};        With[{fman = f, controls = Apply[Sequence, {{#, 0}, -5, 5} & /@ vars]},         Manipulate[          g = fman/(x^2 + y^2 + 1);          grad = D[g, {{x, y}}];          Print[grad];          , controls]         ]        ];      **Edit:** As noticed below, this function is creating a `Manipulate`. My concern is why the `Manipulate` appears to be executing twice for every one update. This is a minimal working example and hence there is significant amount of code (that takes a while to run) excluded from inside the `Manipulate` body. I included `Print` to emphasize that the code appears to be executing twice.


Find parameters of ODEs to fit solution data

# Problem How to find the initial conditions `x[0]`,`y[0]` and the optimal value of parameters `a`,`b`,`c`,`d` to fit the following system of ODEs?                x'[t] ==  a*x[t] - b*x[t]*y[t]      y'[t] == -c*y[t] + d*x[t] y[t]      Solution data is:                   (* The first column is time 't', the second column is coordinate 'x', and the last         column is coordinate 'y'. *)     data = {{11, 45.79, 41.4},    {12, 53.03, 38.9},    {13, 64.05, 36.78},              {14, 75.4, 36.04},    {15, 90.36, 33.78},   {16, 107.14, 35.4},             {17, 127.79, 34.68},  {18, 150.77, 36.61},  {19, 179.65, 37.71},             {20, 211.82, 41.98},  {21, 249.91, 45.72},  {22, 291.31, 53.1},             {23, 334.95, 65.44},  {24, 380.67, 83.},    {25, 420.28, 108.74},             {26, 445.56, 150.01}, {27, 447.63, 205.61}, {28, 414.04, 281.6},             {29, 347.04, 364.56}, {30, 265.33, 440.3},  {31, 187.57, 489.68},             {32, 128., 512.95},   {33, 85.25, 510.01},  {34, 57.17, 491.06},             {35, 39.96, 462.22},  {36, 29.22, 430.15},  {37, 22.3, 396.95},             {38, 16.52, 364.87},  {39, 14.41, 333.16},  {40, 11.58, 304.97},             {41, 10.41, 277.73},  {42, 10.17, 253.16},  {43, 7.86, 229.66},             {44, 9.23, 209.53},   {45, 8.22, 190.07},   {46, 8.76, 173.58},             {47, 7.9, 156.4},     {48, 8.38, 143.05},   {49, 9.53, 130.75},             {50, 9.33, 117.49},   {51, 9.72, 108.16},   {52, 10.55, 98.08},             {53, 13.05, 88.91},   {54, 13.58, 82.28},   {55, 16.31, 75.42},             {56, 17.75, 69.58},   {57, 20.11, 62.58},   {58, 23.98, 59.22},             {59, 28.51, 54.91},   {60, 31.61, 49.79},   {61, 37.13, 45.94},             {62, 45.06, 43.41},   {63, 53.4, 41.3},     {64, 62.39, 40.28},             {65, 72.89, 37.71},   {66, 86.92, 36.58},   {67, 103.32, 36.98},             {68, 121.7, 36.65},   {69, 144.86, 37.87},  {70, 171.92, 39.63},             {71, 202.51, 42.97},  {72, 237.69, 46.95},  {73, 276.77, 54.93},             {74, 319.76, 64.61},  {75, 362.05, 81.28},  {76, 400.11, 105.5},             {77, 427.79, 143.03}, {78, 434.56, 192.45}, {79, 410.31, 260.84},             {80, 354.18, 339.39}, {81, 278.49, 413.79}, {82, 203.72, 466.94},             {83, 141.06, 494.72}, {84, 95.08, 499.37},  {85, 66.76, 484.58},             {86, 45.41, 460.63},  {87, 33.13, 429.79},  {88, 25.89, 398.77},             {89, 20.51, 366.49},  {90, 17.11, 336.56},  {91, 12.69, 306.39},             {92, 11.76, 279.53},  {93, 11.22, 254.95},  {94, 10.29, 233.5},             {95, 8.82, 212.74},   {96, 9.51, 193.61},   {97, 8.69, 175.01},             {98, 9.53, 160.59},   {99, 8.68, 146.12},   {100, 10.82, 131.85}};      I have tried `ParametricNDSolveValue` but get a lot error message. Can you help me? ## Solution(up to now) We now have a **direct method** to solve this problem. The main idea is interpolating many points from `t=11` to `t=100`, then get the value of `dx/dt` and `dy/dt` by Finite Difference method(with minor time step, this can decrease the loss of accuracy). Finally, just use `FindFit` twice to get parameters `a`, `b` and `c`, `d`. So that system of ODEs can be determined, but how can we find `x[0]` and `y[0]`? Just solve the system backward using `NDSolve` or `NDSolveValue`.               {t, x, y} = Transpose[data]; (* extract data *)     {xdata, ydata} = (Transpose[{t, #}]) & /@ {x, y}; (* get {t,x} and {t,y} pairs *)     fx = Interpolation[xdata, Method -> "Spline"];  (* spline interpolation *)     fy = Interpolation[ydata, Method -> "Spline"];     dx=fx'[t];     dy=fy'[t];     ab=FindFit[Transpose[{fx[t], fy[t], dx}], a*X - b*X Y, {a, b}, {X, Y}]     cd=FindFit[Transpose[{fx[t], fy[t], dy}], -c*Y + d*X Y, {c, d}, {X, Y}]      Here we get `{a -> 0.213493, b -> 0.00119763}` and `{c -> 0.104194, d -> 0.000950553}`. As I put above, use `NDSolve` to find `x[0]` and `y[0]`.               (* search backward *)     NDSolve[{X'[u] == a*X[u] - b*X [u] Y[u] /. ab,  Y'[u] == -c*Y[u] + d*X[u] Y[u] /. cd,                  X[11] == 45.79, Y[11] == 41.4}, {X[0], Y[0]}, {u, 0, 12}]      It returns `{{X[0] -> 10.415, Y[0] -> 102.984}}`. Let's see the plot:               (* find solution of x[t], y[t] with NDSolveValue *)     sol = NDSolveValue[{X'[u] == a*X[u] - b*X [u]Y[u] /. ab,Y'[u] == -c*Y[u] + d*X[u]Y[u] /. cd,     X[11] == 45.79, Y[11] == 41.4}, {{u, X[u]}, {u, Y[u]}}, {u, 11, 100}]     (* plot the results *)     Show[{ListPlot[{xdata, ydata}, AxesLabel -> {"time", "value"},           PlotLegends -> {"xdata", "ydata"}, PlotStyle -> {Red, Green}],     ListLinePlot[{Table[sol[[1]], {u, 11, 100, 0.01}], Table[sol[[2]], {u, 11, 100, 0.01}]},           PlotStyle -> {Orange, Blue}, PlotLegends -> {"solution.x", "solution.y"}]}]      ![see the results](http://i.stack.imgur.com/WGMq9.png) It is obvious that scaters at the peaks and valleys are off the curves a little. This implies us that the result is not good enough and there exists improved space of the _direct method_. Can you image how difficult it would be using FDM when the system of ODEs is of much higher order? We must find out an universal way to solve this kind of problem. * * * Here we show another way:               {tval, xval, yval} = Transpose[data]; (*extract data*)     {xdata, ydata} = (Transpose[{t, #}]) & /@ {xval, yval }; (*get {t,x} and {t,y} pairs*)     (* define the embeded function with arguments a,b,c,d *)     px[a_?NumberQ, b_?NumberQ, c_?NumberQ, d_?NumberQ] := (modle[a, b, c, d] =          First[x /. NDSolve[{x'[t] == a x[t] - b x[t] y[t], y'[t] == -c y[t] + d x [t] y[t],                     x[11] == 45.79, y[11] == 41.70}, x, {t, 10, 100}]]);     FindFit[xdata, px[a, b, c, d][t], {{a, .1}, {b, .1}, {c, .1}, {d, .1}}, t]     py[a_?NumberQ, b_?NumberQ, c_?NumberQ, d_?NumberQ] := (model[a, b, c, d] =          First[x /. NDSolve[{x'[t] == a x[t] - b x[t] y[t], y'[t] == -c y[t] + d x [t] y[t],                     x[11] == 45.79, y[11] == 41.70}, y, {t, 10, 100}]]);     FindFit[ydata, py[a, b, c, d][t], {{a, .1}, {b, .1}, {c, .1}, {d, .1}}, t]      Unfortulately, it doesn't work. We need a _good initial value_ for `a`, `b`, `c`, `d`, or will fail to do the fitting work. Maybe we could take a chance to get _good value_ with the help of `NSolve` or `FindInstance`.


Plotting values above a threshold in ListPlot3D

I'm able to plot a 3D plot of a grayscale image using `ListPlot3D`, where it plots a 3D surface of the image pixel intensity. But I would like not to plot the pixel value below a certain value. In the specific case I'm working on, I want to remove all the pixels with value zero but still plot the pixels that are above zero at there original position. Does anyone knows of how to do this?


How to rotate TickMarks in DateListPlot?

Is there a way to rotate TickMarks in DateListPlot to avoid overlap, eg: ![enter image description here](http://i.stack.imgur.com/hnblp.jpg) Part of the code used to generate this is:               TimelineGr[file_] :=       DateListPlot[{{First[#], 1}, {Last[#], Length@#}} &@        Sort@Flatten[ Last /@ I2B2[file, dateIntervals], 1],        Epilog -> ({Text[First@#, {First@Last@#, First@#2}, {1, 0}], Blue,             Rectangle[{First@Last@#, First@#2}, {Last@Last@#,               First@#2 + 0.1}]} &~MapIndexed ~ I2B2[file, dateIntervals]),       PlotRange -> All, AspectRatio -> 1/4, ImageSize -> 800,        DateTicksFormat -> {"Year", "/", "Month", "/", "Day"},        FrameTicks -> {{Automatic, Automatic}, {           First[Last[#]] & /@ I2B2[file, dateIntervals], Automatic}},        PlotLabel -> file <> ".xml"       ]      (Note, this includes custom functions) If not, this is just another example of why it's almost always better to write visualization from the bottom-up


Export to CDF fails

The code below generates the error when I attempt to export to CDF Preview: > Coordinate {xde[4.69588928222656], yde[4.69588928222656]} should be a pair > of numbers, or a Scaled or Offset form. Here is my code:               system = {x'[t] == 2 x[t] - 0.08 x[t] y[t], x[0] == 400,        y'[t] == -y[t] + 0.01 x[t] y[t], y[0] == 25};          sol = NDSolve[system, {x[t], y[t]}, {t, 6}];          {xde[t_], yde[t_]} = {x[t], y[t]} /. Flatten[sol];          Animate[Show[       ParametricPlot[{xde[t], yde[t]}, {t, 0, 5.4},         AxesLabel -> {"Prey", "Predator"}, AspectRatio -> 1,         PlotRange -> {{0, 400}, {0, 80}}],        Graphics[{Red, PointSize[Large], Point[{xde[t], yde[t]}]}]], {t, 0,        5.4, AppearanceElements -> "PlayPauseButton"}, AnimationRate -> 0.5]      How can this be fixed? Thx.


Are there ways to create local variables analogous to a local variable in C++ and other languages?

There has been a great deal of discussion on local variables in Modules and Manipulate. If I am reading this correctly, local variables in a language such as C++ or C# are not exactly analogous to local variables in a Mathematica Module or Manipulate. Developers such as myself who come from a C++, C# background find the ability to restrict the scope of variables to a function very useful. These are often used because they minimize the risk of unintended changes to variable values. This is especially true if writing Modules or Custom Controls that other Mathematica developers may use. I don't want to run the risk of stepping on someone else's variable when they use my code. Is there a way to implement local variables in Modules or DynamicModules so they are not accessible and visible to the notebooks or code calling the Mathematica code? I have noticed that if I use the option LocalizeVariables->True in a Manipulate, the variables used by Manipulate as parameters that set the range and step value of the variable that as soon as the Needs[] is executed on the .m file containing my Module that all variables are visible and settable. I don't have to call the Module[] - just execute the Needs[] for the package or nb that contains the Module. This is a popular topic and with good reason. Below is an example:               BeginPackage["MyPackage`"]            LocalTestModule[]=Module[{localX, localY},                 localX=1; localY=2;]          EndPackage[]      I open a Mathematica notebook and issue the following command:               Needs["MyPackage`"]      My expectation is that I should not be able to set the value of the `localX` variable from the notebook because it is local to `LocalTestModule`. If it is truly local to LocalTestModule[], it should not be visible outside of `LocalTestModule[]`. However:               Information[localX]      returns `MyPackage`localX` And:               MyPackage`localX = 10      returns `10` In C or C++, a calling function would not have access to localX.


Does the VerticalCallout algorithm in PieChart work correctly?

This manufactured example is typical of many real world cases where we have thin slices of the pie:               Clear[labeler];     labeler[datax_][v_, {1, c_}, ___] := Placed[Column[{datax[[c]], v}, Alignment -> Center,      BaseStyle -> Directive[FontFamily -> "Arial", 11]],"VerticalCallout"];     data = Transpose[{"This is label " <> ToString[#] & /@ Range[14],Range[14]}];          PieChart[data[[All, 2]],      ChartStyle -> 54,      ImageSize -> {All, 300},      ImagePadding -> Automatic,      LabelingFunction -> labeler[data[[All, 1]]],      PerformanceGoal -> "Performance",      PlotRange -> All,      SectorOrigin -> {Automatic, 0},      SectorSpacing -> 0.15]      ![enter image description here](http://i.stack.imgur.com/vLO4h.png) It seems inevitable that when thin pie slices are adjacent you will have overlap problems with `RadialCallout` labels but it seems to me that `VerticalCallout` should have labels evenly spaced on the left and right side of the pie chart. Is the (non evenly spaced) distribution of labels as per the image a bug or intended? Does anyone know how to create evenly spaced vertical labels with built in options? (I can probably do this with my own code given enough time and patience but am looking for built in solutions)


How to generate a random matrix with specific parameters?

I want to use Mathematica to generate a random matrix with given dimensions, entries coming from a finite set, and with a determinant also coming from a finite set. (It's very important that the generation of this matrix is random. Ideally this process would give the same results as making a list of all matrices of the given size and possible entries with one of the acceptable determinants, and picking one at random.) Some implementations of this are easy. To solve the 2x2 case with determinant == 1, and integral entries from -10 to 10, I can enter               Solve[{a d - b c == 1, -10 <= a <= 10, -10 <= b <= 10, -10 <= c <= 10, -10 <= d <= 10}, {a, b, c, d}, Integers]      But this doesn't easily extend to the problem of having broader sets of possible entries, e.g. a, b, c, and d being from -20 to 15, and being fractions with denominator between 1 and 10. That isn't essential, but the following condition is: I only need one random matrix, and I need it quickly -- but Mathematica takes forever via the above trick to generate all possible 3x3s. I thought of trying to use FindRoot together with seeding the process with random values, but I couldn't find control over If there isn't a single function that will do the trick, I don't mind writing a function in Mathematica to do what I'm looking for -- but I'm very much a newbie to MM, so as much advice as you can give me would be greatly appreciated! EDIT: As per gpap's excellent answer, here's the code that I've ended up with, modified from his answer to work with fractions.               det = Module[{i}, Sequence @@ (i /. Solve[Det[{{#1, #2, #3}, {#4, #5, #6}, {#7, #8, i}}] == 1, i]) &];          candidates = Apply[{##, det@##} &, RandomChoice[{0, 1/2, 1, 3/2, 2}, {10000, 8}], 2] // Quiet;          RandomChoice[Select[candidates, MemberQ[{0, 1/2, 1, 3/2, 2}, Last@# ] &]];


A bug in Commonest in version 10

**Bug introduced in 10.0.0** * * * m_goldberg demonstrated that in _Mathematica_ 10 `Commonest` does not behave as the documentation indicates that it will. Concisely: ![enter image description here](http://i.stack.imgur.com/YdXqX.png)               Commonest[{1, 2, 3, 1, 2, 3}, 1]  (* should return {1} *)      > >     {3} >   The function did behave as it was supposed to in earlier versions.


Locate Blow-up in NDSolve with Whenevent

At some point I get this error:               Warning: scaled local spatial error estimate of 32773.0090044258` at      t = 987.7919550194803` in the direction of independent variable x is much greater than the          prescribed error tolerance. Grid spacing with 1001 points may be too large to achieve the       desired accuracy or precision.         (etc.) How do I track this time with `WhenEvent`? How is this _scaled local spatial error_ kept in NDSolve?


Export date with specified format

My problem is that I want use _PGFplot_ in $\LaTeX$ to draw my graphs, which x axis is a date. Therefore the output file has to have one column _"UTC time" (YYYY-MM-DD hh:mm:ss)_ and the second one is the corresponding data list. Would it be possible to specify the date format of `Export[]` ?


Problem with integral equations

I have solved an integral equation with the following methods:               Options[FredholmKind2]={Method->Automatic};     FredholmKind2[{a_,b_,lambda_,k_,g_},n_?IntegerQ,OptionsPattern[]]:=          Block[{step,SI,GI,KMatrix,W,DMatrix,f,deltaX,delta},step=(b-a)/n;       SI=Range[a,b,step];       GI=g/@SI;       KMatrix=Outer[k,SI,SI];       W={step/2}~Join~ConstantArray[step,n-1]~Join~{step/2};       DMatrix=DiagonalMatrix[W];       f=If[OptionValue[Method]===NIntegrate,deltaX[x_?NumericQ]:=          W.(k[x,#]&/@SI)-NIntegrate[k[x,y],{y,a,b}];       (*If the integral is expensive ParallelMap is an option here*)delta=deltaX/@SI;          Interpolation[            Transpose@{SI,LinearSolve[IdentityMatrix[n+1]+                  lambda*(DiagonalMatrix[delta]-KMatrix.DMatrix),GI]}],         Interpolation[           Transpose@{SI,LinearSolve[IdentityMatrix[n+1]-                  lambda*(KMatrix.DMatrix),GI]}]];     f]          n=50;(*number of discretization*)a=0.;     b=1.;     lambda=-1.;     Kpart[x_,y_]:=With[{A=2},(A/2)*         (BesselJ[1,A*(x+y)]-BesselJ[1,A*Abs[x-y]]-I*StruveH[1,A*(x+y)]+I*StruveH[1,A*Abs[x-y]])]     Gpart[x_]:=x;     f1=FredholmKind2[{a,b,lambda,Kpart,Gpart},n,Method->Automatic];     f2=FredholmKind2[{a,b,lambda,Kpart,Gpart},n,Method->NIntegrate];     (Plot[Evaluate@(#/@{f1[x],f2[x]}),{x,a,b},Frame->True,Axes->False,         PlotStyle->{{Thick,Opacity@.45},{Dashed,Red}},         PlotLegends->{"Automatic","NIntegrate"},ImageSize->400]&/@{Re,Im})      I now want to evaluate and then plot Ktt(A):               Ktt[A]=A^3*NIntegrate[x f2[x],{x,0,1}]      for A ranging from 0 to 10 with 0.01 step. This means that for all these values of A I must find the corresponding f2(x) and then the corresponding Ktt(A) and then put all the Ktt points into a plot. Is there a way to do this with matrices or maybe with a loop?


Social Network Analysis - Get the End Points of an Edge

I want to get the end points of an Edge of a Graph. For example see the following source,               In[1]:=gFriendShip = ExampleData[{"NetworkGraph", "Friendship"}];     In[2]:= EdgeList[gFriendShip, "Rose" \[UndirectedEdge] _]     Out[2]:={"Anna" \[UndirectedEdge] "Rose", "Ben" \[UndirectedEdge] "Rose",       "Rose" \[UndirectedEdge] "Nora"}      Now I want to write something like `EndPoints["Rose" \\[UndirectedEdge] "Nora"]` (actually, `EndPoints[%2]` in the above example) and want to get `{"Rose", "Nora"}` as output. It might be a basic thing, but I am new to _Mathematica_. I am using _Mathematica 9.0_.


Find points on the surface of a Graphics3D object

If I have a Graphics3D object that was generated from manipulations to PolyhedronData rather than via an explicit equation, for example the Spikey ![Spikey 6!](http://i.stack.imgur.com/N2Kqn.png) (for which the entire code can be found here _The Cover Image: Making the Mathematica 6 Surface-Textured Hyperbolic Dodecahedron_, but which culminates with the following command,               Graphics3D[{EdgeForm[],        addHatToL /@ Take[Flatten[Take[LsOnDodecahedron, All]], All]},       PlotRange -> All, Boxed -> False, ImageSize -> Full,       Lighting -> {{"Ambient", RGBColor[0.2, 0, 0]}, {"Point",          RGBColor[0.4, 0.4, 0.4], {2, 0, 2}}, {"Point",          RGBColor[0.4, 0.4, 0.4], {2, 2, 2}}, {"Point",          RGBColor[0.4, 0.4, 0.4], {0, 2, 2}}, {"Point",          RGBColor[0.2, 0, 0], {-2, -2, -2}}}]      Is there a way for me to extract/generate a table of 3D points along the surface of (or within, I don't actually care) the object? I saw _Efficiently determining if 3D points are within a surface composed of polygons_, which went a bit over my head, but many of the answers given seemed to either require a 'nice' shape (i.e., no concave surfaces, no cusps, no self-intersections, etc.) or be based on the fact that he had generated the object with generated data sent to ListContourPlot3D, which is not the case here.


Finding the common areas of two contourplots

I used ListContourPlot to specify an area for which the function value is less than a number. For example consider the following areas:                plot1 = ListContourPlot[       Table[Sin[i + j^2], {i, 0, 3, 0.1}, {j, 0, 3, 0.1}],        RegionFunction -> Function[{x, y, z}, z < 1], PlotRange -> {0, 1},        DataRange -> {{0, 3}, {0, 3}}]          plot2 = ListContourPlot[       Table[Cos[i + j^2], {i, 0, 3, 0.1}, {j, 0, 3, 0.1}],        RegionFunction -> Function[{x, y, z}, z < 0.7]       , PlotRange -> {0, .7}, DataRange -> {{0, 3}, {0, 3}},        ColorFunction -> ColorData["BlackBodySpectrum"]]      ![enter image description here](http://i.stack.imgur.com/sKiVP.jpg) ![enter image description here](http://i.stack.imgur.com/6Kxyx.jpg) How can I specify the common areas of these two parameter spaces in a plot? RegionPlot doesn't give the common area:               RegionPlot[      Sin[i + j^2] < 1 && Cos[i + j^2] < 0.7, {i, 0, 3}, {j, 0, 3},       PlotPoints -> 80, Mesh -> 2,       ColorFunction ->        Function[{x, y}, ColorData["SolarColors"][Sin[x^2 + y]]],       PlotRange -> {0, 2},       MeshFunctions -> {Sin[#1^2 + #2] &, Abs@Cos[#1^2 + #2] &}]      ![enter image description here](http://i.stack.imgur.com/435jW.jpg) Because RegionPlot uses i and j which change continuously but ListContourPlot uses only certain number of data:               {i, 0, 3, 0.1}, {j, 0, 3, 0.1}


How can I access Mathematica kernel for WebMathematica in Linux(Ubuntu 12.04)

I have been working in `webMathematica` with Application server(Geronimo 3.0.1) in windows, It was working fine. Recently I have changed to Linux(ubuntu 12.04). I have installed mathematica in Linux and made it work then I have installed Application server(Geronimo 3.0.1) and it is working with with sample JSP applicaiton and try to deploy webMathematica 3.2.0 in Application server. I need to change MSPConiguration file to access `mathekernel` like               <KernelExecutable>/home/niren/Wolfram/Mathematica/9.0/Executabales/MathKernel.sh</KernelExecutable>      But it is not working. For windows I used like               <KernelExecutable>C:\Program Files\Wolfram Research\Mathematica\9.0\MathKernel.exe</KernelExecutable>      It was working for windows. Suggest me how should I refer `MathKernel` in `MSPConfiguration` file of `webMathematica` in Linux. Note: I can deploy sample `jsp` application in application server and made it work. But can't make `webMathematica` work.


integrating a Green's function for a damped harmonic oscillator

I have the following integrand:               int = Sin[Sqrt[-g^2 + omega^2]*(t - tp)]*Exp[-g*(t - tp)]*A*Exp[-(tp - t0)^2/sigma^2]*Cos[Omega*tp]/Sqrt[-g^2 + omega^2]      and am trying to integrate it with:               Integrate[int, {tp, 0, t}, Assumptions -> {g > 0, omega > 0, Omega > 0, A > 0, sigma > 0, t > 0, t0>0}]      but _Mathematica_ is not able to do it (I have tried to do this with no assumptions as well). Maple does the integration in under a second and returns a solution (which can be expressed in terms of the Erf functions). Is there a way to help _Mathematica_ calculate this integral? ... and just to note, the result of the integration is a solution of damped harmonic oscillator, driven by a force:               A*Exp[-(t - t0)^2/sigma^2]*Cos[Omega*t]


Speed up Eliminate

I have a set of trig equations, c1,c2,c3 are constants, I excepted the result is `c1 c2 c3 r^2 + (c1^2 + c2^2 + c3^2 - 1) r + c1 c2 c3 == 0` but following code worked so slow, is there a faster method do this?               Eliminate[{       c1 == Cos[a] Sin[b],       c2 == Cos[b] Sin[c],       c3 == Cos[c] Sin[a],       r== Tan[a] Tan[b] Tan[c]}, {a, b, c}]


How to make endpoints flush with fill in ListLinePlot?

If one plots a filled line plot such as, for example, the one produced by               ListLinePlot[{{{0, 0.6}, {0.5, 0.6}}, {{0.5, 0.3}, {1, 0.3}}},          Filling -> Axis, PlotStyle -> AbsoluteThickness[10],         AspectRatio -> Automatic, PlotRange -> {Automatic, {0, 0.8}},         PlotRangePadding -> None]      ![](http://i.stack.imgur.com/bUxRT.png) the ends of the plot's lines have a rather noticeable "overhangs" beyond the fill regions below. How can I make this line be flush with the fill?


Automatically generated summation region

In a multiple `Sum` I need to put an automatically generated summation region. But when I generate the summation region automatically I get a list whose elements are lists. Then the summation does not work. For example:               Sum[1,{i,1,2},{j,1,2}]      works;               Sum[1,{{i,1,2},{j,1,2}}]      or               A = Table[{i[j],j+1},{j,2}];     Sum[1,A]      doesn't work.


Why my if statement does not work

Thanks for your attention. I'm new to mathematica. I have the codes as below. But the If statement does not work. Anything wrong with my code? Thanks for help! Ben               ClearAll;     (*Define of hill function*)          Hillinh[x_, nx_, x0_] = 1./(1. + (x/x0)^nx) ;     Hillexc[x_, nx_, x0_] = 1. - Hillinh[x, nx, x0];     Hillshift[x_, nx_, x0_, lamda_] = lamda + (1. - lamda)*Hillinh[x, nx, x0];     (*Parameters*)     aa =  2(*gx/(k*xT)*);     (*bb= 10 gy/(k*yT)*)     py = 4;     px = 4;     yT = 1;     xT = 1;     data = {};          For[i = 1, i <= 20, i++,           bb = i*0.5;           (*Equations for system*)      eqs1 = aa*Hillinh[y, py, yT] - x;      eqs2 = bb*Hillexc[x, px, xT] - y;      eqscomb = {eqs1, eqs2};           (*calculate the fixpoint and eigenvalues*)      r = {x, y};       fp = NSolve[Rationalize[Thread[eqscomb == 0 && x > 0 && y > 0]], r, Reals];           (*Calculate tau*)      xs = x /. fp;      ys = y /. fp;           alpha = (py/aa)*xs^2*ys^(py - 1);      beta = (px)*(ys/xs)*(1 - ys/bb);      test = alpha*beta - 1;                If[test <= 0, Continue[], Print[-2*ArcTan[Sqrt[test]]/Sqrt[test]+Pi/Sqrt[test]]];           ]


NDSolve PDE, not enough boundary condition?

The PDE that I want to solve is: $$ \frac{\partial f}{\partial t} + \frac{1}{m} \left( p_x \frac{\partial f}{\partial x} + p_y \frac{\partial f}{\partial y} + p_z \frac{\partial f}{\partial z} \right) - \frac{\partial V}{\partial x} \frac{\partial f}{\partial p_x} - \frac{\partial V}{\partial y} \frac{\partial f}{\partial p_y} - \frac{\partial V}{\partial z} \frac{\partial f}{\partial p_z} = 0 $$ where $$ V(x,y,z) = c \sqrt{\frac{x^2 + y^2}{4 a^2} + \frac{z^2}{a^2}} $$ the boundary/initial condition I have is: $$ f(x,y,z,p_x,p_y,p_z,t=0) = exp \left(- \frac{p_x^2 + p_y^2 + p_z^2}{2 m} - (x^2 + y^2 + z^2) \right) $$               potentialCartesian[x_, y_, z_, a_, c_] := c Sqrt[(x^2 + y^2)/(4 a^2) + z^2/a^2]          eqn = D[f[x, y, z, px, py, pz, t], t] + 1/m (px D[f[x, y, z, px, py, pz, t], x] + py D[f[x, y, z, px, py, pz, t], y] + pz D[f[x, y, z, px, py, pz, t], z]) - D[potentialCartesian[x, y, z, a, c], x] D[f[x, y, z, px, py, pz, t], px] -D[potentialCartesian[x, y, z, a, c], y] D[f[x, y, z, px, py, pz, t], py] - D[potentialCartesian[x, y, z, a, c], z] D[f[x, y, z, px, py, pz, t], pz] == 0;          ic = f[x, y, z, px, py, pz, 0] ==  Exp[-((px^2 + py^2 + pz^2)/(2 m)) - (x^2 + y^2 + z^2)];          sol = NDSolve[        {         eqn /. {m -> 1, a -> 1, c -> 1},         ic /. {m -> 1, a -> 1, c -> 1}        },        f,        {x, -5, 5},        {y, -5, 5},        {z, -5, 5},        {px, -5, 5},        {py, -5, 5},        {pz, -5, 5},        {t, 0, 5}     ]      When I run the NDSolve command, I get the following warnings:               NDSolve::nerres: The maximum number of spatial points (10) for independent variable x allowed by MaxPoints -> Automatic or MinStepSize -> Automatic is too few to compute a spatial error estimate. >>     NDSolve::nerres: The maximum number of spatial points (10) for independent variable y allowed by MaxPoints -> Automatic or MinStepSize -> Automatic is too few to compute a spatial error estimate. >>     NDSolve::nerres: The maximum number of spatial points (10) for independent variable z allowed by MaxPoints -> Automatic or MinStepSize -> Automatic is too few to compute a spatial error estimate. >>     General::stop: Further output of NDSolve::nerres will be suppressed during this calculation. >>     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. >>     NDSolve::bcart: Warning: an insufficient number of boundary conditions have been specified for the direction of independent variable y. Artificial boundary effects may be present in the solution. >>     NDSolve::bcart: Warning: an insufficient number of boundary conditions have been specified for the direction of independent variable z. Artificial boundary effects may be present in the solution. >>     General::stop: Further output of NDSolve::bcart will be suppressed during this calculation.       Is this because I don't have enough boundary/initial conditions? The problem I am trying to solve only has a single initial condition, do I need to use other methods to solve it?


Is there a more idiomatic way to solve this implicit differentiation problem?

Here's an exercise from a calculus text by _Larson_ and _Edwards_ : > Find the rate of change of the distance between the origin and a moving > point on the graph of $y = x^2 + 1$ if $dx/dt = 2$ centimeters per second. Here's one way to solve it:               eq1 = d[t]^2 == x[t]^2 + y[t]^2;     eq2 = y[t] == x[t]^2 + 1;     {eq1, D[eq1, t], eq2, D[eq2, t], x'[t] == 2};     Reduce[%, {d'[t], d[t], y'[t], y[t]}]      Is there another way to solve it that might be considered more idiomatic?


Split list of states by run lengths and discontinuous changes in state

I was asked to look into writing some simulation code for a user, where the simulation output (`x`) would oscillate between three possible states:               states[x_, γ_] := Which[     x < -γ,  1 (*top*),     x < γ , -1 (*bottom*),     True  ,  0   (*middle*)]      The simulation essentially boiled down to the following, and what they were interested in is computing the lengths runs in each state - which could be easily computed with `SplitBy`:               γ = 0.9;     sampleSimulation = RandomChoice[{-1, 0, 1}, 1000000];     runLengths = Switch[Sign[#[[1]]],           1, {"top", Length[#]},         -1, {"bottom", Length[#]},           0, {"middle", Length[#]}      ] & /@ SplitBy[sampleSimulation, states[#, γ] &]      However, if the simulation output moved between the `"top"` and `"bottom"` states (in either direction) without occupying the `"middle"` state they needed this information in `runLengths` via the string `"unoccupied middle"`. The following code achieves that and is surprisingly performant and the experimenter was happy. However it feels unnecessary to `SplitBy` and then `Reap` and `Sow` with a `Do` loop to find where the simulation moves seemlessly between `"top"` and `"bottom"`. What would be a more natural, and less wasteful method to solve such a problem?               runLengthsFunc[list_, γ_] :=      Block[{splitting},       splitting =         Switch[Sign[#[[1]]],            1, {"top", Length[#]}, -1, {"bottom", Length[#]},            0, {"middle", Length[#]}] & /@          SplitBy[list, states[#, γ] &];       Append[Flatten[         Reap[Do[If[(splitting[[k, 1]] == "top" &&                 splitting[[k + 1, 1]] == "bottom") || (splitting[[k, 1]] ==                  "bottom" && splitting[[k + 1, 1]] == "top"),              Sow[{splitting[[k]], "unoccupied middle"}],             Sow[{splitting[[k]]}]],            {k, Length[splitting] - 1}            ]][[2]], 2], splitting[[-1]]]]      Timing:               In[10]:=AbsoluteTiming[runLengthsFunc[sampleSimulation, γ];]     Out[10]:={7.526282, Null}      **Solution Choosing** Thanks for the three very different solutions, as requested the focus was on different methodologies rather than sheer blistering speed. I'm going to accept Mr Wizard's answer as it provided the most different approach (and best learning experience for me) as well as exceptional speed - under a second for an initial set of 1,000,000 states. However, there was an apparently superfluous process; Unitize where a list already contained only 0,1. Kguler's method falls apart for more than ~3000 elements, but is a great example of pattern matching. And it's great to see in both this and Mr Wizard's solutions the convergent evolution of SE toward Composition. Leonid's answer introduced me to linked lists which will be a useful tool for similar problems I have. Unfortunately, I can't benchmark Leonid's as he elected to focus on methodology rather than speed so did not include an implementation of runLengths - but the linking of lists is much more performant than my `Reap[Do[Sow]` approach.


Finding elementary cycles of (directed) graphs

I need to enumerate all the simple cycles (i.e. elementary cycles where no vertex is repeated other than the starting) of a graph which has both directed and undirected edges, where we can treat the undirected edges as doubly directed. (Specifically, I am looking at the Cayley graphs of S3 and S4, which can be produced using `CayleyGraph[SymmetricGroup[3]]` and `CayleyGraph[SymmetricGroup[4]]` respectively.) I have tried two ways of doing this so far. First, I have tried using `ExtractCycles` in the _Combinatorica_ package, as detailed in this answer by TomD. For example, entering the ordered pairs for S3 (as "el"):               el = {{1, 2}, {1, 4}, {2, 3}, {2, 5}, {3, 1}, {3, 6}, {4, 1}, {4, 6}, {5, 4}, {5, 2},      {6, 5}, {6, 3}}      And then using:               Needs["Combinatorica`"]     ExtractCycles@FromOrderedPairs@el      returns:               {{5, 4, 6, 5}, {6, 3, 6}, {5, 2, 5}, {4, 1, 4}, {3, 1, 2, 3}}      However, that set is incomplete - what about e.g. `{{5, 4, 1, 2, 5}, {5, 4, 1, 2, 3, 6, 5}}`? These are simple cycles, so why are they not included in the list? The output for S4 is also much truncated (obviously we would expect a _lot_ of cycles there, but the output gives only eighteen). The second thing I tried was this answer by kguler. Taking the example of S3, using `CycleGraph[3, DirectedEdges -> True]` gave the right results, but `CycleGraph[4, DirectedEdges -> True]` did not - i.e. the cycles `{5, 4, 1, 2, 5}` etc. were not picked up again. Presumably this is something to do with the doubly directed edges? Any help with this would be much appreciated! **Edit:** As requested, the ordered pairs for the Cayley graph of S4 are:               el2 = {{1, 2}, {1, 9}, {2, 3}, {2, 17}, {3, 4}, {3, 13}, {4, 1}, {4, 5}, {5, 4}, {5, 6},     {6, 16}, {6, 7}, {7, 8}, {7, 22}, {8, 5}, {8, 10}, {9, 1}, {9, 10}, {10, 8}, {10, 11},     {11, 12}, {11, 21}, {12, 9}, {12, 18}, {13, 14}, {13, 3}, {14, 15}, {14, 20}, {15, 16},     {15, 23}, {16, 13}, {16, 6}, {17, 2}, {17, 18}, {18, 19}, {18, 12}, {19, 24}, {19, 20},     {20, 17}, {20, 14}, {21, 11}, {21, 22}, {22, 7}, {22, 23}, {23, 15}, {23, 24}, {24, 19},     {24, 21}}


Trying to use NDSolve to solve Blasius equation

s = NDSolve[{f'''[eta] + 0.5*f[eta]*f''[eta] == 0.0, f[0] == 0.0,      f'[0] == 0.0, f'[Infinity] = 1.0}, f, {eta, 0, 1}];     Plot[Evaluate[f[eta] /. s], {eta, 0, 1}, PlotRange -> All]      I don't understand why this doesn't work. I followed exactly the instructions from the site. I get the following error (among others)               NDSolve::deqn: Equation or list of equations expected instead of 1.` in the first argument


Scaling of ChartElements

In attempting to answer this question from @Cam on `BubbleCharts` with elliptical bubbles, I suggested using separate `ChartElements` which themselves could be ellipses. My idea was to define them as regular graphics objects and use them like this:               datatoplot = {{1, 2, 0.5, 0.7}, {10, 5, 10, 0.2}};     ellipse[v_] := Disk[{v[[1]], v[[2]]}, {v[[3]]/10, v[[4]]/10}];     ce = Graphics[Style[ellipse[#], Blue]] & /@ datatoplot;     Show[BubbleChart[{datatoplot[[;; , ;; 3]][[#]]},ChartElements->ce[[#]]]&/@{1,2}, PlotRange -> All]      However, while the objects I've called `ce` above are indeed ellipses, they get rescaled when they are used as ChartElements and their ellipsicity is undone (or at least altered). It seems in the help section for `ChartElements` that the format to define the width and height is to give               ChartElements->{g,{w,h}}      but this gives an error message when I try and implement it naively (with an arbitrary scaling of `{0.3,0.6}`). Trying it by hand:               Show[BubbleChart[{datatoplot[[;; , ;; 3]][[#]]},ChartElements -> {ce[[#]], {0.3, 0.6}}]&/@{1,2}, PlotRange -> All]      gives me the error shown here: ![error message](http://i.stack.imgur.com/3KZ7N.png) Does anyone know how to correctly implement the scaling for `ChartElements`? Is it that the elements should somehow be different from regular Graphics objects?


Histogram scale error when using DistributionChart

I'm a novice Mathematica user that is having some problems using the HistogramDensity function in a DistributionChart. My observations are heavily skewed to one category and the height of the other categories are larger than the number of observations should imply. Any ideas? Here's a stylized example of my problem:               data = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4}     DistributionChart[data, ChartElementFunction -> ChartElementDataFunction["HistogramDensity", "Bins" -> 4]]      ![enter image description here](http://i.stack.imgur.com/cksjk.png)


What are good/best practices to take the Fourier transform of an InterpolatingFunction?

I have a function which I have obtained from numerical integration of a differential equation, and I would like to take its Fourier transform. What are good practices for doing this? To make things more precise, suppose I have a function like the following:               solution =  u /. First@NDSolve[{              u'[t] == -E^(-(t^2/2)) t Cos[5 t] - 5 E^(-(t^2/2)) Sin[5 t] t,              u[0] == 1           }, u, {t, 0, 50}]      (Note that, while this example has an analytical solution, my full problem does not.) I am using `NDSolve` since it appears to be the best way to obtain functions $F$ of the form $F(t)=\int_{t_0}^t f(\tau) \,\text d\tau$ where $f$ is known. I am interested in the Fourier transform of this solution. I know of course that I can sample this function over a discrete set of points and then use the discrete Fourier transform `Fourier` to obtain a fair approximation:               ListPlot[      Abs[       Fourier[solution /@ Range[0, 50, 0.01]]       ]      , PlotRange -> {{0, 150}, {0, 1}}]      ![enter image description here](http://i.stack.imgur.com/6xKbc.png) However, this completely ignores the fact that the `InterpolatingFunction` itself is already a discrete representation of the desired function. As it stands, the code above includes interpolation from a discrete data set into a new discrete data set, and this can only   * lose information, in the case that the sample grid is too sparse, or alternatively   * give the impression that it contains more information than was already in the original data, if the sample grid is too closely spaced. Either way, this extra sampling step has no communication with the internals of the `InterpolatingFunction` and as such it cannot know how much information it contains or how good it is. **I am looking for a method which uses this information as optimally as possible.** The accuracy of the ODE solution, and therefore of its transform, are best controlled from the options of `NDSolve`, and the subsequent transformations of the data should take heed of this. I am aware of `NFourierTransform`, which, as I understand, uses `NIntegrate` internally; I'm also aware that `NIntegrate` natively supports `InterpolatingFunction` objects, which is presumably still the case if they are multiplied by a further factor of $e^{i\omega t}$. (On the other hand, the behaviour of this factor can rather radically change the overall behaviour of the whole integrand from 'slow' into highly oscillatory, so that some attention to `Method` would be warranted.) It could be, though, that the Fast nature of `Fourier` might be enough to outstrip such advantages, and still be faster than `NFourierTransform` even when over-blasted on the accuracy. Speed is definitely an issue, as I will be performing automated scans over many such spectra, so I want them to be accurate enough but not waste time overcalculating. So: what are good ways of performing this transform?


Plotting the solutions to a transcendental equation

I am trying, to no avail, to use _Mathematica_ to produce a plot in (x, y)-space of the solutions to the equation               Cos[Sqrt[y]] + Sin[Sqrt[y]]/Sqrt[y] == Cos[x]      Neither `NSolve` nor `InverseFunction` seem to work for inverting the equation (probably because there are multiple solutions for y for each x). Does anyone know a way to make such a plot?


Automatically shrink stretched images back to their original dimensions

We all sometimes find images on the web that are carelessly stretched to larger dimensions than original, which results in nothing but a reduction of the detail / dimensions ratio. See **Original** vs **Stretched** below: * * * Source: Kaley Cuoco (Model), Esquire (Latin America) # Original ![original](http://i.imgur.com/WsXXsnL.jpg) # Stretched ![stretched](http://i.imgur.com/RMEuvh3.jpg) * * * Questions:   1. Given only **Stretched** , is there a way to automatically find the best dimensions to shrink _Stretched_ down to which maximizes the `detail / dimensions` ratio?   2. Is there a generic way to define `detail` for all images (photos, line-art, text, etc.)?   3. Is 'stretched' the correct term or is there a more technically correct applicable?


Dynamic boundaries for FindRoot

As documented               FindRoot[f[x], {x, xs, min, max}]       searches for a solution, stopping the search if `x` ever gets outside the range `min` to `max` and returning the error `FindRoot::reged`. Now I have               FindRoot[{f[x, y], g[x, y]}, {{x, xs}, {y, ys}}]      and I want to obtain the same behavior but for the constrain `x > y`. Is this possible? In particular, I'm interested in the case in which there are many solutions that satisfy the constrain, and I want to get as many as possible of them by giving several starting points.


Is there a summary of answers Head[] can give?

Sometimes you need to check for the type of an expression. You use Head[data] to get answers. Some data:               data = {7, 1.4, Red, "hp", hps};     Head /@ data     (*{Integer, Real, RGBColor, String, Symbol}*)      Is there summary of what kind of answers `Head[]` can give?


Extract attribute data from an XMLElement

I'm trying to come to grips with parsing an XML file but I'm having difficulty working out how to extract specific attribute data from an XMLElement. Sample XML file below:               <!DOCTYPE DEXXMLDoc SYSTEM "DEXXMLDoc.DTD">     <DEXXMLDoc name="RSM-a.xml" creator="DX8" version="8.0.6">     <designInfo studyType="ResponseSurface" designType="CCD" noOfRuns="20" noOfFactors="3" noOfResponses="2">     <designNotes>This data file created by Design-Expert 6</designNotes>     </designInfo>     <blockInfo>     <block code="0" name="Block 1"/>     <block code="1" name="Block 2"/>     </blockInfo>     <factorInfo>     <factor id="A" name="time" unit="min." type="Numeric">     <numeric low="40" high="50" stdDev="0"/>     </factor>     <factor id="B" name="temperature" unit="deg C" type="Numeric">     <numeric low="80" high="90" stdDev="0"/>     </factor>     <factor id="C" name="catalyst" unit="%" type="Numeric">     <numeric low="2" high="3" stdDev="0"/>     </factor>     </factorInfo>      As you can see, this particular XML file relies on attributes to hold much of the data. I have no trouble selecting entire XMLElement(s) by name using `Cases` but I can't seem to work out how to extract specific attribute data by name. For example, I'd like to be able to extract the `studyType` attribute from the `designInfo` element. This is what the XMLElement that I'm working with looks like:                   XMLObject[       "Document"][{XMLObject["Doctype"]["DEXXMLDoc",         "System" -> "DEXXMLDoc.DTD"]},       XMLElement[       "DEXXMLDoc", {"name" -> "RSM-a.xml", "creator" -> "DX8",         "version" -> "8.0.6"}, {XMLElement[         "designInfo", {"studyType" -> "ResponseSurface",           "designType" -> "CCD", "noOfRuns" -> "20", "noOfFactors" -> "3",           "noOfResponses" -> "2"}, {XMLElement[           "designNotes", {}, {"This data file created by Design-Expert \     6"}]}], XMLElement[         "blockInfo", {}, {XMLElement[           "block", {"code" -> "0", "name" -> "Block 1"}, {}],           XMLElement["block", {"code" -> "1", "name" -> "Block 2"}, {}]}],      Does anyone have experience in extracting named attribute data from XMLElements?


Prevent Mathematica to automatically evaluate Manipulate at start

I'm using an initialization cell to import a lot of data:               data = Import[myFiles];      and then I use a custom function to display this data with Manipulate:               Manipulate[customFunction[data,variable],{variable,{0,1}}]      I have to keep these two commands in two seperate cells, because importing the data in `customFunction` each time I manipulate `variable` would take a lot of time. The problem is, when I start my notebook, `Manipulate` is evaluated automatically and sends a lot of error messages, because `data` is not defined. I know it might go against what Manipulate is made for, but is there a way to prevent Manipulate from being evaluated until I import my data for the first time?


3D bubble textures in Bread (and other solids)

Bread has a bubbly texture that I would like to be able to recreate using Mathematica. Here are some examples of bubble textures:   * Bread ![enter image description here](http://i.stack.imgur.com/MdNcU.jpg)   * Swiss cheese ![enter image description here](http://i.stack.imgur.com/jURI2.jpg)   * Foam ![enter image description here](http://i.stack.imgur.com/wIj9K.jpg) Note that most of the bubbles are ellipsoids or more complex 3D forms (only 'isolated' bubbles in the second case are approximately spherical). Bubbles generally do not intersect but are deformable by each other (and by the original 'pre-cut' boundary of the object - e.g. in the case of bread). Closely spaced bubbles approach polyhedrons with a minimum curvature at the 'vertices' (like 3d voronoi texture). I can generate a bunch of spheres intersecting a cube easily using something like:               Graphics3D[{Cuboid[{-2, -2, -5}, {8, 10, 10}],      Sphere[RandomReal[10, {500, 3}], RandomReal[{0.1, 1}]]}]      ![enter image description here](http://i.stack.imgur.com/Y6gDb.png) But I can't see how to variably change their shape or allow them to deform without intersecting. Ultimately I'm looking to make bubbles that are deformed by each other and the 'pre-cut' boundary of the solid. I am thinking that one way to visualise this would be generate the bubbles (for example, within a 'pre-cut loaf' shape) and combing this with a surface slice using `ParamtericPlot3D` to end up with something like this: ![enter image description here](http://i.stack.imgur.com/f9kw9.png) (but with nice bubbles inside!) I realise that it may be non-trivial to work out how the bubbles deform... Also, it would be nice to be able to add colours and 2D textures to the different surfaces to, for example, brown the crust, add wholemeal flakes etc. How would one go about creating a semi-realistic bubble texture _intersecting_ a 3D surface and/or volume? (P.S - Not entirely relevant but there are some inspiring forms here and here)


How can I make a 2D line plot with a drop shadow under the line?

You often see plots styled like this (ignore the bar chart component): ![enter image description here](http://i.stack.imgur.com/Slmeh.jpg) i.e. with a small drop shadow under the line. (I'm assuming Excel is being used to produce these plots). How could you make something similar in Mathematica?


How to specify optional arguments that take functional values

I am trying to make a function with an optional argument that may change but mathematica caches the value when the function is defined. Here is an example where the optional time variable is set when the function is defined.               Remove[CurrentTime]     CurrentTime[time_: DateList[]] := {time, DateList[]};     Pause[1]     CurrentTime[]      The output is split by 1 second               {{2013, 6, 4, 13, 57, 46.149504}, {2013, 6, 4, 13, 57, 47.150726}}      Is there a way to tell it its a delayed set, or to just read the function each time?


How do I find the coordinates of points in this image?

I have never used image processing with Mathematica. I need to get the coordinates of the red points from this image I made in Illustrator. Is there a way to get Mathematica to read or detect the x-y coordinates? ![enter image description here](http://i.stack.imgur.com/R0Dqo.png)


How to solve this exponential inequality?

I want to solve the exponential inequality $$8^x +18^x -2\cdot 27^x>0.$$ I tried               Solve[8^x + 18^x - 2*27^x > 0, x]      and               Reduce[8^x + 18^x - 2*27^x > 0, x]      How do I tell _Mathematica_ to do that?


Is it possible to impose "Assumptions" in DSolve or equivalent? (differential equation solving)

When `DSolve` tries to solve differential equations, it is sometimes not smart enough to generate conditions according to different possible value of parameters. Consider the following minimal example, $x'=x^2-a$:               DSolve[x'[t] == x[t]^2 - a, x[t], t]      The result is               {{x[t] -> -Sqrt[a] Tanh[Sqrt[a] t - Sqrt[a] C[1]]}}      This would be wrong if $a \leq 0$. (When $a<0$ one may argue that the above result is correct in the sense of complex $\tanh$ function; I did not bother to think about this, but this is definitely not we normally want.) If the problem at hand is `Integrate`, we can use `Assumptions` to explicitly state the range of parameter; but `DSolve` does not provide such an option. So, is there any way to achieve a similar effect? I tried to use `Boole` etc. but failed.


Shooting method for solving 3rd Oder ODE with RK method

This is my 3rd Order IVP. `D[y[x], {x, 3}] == (m/2)*((D[y[x], x])^2 - 1) - ((m + 1)/2)* y*(D[y[x], {x, 2}])^2`. Initial conditions given are as follows `y[0] = 0; y'[0] = 0; y''[0] = 1; (* This is the First assumed value of y''[0] for initializing shooting method using RK 4rth order method *) ` For this problem y'[infinity] is equal to 1, I want to loop the shooting method using Runge Kutta 4 th order method in such a way that after calculations, it will check the y'[] value at sufficiently large value of x and from experimental results, for x ~ 7-8, f'[] is 1. To Use RK method I redefined the equation like               D[l[x], {x, 2}] ==  z; D[y[x], x] ==  l; D[z[x], x] == (m/2)*(l^2 - 1) - ((m + 1)/2)*z*y;      Now I could write one loop for RK method but this is proving out a bit tough for me because I have to generate a list for different values of f[0] { 0,1} and m is also a variable with range (0-1) step size 0.01 & then I have to deal with 3 equations simultaneously. I am solving this over C programming but its not that efficient. I dont know how to go ahead. If anyone could throw some light.....


plotting a trig functions along with its envelope

**Note** : This questions is quite different from the ones referred to in the comments. Those deal with numerical questions, while this one is algebraic. I have plots of the following type:               Plot[Cos[50 t] + Cos[51 t], {t, 0, 10}]      ![enter image description here](http://i.stack.imgur.com/LyJHJ.png) I would like to plot a envelope over this plot, i.e. another plot that joins all of maxima and minima of this plot respectively. Here is my attempt, but it's not exactly what I'd like:               Plot[{Cos[50 t] + Cos[51 t], Cos[t] + 1.5, -Cos[t] - 1.5}, {t, 0, 10}]      ![enter image description here](http://i.stack.imgur.com/XFAQj.png) How can I generate the actual envelope?


Minimization in single component of BSpline to extract points

I smoothed some data with a BSpline $B[t] = (x[t],y[t])$. I would like to extract certain points from this spline by their x-Values, $x_0$. The easiest way I came up with was to minimize $B[t][[1]]-x_0$ for $t \in [0,1]$. So for finding the parameter t at which the x value is 13.46 if have the following code:               data = {{9.93114`, 379022.8`}, {11.71875`, 321705.7`}, {13.46983`,      280830.8`}, {15.625`, 243949.8`}, {18.60119`, 206915}, {21.70139`,      179663.2`}, {24.93351`, 158942.4`}, {29.29688`,      138396.2`}, {33.48214`, 123873.8`}};          spline = BSplineFunction[data, SplineDegree -> 3];     tstfc[t_] := spline[t][[1]]          FindMinimum[Abs[tstfc[x] - 13.46] , {x, 0}]      It seems like the Spline is not getting evaluated. How can I solve this? And is there a standard way to extract points from a spline? Thanks!


Why is my solution to PE #5 so slow

I'm new to _Mathematica_ and it was suggested to me to go through the Project Euler problems in order to learn it. However, I can't quite figure out why my solution to #5 is so slow. The problem: > What is the smallest positive number that is evenly divisible by all of the > numbers from 1 to 20? My _Mathematica_ solution:               n = 1;      max = Fold[Times, 1, Range[20]];      While[Fold[Plus, 0, Table[Mod[n, x], {x, 20} ]] != 0 And n < max,          Null;          n++     ];      Print[n]      This works but takes a _long_ time to finish (to give you an idea I had time to eat supper and it still wasn't done). For comparison I wrote a close analogue of the above code in C++:               #include <algorithm>     #include <array>     #include <iostream>     #include <numeric>          int main(int argc, char* argv[])     {         std::array<int, 20> divisors;         std::iota(std::begin(divisors), std::end(divisors), 1);         auto isMultipleOf = [&](unsigned long long x)         {             return std::all_of(std::begin(divisors), std::end(divisors), [=](int i) { return (x % i) == 0; });         };              unsigned long long n = 1;         while (!isMultipleOf(n)) { n++; }              std::cout << n << std::endl;              std::cin.get();         return 0;     }      It follows the same structure, a while loop that stops when Modulo returns 0 for each divisor from 1 to 20. To give you an idea of how much faster this is, I've benchmarked it using nonius with the following setup:               #define NONIUS_RUNNER     #include "Nonius.h++"          #include <algorithm>     #include <array>     #include <iostream>     #include <numeric>          NONIUS_BENCHMARK("Project Euler #5", [](nonius::chronometer meter)     {         std::vector<unsigned long long> results(meter.runs());         std::array<int, 20> divisors;         std::iota(std::begin(divisors), std::end(divisors), 1);              auto isMultipleOf = [&](unsigned long long x)         {             return std::all_of(std::begin(divisors), std::end(divisors), [=](int i) { return (x % i) == 0; });         };              std::vector<int> storage(meter.runs());         meter.measure([&](int i)         {             unsigned long long n = 1;             while (!isMultipleOf(n)) { n++; }             results[i] = n;         });     })      And these are the results (and in HTML for here): ![enter image description here](http://i.stack.imgur.com/yK8LY.png) As you can see, the average is about 5.2s seconds per run. In fact the whole benchmark took less time than one run in _Mathematica_ and I'm really curious as to why.


FindFit (Jacobian Error)

I, like others before me, am struggling with `FindFit`. So, I tried a simple example.               data2 = Table[{x, x^2}, {x, -2, 2, 0.1}]          ListPlot[data2]          FindFit[data2, a x^d, {a, d}, x]      Which then produces the error: > >     "FindFit::nrjnum: The Jacobian is not a matrix of real numbers at {a,d} > = {1.,1.}" >   The plot looks good, but the error message doesn't mean anything to me. Where the bottom of the range of `x` is greater than zero, FindFit `enter code here`works okay, and gives the right result. When the bottom of the range is zero or less, the error message comes back. Two questions please. What does the error message mean, and how can I avoid running into it?


How to scale the size of Pane to make it fit a Grid element?

I am wanting to make a `Pane` scale to fit (if `Spacings` are zero) a `Grid` element.               Grid[{{x, x,        Framed[         Pane[x,          ImageSize -> {Scaled[1], Scaled[1]},          ImageMargins -> 0,          Alignment -> Center],         FrameMargins -> 0,         ImageMargins -> 0], x, x}, {x, x, x, x, x}, {x, x, x, x, x}},       Background -> {None, None, {{1, 3} -> Red}}, ItemSize -> {5, 5},      Frame -> All,      Spacings -> {0, 0}]      Note that I added the `Frame` solely to outline the `Pane` so that the dimensions could be seen. On my system, OS X 10.6.8, Mma V8.0.4, the scaling works in the x direction but not in the y direction. Can anyone offer an explanation and solution (or could this be a bug)? ![enter image description here](http://i.stack.imgur.com/BjnqH.png)


Implementation of Balaban's Line intersection algorithm in Mathematica

I'm trying to implement a Brillouin Zone algorithm within _Mathematica_ , including the generation of Brillouin zones of higher order in 2D and 3D. There is a nice implementation of generating these zones in the _Mathematica Guidebook for Graphics_. However, this implementation uses the brute force approach in calculating line segment intersections of order $\mathcal O(n^2)$ with $n$ number of lines:               intersectionPoint[{{p1x_, p1y_}, {r1x_, r1y_}}, {{p2x_, p2y_}, {r2x_, r2y_}}, maxDist_] :=     Module[{aux},     If[PossibleZeroQ[r1y r2x - r2y r1x], Sequence @@ {},      aux = {p1x + (r1x (p1y r2x - p2y r2x -                      p1x r2y + p2x r2y))/(r1x r2y - r1y r2x),                p1y + (r1y (p1y r2x - p2y r2x -                      p1x r2y + p2x r2y))/(r1x r2y - r1y r2x)} // N;      If[Simplify[aux.aux] <= maxDist &&       IntervalMemberQ[       IntervalIntersection[Interval[{p1x, p1x + r1x}],         Interval[{p2x, p2x + r2x}]], aux[[1]]] &&       IntervalMemberQ[       IntervalIntersection[Interval[{p1y, p1y + r1y}],         Interval[{p2y, p2y + r2y}]], aux[[2]]], aux, Sequence @@ {}]]]      I'm sure there are a lot of improvements to above code, but the fact persists that the order will be of $\mathcal O(n^2)$. Since the line intersection for the Brillouin zone algorithm for high order zones in 3D is by far the most costly step, I'm looking into smarter approaches to find intersecting line segments. The very smart algorithm by Balaban entitled _An optimal algorithm for finding segments intersections_ achieves an order of at least $\mathcal O(n\log\,n)$. However, the algorithm involves a rather complex binary search tree implementation. Since _Mathematica_ has very efficient search implementations within lists already natively supported, I wonder if someone has implemented the Balaban or equivalent sweep line and sweep plane algorithms within _Mathematica_ that takes advantage of the built-in _Mathematica_ search functions? I'm especially interested in a 2D **and** a 3D implementation of a line segment intersection within _Mathematica_. Many thanks in advance for any help!


How to thread a list

I have data in format               data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}}       Tableform: ![enter image description here](http://i.stack.imgur.com/4fzOI.png) I want to thread it to :               tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}}       Tableform: ![enter image description here](http://i.stack.imgur.com/HTptq.png) * * * And I would like to do better then               pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}];     SetAttributes[pseudofunction, Listable];     Range[2, 4] // pseudofunction      * * * Here is my benchmark data, where data3 is normal sample of real data.               data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1];     data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5];     data = RandomReal[{0, 1}, {10^6, 4}];      Here is my benchmark code               kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list     kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list     OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}]     paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1]     RM[list_] := FoldList[Transpose[{First@list, #2}] &, Null, Rest[list]] // Rest     rcollyer[list_] := With[{fst = First@#, rst = Rest@#}, Thread[{fst, #}] & /@ rst] &@list          Drop[Timing[paradox2[#];] & /@ {data, data2, data3}, None, -1]     Drop[Timing[OleksandrR[#];] & /@ {data, data2, data3}, None, -1]     Drop[Timing[kptnw[#];] & /@ {data, data2, data3}, None, -1]     Drop[Timing[kptnw2[#];] & /@ {data, data2, data3}, None, -1]     Drop[Timing[RM[#];] & /@ {data, data2, data3}, None, -1]     Drop[Timing[rcollyer[#];] & /@ {data, data2, data3}, None, -1]      Results               {{7.503}, {0.968}, {0.031}}     {{0.983}, {0.296}, {0.031}}     {{0.312}, {1.67}, {0.031}}     {{0.094}, {0.218}, {0.031}}     {{3.759}, {0.546}, {0.032}}     {{3.073}, {0.733}, {0.031}}


BlockRandom and NestList: how get random maps with the same noise?

I need to compare solutions in random systems with the same noise and different initial conditions. Here I run twice a random map with the same initial condition, inside a `BlockRandom`. The output expected should be exactly the same orbit but they are different. What have I done wrong?               map[x_, α_] := α/2 ArcTan[x] + 1/2 x          ClearAll[α]     noisymap[x_, α_, σ_] := map[x, α] + σ RandomReal[{-1, 1}]          ClearAll[noisy1, noisy2]     BlockRandom[         noisy1 = NestList[With [{α = 2, σ = 0.1}, noisymap[#, α, σ] &], -0.32, 1000];         noisy2 = NestList[With [{α = 2, σ = 0.1}, noisymap[#, α, σ] &], -0.32, 1000];     ]          ListLinePlot[{noisy1, noisy2}]          ListLinePlot[Abs[noisy1 - noisy2]]


How to efficiently take complement of two big lists?

I have a giant list `l1` and some smaller lists `l21`, `l21`, ..., `l2n`. The `l1` is the superset and has $\tilde{}10^7$ elements. `l2?` is subset of `l1` (if my other code does correct job). All lists only contain numbers (again, if my code does correct job). I need to take complement of `l1` and each of the `l2?`. The number of subsets (i.e. `n`) is several hundreds. What's the most memory/time efficient way of doing this? I run this on 4GB machine and usually have 1.* GB of free memory when the program reaches that stage. I'd probably save numbers in file and use some command-line tool like `grep` to do this. But the original lists are all prepared in a Mathematica program. If there is a good solution in Mathematica then i'd like to avoid going out.


How do we solve N-Rooks variation using primes?

Using a $p_n $x $p_n$ matrix, how can we solve the N-Rooks problem to find a prime in every row and column?               Table[MatrixForm[Table[If[PrimeQ[n], "P", "."], {m, 0, Prime[o]^2 - Prime[o],      Prime[o]}, {n, m + 1, m + Prime[o]}]], {o, 1, 8}]        Here is the $11 $x$11$ matrix with the possible prime positions for the queens: ![N-RooksPrimeVariation](http://i.stack.imgur.com/OYfi0.jpg) Note: single primes are always in the $p$-th column. This is one possible solution (done by hand): ![N-RooksPrimeSolution](http://i.stack.imgur.com/V7Ojp.jpg) **Edit** Changed the title and link as Paxinum suggested.   OEIS A215637 has these counts of multiple solutions through $10th$ prime:   $$ 1, 1, 1, 2, 7, 72, 2144, 2641, 1345721, 2191254096$$


Replacement variable in list plot

I would like the replacement:               /. {ComplexInfinity -> 0}       to be treated as a variable. I am trying to overlay the following list plots:               g1 = (d = (q = 20;      f = (lop =          Transpose[{Flatten[            Reverse[              Table[Zeta[y], {y, 0, q}]] /. {ComplexInfinity -> 0}],           Flatten[Table[x^n, {n, 0, q}]]}];        {#1*#2} & @@@ lop);      Flatten[f];      Total[f]);     sol = Solve[d == 0];     r = ListPlot[{{Re@x, Im@x} /. sol}, AspectRatio -> Automatic, PlotStyle -> Black];     Show[r, PlotRange -> {{-q/10, q/3}, {-q/10, q/10}}, Axes -> False, ImageSize -> 800]);          g2 = (d = (q = 20;      f = (lop =          Transpose[{Flatten[            Reverse[              Table[Zeta[y], {y, 0, q}]] /. {ComplexInfinity -> 1}],           Flatten[Table[x^n, {n, 0, q}]]}];        {#1*#2} & @@@ lop);      Flatten[f];      Total[f]);     sol = Solve[d == 0];     r = ListPlot[{{Re@x, Im@x} /. sol}, AspectRatio -> Automatic, PlotStyle -> Black];     Show[r, PlotRange -> {{-q/10, q/3}, {-q/10, q/10}}, Axes -> False, ImageSize -> 800]);          ...      For:               Show[{g1, g2, g3.....}]      Is there an easier way to do this - ie, in a single command?


Using list elements in TrackedSymbols for Dynamic

During the execution of the following code a column of three lists and two sliders are displaying in output. The first list updates if either a or b changes. The second list updates only if the value of a is changed. Similarly, the third list updates only if the value of b is changed.               a = 0;     b = 0;     Column[     {       Dynamic[{a, b}, TrackedSymbols :> {a,b}],       Dynamic[{a, b}, TrackedSymbols :> {a}],       Dynamic[{a, b}, TrackedSymbols :> {b}],       Slider[Dynamic[a], {0, 1}],       Slider[Dynamic[b], {0, 1}]     }     ]      Next I would like to replace {a,b} by a list x with two elements:               x = {0, 0};     Column[     {       Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x}],       Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x[[1]]}],       Dynamic[{x[[1]], x[[2]]}, TrackedSymbols :> {x[[2]]}],       Slider[Dynamic[x[[1]]], {0, 1}],       Slider[Dynamic[x[[2]]], {0, 1}]     }     ]      It is easy to check that now only the first list updates. Please help me to solve this problem.


how can I solve integrals including recursion of some sequences of functions

I would like to solve the equations as given below in mathematica. I have written some codes before but I have no idea when there is sub indexing to indicate the series of functions. I will be very happy and grateful if you could help me. Here are the equations: $$P[n]=\int_{(-\infty,B)\cup (A,\infty)} q_n (x) \mathrm{d}x$$ and $$q_n(x)=\int_{B}^A q_{n-1} (\omega)f(x-\omega)\mathrm{d} \omega,\quad q_1=f,\quad n\geq 1.$$ and $f$ is some density function, say standard Gaussian density. Eventually, I want to obtain the probability mass $P[n]$. Thank you very much! * * * I wrote this (from Hector's post):               f0[x_] := 1/Sqrt[2*Pi*1^2]*E^(-(x + 1)^2/(2*1^2))     q[n_ /; n > 1, B_, A_, f_][x_] := NIntegrate[q[n - 1, B, A, f][ω] f[x - ω], {ω, B, A}]     q[1, B_, A_, f_][x_] :=f[x]     p[n_, B_, A_, f_] := NIntegrate[q[n, B, A, f][x], {x, -∞, B}] +                                        NIntegrate[q[n, B, A, f][x], {x, A, ∞}]          N[p[1, -2, 2, f0[x]]] --> 0.160005     N[p[2, -2, 2, f0[x]]] --> 0.35594     N[p[3, -2, 2, f0[x]]] --> 0.237045     N[p[4, -2, 2, f0[x]]] --> 0.229432     N[p[5, -2, 2, f0[x]]] --> 0.222063      ##  ... these results seem incorrect because $p$ is the probability mass function and should add up to $1$. Correct results for $f_0$ Gaussian with mean $-1$ and variance $1$ and $A=2$ and $B=-2$:               n=1-->0.1600     n=2-->0.3559     n=3-->0.2323     n=4-->0.1238     n=5-->0.0633     n=6-->0.0320     n=7-->0.0162


How to get complement of a pattern

I have a list. I want to get all the elements in that list which do not match a given pattern. That is, I want the strings which do not match any of the following patterns:   1. First and last characters are the same: $123aw1$    2. Does not have two consecutive similar characters: $1era22we, awe33rt, 123aa123$ I wrote following code               inputset = ToString /@ {       11223434, 12123434, 11234342, 11234243, 11234234, 11232434, 12132434,        12134234, 11234324, 11232443, 11234423, 12134243, 12314234, 12314324,        12341234, 11223344, 11223443, 11234432     };     outputset = Complement[inputset,        Select[inputset,          StringMatchQ[#, StringExpression[x_, ___, x_]] ||            StringMatchQ[#, StringExpression[___, x_, x_, ___]] &]];      and I got > >     outputset = {12123434, 12132434, 12134234, 12134243, 12314234, 12314324, > 12341234} >   Is there an easy simple and efficient way to do this?


Recognizing special cases of a defined function for permuted arguments

I have a number of ugly ways to implement the following **pattern recognition** task, but I'm looking for something elegant to keep my notebook tidy. I need to define a function of six variables $f(a,b,c;A,B,C)$ which is known to be unchanged under the simultaneous interchange of any two of $a,b,c$ and of the corresponding $A,B,C$: $$\begin{align}&f(a,b,c;A,B,C) = f(a,c,b;A,C,B) = f(b,a,c;B,A,C) \\ =&f(b,c,a;B,C,A) = f(c,a,b;C,A,B) = f(c,b,a;C,B,A)\end{align}$$ **EDIT for clarity: Given one definition, how do I get** **_Mathematica_** **to try all possibilities within the** **_restricted_** **set of permutations shown above for pattern matching? I need to mimic the effect of** `SetAttributes[f,Orderless]`. More concretely, if I define the special case:               f[a_, 0, b_, A_, 0, C_] := (a+b)/(A-C)      a function call `f[x, y, 0, m, n, 0]` should match, and return `(x+y)/(m-n)`. But `f[x, y, 0, m, 0, n]` should _not_ match, and thus return it must be returned unevaluated. **Added question:** Instead of finding a way to get _Mathematica_ to try all the possibilities when pattern matching, would it be easier to write code such that when a representative definition for `f` is made, the kernel automatically adds further definitions of `f` for the remaining permutations of the arguments?


Read and filter a text file without importing

I have a large text file of a million sections. Each section contains A lines of header and B lines of numeric data. I want to read the first and last line of B from each section (to have a list of 2 x million lines at the end). `Import` doesn't work since my file is too big to be read into memory. Is there a command like scan and filter for this?


Series command no longer expands arbitrary functions after aborting previous evaluation

I asked Mathematica 9 to execute the `SeriesCoefficient` command on a rather horrendously complicated expression. After some time I decided to abort the evaluation and try something different. Somehow, this has caused the `Series` and `SeriesCoefficient` commands to stop working properly. They can still correctly expand known functions, for example things like `Series[x^2*BesselJ[Sin[x],x],{x,0,5}]` do work as expected, but for arbitrary, not-yet-defined functions they no longer work, so `Series[f[x],{x,0,2}]` now returns just `f[x]` rather than the expected `f[0]+f'[0]x+f''[0]x^2/2+O[x]^3`. Does anyone know what exactly might have caused this and how I could fix it without having to restart the kernel? (Presumably the previous call to `SeriesCoefficient` changed some obscure internal parameter in the kernel which may be reversible...) I have a bunch of long, precalculated expressions in the kernel's memory and it would be quite annoying to have to export all of them and reimport into a new kernel.