Getting an InterpolatingFunction from a ContourPlot

I have a function, say               minimizeme[Ω_][β_][ϵ_] = ϵ^2 Ω - Log[2 (Cosh[2 β] + Cosh[2 β ϵ])]/(2 β);      I want to find its critical points in $\epsilon$ for a given value of $\omega$, varying $\beta$, within certain ranges, i.e. $\omega\geq 0$, $\beta\geq 0$ and $-1\leq \epsilon \leq 1$. When I pick, say, $\omega$ equal to $0.2$, e.g. I define               min20 = minimizeme[0.20];      I can make a `ContourPlot` of the locus of couples $(\beta, \epsilon)$ for which $\frac{\partial m}{\partial \epsilon }=0$, using code               ContourPlot[D[min20[β][ϵ], ϵ] == 0, {β, 0, 10}, {ϵ, -1, 1}, Evaluated -> True]      while I cannot get the software to solve the related equation:               Solve[D[min20[β][ϵ], ϵ] == 0, β, MaxExtraConditions -> All]      yields a `Solve::inex:` message, while               Solve[D[minimizeme[Ω][β][ϵ], ϵ] == 0, β, MaxExtraConditions -> All]      yields `Solve::nsmet:`. Furthermore,               Table[NSolve[D[min20[β][ϵ], ϵ] == 0, ϵ], {β, 1.*^-10, 10}]      results in a few `NSolve::nsmet:` until `General::stop:` kicks in. Finally, `Reduce` behaves just like `Solve`, resulting in either a `Reduce::inex:` or a `Reduce::nsmet:` message. Yet I think that since `ContourPlot` manages to produce a result somehow, Mathematica has a way to find what I need. So, to summarize:   1. How does `ContourPlot` work "internally"? How does it manage to produce the results I see when even `Solve`, `NSolve` and `Reduce` fail?   2. Can I turn the results of this `ContourPlot` into one (or more) `InterpolatingFunction` objects?   3. (bonus question) Are there any alternatives for solving my equation beyond Taylor series expansion? (I have already solved this with Taylor expansion, so I'd like to avoid that at all if possible) Thanks a lot.


Cropped pdf file after export

I have plot generated by `Plot[]` function that I want to export to pdf file. The problem is that `Export[]` function somehow cuts a tiny bit of plot on the left side which results in something like this: ![Exported image](http://i.stack.imgur.com/RVEQr.png) I'd like to know what should I do to get exported file without cropped $0$.


ItoProcess for stochastic reaction-diffusion equation

I am trying to simulate a stochastic differential equation in time and space, but I'm unsure if this can be done in Mathematica. The sde that I would like to study is: $$ dN[x,t]=N[x,t](1-N[x,t])dt+\sqrt{N[x,t]}dw+\partial^2_xN[x,t]dt $$ With an exponential decreasing (in space) initial condition N[x,0]=Exp[-|x|]. Is this possible to simulate with ItoProcess? Thank you, Best, Andrea


Reflection transform of function

I am trying to find the reflection function. Here is my function and its graph.               eq[n_, \[Beta]_, a_] :=  Hypergeometric1F1[1/2 - 1/4 a, n + 1, \[Beta]]     ED[n_, a_, k_Integer: 1] := \[Beta] /.   FindRoot[eq[n, \[Beta], a] == 0, {\[Beta], 0}]     rootslist[n_Integer, k_Integer, a_Integer] :=  Rest@FoldList[     FindRoot[eq[n, \[Beta], #2] == 0, {\[Beta], #1}][[1, 2]] &, 0,Range@a]     firstroot = Table[rootslist[n, 1, 50], {n, 0, 5}]     gr = ListLinePlot[firstroot, PlotRange -> Automatic, AxesLabel -> {(2 - 4 a), \[Beta]},     frame -> False]      If I tried this I can get the function of a graph, (x-axis:a and y-axis:$\beta$). I am wondering how to get the reflection function of this? (x-axis:$\beta$ and y-axis:a)? I have tried this code, but it didn't work.               Show[gr, Plot[a, {a, Automatic}, PlotStyle -> Black],      gr /. L_Line -> {Red, GeometricTransformation[L, ReflectionTransform[{-1, 1}]]}, PlotRange        -> All]


Rescale axes (e.g change from Hz to THz)

I have multiple plots of permittivity against frequency, but they're hard to read because the frequency labels go from 4x10^14 to 1x10^15 in Hz. I want to label the frequency with THz instead of Hz, so each value would just get divided by 10^12. How do I do this?


How to define a function that operate with a base case recursively?

Let's start from the simplest case: say I have a function $f(x)=x$, and let's say I want to define a new function (of $x$) to be its $n$-th power $(f(x))^n$. How should I write the code? I tried:               f[n_, x_] := f[n - 1, x]*f[n - 1, x]     f[1, x] = x      But the result is much different from what I wanted.


Iterative Function Mapping

> **Possible Duplicate:**   >  How to nest my own “times” function to get powers What I want to do is something like :               Sin[...Sin[Sin[Sin[Sin[x]]]]]      Basically, defining a function that maps a said function on an argument said number of times.


Outline around sphere

Is there an easy way to draw an outline around a sphere? Is there something like `EdgeForm[]` that will work? I'm looking for perhaps a thick red line; I'm making a plot with many spheres of different colors and opacities, and I need a way of visually distinguishing the ones that are "in use" from the ones that are "inert".


Applying different color to result of a geometric transformation

Background: consider the following two snippets.                 GeometricTransformation[{Cyan, Polygon[{{0, 0}, {.2, .6}, {.8, .2}}]},          Table[RotationTransform[2 \[Pi] k/6], {k, 0, 5}]] // Graphics      ![Mathematica graphics](http://i.stack.imgur.com/m1f93.png)                 Table[GeometricTransformation[{Opacity[.15*k], Cyan, Polygon[{{0, 0}, {.2, .6}, {.8,.2}}]},          RotationTransform[2 \[Pi] k/6]], {k, 0, 5}] // Graphics      ![Mathematica graphics](http://i.stack.imgur.com/OdLnw.png) I make most of my graphics as in the first example. Because that is ( supposedly ) the most efficient way. But I have to add gradient colors ( and other options later ), I found no other way to do it as in the second example. What I in fact want is this:                 GeometricTransformation[g, {ListOfTransformations}]       where g is some geometry. I want to be able to apply different colors to the transformed g's. But not in the way as done in example 2. **Question: How can I apply a different color to the result of a geometric transformation?**


Plot3d of explanation of partial partial derivatives

I want to plot a two functions together that looks like this: ![enter image description here](http://i.stack.imgur.com/JyJHB.png) But I am only able to come up with this;"which is clearly wrong"               Plot3D[{x^2 + x + y^2, x + y}, {x, -20000, 20000}, {y, -20000, 20000}]      I have looked through the help section but somehow I am not getting how to change it. Ps: I do not care about the range that its plotted in.


How do I find an equilateral triangle whose vertices have integer coordinates?

In geospace, how do I find coordinates of the vertices of an equilateral triangle whose vertices have integral coordinates? How do I tell _Mathematica_ to do that?


Printing a success message if no errors have yet been thrown in the current session

I plan to run a lengthy Mathematica script on a Linux terminal (by "a Linux terminal," I mean that I have text output only -- no GUI), using the program `math`. To be able to track the execution progress of my script, I would like to `Print` "success messages" to the terminal when no errors or warnings have been thrown by Mathematica in the current session. For example, here is a very basic script that `Import`s two text files, `test1.txt` and `test2.txt`, using the `"Table"` specification. I would like to write a function or expression that sets the variable `success` to `True` when no error or warning messages have yet been thrown by Mathematica.               Import["test1.txt", "Table"]     success = f;     If[success, Print["test1.txt import successful!"];, Print["General failuire!"];];          Import["test2.txt", "Table"]     success = f;     If[success, Print["test2.txt import successful!"];, Print["General failure!"];];      where `f` is a function or expression that evaluates to `True` when _no error or warning messages have yet been thrown by Mathematica_. Please note that I am _not_ trying to write a function or expression `f` that determines if `test1.txt` or `test2.txt` exists. Rather, I am trying to write an `f` that determines whether **any** errors or warnings **at all** have been thrown during the current Mathematica session. If any have been thrown prior to when `f` is called, then `success` should _always_ be set to `False`, for the remainder of the Mathematica session. Do you have any advice on this? Thank you for your time.


How can I solve the equation with integers as a solution?

I want to solve the equation $$(x-1)^2 + (y-1)^2 + (z-1)^2 = 49$$ where $x$, $y$, $z$ are integer and $x \neq 1$, $y \neq 1$, $x \neq 1$. How do I tell Mathematica to do that?


How do I subtract two contours?

Suppose I have this contour described by the equation the root $z$ of this equation $$ \frac{1}{x^2 + y^2} + \frac{1}{xz} = 2y $$ Now suppose the equation is tweaked slightly, with an addition of $w$, where $w$ is a number: $$w + \frac{1}{x^2 + y^2} + \frac{1}{xz} = 2y$$               eq1[x_, y_, z_]  :=  1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq1[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq2[x_, y_, z_]  :=  2 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq2[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq3[x_, y_, z_]  :=  4 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq3[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]      ![enter image description here](http://i.stack.imgur.com/Czleg.png) By visual inspection we see that the curves shift upwards as $w$ increases. However, I need a better way to describe it. Is there a way to **"differentiate the contour"** to find the contour $\frac{\partial z}{\partial w}$? Now suppose the equation is tweaked slightly, with an addition of $w$, where $w$ is a number. Is there a way to **"differentiate the contour"** to find the contour $\frac{\partial z}{\partial w}$? I tried "subtracting" the roots then plotting the contour, but mathematica can't seem to execute this:               eq1[x_, y_, z_] := 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq1[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq2[x_, y_, z_] := 2 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq2[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          sol[x_,y_] := FindRoot[eq2[x, y, z], {z, 1}] - FindRoot[eq1[x, y, z], {z, 1}]          ContourPlot[ sol[x,y], {x, -5, 5}, {y, -5, 5}]


C interface for Mathematica

I would like to write a small C program which starts a Mathematica session, executes some user defined code and retrieves the output and finally quits the session. Basically I like to have a simple custom made user interface for Mathematica based on standard C. I am confident that such libraries exist since I am using a program of this kind for Maple (based on OpenMaple libraries). I just do not know where to start. Maybe somebody can point me to the documentation. Ideal would be a small sample application. Maybe something like this ships with Mathematica? * * * Don't be confused by the comments. Eventhough the answer "see the Documentation" seems obvious here (as I ask for it), the by far best resource for the solution is on the Wolfram webpage. See also my answer below. As far as I can see it is neither referenced in the documentation nor contained in the builtin examples. Not knowing the words to search for it took some effort to find it.


replace is not happening for specific vector valued expression

Given               x[t_] := {Subscript[x, 1][t], Subscript[x, 2][t]}      following replace works fine               x[t] /. x[t] -> 0     0      but following one is a problem               x[t] - 1 /. x[t] -> 0     {-1 + Subscript[x, 1][t], -1 + Subscript[x, 2][t]}      because I expect there '-1'.


How to apply a trigonometric identity to a formula

The product of cosines is given by (Wikipedia): $ \prod_{k=1}^{n} \cos{\theta_k} = \frac{1}{2^n}\sum_{e\in S} \cos(e_1\theta_1+\ldots+e_n\theta_n) $ where $S={1,-1}^n$. How can I apply this to a formula in Mathematica, say the formula: $ \cos{n_1}+\cos{n_2}+\cos{n_3}\cos{n_4}+\cos{n_5}\cos{n_6}\cos{n7} $


Solve pair of recurrence relations

[Corrected equations and added simple example] Can you solve a system of (loosely) coupled recurrence relations like this in _Mathematica_ somehow?               {A[k] ==1+((n-k-2)/n) A[k+1] +(2/n) B[k+1] + (k/n) (A[0]),       B[k]==1+((n-k-1)/n) B[k+1] + (k/n) A[0]}      We want to solve it for $A[0]$ as a closed form function of $n$. $A[k]$ is defined for $0 \leq k \leq n-2$ and $B[k]$ is defined for $1 \leq k \leq n-1$. Version 8 doesn't do anything useful but I suspect I am not asking it in the right way. As a simple example, if you set $n=3$ then you get four simulataneous equations.               A[0] == 1 + (2/3)*B[1] + (1/3)*A[1]     B[1] == 1 + (1/3)*A[0] + (1/3)*B[2]     B[2] == 1 + (2/3)*A[0]     A[1] == 1 + (2/3)*B[2] + (1/3)*A[0]      Solving for $A[0]$ gives you $33/5$ I believe. To start things off, how do you get _Mathematica_ to do this? **Update.** If you just take the second recurrence alone.               B[k]==1+((n-k-1)/n) B[k+1] + (k/n) A[0]      How can you get _Mathematica_ to give a sensible solution for $B[k]$ in terms of $n$ and $A[0]$? It seems Rsolve ought to be able to do this. I even tried               RSolve[{B[k] == 1 + ((n - k - 1)/n) B[k + 1] + ((k)/n) (A[0]),        B[n - 1] == k A[0]/n}, B[k], k]      which should be identical. However this now gives an empty solution with the following warning.               RSolve::bvnul: For some branches of the general solution, the given boundary conditions lead to an empty solution.      I would like to tell _Mathematica_ to only try to solve it for the defined range of $k$. Is that possible?


Solving an Integral equation

I would like to solve the equation $$\frac{2}{p}\int_0^1((1-u)^{1-p}+u^{1-p})^{\frac{1}{p}}\text{d}u=42$$ for p numerically. I tried               NSolve[2/p*Integrate[(u^(1 - p) + (1 - u)^(1 - p))^(1/p), {u, 0, 1}] == 42, p]      and               FindRoot[2/p*Integrate[(u^(1 - p) + (1 - u)^(1 - p))^(1/p), {u, 0, 1}] == 42, {p, 0.08}]      and               h[p_?NumericQ] := 2/p*NIntegrate[((1 - u)^(1 - p) + u^(1 - p))^(1/p), {u, 0, 1}]     FindRoot[h[p] == 42, {p, 0, 1}]      (I know the answer is approximately 0.0804670), however I still would like to know how it is computed. In both cases, I received errors:               NSolve::nsmet: This system cannot be solved with the methods available to NSolve      and               GCD::exact: "Argument 0.92` in GCD[0,0.92] is not an exact number.     FactorSquareFree::lrgexp: Exponent is out of bounds for function FactorSquareFree.     GCD::exact: "Argument 0.9195355178111501` in GCD[0,0.919536] is not an exact number.      How do I solve this equation? Preferably with as little Integral evaluations, because they are horribly slow. **EDIT** nevermind, sorry. There was a typo in the third try. Thank you for your time >_<


How to get full-screen graphics canvas?

Is it possible to create a full-screen graphics without any front end elements like cell brackets and scrollbars? The zero approximation can be               {{{z, w}, {z, h}}} = FullScreenArea /. (ScreenInformation /.           Options[$FrontEnd, ScreenInformation]);     CreateDocument[       Graphics[{EdgeForm[Green], Rectangle[{0, 0}, {w, h} - 1], Red,          AbsolutePointSize[1], Point[{100, 100}]},        PlotRange -> {{0, w - 1}, {0, h - 1}}, ImageSize -> {w, h}],       WindowSize -> Full];      As a result I expect a black screen with green border of one pixel width and one red pixel. I guess some options are missing to do the job, but there are quite many places one could try to put them to, so I expect someone more familiar with this functionality will respond.


Old notebook (Version 3) not opening in version 9

I have some old notebook files in version 3 format from the book "Mathematica for Physicists". These files are blank except for the chapter header when opened in Mathematica 9. I have similar problems with other old notebooks. For example, there is an old notebook called Mir Space Station and it exhibits similar behavior, opening it shows only headers, no formulas or calcuable cells. How can I recover these notebooks and use them in Version 9?


How to add an entirely new menu

Is it possible to add an entirely new menu, say menu "CustomApp" on the fly? For example a _CustomApp_ package could add its own menu "CustomApp" with submenus, ect, once _Needed_. Former examples I have seen, only dealt with adding to an existing menu.


Moles/Liters doesn't get simplified to Molar even though Molar*Liters gets simplified to Moles

Why can't Mathematica 9 simplify mol/L to M, when it can simplify M*L to mol?                Quantity["Moles" / "Liters"] // UnitSimplify      (* => 1 mol/L *)           Quantity["Molar" * "Liters"] // UnitSimplify      (* => 1 mol *)      And is there a way to fix this behaviour?


Running PlotLegends in Mathematica 8

I will like to get a density plot (in _Mathematica 8_ ) as in: Make legend same height as plot.   However, anytime I run               DensityPlot[ Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, PlotLegends -> Automatic]      I get a red coloured `"PlotLegends"` within the input text followed by an error message. I need your help!


Can styles be exported in EPS as simple text tags for use by LaTeX's psfrag?

Is there a way to export graphics as EPS so that _LaTeX_ can perform style substitutions or modifications on them? I know that it is possible to replace simple text elements in imported EPS files using _LaTeX's_ `psfrag`; but if this is all that is possible, it is not sufficient to enforce a consistent appearance for graphics. That requires the ability to make substitutions to things like line weights and colors. Is there a way to use Mathematica to export EPS files in such a way that style elements are represented as simple text tags that can be easily replaced using `psfrag` (or a similar technique) in _LaTeX_?


How to solve an overdetermined system in Mathematica

I would like to understand the reasons and find a way to avoid such behaviour of the `Solve` function in Mathematica 8.               Solve[x + y + z == 5 && y == 3 , {x, y}]     (* Out[1]= {{x -> 2 - z, y -> 3}} *)          Solve[x + y + z == 5 && y == 3 , {x}]     (* Out[2]= {} (why empty?) *)      I need to get an answer in the second case. Any suggestions on how to persuade the program to calculate an answer that is even simpler than the first?


Package function not called from button in a DockedCell expression

Consider the following minimal example package:               BeginPackage["Test`"];          DuplicateNotebook::usage = "Makes a copy of the notebook";          Begin["`Private`"];          DuplicateNotebook[] :=        NotebookPut @ NotebookGet[EvaluationNotebook[]];       ex2 =          Grid[{{Item[ButtonBar[{             Style["Duplicate", 10] :> DuplicateNotebook[],             Style["Quit Kernel", 10] :> FrontEndTokenExecute["EvaluatorQuit"]}],            Alignment -> {Right, Top}]}}];       SetOptions[EvaluationNotebook[],          DockedCells -> Cell[BoxData[ToBoxes[ex2]], "SystemDockedCell"]];          End[];          EndPackage[];      **So what's happening?** The function `DuplicateNotebook[]` defined in the package doesn't get called when the button is clicked, but calls of type `FrontEndTokenExecute["EvaluatorQuit"]` work. What's more, this code was working perfectely well in _Mathematica_ V9, but now in _Mathematica_ V10, I can't get it working without putting the function body directly into `DockedCells`, which of course is a very messy solution. Therefore I'm looking for better workarounds. This seems to be a problem with `DockedCells` context, because putting the cell in the notebook (not in `DockedCells`) works. However adding context information to the call didn't work (I've tried `Test`DuplicateNotebook[]`) Zipped version of the test package http://cl.ly/2C3U2O2n0y21


Using new symbol in WhenEvent in NDSolve

This is an example in Mathematica's help document.               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,          WhenEvent[y[t] == 0, y'[t] -> -0.95 y'[t]]}, y, {t, 0, 10}];     Plot[y[t] /. %, {t, 0, 10}]      I do a modification like this:               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0, a = y[t]; b=y'[t];        WhenEvent[a == 0, b -> -0.95 b]}, y, {t, 0, 10}];     Plot[y[t] /. %, {t, 0, 10}]      It doesn't work. If I want to keep a new symbol just as here `a` to represent the `y[t]` or some expression about `y[t]` in the `WhenEvent`, what can I do to achieve this goal? (The error may be caused by the `HoldAll` attribute of `WhenEvent`. Why I want to replace the `y[t]` by `a`? It is important to me. Bucause I will use a dynamic `a` in the WhenEvent )


Trying to study the three points theorem of the Mobius Transformation

I am trying to study the three points theorem of the Mobius transformation. This theorem says that the Mobius transformation $M$ maps three distinct points p, q, r to three distinct points p', q', r'. Based on this formula $$\frac{(z-p)(q-r)}{(z-r)(q-p)}=\frac{(w-p')(q'-r')}{(w-r')(q'-p')}$$, I solved for $w$ and came up with this function.               mobius[z_, z1_, z2_, z3_, w1_, w2_, w3_] :=      (w1 (-w2 (z1 - z2) (z - z3) + w3 (z - z2) (z1 - z3)) -        w2 w3 (z - z1) (z2 - z3))/(w3 (z1 - z2) (z - z3) -        w2 (z - z2) (z1 - z3) + w1 (z - z1) (z2 - z3))      If I substitute z with a eaquation of plane, then I can see how the $M$ maps the plane. What I want to know is that is there a way to mark these points on the graph so that I can see how these points behave?? I am using parametric plot to see the graph. Thanks! \--------Edit---------               plane[x_, y_] := x + y I;     Manipulate[      ParametricPlot[       {{plane[x, y] // Re, plane[x, y] // Im},         {mobius[plane[x, y], z1, z2, z3, w1, w2, w3] //Re,         mobius[plane[x, y], z1, z2, z3, w1, w2, w3] // Im}},        {x, 0, 40}, {y, 0, -40}, PlotRange -> {{-50, 50}, {-50, 50}}],       {z1, {10, 20}}, {z2, {10 I, 20 I}},       {z3, {15, 25}},       {w1, {10, 20}}, {w2, {10 I, 20 I}},       {w3, {15, 25}}]


Can Apple's Numbers spreadsheet link to a Mathematica function?

I use Apple's Numbers spreadsheet for a single thing, a double entry accounting model to understand complicated financial transactions. A current model depends on the value of a single initialization cell. I calculate this value in Mathematica using `Solve[]` as Numbers can't solve a system of equations. Currently I have to manually input this value in the Number's spreadsheet. Ideally I'd like the cell in Number's to call the Mathematica function. Does any means exist to do this? Excel/Link or Math/Link would appear to provide functionality similar to this, but reading through their respective documentation doesn't provide any clear way to do this with Numbers. I can write command-line code to do this (generally):               $ MathKernel -script file.m      which suggests that AppleScript or some other scripting language could do this if callable/runnable from Numbers. Perhaps all of this suggests a better or more general question: What means exist, if any, for calling a Mathematica function or script from applications outside of Excel or specifically applications programmed for J/Link or Math/Link?


How to vary line thickness to add a sense of perspective?

Is there a simple way to vary the line thickness relative to the viewpoint so as to add a sense of perspective? Take for example the following:               Manipulate[      lines = Table[{RandomInteger[{-1, 1}] a, RandomInteger[{-1, 1}] a,          RandomInteger[{-1, 1}] a}, {2^a}];       Graphics3D[Line[lines], Boxed -> False], {a, 1, 12, 1}]      ![enter image description here](http://i.stack.imgur.com/4nS3T.png) which generates some lines projected in a 3-dimensional fashion with a clearly visible perspective i.e. the lines of similar length appears longer when closer to the viewer. Since the information regarding apparent distance to the viewpoint is known to the system, it should be possible to retrieve this and modify the thickness of lines accordingly. Is this possible in a simple manner? ![enter image description here](http://i.stack.imgur.com/rt6J9.png) The sketch above illustrates my point, although somewhat clumsy.


Select/Delete with Sublist elements?

Probably easy and short question, I still didn't fully figure out how to easily select/delete sublists from a list. Example: > tt = {{2, 4}, {4, 8}} I want to delete/select all the elements where the difference between them (`Abs`) is greater than four.


Filtering Lists in Mathematica

> **Possible Duplicate:**   >  Select/Delete with Sublist elements? I need help in filtering long lists of `x,y` coordinates.Lets use the following list as an example:               list={{3,5},{7,6},{15,6},{23,123}}      I need to filter out all the data points for which `x<10`. Therefore once the filtering is complete the new list should be:               newlist={{15,6},{23,123}}      Please help.Thank you!


How to cut elements from set of data based on function restrictions?

For example, say I have a set of data which takes the form               list = {{1,2,4,5,3,2},{2,3,4,2,1,6},{2,3,4,5,4,3}}        where all of the elements have a length of 6. Then I have to run this `list` through many functions each with various restrictions e.g.:               ptOf[event_]:=px+py/;(px+py)<4,       where `px` is the first element in the 6 vector `{px,py,_,_,_,_}` and `py` is the second element. How would I cut the elements from the original list that do not satisfy this condition?


Picking certain pairs according to a condition

I'm a Mathematica beginner and can't find out a solution to my problem. I have a list of pairs of numbers, for example something like this, but much longer: list={{2., 3.}, {3., 2.}, {5., 4.}, {4., 0.}, {5., 0.}, {5., 0.}, {4., 0.}, {5., 4.}}. And now I need to get only pairs for which some rule is true. For example, I'd like Mathematica to give me pairs {x,y} from the aforementioned list, where x=5 and y is any. So in this case I'd get pairs {5., 4.},{5., 0.},{5., 0.} and {5., 4.}. Is there any way to do this? Thanks :))


Select {x,y} pairs from a list where x conforms to a rule

I'm working on some pet project and I have a very large list of {x,y} pairs. I want to make a new list containing all {x,y} pairs where x is, let's say, even (I actually need something more complicated, but I assume same principle will apply). I just don't get how I'm even supposed to do it, Select doesn't work (or can't make it work) on pairs. I've read Select documentation but it seems I'm missing something essential.


What is the best way to create a correlation matrix heatmap with values?

This may have been asked somewhere else, but I couldn't find an answer by searching. I'm trying to create a correlation table that colors the background behind the numbers as a heatmap. I've been trying to use `ArrayPlot` with `ColorFunction -> "TemperatureMap"`, but I'm kind of stuck. Example:               data = {{1, 0., -0.8}, {0., 1, 0.}, {-0.8, 0., 1}};     ArrayPlot[data, ColorFunction -> "TemperatureMap", Frame -> None, Mesh -> True]      ![enter image description here](http://i.stack.imgur.com/962mg.png)


Manipulate a Differential Equation result

I want to Manipulate the result of Differential Equation like :               F[x_] = y[x] /. First@DSolve[x - y'[x] + y''[x] == 0, y[x], x]     Manipulate[Plot[F[x], {x, -10, 10}], {C[1], 1, 6}, {C[2], -2, 5}]      the result of the equation is :               x + x^2/2 + E^x C[1] + C[2]      but I don't get any Curve on the display. ![enter image description here](http://i.stack.imgur.com/zRcut.jpg)


Retain values between sessions

This is a real newbie question, so apologies in advance for may seem a very dumb question ... I'm trying to understand the various ways in which information can be retained in a notebook between sessions, using `DynamicModule[]` etc. Understanding how a good MMA user would solve the following simple task would be really helpful: Say I want to load a video file and then create a simple slider to scroll through the frames. This works:               frames = Import["myvideofile.avi", {"Frames", All}];      Manipulate[frames[[f]], {f, 1, Length[frames],1}]      But, say I want to remember which frame the slider was left at between Mathematica sessions, how would I do that elegantly? If I re-open the code above, there's an error because 'frames' isn't defined until the video is imported. In other words, upon re-opening the notebook, the first thing I'd like to happen is for 'frames' to be imported. I'm speculating that I need `DynamicModule`, with `Initialization` but have tried many different ways and can't get it to work.


Variables Inside Functions Not Evaluating

x = 5*y     function1[y_] := x     function1[5]      Am I wrong in thinking that function1[5] should equal 25? Instead this comes out.               5y     5y


How does Return work?

It is not completely clear to me how `Return[]` works. The documentation says: > `Return[expr]` returns the value expr from a function. But in _Mathematica_ it is not clear where are the boundaries of a "function" defined using patterns and `Set(Delayed)`. The system simply applies replacement rules until there's nothing to change anymore. Consider these examples:               a := (Module[{}, Return[0]; 1]; 2)         a     (* 0 *)      It is not completely clear to me why `Return` breaks out from `a`, and not from `Module` or one of the `CompoundExpression`. The following doesn't work, and simply returns the `Return` expression. It reminds me a bit of how `Unevaluated` is handled.               (Module[{}, Return[0]; 1]; 2)     (* Return[0] *)      If we add another layer of definitions, the effect of `Return` will stop there:               b := (a; 3)     (* 3 *)      Why do these three inputs give different results? What is the general rule for deciding where `Return` breaks out to precisely? The answer lies somewhere in fully understanding the evaluation process. Would someone care to elucidate this point, perhaps with pointers to the parts of the documentation which make this clear?


Fourier Transform of a Step Function

I'm trying to obtain the form of a sinc function that I know I'm supposed to get in _Mathematica_. I'm doing this because I intend to do a lot with Fourier transforms (FT) and I'd like to know I'm not missing constants or something of the like. For example, consider: $$ f(x) = \begin{cases} A && -\frac{a}{2} ≤ x ≤ \frac{a}{2}\\\ 0 && \text{otherwise}\\\ \end{cases}$$ Employing the following:               FourierTransform[UnitStep[a/2 + x] UnitStep[a/2 - x], x, k, FourierParameters -> {1, -1}]      It gives: `(2 Sin[(a k)/2] UnitStep[a])/k` Is this _Mathematica_ 's way of giving the sinc function? I guess I was expecting something more like `(2 Sin[(a k)/2])/(k a)`. I know there are different parameters that can be used, but none of them have given the form I was expecting. When I try to do the FT directly as an integral:               Integrate[A Exp[-I k x], {k, -a/2, a/2}]      It gives: `(2 A Sin[(a x)/2])/x` Are these the same? I was expecting something that would lead to $\rm{sinc}[k a/2]$. I have not found previous questions that can help, and the documentation in _Mathematica_ (version 8) also has not helped either.


Mathematica inserts extra \left and \right for absolute values in LaTeX output

Type the following in a _Mathematica_ DisplayFormula cell(other styles may also encounter this problem): `Esc`+`l`+`|`+`Esc` and `Esc`+`r`+`|`+`Esc`, and save as LaTeX. ## Note: See the difference of the character between | |. $z$ and $z_1$, $|z|$, $|z_1|$               Cell[BoxData[      RowBox[{"\[LeftBracketingBar]",       SubscriptBox["z", "1"], "\[RightBracketingBar]"}]], "DisplayFormula"]      with subscript, then... _Mathematica_ inserts extra `\left` and `\right` for absolute values in the LaTeX output:               %% AMS-LaTeX Created by Wolfram Mathematica 9.0 : www.wolfram.com     \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}     \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}     \newcounter{mathematicapage}          \begin{document}         \[         \left\left| Z_1+Z_2\right\right| \leq \left\left| Z_1\right\right| +\left\left| Z_2\right\right|         \]         \end{document}      What should I do to get valid output that LaTeX will accept?


What is the most elegant way to see if an expression is affected by a certain symbol?

> **Possible Duplicate:**   >  Determine whether some expression contains a given symbol Let's say I have some expression:               sample = {1, 1/q, f[m]}      And I want to check it if it has the symbol `m` in it. My question: Is there a clean or fast way of checking if `m` is in the equation? * * * What I came up with so far:               Do[StringFreeQ[ToString[sample], "m"], {i, 300}] // AbsoluteTiming     (* {0.0120007, Null} *)      and               Do[(sample /. m -> Unique[]) === (sample /. m -> Unique[]), {i, 300}] // AbsoluteTiming     (* {0.0100005, Null} *)      These solutions work, but I feel like there might be a faster, functional way of doing this.


Check if a matrix is Positive Semidefinite

I have a question concerning the check whether a given matrix is positive semidefinite or not. In mathematica the function `PositiveDefiniteMatrixQ[m]` tells me whether the matrix `m` is positive, but not semidefinite. I wanted to ask whether there exists an implementation for that purpose, and if not, how to implement a code that is as fast as possible.


Problems with DumpSave and memoization

I defined a function that takes some time to compute using memoization:               y[a_, b_, c_] := y[a, b, c] = First[$y /. NDSolve[.........]       so that if I call y[a,b,c] a second time it doesn't do the `NDSolve` computation all over again if it has already done it. How can I save the result of this to file? I tried `DumpSave["test.mx", y[3/10, 2, 0]]` after calling `y[3/10, 2, 0]` (i.e. it is now an `InterpolatingFunction`; the result of `NDSolve`), but I get the error               "DumpSave::bsnosym: y[3/10,2,0] is not defined as a symbol or a context. >>"      If I call `y[3/10,2,0][2]` etc I get the correct numeric result. Is there some reason this is not working?


Why doesn't FullSimplify work properly on this?

I wish to simplify the simple expression `fac[n_] := Sum[R^i, {i, 0, n}];` as much as possible for various $n$. `FullSimplify` or `Factor` work on this, but not always, as good as it should be. For example, in the sixth line of               Table[{fac[j], fac[j] // FullSimplify, fac[j] // Factor}, {j, 1, 8}] // TableForm      it seems that `FullSimplify` does not work at all!? ![enter image description here](http://i.stack.imgur.com/hEAEv.png) $1+R+R^2+R^3+R^4+R^5+R^6$ has not been simplified! It is well-known that $$1+R+R^2+R^3+R^4+R^5+R^6=1+(R+R^4)(1+R+R^2).$$ So, now my question is: Is there any way in _Mathematica_ to obtain the very simplified form of the expression `fac[n_] := Sum[R^i, {i, 0, n}];`, just like $1+(R+R^4)(1+R+R^2)$ or even simpler for various $n$? I will be grateful if anyone can give me some tips.


Passing a function as an argument of another function

> **Possible Duplicate:**   >  Pass function or formula as function parameter I am trying to implement a simple Plot[]-like function, with the same synopsis; my first (and unique so far) try would be something along these lines:               MyPlot[f_, {var_, xmin_, xmax_}] := ListPlot[Table[{y, f[y]}, {y, xmin, xmax, (xmax - xmin)/100}]]      however I have to call the function as follows               MyPlot[Sin,{x,0,1}]      while I would prefer calling the function just like Plot[]               MyPlot[Sin[x],{x,0,1}]      I just don't know how to strip the "[x]" when a function is used as an argument to another function. This is not only a matter of consistency with Plot[], it is also needed in order to use a multi-argument function as the argument, such as:               MultiSin[x_,y_]:=Sin[x+y]/(Sqrt[x^2+y^2])     MyPlot[MultiSin[x,1],{x,0,1}]      which is not possible AFAIK with my simple re-implementation.


Multi-Factorial and Series with Triple-factorial terms

> Let $n!^{(k)}$ denote a multi-factorial which is defined by $$ n!^{(k)} = > \begin{cases} 1 & n \leqslant 0, \\\ n, & 0 < n < k,\\\ n\times(n-k)!^{(k)}, > & n \geqslant k. \end{cases} $$ > > _E.g._ $8!^{(3)}=8\times5!^{(3)}=8\times5\times2!^{(3)}=8\times5\times2=80$. > For $k=3$ we may also put down $8!!!$. For the case of $k=1$, _Mathematica_ has `Factorial[]` or `!` at hand. For the case of $k=2$, there is `Factorial2[]` or `!!` which calculates double factorials. For the general case of a $k$th factorial, I could define by recursion               In[1]:= MultiFactorial[n_, k_] := If[n < k, If[n <= 0, 1, n], n MultiFactorial[n - k, k]]      which correctly outputs $8!^{(3)}$ as               In[2]:= MultiFactorial[8, 3]     Out[2]:= 80      But when I have a multi-factorial in every term of an infinite series, _Mathematica_ spits out the original input:               In[3]:= Sum[((-1)^n MultiFactorial[3 n, 3])/MultiFactorial[3 n + 1, 3], {n, 0, +∞}]     Out[3]:= (* More or less the same *)      [ ** _Edit_** ] Definition by `Product[]`               In[4]:= MultiFactorial[n_, k_] := Product[i, {i, n, 1, -k}]     In[5]:= Sum[((-1)^n MultiFactorial[3 n, 3])/MultiFactorial[3 n + 1, 3], {n, 0, +∞}]      suggests that the sum is divergent. Yep, I'm trying to verify if $$\sum\limits_{n=0}^{+\infty} \frac{(-1)^n (3n)!^{(3)}}{(3n+1)!^{(3)}} = -\frac{\sqrt[3]{2}}{4} \ln\left(\sqrt[3]{2}-1\right)+\frac{\sqrt{3}\sqrt[3]{2}}{6}\arctan\frac{\sqrt{3}}{1+2\sqrt[3]{2}}.$$ **Question** : Are there any built-in functions for the cases of $k\geqslant3$ which is OK to sum?


Pattern matching in subscripted variables

I am trying to use subscripted variables as symbols and provide assumptions elegantly for them, e.g. in order to simplify logs, I'd like to have               Simplify[ Log[Subscript[x,1]^2] - Log[Subscript[x,2]^2], Assumptions -> Subscript[x,_] > 0]      be simplified to               Log[Subscript[x,1]^2 / Subscript[x,2]^2]      I am aware of the Notation package, but symbolizing any subscripted variable prevents me from pattern matching variable names. I am as well aware of the fact, that this is an incarnation of the same old story of "Don't put data in your variable names". Apart from that it makes the output hard to read, I couldn't get               Simplify[Log[y[1]^2] - Log[y[2]^2], Assumptions -> y[_] > 0]      to make the desired simplification, either. Hence, putting the subscript as an extra parameter of a "function" fails as well. What would be the elegant and formally correct way to implement the desired behaviour without enumerating the different variables as x1, x2, ... and having to explicitly state the assumption for every single variable in the game? Scope: I have a whole lot of different masses in my calculation, hence I wanted to keep track of them by using subscripts. In the end, I'd like to give certain linear combinations of fundamental masses special names and have logarithms like the ones above simplified. Thank you very much in advance! Best Ben


Is there SVM packages available for free?

I want to do date minings. And do you know some packages that have been made available online? I am using Mathematica 8 and 9. Thanks.


I ran into an error when I was trying to solve a PDE with a piecewise initial condition by NDSolve

This is a very simple one-dimensional heat-conduct equation, the only special part of it is the piecewise initial condition:                   b = NDSolve[{D[tes[t, x], t] == D[tes[t, x], x, x] + Exp[-1/(tes[t, x])],                       tes[t, 0] == 1, tes[t, 1] == 1,                       tes[0, x] == Piecewise[{{-100 (x - 0.1)^2 + 2, 0 <= x <= 0.1},                                              {2, 0.1 <= x <= 0.9},                                              {-100 (x - 0.9)^2 + 2, 0.9 <= x <= 1}}]},                      {tes[t, x]}, {t, 0, 100}, {x, 0, 1}]      If you run the code, you will get this warning message: > NDSolve::mxsst: Using maximum number of grid points 10000 allowed by the > MaxPoints or MinStepSize options for independent variable x Why does this message come out? I read the help but I don't think my initial condition has that kind of fault: it's piecewise but smooth, right? * * * I'd like to add another sample here since its behavior makes a interesting contrast to the sample above:               c = NDSolve[{D[tes[t, x], t] == D[tes[t, x], x, x] + Exp[-1/(tes[t, x])],                  tes[t, 0] == 1, tes[t, 1] == 1,                   tes[0, x] == Piecewise[{{-Exp[-1000 x] + 2, 0 <= x <= 0.1},                                          {2, 0.1 <= x <= 0.9},                                           {-Exp[-1000 (1 - x)] + 2, 0.9 <= x <= 1}}]},                 {tes[t, x]}, {t, 0, 100}, {x, 0, 1}]      This example choose `Exp` as the transition between initial condition and boundary conditions, in fact this initial condition is not even continous at `x=0.1` and `x=0.9` in the view of math, and I think the change of `Exp` is more drastic than the polynomial function, but it gets no warning message. Well, I should say, after all this time (notice the time I posted this question) I've already treat this as some kind of bug, but I still expect an in-depth explain for it.


Problem creating MeanPredictionBands

I have a problem creating `MeanPredictionBands` for my function which I fitted using `NonlinearModelFit`. I have a complex-valued function and I am fitting the real part of the function. Mathematica 8 gives me back a fitted function and with it the `BestFitParameters`. But as soon as I try to feed it the `"MeanPredictionBands"` command, it gives me back the following line: > Experimental`NumericalFunction::nnum: The function [...] is not a number at > {fitparameters}. I have also tried using the `ComplexExpand` function on the real part of my function, which still doesn't help with my situation. Has anybody encountered this particular problem before? All my variables are real, as are the fit parameters. Thank you all for your help! * * * From the file linked in comment a reduced code sample that exhibits the same problem:               ClearAll[msymm2fit];     msymm2fit =  Re[0.145` mV^6 Log[-(0.5929`/mV^2)] + 12 b0V \[Nu]^2 + 8 bDV \[Nu]^2]          MyData2 = {{0.332, 0.807^2}, {0.386, 0.821^2}, {0.447, 0.855^2}};     MyError2 = {0.027, 0.011, 0.029};     MyFit2 = NonlinearModelFit[MyData2, msymm2fit, {mV, b0V, bDV}, \[Nu],        VarianceEstimatorFunction -> (1 &), Weights -> 1/(MyError2)^2,        Method -> {NMinimize, Method -> "DifferentialEvolution"}]          MyFit2["BestFitParameters"]     MyFit2["MeanPredictionBands"]      * * * The inability to create the Bands apparently comes simply from taking the Real part of the function. I tried this out on another, really easy function. If you take               ComplexExpand[Re[]]      of a real valued function, this problem with creating the error bands goes away. In my case, taking the Real part analytically (i.e. by hand) is not that easy, since it is created while i am fitting the data. TL;DR Simply taking the Real part of any function will hinder Mathematica 8 from creating error bands from the fitted function.


Import Fortran unformatted binary

I have an unformatted binary file generated using the Compaq Visual Fortran compiler (big endian). Here's what the little bit of documentation states about it: The binary file is written in a general format consisting of data arrays, headed by a descriptor record:   1. An 8-character keyword which identifies the data in the block.   2. A 4-byte signed integer defining the number of elements in the block.   3. A 4-character keyword defining the type of data. (`INTE`, `REAL`, `LOGI`, `DOUB`, or `CHAR`) The header items are read in as a single record. The data follows the descriptor on a new record. Numerical arrays are divided into block of up to 1000 items. The physical record size is the same as the block size. Additional keyword info:   1. `SEQHDR` \- 1 item - `INTE` \- Sequence header, with data value. If number is present it is an encoded integer corresponding to the time the file was created.   2. `MINISTEP` \- 1 item - `INTE` \- Ministep number is essentially the data number (ex: psi on day 1)   3. `PARAMS` \- n items - `REAL` \- Vector parameter at ministep value. Attempts to read such data into _Mathematica_ including `Import`               data=Import["file", "Binary", ByteOrdering -> +1];     data = FromCharacterCode[data]      and `OpenRead`               OpenRead["file", BinaryFormat -> True]      ![enter image description here](http://i.stack.imgur.com/f2NYv.jpg) show me some identifiable text, but no useful numerical values. A file in question is available here. Is _Mathematica_ able to parse this file type, and if so, what is the best way?


How to switch off all messages?

How can I want to switch off **all** messages in a _Mathematica_ session? `Quiet[expr]` allows me to evaluate `expr` without messages. `Off[msg]` switches off the particular message `msg`. Is there a command that, once evaluated, guarantees that all further evaluations will run quietly? (Unless some messages are turned back `On`)


Using Table[ ] vs using Do[Append [ ] ]

Is it generally better/faster to use the `Table` function over using `Do[Append []]`? For example, I have this piece of code:               inttstar[1] = (tstar[2] - tstar[0])/8;      inttstar[j_] :=       inttstar[j] = (1/4)*(tstar[j + 1]/(j + 1) -            tstar[Abs[j - 1]]/(j - 1)) -              ((-1)^j*tstar[0])/(2*(j^2 - 1))     G = Table[        Coefficient[inttstar[i], tstar[j], 1], {i, 0, m - 1}, {j, 0,          m - 1}];          Gt=Transpose[G];     cmat = T {{0, 1}, {-a, -d}};     cmatk = Outer[Times, cmat, Gt];          aI = {};     Do[      Do[       Do[aI = Append[aI, cmatk[[i, k, j]]], {k, 1, 2 n}], {j, 1,             m}], {i, 1, 2 n}]      As is, it runs correctly. But, can I improve performance by replacing the `Do[Do[Do[....]]]` section with a `Table` function? If so, how would I do that?


Text Annotation Disappears in Wrapped 3D Graphics

In a 3D graphic, if I wrap a figure, for example,               imagewrapped =       With[{Lx = 10, Ly = 10, Nx = 5, Ny = 5, r0 = 2, ftsz = 12},        Graphics3D[{Table[{Sphere[{ix Lx, iy Ly, 0}, r0]}, {ix, 1, Nx}, {iy,            1, Ny}], Red,          Table[Text[Style[ix, ftsz, Bold], {ix Lx, 0, 0}], {ix, 1, Nx}],          Cyan, Table[          Text[Style[iy, ftsz, Bold], {0, iy Ly, 0}], {iy, 1, Ny}]},         Boxed -> False, Lighting -> Automatic, ViewPoint -> {1, 1, 1},         ImageSize -> {Automatic, 100}, Method -> {"ShrinkWrap" -> True}]]      ![image wrapped](http://i.stack.imgur.com/toGNV.png) some text disappear. How can I wrap the figure without loosing information?


unlisting a nested list

I have a list like this:               list = {{a,{1,2,3}},{b,{1,2,4}},{c,{{1,4,5,5},{6,3,2,1}}}}      This is a nested list which each element has a name. I want to export it to CSV so I want to un-nest it to look like:               unlist = {{a,{1,2,3}},{b,{1,2,4}},{c1,{1,4,5}},{c2,{6,3,2,1}}}      As the list is very dynamic, the solution solution should be dynamic as well. I mean in different files the `list` has different lengths but the nesting structure is the same. How can I deal with this?


Animation of tube with fixed height

the problem is following: my task is to make an animation: tube changes its radius but doesn't change its height. With command               Animate[Graphics3D[{CapForm["Square"], Tube[{{0, 0, 0}, {0.5, 0.5, 0.5}}, r]}],              {r, 10^(-9), 1}, AnimationRunning -> False]`      It changes both radius and length. How to make the fixed length?


Conditions for proper integrals with DSolve on Mathematica

DSolve[{RCS'[s] == SNPH[s] - Sqrt[R2[s] - RCS[s]^2]/b,SNPH'[s] == RCS[s]/a^2, R2'[s] == 2 RCS[s] SNPH[s], RCS[0] == 0., SNPH[0] == snal, R2[0] == ri2}, {RCS, SNPH, R2}, s ]; Here {a,b,snal,r12} are constants.In NDSolve a small shift given in boundary value trick works fine, showing that it is a proper integral. However, what are standard procedures as a workaround in DSolve ( no limits of integration assigned) when the integrand is not improper ?


Series expansion of an inverse

I have to find the series expansion of the inverse function of : $\arctan\left(\frac{\ln(1+x)}{1+x}\right)$ How do I find out the series expansion of any inverse ? Note: The inverse of a function $f$ is the unique function $f^{-1}$ that verifies $f(f^{-1}(x))=x$ (given $f$ is a bijection)


Mouse gestures or keyboard shortcuts for navigating forward/backward in the documentation center

Is there any way to get gestures (e.g. trackpad- or Magic-Mouse-swiping left/right) to work for navigating forward and backward in the _Mathematica_ help browser, particularly on a Mac? If not, what are the keyboard shortcuts to navigate forward and backward?


Extract urls from list

If I have a list like               list = {"my element 1 http://link.com", "http://link2.com my element 2"}      how do I get a list of the links inside each element? Something like               StringCases[list, "http" ~~ _]      probably but I wasn't able to know how to end my pattern.


Optimized subset algorithm implementation

I was reading a paper from Mathematica Journal.It mentions a code for calculating subsets.                   subSets[s_List] := Variables /@ (Expand[Times @@ (1 + s)] /. Plus -> List) // Sort      Then it mentions the following code as optimized code,               subSetsV[s_List] :=  Distribute[{{}, {#}} & /@ s, List, List, List, Union] // Sort      My problem is I could not get both of these.Can someone please help me with bit of explanation of these snippets.


How to make Graphics3D object with different colors

Here is a sample `Graphics3D` object:               gr1 = Graphics3D[       GeometricTransformation[        {Red, Sphere[]},         Table[TranslationTransform[{i, 0, 0}], {i, 10}]       ]     ]      ![enter image description here](http://i.stack.imgur.com/tglYM.gif) How do I apply different colors (or other directives) when using `GeometricTransformation`? I get something like the following effect               gr2 = Graphics3D[       GeometricTransformation[{RGBColor @@ RandomReal[{0, 1}, {3}], Sphere[]}, #] & /@        Table[TranslationTransform[{i, 0, 0}], {i, 10}]     ]      ![enter image description here](http://i.stack.imgur.com/3Xngq.gif) So, how to change `gr1` to `gr2`? `Normal@gr1[[1]]` does not change it to many spheres.


Clearing memory of a subkernel in a Do loop

I have a `Do` loop, which saves data directly to a `.txt` file. However when I leave it running for long periods of time the RAM starts to run out till finally my laptop crashes. I've read similar posts on here but nothing seems to have worked. After each run of the `Do` loop, I no longer need the data because it has been saved in a `.txt` file. This means I don't require _Mathematica_ to use up my RAM remembering it... but I can't get it to stop! I tried putting `ClearSystemCache[]` inside the `Do` loop at the end but this didnt work. I read somewhere that this could be because I need to clear the memory of the individual subkernels. What is meant by subkernel? I run `ParallelEvaluate[]` and it launches four kernels, one for each CPU. Are these 4 kernels called subkernels? If so what is 'sub' about them? But the main question is how do i go about clearing the memory of the subkernals? My set up is               ParallelEvaluate[             Do[                 (bulk of formulae)                If[ (condition), PutAppend[ ]     ]               ]                     ]      I have tried putting               ParallelEvaluate[             Do[                (bulk of formulae)               If[ (condition), PutAppend[ ]     ]               ClearSystemCache[]               ]                     ]      However this doesnt seem to work. I've also tried:   * putting `$HistoryLength = 0;` at the start of the `Do` loop (doesn't change anything)   * putting `Clear["Global`*"]`   * putting `Remove["Global`*"]` inside end of `Do` loop (gives an error) If someone could explain how to clear memory of subkernels and/or give any other suggestions that would be great. Thanks


How to open Mathematica from the terminal in OS X

So far, when I was working in Linux, I would open my _Mathematica_ files from the terminal by typing:               mathematica filename.nb &      But now, I got a mac, and when I try it says               -bash: mathematica: command not found      So, I have to open the _Mathematica_ files by going to Finder and double clicking the file in a Finder window, which is annoying! I tried to google it, and I expected that it would be easy to find info about it, but I did not find any. Can anybody help me?


Problems with For statement

I'm trying to iterate some expression through for loop:                a = 0; b = 0.1; ϵ = 0.01; Ns = 100;      lhr[t_] := Normal[Series[-k7 x[t] y[t] /. Nsol /. initConst, {t, 0, Ns}]][[1]]; lhr[t]      rhr1[t_] := Normal[Series[-k7 x[t] y[t] /. Nsol /. initConst, {t, 0, Ns}]][[1]]; rhr1[t]      h = 0.01      For[t = a, t < b, t += h;         If[Abs[lhr[t]] < ϵ*Max[Abs[rhr1[t]]], Print[t]]]      I'm getting following errors: > General::ivar: 0.01` is not a valid variable. >>   >  General::ivar: 0.01` is not a valid variable. >>   >  General::ivar: 0.01` is not a valid variable. >>   >  General::stop: Further output of General::ivar will be suppressed during > this calculation. >> Can you help with this problem?


Loading graphics consumes execution time

I have created a grid, and also made a list of control objects(ex:inputfields, buttons, etc..). Then, I lay the list in my grid. There is no problem. However, the final layout takes a lot of time. I timed each operation and realized that the final grid layout is the one that takes up a huge chunk of time. Is there a better way of controlling the execution time of the graphics grid. `mygrid = ConstantArray["", {100, 100}]; mybutton1 = Button["Example", ImageSize -> {40, 50}]; myinput2 = InputField[x]; updatedlist = {}; updatedlist = ReplacePart[mygrid, {1, 2} -> mybutton1]; updatedlist = ReplacePart[updatedlist, {2, 3} -> myinput2]; Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]` The above code takes a lot of time to execute. I used the `Timing` function of mathematica to figure out which part took the long time to execute and it was the `Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]` part that was the longest. Because of this, my entire application has slowed down. Can I finetune my code to improve the performance? Look forward to hearing your inputs! Based on the comments blow, I tried to use a grid for the `updatedlist` above, but the problem is, how can I set the `ImageSize` of the `Grid`which is an option for the `GraphicsGrid` and not `Grid`? Thanks in advance,Anuk


How to change element color in Periodic Table?

The command               ColorData["Atoms", "Panel"]      generates a periodic table. As I don't want to reinvent the wheel, I asked myself how to change the color of each cell in the periodic table, (hydrogen -> pink, iron, gray etc.). I want to do it in the simples way. How can I do that? Since               ElementData[Element, "IconColor"]      is protected I dont have any idea.


Debugging with Breakpoints

re: Version 9. I typically write concise code and make a real effort to refactor. As such debugging has tended to take care of itself. Recently, I've needed to assemble applications of more complexity, in that it they have deeper hierarchies of functions, lots of them, and often from multiple packages. So I've started to want just a bit more debugging help. I prefer as simple development environment as possible, so I'd like to focus on debugging with native functionality of `Breakpoints`, rather than debugging functions from third parties or Workbench. I just need to see what goes on in the code. While, several questions on the site explore strategies and tactics for debugging. I have not found a concise description of how to effectively use the `Breakpoints` debugging functionality accessible from the menu items:               Evaluation > Debugger Controls > Show Breakpoints Window      either on this site, on Wolfram's site, or in the Mathematica documentation. Opening the Breakpoints debugging window doesn't tell one much. ![enter image description here](http://i.stack.imgur.com/HpqAZ.png) One would expect a clear way to set up breaks and variables to watch, and a way to run code to the specified point. In particular can and how can one:   * set a series of breakpoints both at a functional level and within a function and   * step through processing, point to point? Some examples or mini-overview? Thx.


Higher RAM handling by 32bit Mathematica

Can 32 bit Mathematica run program which requires more than 4GB RAM ?


Legend for ListContourPlot

Consider this example below for ListContourPlot.               ListContourPlot[       Table[Sin[j^2 + i], {i, 0, Pi, 0.02}, {j, 0, Pi, 0.02}],        PlotLegends -> Automatic]      I wish to make the Legend look like this: ![enter image description here](http://i.stack.imgur.com/iPTNc.png) I have searched the net but did not find any way of doing this. I'm sure this can be done because that legend in the link is created using _Mathematica_ but I can't figure out how. Maybe it's something very trivial but I would really appreciate if someone could help me with this because I always had a hard time dealing with legends in _Mathematica_. The example that I gave above was just for illustration. My actual function is more like this:-               ListContourPlot[     Table[Cos[Sqrt[bx^2 + by^2]], {bx, -1, 1, 0.1}, {by, -1, 1, 0.1}],      ContourLabels -> All, ColorFunction -> "Rainbow",        PlotLegends -> BarLegend[Automatic, All]]      So the plot looks like this:- ![enter image description here](http://i.stack.imgur.com/GJAtx.jpg) This legend has clear color bands which can be separated like that shown in the legend above. So my question is whatever may be the case can we make a legend that looks like the one I showed.


Why is Mathematica limiting the execution time of my calculation?

Is there a Front End option (or programming option) in Mathematica 9 that limits the amount of time that functions take to execute? I have a function (as part of a Mathematica Application) that shows page breaks and iterates though each cell of a notebook. The function operated on large notebooks without problem in Mathematica 8, however in Mathematica 9, it reaches a different point of the notebook each time (and almost gets to the end if page breaks are already showing). The function operates without problem on each half of the notebook (and on smaller notebooks). I have not used any TimeConstraint options. Also note, that I am able to execute the function using Workbench (with Mathematica 9). **EDIT** The function is to create a table of contents (a slightly modified version of the code given on Stack Exchange: Generating a Table of Contents). It includes cells that are already tagged. The code is executed via a button.


Button doesn't evaluate variable containing Module

I have a huge set of code to accomplish a data transformation. I have saved this set of code as eg:                codeset:=Module[{},                 FileNameSetter[Dynamic[Tab2excelFileLocation]];                 RawDataTonnages =Import[Tab2excelFileLocation, {"Sheets", "Tonnages"}];       (*...blah blah blah...data transformation and setting up graphs and stats tables...*)                 FileNameSetter[Dynamic[Tab3excelFileLocation]];                 Tab3RawDataTonnages =Import[Tab3excelFileLocation, {"Sheets", "Tonnages"}]      (*...blah blah blah....data transformation and setting up graphs and stats tables...*)                 ];      Button["Recalculate", codeset]      Later I want to use the two `FileNameSetter` buttons to locate new files. Once this has been done I then want to press the `Recalculate` button to re- evaluate `'codeset'` so that my answers reflect the data from the new files. I have get this to work partially - when I press the button the codeset re- evaluates for the 1st filename setter only even though I have changed both. If I test not by using the button but by re-evaluating the code using shift+enter it works for both filename setters. Why is this happening, I can't understand it.


Series of piecewise  functions

Let $f_{0}(x):[0,1]\to[0,1]$ be defined by $$f_{0}(x):=\begin{cases} 3x, & \text{if } x\in [0,\frac{1}{3}] \\\ \\\ -3x+2, & \text{if } x\in (\frac{1}{3}, \frac{2}{3}] \\\ \\\ 3x+2, & \text{if } x\in (\frac{2}{3},1] \end{cases} $$ Construct a sequence of function such that $$f_{n+1}(x):=\begin{cases} \frac{1}{3}f_n(3x), & \text{if } x\in [0,\frac{1}{3}] \\\ \\\ \frac{1}{3}+\frac{1}{3}f_n(3x-1), & \text{if } x\in (\frac{1}{3}, \frac{2}{3}] \\\ \\\ \frac{2}{3}+\frac{1}{3}f_n(3x-2), & \text{if } x\in (\frac{2}{3},1] \end{cases},\;\; \forall n\in\mathbb{N}. $$ And then, take the series associated with this sequence. $$f(x):=\sum_{i=0}^{\infty}(-1)^{i}f_i(x).$$ How do I plot some $f_n(x)$ (in function of n) and a good approximation for $f$? I want a plot of then separately and one in the same picture (with more than one $f_n$). Is it possible to make a "zoom" on the picture? Furthermore, is it possible to create a simulation in which one gives a natural number $p$ as an input, and receives as output the graph of some $f_n$ (in function of n) and a good approximation for $f$? $$f_{n}(x):=\begin{cases} \frac{1}{p}f_{n-1}(px), & \text{if } x\in [0,\frac{1}{p}] \\\ \\\ \frac{1}{p}+\frac{1}{p}f_{n-1}(px-1), & \text{if } x\in (\frac{1}{p}, \frac{2}{p}] \\\ \\\ .\\\ .\\\ .\\\ \\\ \frac{p-1}{p}+\frac{1}{p}f_{n-1}(px-p-1), & \text{if } x\in (\frac{p-1}{p},1] \end{cases} $$


How to partition three years of data into daily samples

I'm trying to find mean of temperature data list. The temperature data list has 3 hours steps which means I have 365*8=2920 temperature measurements per year. My data are temperatures of 13 years. First I found mean temperature of 13 years "t" one by one list by the following:                MeanTemp={Mean[Transpose[Partition[t[[1 ;; 365*8]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8 + 1 ;; 365*8*2]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*2 + 1 ;; 365*8*3]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*3 + 1 ;; 365*8*4]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*4 + 1 ;; 365*8*5]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*5 + 1 ;; 365*8*6]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*6 + 1 ;; 365*8*7]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*7 + 1 ;; 365*8*8]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*8 + 1 ;; 365*8*9]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*9 + 1 ;; 365*8*10]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*10 + 1 ;; 365*8*11]], 8], {2, 1}]],       Mean[Transpose[        Partition[n[[365*8*11 + 1 ;; 365*8*12]], 8], {2, 1}]],       Mean[Transpose[Partition[n[[365*8*12 + 1 ;; 365*8*13]], 8], {2, 1}]]};      Then I subtract mean temperature of all years from it. Which means I found variance of temperature:               TempVariance={Mean[Transpose[Partition[t[[1 ;; 365*8]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8 + 1 ;; 365*8*2]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*2 + 1 ;; 365*8*3]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*3 + 1 ;; 365*8*4]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*4 + 1 ;; 365*8*5]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*5 + 1 ;; 365*8*6]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*6 + 1 ;; 365*8*7]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*7 + 1 ;; 365*8*8]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*8 + 1 ;; 365*8*9]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*9 + 1 ;; 365*8*10]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*10 + 1 ;; 365*8*11]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*11 + 1 ;; 365*8*12]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*12 + 1 ;; 365*8*13]], 8], {2, 1}]] -        meanofyear}      I think this manuscript would be so long if the data increases.How to decrease the manuscript and increase flexibility?


Automatically counting the number of lines of code in a set of notebooks

How can I automatically count the number of lines of code "Input" existing inside all the notebook files contained in a specified folder? I know there is the issue of considering or not the automatic line breakings as new lines. But considering the purpose of this exercise (statistically convince that the amount of developed work on Mathematica justifies keeping a license), I'm not searching for exact values.


Visualize the output of Trace in a tree structure

The output of `Trace[expr]` can be nicely represented as a tree, I guess. Here is an example trace.               x = 5;     Trace[Mod[(3 + x)^2, x - 1]]          (* {{{{x,5},3+5,8},8^2,64},{{x,5},5-1,4},Mod[64,4],0} *)      How can I make a tree graph from this list?


Differentiation w/o assiging concrete values

v = Subscript[v, 0]*Sin[(Pi*S)/Subscript[S, 0]];     a = dv/ds v;     a = D[v, s]      returns               $RecursionLimit::reclim: Recursion depth of 256 exceeded.      Reference in the link shown by error msg doesn't give me a relief. I'm assuming the root cause is that I'm not assigning concrete values to the variables. But here I want to operate differentiation w/o assigning values (is there explicit name in math for this kind of operation?). Don't even know if it's differentiation specific or general issue for an operation not assigning concrete values (and thus can't assign proper tags to this question either). I haven't been able to find the corresponding reference. Thanks. * * * Update) Code @acl gave works for me now. However, I'm just curious why my code returns the same error even after I corrected "S" to "s", and also removed 2nd line which I didn't really expect `Mathematica` to do anything for.


Attaching persistent assumptions to symbol definition

_Is it possible to attach assumptions to a symbol?_ This relates to this question. Most of my work involves physical equations, i.e. there are basic assumptions on variables that will always hold true (in a physical sense). My current example involves higher-order Laguerre Gaussian modes:               u[p_, m_, λ_, w_, R_, ψ_, ψ0_, r_, θ_] :=      Sqrt[(2 p!)/((1 + DiscreteDelta[0, m]) π (m + p)!)]     Exp[I (2 p + m + 1) (ψ - ψ0)]/w      ((Sqrt[2] r)/w)^m LaguerreL[p, m, (2 r^2)/w^2]     Exp[-I (2 π)/λ r^2/2 (1/R - I λ/(π w^2)) + I m θ]      For this example, consider $p=m=\psi=\psi 0=0$, which gives the electric field distribution for the basic Gaussian mode. I can get the mode intensity with (I'm sure there is a more concise way of writing the assumption):               Assuming[(And @@ (# > 0 && # ∈ Reals & /@ {λ, w, R, r, θ})) ~And~          (r > 0 && r ∈ Reals && -π < θ <= π && θ ∈ Reals),          Abs[u[0, 0, λ, w, R, 0, 0, r, θ]]^2 //Simplify]      $$\frac{e^{-\frac{2 r^2}{w^2}}}{\pi w^2}$$ Back to the question, _how can I define a function that "simplifies" without explicitly listing the assumptions every time a I perform an algebraic operation on said function?_ Looking at the previously linked question, I can define a function               v[p_, m_, λ_, w_, R_, ψ_, ψ0_, r_, θ_] :=      Assuming[(And @@ (# > 0 && # ∈ Reals & /@ {λ, w, R, r, θ})) ~And~          (r > 0 && r ∈ Reals && -π < θ <= π && θ ∈ Reals),          u[p, m, λ, w, R, ψ, ψ0, r, θ]]      but the `Simplify` operation applies only to the definition, any operation such as               Abs[v[0, 0, λ, w, R, 0, 0, r, θ]]^2 // Simplify      $$\frac{e^{-2 \text{Re}\left[r^2 \left(\frac{1}{w^2}+\frac{i \pi }{R \lambda }\right)\right]}}{\pi \text{Abs}[w]^2}$$ does not simplify. Defining functions using pattern conditions, i.e. `f[a?Positive]:=...` do not allow for algebraic manipulation, as `f[a]` will remain unevaluated. I am hesitant to use `$Assumptions`. Whilst it would work in this specific example, I can see several problems where I'd like to use the same approach, but setting global assumptions would cause other issues.


How to linearize an expression automatically?

I would like to automatically linearize some long equations in the scope of variational calculus. Here follows an example of what I need to do : Given two variables $a_1 = q_1 + \delta q_1$ and $a_2 = q_2 + \delta q_2$ and a product $${a_1}^2\, a_2 = {q_1}^2 q_2 + 2q_1q_2\delta q_1 + q_2{\delta q_1}^2 + {q_1}^2\delta q_2 + 2q_1\delta q_1 \delta q_2 + {\delta q_1}^2 \delta q_2$$ I would like to eliminate any variable preceded by the $\delta$ symbol which power is superior to 1 (make it equal to zero), and any product of two variables preceded by the $\delta$ symbol (make the product equal to zero also). So as to obtain : $${a_1}^2\, a_2 = {q_1}^2 q_2 + 2q_1q_2\delta q_1 + {q_1}^2\delta q_2$$ I first tried the `Assumptions` options while expanding :               a1 = Subscript[q, 1] + Subscript[\[Delta]q, 1];     a2 = Subscript[q, 2] + Subscript[\[Delta]q, 2];     Expand[a1^2*a2, Assumptions -> Subscript[\[Delta]q, 1]^2 = 0]      Which returned the following :               Set::write: Tag Rule in Assumptions->Subsuperscript[\[Delta]q, 1, 2] is Protected. >>     (Subscript[q, 1] + Subscript[\[Delta]q, 1])^2 (Subscript[q,         2] + Subscript[\[Delta]q, 2])      Of course it didn't work. Truth is that I don't know how to start this... Does someone has any ideas? I also tried :               a1 = Subscript[q, 1] + Subscript[\[Delta]q, 1];     a2 = Subscript[q, 2] + Subscript[\[Delta]q, 2];     b = Expand[a1^2*a2];     Assuming[Subscript[\[Delta]q, 1]^2 == 0, b]      which didn't work either and returned :               \!\(     \*SubsuperscriptBox[\(q\), \(1\), \(2\)]\      \*SubscriptBox[\(q\), \(2\)]\) +       2 Subscript[q, 1] Subscript[q, 2] Subscript[\[Delta]q, 1] +       Subscript[q, 2]      \!\(\*SubsuperscriptBox[\(\[Delta]q\), \(1\), \(2\)]\) + \!\(     \*SubsuperscriptBox[\(q\), \(1\), \(2\)]\      \*SubscriptBox[\(\[Delta]q\), \(2\)]\) +       2 Subscript[q, 1] Subscript[\[Delta]q, 1] Subscript[\[Delta]q,        2] + \!\(     \*SubsuperscriptBox[\(\[Delta]q\), \(1\), \(2\)]\      \*SubscriptBox[\(\[Delta]q\), \(2\)]\)


Solving an algebraic equation with one or more constraints?

Just as a simple example, say I wanted to solve Sin[x] == a for x with the constraints -1<=a<=1 and 0 < x < Pi. Is there any way to do this?


How can I make a plot of the Higgs potential?

I was wondering, how would could I make a drawing of the Higgs potential aka "mexican hat potential". I am quite new to _Mathematica_ and don't know where to look to learn how to implement such a complex function.


Extract memoized results in the form of a rule

Lets say I define a function `f` with memoization. Is there some way to extract the memoized values? For example,               f[0] = 1; f[1] = 5; f[20] = 42      Is there some way to get a list similar to `{0 -> 1, 1 -> 5, 20 -> 42}`? Note, `FullDefinition` is close, but I dont know how to handle its output.


Is there a faster way to compute the endpoint for a DateRange given the start, step, and length?

Say I am given a date `start` an increment `step` (possibly mixed radix) and a desired number of steps `n`. I would like to compute a date `end` that will satisfy `Length[DateRange[start,end,step]]==n`. I can compute this date `end` with the following function.               f[{start_, Automatic,  step_}, n_]:= Nest[DatePlus[#, step] &, start, n - 1]      This works nicely in examples where `n` is small.               start = {2008, 1, 1};     step = {{1, "Day"}, {5, "Week"}};     n = 50;          AbsoluteTiming[end = f[{start, Automatic, step}, n]]     (* {0.015600, {2012, 10, 30}} *)          DateRange[start, end, step] // Length     (* 50 *)      However, when `n` is large, this is terribly slow.               n = 10000;          AbsoluteTiming[end = f[{start, Automatic, step}, n]]     (* {5.148009, {2993, 7, 19}} *)      Is there a significantly faster way to compute the date `end`?


Matrix algebra vs. PrincipalComponents and Varimax/Oblimin

Using matrix algebra I can calculate loadings and scores from the covariance matrix (data matrix is column centered):               covariancematrix=Covariance[data];     loadings=Eigenvectors[N[covariancematrix]];     scores1=data.Transpose[loadings];      I can obtain exactly the same scores using PrincipalComponents:               scores2=PrincipalComponents[data];        1. my problem is about the signs of the scores values. The absolute values are the same but scores1 and scores2 can differ in the signs. Why?   2. how can I apply the Varimax and Oblimin methods in Mathematica?


How to reset the $ModuleNumber?

According to the documentation, we _can reset $ModuleNumber to a positive machine integer_. There is even an example in the doc:               $ModuleNumber = 17; {Module[{x}, x], $ModuleNumber}      > >     {x$17, 18} >   However, when I try evaluating it again and again, instead of keeping `17`, the "serial number" after `$` increases _every_ time. I double checked that the `$ModuleNumber` does get reset at the beginning:               $ModuleNumber = 17; {$ModuleNumber, Module[{x}, x], $ModuleNumber}      > >     (* first time evaluation: *){17, x$17, 18} >     (*secend time evaluation: *){17, x$18, 19} >     (* third time evaluation: *){17, x$19, 20} >   > > ...... > > ... I did the test in _9.0.1 home edition_ on Windows 8, and also in _10.0_ on Raspberry Pi with the same result: ![$ModuleNumber reseting failed](http://i.stack.imgur.com/BPOo6.png) It's interesting to notice that using loop to automize the evaluation will NOT increase the number _during_ the loop:               Do[        Print[              $ModuleNumber = 17;              {$ModuleNumber, Module[{x}, x], $ModuleNumber}             ],        {5}]      > >     {17,x$19,20} >     {17,x$19,20} >     {17,x$19,20} >     {17,x$19,20} >     {17,x$19,20} >   But               $ModuleNumber = 17;     Do[        Print[              {$ModuleNumber, Module[{x}, x], $ModuleNumber}             ],        {5}]      > >     {17,x$17,18} >     {18,x$18,19} >     {19,x$19,20} >     {20,x$20,21} >     {21,x$21,22} >   > > **So question:** Do I misunderstand the documentation? What do I miss? And most importantly, how can I reset the `$ModuleNumber` so the subsequent `Module`/`Unique` will use the "serial number" I specified?


Putting large amounts of data inside a self-contained Manipulate

This is half tip, half question. If one tries to put a large amount of data inside the Initialization:>(code) part of a Manipulate, as one may be compelled to do in a Demonstration or where one wants to create a self- contained CDF document, I find that the Front End gets bogged down trying to format the input. One way around this that I've discovered is to embed the data inside a Raster. Thus:               embedded=Framed@Graphics[Raster[bigdata]] (*Framed is so you can see it*)      The visual output is meaningless. But ... you can then cut and paste the Framed object inside your initialization block and get the data out easily               Manipuate[f[data,n],{n,0,1},     Initialization:>(embedded=(*paste cut framed graphic here*);     data=embedded[[1,1,1]])     ]      So far as I can tell, this works. But it depends on an abuse of Raster and Graphics. Does anyone have suggestions about alternative means of putting large amounts of data inside a Manipulate?


Application on systems of equations

Lauren has 20 coins in her piggy bank, all dimes and quarters. The total amount of money is $3.05. How many of each coin does she have?


GridGraph layout with added edges

I noticed that the nice symmetric layout of a grid graph gets distorted when additional edges are added to the graph. Is there way to prevent that from happening and to keep the rectangular, grid-like layout? A minimal example would be               g = GridGraph[{3, 3}]     Graph[Range[9], Join[EdgeList[g], {1 \[UndirectedEdge] 5}]]      giving the following two outputs. ![enter image description here](http://i.stack.imgur.com/FKJq5.png) I would like the additional edge(s) added to the original graph, keeping its layout unchanged. Thanks. **Edit** : I realize that               EdgeAdd[g, 1 \[UndirectedEdge] 5]      does what I want. I'd still be interested to learn how I can force a grid-like layout when constructing the graph explicitly from vertex and edge lists, in particular since `EdgeAdd` does not seem to work well with edge weights. **Edit 2** : A concrete example of how I would go about constructing the weighted edge would be               n=5;     ind = RandomVariate[BernoulliDistribution[1/2],{n-1,n-1}]+1;     crossedges = Table[{(j-1)n+i \[UndirectedEdge] (j-1)n+i+n+1,(j-1)n+i+1 \[UndirectedEdge] (j-1)n+i+n}[[ind[[j, i]]]],{j,1,n-1},{i,1,n-1}] // Flatten;          g = Graph[Range[n^2],Join[EdgeList[GridGraph[{n,n}]],crossedges],EdgeWeight -> Join[ConstantArray[1,2n(n-1)],ConstantArray[Sqrt[2],(n-1)^2]]];      This construction is motivated by this question on MO.


Command Completion

**Note:** As of version 9, this functionality is available and works out of the box. * * * I've a few questions about Command Completion in Mathematica. I recently discovered this feature, and it's really convenient. However, it gets tiring to hit `Ctrl`-`K` all the time. Is there a way to turn Command Complete on after every keystroke, like autocompletion is for many programming IDE's? Or, failing that, to map it to another key like `Tab`, which I find much more convenient to hit? I've looked up some internet sources on changing Keyboard shortcuts for Mathematica, but they all seem pretty complicated.


Hex Representation in Mathematica and Python

I want to convert a code from _Mathematica_ to Python. I am using the following code to convert a code to hexadecimal, binary and so on:                   BinaryWrite[*file*, 8192, "Integer16"]      But I'd like to see the hex representation, so I am using this code:               BaseForm[8192, 16]      So I get the following answer: $2000_{16}$ I am trying to convert this program to Python. If I use `hex(8192)` I get `0x2000`. Is _Mathematica_ writing the hex file as `2000` or `0x2000`? Can I just use `hex(number)` in Python?


How can I draw a bifurcation for the following system between b and T ![bifurcation](http://i.stack.imgur.com/UCMeA.png)


FindFit giving weird values on a logistic equation

I was trying to fit a set of data onto a logistic equation, however it ended up telling me that the initial value when $t=0$ is greater than the maximum limit, thus I am led to believe that it isn't working. My approach: Here are the data points with the top row being day and the second row being height (cm) $\begin{matrix}7&14&21&28&35&42&49&56&63&70&77&84\\\17.93&36.36&67.76&98.1&131&169.5&205.5&228.3&247.1&250.5&253.8&254.5\end{matrix}$ I put them into mathematica by the following:               points={{7,17.93},{14,36.36},{21,67.76},{28,98.1},{35,131},{42,169.5},{49,205.5},{56,228.3},{63,247.1},{70,250.5},{77,253.8},{84,254.5}};      I need to fit this data into this equation $\frac{C}{1+\frac{C-N_0}{N_0}e^{-rt}}$, where $C$ is defined as the maximum possible height, $N_0$ is the height when $t=0$, $r$ is some constant, $e$ is Euler's Constant and $t$ is time Since $C$ and $N$ are already used by mathematica, i used $c$ and $n$               FindFit[points,c/(1+((c-n)/n)*E^(-r*t)),{c,n,r},t]      The output was:               {c->163.363, n->653566, r->236.408}      What have I done wrong to get these values? Also I am positive I have the correct equation as this is what the assignment tells us is the equation and all the other questions work. (Although they are a different style and we are given $N_0$ and $C$ in those ones) My expected output for $C$ and $N_0$ I believe is around               {c->256, n->9}      However I am unsure about $r$ but believe it to be under $1$ and positive


Is the MaximalBy function still used

On the mathematica reference website it gives examples using the MaximalBy function, However when I am using it, I see no desired output. This leads me to wonder if mathematica has stopped using this function. example:               MaximalBy[{{25, 16}, {1, 50}, {2, 8}, {13, 93}, {41, 21}}, Last]      and i get:               MaximalBy[{{25, 16}, {1, 50}, {2, 8}, {13, 93}, {41, 21}}, Last]      when I should get:               {13,93}      Since this does not work, how can I use RankedMax to get this desired result


Can I simplify an expression into form which uses my own definitions?

This seems like a simple thing to do, but I couldn't find anything relevant from Mathematica documentation. So suppose I have an expression:               a*b/(a + a*Cos[a/b])      And I have defined:               k=a/b      Now I want to simplify the expression above so that the simplify would use my definition of k in place of a/b in as many places as possible so that the final expression would look something like:               a/(k+k*Cos[k])      This was just a simple example I made up to demonstrate what I'd like to do, but I have encountered a similar situations many times every now and then.


Introducing new variables implicitly

I have a calculation               expr111 = cs[giso, xiso, 1, 1, 1]      that gives the result > >     -((k x)/(2 (1 + 1/4 k (x^2 + y^2 + z^2)))) >   I also have two other expressions:               fx = -((k rho^2 x)/(1 + 1/4 k (x^2 + y^2 + z^2))^3)     ff = rho^2/(1 + 1/4 k (x^2 + y^2 + z^2))^2      Pretty obviously `expr111 == fx/(2 ff)`. How do I get _Mathematica_ to make this substitution?


How do I format expressions so that replacement rules correctly apply to exponents?

I have a series of rules that I would like to apply to a series of expressions with variables, but cannot get _Mathematica_ to correctly recognize that these rules should apply when my variables have exponents in them. For example, let's suppose I know that `a b=1`.               a b /. a b -> 1     (* 1 *)          a c b /. a b -> 1     (* c *)      So those work fine. Then I try:               a a b /. a b -> 1     (* a^2 b *)      In general, my rules are a good deal more complicated, but the problem is always the same. How do I get mathematica to recognize `a^2` as `a a` so that it correctly applies the reduction rules?


Simplify symbolic expression in terms of constants

Say I have an expression $a+b+a\times b$ and I define $c:= a\times b$. How do I get _Mathematica_ to write $a+b+a\times b$ in terms of $c$, i.e. $a+b+c$?


Reducing Output length by introducing new variables

I have outputs like "expression/(1+3*c^2) +anotherexpression/(1+3*c^2)" and so on. Is there any way to set 1/(1+3*c^2)=A where A is a new variable so that the output reads like "A*expression+A*anotherexpression"? Thanks


Replace expressions with symbols

First of all: I'm new to Mathematica, so I would appreciate it if the answers are quite complete. I have the result of calculation that is expressed in $\sin$ and $\cos$. Now, all of these can be rewritten in terms of the values $T_j = \frac\pi{j} (1 - \cos^j(\alpha_\text{max})$). So now my question is, how do I "translate" for example $1 - \cos(\alpha_{\text{max}})$ to $T_1$ using Mathematica? Of course, it sometimes requires some goniometric formulas. I have tried to use the function `Eliminate` but it gives me a lot of garbage. A minimal example:               Eliminate[      Join[{g ==          1/3*Pi*(Subscript[v, y]^2*Cos[Subscript[α, max]]^3 -             2*Subscript[v, z]^2*Cos[Subscript[α, max]]^3 -             3*Subscript[v, y]^2*Cos[Subscript[α, max]] +             2*Subscript[v, z]^2 + 2*Subscript[v, y]^2)},        Table[Subscript[t, i] ==           Pi/i (1 - Cos[Subscript[α, max]]^i), {i, 1,          5}]], {Subscript[α, max]}]      \-------- **Edit** \-------- Following Daniel Lichtblau's code I want to write the following result of an integral in terms of the $T_i$: $\frac16 k^2 \pi [8 - 9 \cos(\alpha_{\text{max}}) + \cos(3 \alpha_{\text{max}})] v_y$. Maple computes this as $\frac23 k^2 [2 + \cos( \alpha_{\text{max}})^3 - 3 \cos(\alpha_{\text{max}})]v_y$ and a `FullSimplify` tells me that these expressions are actually the same. So, some visual inspection tells me that this is $2(T_1 - T_3)v_y$. However, the `PolynomialReduce` yields $\frac16 [-k^2 \pi v_y + k^2 \pi \cos(3 \alpha_{\text{max}}) v_y + 9 k^2 T_1 v_y]$ which is clearly not what I want.


Rewriting one expression using a variable representing another expression

I have two expressions:               w1 = (a+b)/c^2;          w2 = (a^3 + 3 a^2 b + 3 a b^2 + b^3)/c^6;      How can I ask _Mathematica_ to try to find an alternative expression for `w2` that just uses the variable `w1` ? In the above example, for instance, we can write: `w2 == w1^3`, however, its not always so obvious how to proceed in general instances where one is asked to rewrite one expression ONLY in terms of a variable representing another expression (or to check if this is possible). [6-5-2014] I've read through Replace expressions with symbols, and its still confusing exactly how to ask Mathematica to do what I'm specifying in my positing. It would really be helpful to see how to do something like my specific example.


Breaking up long equations in TeXForm

If I have a horrifically long expression and output it to TeX using TeXForm, I get a long equation which needs to be split up into multiple lines. But splitting it up manually can be quite cumbersome. Is there a solution to this within Mathematica, i.e., a way to output an equation in multiline format? I'm sure I'd need to put in some input about the size of the page, but that's fine.


Generating a graph where vertices correspond to points in an integer lattice and edges connect points less than a threshold distance apart

I'd like to automatically generate a graph where vertices correspond to (and have the coordinates of) points in an $A \times B$ integer lattice, and a graph is generated by connected vertices within a real-valued cutoff distance $r$. Is there a (relatively) automated manner of doing this in Mathematica v9? How can we display this graph properly, respecting the vertex coordinates?


Awkward Two-Point Boundary Value ODE

I'm trying to solve the following differential equation: -u''(x) + ((x-k)^2 -en)u(x)=0 with boundary conditions u(0)=0 and u(infinity)=0. Implementing this is Mathematica has led me to very cumbersome code. I have used the following approach: Use NDSolve to solve for general u(x) (which is also a function of k and en) with boundary conditions u(0)=0, u'(0)=1.                   solution1 =      NDSolve[{-D[uall[x, en, k], x, x] + ((x - k)^2 - en) uall[x,         en, k] == 0., uall[0, en, k] == 0,      Derivative[1, 0, 0][uall][0, en, k] == 1},      uall, {x, -8, 8}, {en, 1.8, 3.6}, {k, -.1, 0.6}];      Go on to solve for the eigenvalues en by imposing u(8)=0 (this acts to approximate the condition u(infinity)=0               Eofk1[k_] :=       en /. FindRoot[(uall[8, en, k] /. solution1) == 0, {en, 2.4}];      Whilst this approach does technically work, it is required that I specify a different range of the parameter k and en for NDSolve to work within for each solution. This means that I have to manually write out very similar lines of code again and again... I need help to make the code more efficient. Thanks!!!! UPDATE: I tried modifying the example on "StartingInitialConditions" on this page http://reference.wolfram.com/mathematica/tutorial/NDSolveBVP.html               sols = Map[     First[Block[{en = 1, k = 1},      NDSolve[{-u''[x] + ((x - k)^2 - en) u[x] == 0.,      u[0.] == u[8.] == 0.}, u, x,      Method -> {"Shooting",      "StartingInitialConditions" -> {u[0] == 0,      u'[0] == #}}]]] &, {1.5, 1.75, 2}];     Plot[Evaluate[u[x] /. sols], {x, 0, 10},      PlotStyle -> {Black, Blue, Green}]      The problem is that I want to be able to find the values of en as a function of k that satisfy the boundary conditions properly.


Replacing one element of list

I have a list of sequences of `x`'s and `y`'s. I want to switch the last position to the "opposite" symbol - if `x`, replace with `y`; if `y`, replace with `x`. It is in the following format:               {{{x,x,x,x,x,y,y},{x,x,x,x,y,y,x},{x,x,x,y,y,x,x},{x,x,y,y,x,x,x},       {x,y,y,x,x,x,x},{y,x,x,x,x,x,y},{y,y,x,x,x,x,x}},      {{x,x,x,x,y,x,y},{x,x,x,y,x,y,x},{x,x,y,x,y,x,x},{x,y,x,x,x,x,y},       {x,y,x,y,x,x,x},{y,x,x,x,x,y,x},{y,x,y,x,x,x,x}},      {{x,x,x,y,x,x,y},{x,x,y,x,x,x,y},{x,x,y,x,x,y,x},{x,y,x,x,x,y,x},       {x,y,x,x,y,x,x},{y,x,x,x,y,x,x},{y,x,x,y,x,x,x}}}      So for each monomial with length 7, I want to replace the last part with the opposite. Does anyone know an easy way to program it with _Mathematica_? I will be doing this for lists of different length: 7,11,13,15,17.


On a Mac OS X, Ctrl-Backspace generates ascii code 8 (backspace), which is almost invisible but very annoying

When I press Ctrl-Backspace, Mathematica inserts what looks either like a tiny white space or sometimes is invisible. Actually, though, it is an ascii character code 8, also enterable in Mathematica as `\.08`. The presence of this character completely messes up code and is very difficult to diagnose (for example, `\.08a` is different from `a`, but they look identical). I can't imagine the purpose of this behavior but I desperately want to get rid of it. Ideally, Ctrl-Backspace would delete the previous word, like in a sensible application. I would be completely content, though, with disabling all behavior when I press Ctrl-Backspace. I have tried looking in KeyEventTranslations.tr but I didn't find the origin of this behavior. Note that I am using Mac OS X 10.9.3 and Mathematica 9.0.1.0 on a MacBook 2012.


How to paint part of DateListPlot?

My graph is about fires (burned area) over 12 years presented in one Date List Log Plot. Because most of fires are in summer (as expected) I would like to highlight that with different background colors. How can I paint seasons in Date List Plot in different colors? I want to put different background color for winter, spring... Thank you!


Constructing election cartograms?

I found this pretty neat page showing cartograms for the US elections and I don't really know how to get started doing these graphics in _Mathematica_. For those who don't know, a cartogram is a map in which the geometry is distorted in proportion to the variable being plotted. For example, the standard red/blue US election map ![enter image description here](http://i.stack.imgur.com/XRyKF.png) is is transformed to a _population cartogram_ by scaling each state so that its size on the map is proportional to the state's population: ![enter image description here](http://www- personal.umich.edu/~mejn/election/2012/statepop512.png) Or again, according to a each state's number of electoral votes: ![enter image description here](http://www- personal.umich.edu/~mejn/election/2012/stateelec512.png) Here's the population cartogram based on county data: ![enter image description here](http://i.stack.imgur.com/KkMuL.png) Even more exotic plots are discussed on the linked page. I'm asking for a kick start and ideas on how to approach it since I haven't done something like this before.


Table not working with Plot

Because `NIntegrate[]` does not support parallel computation out of the box, I'm doing a simplified version by breaking the integration limit into pieces and using `ParallelTable[]`. The following code is just a minimum working example in which I used `Sinc[]` as the integrated function.               iser[x_] := NIntegrate[Sinc[t + x], {t, 0, 100}];          ipar[x_] := Total[ParallelTable[                  With[{xx = x}, NIntegrate[Sinc[t + xx], {t, ii*25, ii*25 + 25}]                  ], {ii, 0, 3}]                 ];      where `iser[]` is the usual serialize version, and `ipar[]` is the parallel version. Then I do `DistributeDefinitions[ipar]`. Passing a value to `iser[]` and `ipar[]` and **both give the correct answer** :               In[28]:= ipar[3]          Out[28]= -0.270322      But, when I try to run `Plot[ipar[x], {x, 0, 10}] // Timing` I get error messages that says                NIntegrate::inumr: The integrand Sinc[t+x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,25}}.           NIntegrate::inumr: The integrand Sinc[t+x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{50,75}}.           NIntegrate::inumr: The integrand Sinc[t+x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{75,100}}.           NIntegrate::inumr: The integrand Sinc[t+x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{25,50}}.           NIntegrate::nlim: t = 25. ii is not a valid limit of integration.                General::stop: Further output of NIntegrate::nlim will be suppressed during this calculation.           $Aborted      I know I can just generate a table of values and use `ListPlot[]` instead, but it's not easy to do adaptive sampling as `Plot[]` does. How can this be fixed?


Rules governing Plot line generation

I was looking at the Documentation Center for `Round`, `Ceiling` and `Floor` when I noticed that the plots for `Round` showed some variation, even at the small size that the Documentation Center displays them, when blown up... well:               Plot[Round[x, 10], {x, -30, 30}, Filling -> Axis]      ![Rounding at 10](http://i.stack.imgur.com/fABno.png)               Plot[Round[x], {x, -3, 3}, Filling -> Axis]      ![Rounding at 1](http://i.stack.imgur.com/PJdok.png) This intrigued me, I don't fully understand the rules governing generation of plots from functions. Clearly the method is adaptive, generating more data points where there is "activity," but is the (dis)continuity just based on the resolution that the plot is generated using? Any insight is welcome.


Bit Operations -- Force Binary Bit Representation

How to force binary bit representation of a number, so BitNot does yield the 1s-complement? > BitNot[n] turns ones into zeros and vice versa in the binary bit > representation of n. I was unable so far to produce a number which Mathematica accepts as a binary bit representation. Is there a way (like casting) to convince Mathematica that some number has to be treated as a binary bit representation? Any help appreciated.


Determine if solution to linear system exists

I'm trying to determine _only_ if a solution to a linear system of equations exists. I have been using `LinearSolve`, which works fine, but it solves the system as well. Is there another more efficient method for only checking the existence of a solution?


Create a table with inline conditions

I am trying to create a table with conditionals inline. For example, I'd like to create a 2 dimensional table like this:               Table[{i, j} -> 1, {i, 1, 3}, {j, 1, 3}]      Now, I'd like `Table` to generate values _only if_ `i != 1`. It should be easy, but I'm lost. I've tried several approaches, like the following, but I don't get what I want in a neat way:               Table[If[i != 1, {i, j} -> 1], {i, 1, 3}, {j, 1, 3}]      > {{Null, Null, Null}, {{2, 1} -> 1, {2, 2} -> 1, {2, 3} -> 1}, {{3, 1} -> 1, > {3, 2} -> 1, {3, 3} -> 1}} I know, I could delete cases, but there must be a clean and simple way!


FindFit: Fit that is always lower - Change of Norm?

I am trying to find a fitting function for a multidimensional set of data. I will have to find a fitting function that is always lower (conservative) than the data fitted. The easiest way is to look for the largest underestimation and add this value to the fit function. But this does not lead to very good fits. I have illustrated this in the following using some random data:               test = {{0.0, 120.0}, {1, 115}, {2, 50}, {3, 50}, {4, 30}, {5, 25}};     function[x_] := a + b x + c x^2;     rep = FindFit[test, function[x], {a, b, c}, {x}]     delta = (test -          Table[{x, function[x]} /. rep, {x, 0, 5, 1}])[[All, 2]];     Show[      ListLinePlot[test, PlotMarkers -> Automatic, AxesOrigin -> {0, 0}],      Plot[function[x] /. rep, {x, 0, 5}, PlotStyle -> Red],      Plot[(function[x] /. rep) + Min[delta], {x, 0, 5},        PlotStyle -> Green]      ]      ![plots of fitted functions](http://i.stack.imgur.com/GvEvt.jpg) Red is best fit, Green is shifted fit (no longer a good fit). If I understood correctly I will have to change the norm. But I do not how such a norm could look like and how to implement it. To me it seems like some kind of penalty method could be implemented in the norm. Thank you very much for your answers and hints!


Import values from tab separated file, change decimal point?

I have files that look like this:               8853,548600 39,021824        8143,632600 37,200790        7815,964200 35,926544        7106,337000 34,761822        6724,260400 33,491154        6178,100200 32,254318      I want to import it and then change the decimal point from , to . and convert it so that it has the the right head (so I can manipulate it like a number). My attempt that doesn't work:               data = Apply[StringReplace[#, {"," -> "."}] &,        Import[file, "Data"], {2}]


Output cell written with NotebookWrite dissappears on whole notebook evaluation, yet remains if I individually evaluate it

Create a new notebook with the following two input cells:               NotebookWrite[EvaluationNotebook[], Cell[BoxData[ToBoxes[Manipulator[Dynamic[x]]]], "Output"]]      and               y = 10  (* dummy cell *)      If you evaluate the whole notebook (`Evaluation menu\Evaluate Notebook`), you will see the manipulator appear then quickly disappear. If you manually evaluate the first cell, the manipulator will not disappear. Why is this happening?