Implementing OCR without using TextRecognize

I am new to _Mathematica_ and trying to figure out whether it is a good tool for algorithmic exploration. So I had the idea of implementing a simple OCR with _Mathematica_ , just using standard algorithms. I have this picture: ![Block of text](http://i.stack.imgur.com/Ta5wf.png) I'd like to apply the following steps:   1. Finding the cells of the picture: Could one use a voronoi algorithm to recognize the grid in the picture? After having the cells I'd like to apply these steps to each:   1. Use `Thinning` to find the skeleton of the character.   2. Use `EditDistance` to compare the character to a skeletized version of every possible character and then select the character which is closest. I have seen in the documentation that _Mathematica_ has all these algorithms I am just not sure whether it would actually be feasible to do what I want. (If it's impossible to do without knowing the name of the font I used: It's "Osaka, Regular-Mono, 144 pt".)


Tokenize Mathematica input in a simple way

## Background Usually, I give detailed descriptions when I have a question which sometimes lead to that users don't write their answers because they maybe think their answer is too simple. Therefore, I chose to just throw the direct question in the room and collect the ideas of all answers. Although it seems, that we cannot get a simple tokenizer by using functions like `TreeForm`, `MakeBoxes`, `MakeExpression`, ... I want to give some background information now: What really bothers me is, that we have here on Mathematica.SE a highlighter for Mathematica code which is far away from perfect, but which does a reasonable job. If I want to include a snippet of code into a LaTeX document on the other hand, I'm totally stuck with a b/w-pdf export from Mathematica or with the Mathematica **5.2** support of the listings package. Therefore, I hacked a simple parser of the html-output of our google-prettify plugin. This seems to work reasonable and with a little bit adjustment, one could include _styled_ Mathematica-code into a LaTeX document. It should be noted, that I don't intent to export formulas or sophisticated styled code. I want to stick with good old ascii-style code which is used in most packages. Before I used the html-output I was again having a long look at Leonids formatter but at its current state it lacks of the same issues since it relies on `MakeBoxes` as well and there are other issues. Leonid pointed out, that he want to reimplement this completely. On the other hand, we have functions like `SyntaxLength`, `SyntaxQ`, `MakeExpression`, `MakeBoxes` (and their `To` counterparts), all kind of `Forms`, we can keep expressions unevaluated and so on. Therefore, I was asking myself whether we can do the tokenizing much easier with Mathematica that it is possible with the JavaScript from google-prettify. ## Question Is it possible to implement a reliable tokenizer which takes a valid input- string of Mathematica code and returns a list of tokens without implementing the rules of the Mathematica-language itself? Although tokens usually don't contain whitespace characters, for the purpose of testing it would be nice, if **all characters stay even in the tokenized version**. Especially I want               input == StringJoin@@Tokenize[input]      to return `True`. Take for instance this function               Tokenize[str_String /; SyntaxQ[str]] :=        With[{expr = MakeExpression[str, StandardForm]},        Most[Drop[Flatten[MakeBoxes[expr] /. {             RowBox -> List, SuperscriptBox[a_, b_] :> {a, "^", b},              "\[Rule]" :> "->"}], 2]]     ];          Tokenize[     "Plot3D[{x^2+y^2,-x^2-y^2},{x,-2,2},{y,-2,2},RegionFunction->Function[{x,y,z},x^2+y^2<=4]]"     ]     (*      {"Plot3D", "[", "{", "x", "^", "2", "+", "y", "^", "2", ",",       "-", "x", "^", "2", "-", "y", "^", "2", "}", ",", "{", "x",       ",", "-", "2", ",", "2", "}", ",", "{", "y", ",", "-", "2",       ",", "2", "}", ",", "RegionFunction", "->",       "Function", "[", "{", "x", ",", "y", ",", "z", "}", ",", "x",       "^", "2", "+", "y", "^", "2", "<=", "4", "]", "]"}     *)      Although the output looks good here, inside Mathematica we have `\[LessEqual]` instead of `<=` (due to the `StandardForm` I assume). Furthermore, all different kind boxes need to be handled and I'm afraid many more things. Is there any chance to get this working really correctly? **Test examples:** In some of these cases I'm not sure whether my given output is the correct one. E.g. the handling of linebreaks may be system-dependent, `a_` seems to stay together in the box-representation (which would be ok), ...               "a\nb" (* {"a","\n","b"} *)     "a_:>a/2<=3" (* {"a_",":>","a","/","2","<=","3"} *)     "1`3+1.00`3" (* I'm not sure how this should be tokenized but my intention should be clear *)


How to perturb a Dynamic System?

I'm trying to model a basic feedback system with delayed feedback. I've done the initial setup and now want to add a few more advanced features to my system. Currently, it's just a simple delayed-differential equation with manipulatable delay to show how increasing the delay can send the system out of equilibrium. What I'd like to add, however, is the ability for the system to be perturbed at a particular point in time. For example, in the Predator-Prey model this might mean that the system acts exactly as normal at all times against the given initial condition, but suddenly at t = T, where T is the perturbation point, either the number of predators or prey is shocked. I want to model how this affects equilibrium for various parameters. Any good places to start? Thanks again! Edit: What I have initially is -               Manipulate[      HumanFaucetSystem =        NDSolve[{y'[time] + a*y[time - delay] == 0,          y[time /; time <= 0] == deviation}, y, {time, 0, 200*delay + 1}];      Plot[Evaluate[y[x] /. HumanFaucetSystem], {x, 0, 100*delay + 1},        PlotRange -> All], {{delay, 0, "Delay"}, 0,        15}, {{a, 1, "Multiplier"}, -5,        5}, {{deviation, 25, "Initial Deviation"}, 0, 100}]      I want to add another interactive parameter to the system that allows the user to schedule a specific time point at which a certain perturbation will occur. This can be positive or negative in the value of y. On this logic, I want to expand it to a two-agent delayed system that I've modeled already but add this feature.


Kramers-Kronig in Mathematica

I am trying to calculate the change of the refractive index from the change of the absorption coefficient using the Kramers-Kronig relations, in Mathematica.               c = 300000000;          daF[l_] = 500 * 0.28 Exp[-((l - 500)/90)^2];          dnFpoints = Table[         {             ln,             c/Pi NIntegrate[                 daF[li] / ((2 Pi c 10^9 /li)^2 - (2 Pi c 10^9 / ln)^2),                 {li, 800, 200},                 Method -> {"PrincipalValue"},                 Exclusions -> ((2 Pi c 10^9 /li)^2 - (2 Pi c 10^9 / ln)^2) == 0             ]         },         {ln, 300, 600}     ];      Unfortunately, Mathematica displays an error that it does not converge to prescribed accuracy and the output is junk (I would expect a smooth curve with a negative minimum first and then a positive maximum). I am using version 8, if it matters. Any ideas?


Solving a system of 4 logarithmic equations?

I would like to solve this system of 4 logarithmic equations in Mathematica.   * **a*log(b+d)=20**   * **a*log(b*30^c+d)=125**   * **a*log(b*180^c+d)=710**   * **a*log(b*360^c+d)=1350** I am looking for the values of **a** , **b** , **c** , and **d**. Thanks in advance!


Trying to solve a differential equation with a piecewise initial condition

I am trying to solve $$u_t=\frac{1}{4}u_{xx}$$ $-\infty<x<\infty,\: t>0$ With the initial condition $u(x,0)=\phi(x)$ where $$ \phi(x)= \left\\{ \begin{array}{lr} 1 & |x|<1\\\ 0 & |x|\geq 1 \end{array} \right.$$ So I initially typed in my piecewise function like this               ϕ[x_] := Piecewise[{{1, Abs[x]<1}, {0, Abs[x] >= 1}}]      But I have also tried this, (are they both valid, or is just one, or is neither?)               ϕ[x_] := Piecewise[{{1, -1 < x < 1}, {0, x >= 1 || x <= -1}}]      Then, following the mathematica examples I tried to solve the differential equation:               pde = D[u[x, t], t] - 1/4 D[u[x, t], {x, 2}] == 0     soln = DSolve[{pde, u[x, 0] == ϕ[x]}, u[x, t], {x, t}]      Which outputs a bunch of weird stuff, not the solution (I think) I was expecting. If my math is correct I think the solution to this would involve the error function. Any tips to where I might be going wrong would be aprreciated!


Answer when integrating by partial fractions

Evaluating $$\int \frac{x^2-x+5}{(x-2) (x-1) (x+3)} \, dx$$ Version 9.0.1 gives the following answer $$\frac{1}{4} (-5) \log (1-x)+\frac{7}{5} \log (2-x)+\frac{17}{20} \log (x+3)$$ It seems to me that the correct answer should be $$ \frac{1}{4} (-5) \log \color{Red}{|x-1|}+\frac{7}{5} \log \color{Red}{|x-2|}+\frac{17}{20} \log \color{Red}{|x+3|} + C $$ Am I missing something? Is there a fix? Edit:               Integrate[(x^2 - x + 5)/((x - 2)*(x - 1)*(x + 3)), x]


Number precision in a list

I have list with elements:               l = {1.000000000*10^-2076, 2.052685846*10^-1865, 7.337942425*10^-1741,      6.994455902*10^-1652, 2.007623567*10^-1582, 2.482890841*10^-1525,      8.737178026*10^-1477, 1.673592426*10^-1434, 5.183426213*10^-1397,      2.634095605*10^-1363}      I want to make a list l2, where each element i is equal to 1 - l[[i]]. So I made:               For[i = 1, i <= Length[l], i++, a = l[[i]]; b = 1 - a;        l2 = AppendTo[l2, b]];      But as a result I have :               l2 = {1.000000000, 1.000000000, 1.000000000, 1.000000000, 1.000000000,      1.000000000, 1.000000000, 1.000000000, 1.000000000, 1.000000000}      What is wrong, because if I will take the first element from l               a = 1.000000000*10^-2076      b = 1 - a = 0.99999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     9999999999999999999999999999999999999999999999999999999999999999999999\     999999999999999999999999999999999999999999999979473141540      what is ok. How can I convert l to l2, to have the good precision?


How to get the series expansion of $e^{x^a}$ at $x=0$?

I want to have a series expansion of $e^{x^a}$ or $e^{c_1x^a+c_2x^b}$ at $x=0$, but `Series` cannot give any useful result even if the assumption $a>0$ is specified.               Series[Exp[x^a], {x, 0, 2}]     Series[Exp[x^a], {x, 0, 2}, Assumptions -> {x > 0, a > 0}]     (* -> E^x^a *)      However, if $a$ is a number, we can get a result.               Series[Exp[x^(2/3)], {x, 0, 2}]     (* -> 1+x^(2/3)+x^(4/3)/2+x^2/6+O[x]^(8/3) *)


How to find the index of a square matrix in Mathematica quickly?

Let $A$ be an $n\times n$ complex matrix. The smallest nonnegative integer $k$ such that $\mathrm{rank}(A^{k+1})=\mathrm{rank}(A^{k})$, is the _index_ fo $A$ and denoted by $\mathrm{Ind}(A)$. I would like to compute $\mathrm{Ind}(A)$ quickly in Mathematica (I am using V8). Let us as a very simple example consider $$A=\left(\begin{array}{rrrrrr} 1 & -1 & 0 & 0 & 0 & 0 \\\ -1 & 1 & 0 & 0 & 0 & 0 \\\ -1 & -1 & 1 & -1 & 0 & 0 \\\ -1 & -1 & -1 & 1 & 0 & 0 \\\ -1 & -1 & -1 & 0 & 2 & -1 \\\ -1 & -1 & 0 & -1 & -1 & 2 \end{array}\right) $$ then it is clear that $\mathrm{Ind}(A)=2$. For computing this in _Mathematica_ , I used               Solve[MatrixRank[MatrixPower[A, k + 1]] == MatrixRank[MatrixPower[A, k]] && k > 0,         k, Integers]      But unfortunately, I cannot get the result. I will be grateful if anyone could design a way to compute $\mathrm{Ind}(A)$ for random matrices of the size $n\times n=200\times 200$ in _Mathematica_.


Proving a recurrence in Mathematica

I have $$j_n=\int_0^1 x^{2n} \sin(\pi x)dx.$$ How do I show that $$j_{n+1}= \frac{1}{\pi^2}(\pi- (2n+1)(2n+2)j_n)\, ?$$ I keep getting a recurring integration by parts and I can't simplify it. Please tell me where I'm going wrong.


What kind of object results from RegionIntersection function?

I'm trying to use RegionIntersection in a couple of Polygons. The polygons are the following:               p1=Polygon[{{-102.251, 21.8628}, {-102.252, 21.8628}, {-102.252, 21.8631}, {-102.251, 21.8631}, {-102.251, 21.8628}}]      and               p2=Polygon[{{-102.253, 21.8671}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8681}, {-102.252, 21.868}, {-102.252, 21.8678}, {-102.252, 21.8673}, {-102.253, 21.8672}, {-102.253, 21.8671}}]      When I run `r = RegionIntersection[p1, p2]` I was expecting that the resulting object was a "Region", however it is something like `RegionIntersection[Polygon{{...}},Polygon{{...}}]`. When I try to compute the Area of the resulting region it gives me:               Area::reg: "RegionIntersection[Polygon[{{-102.253,21.8671},{-102.253,21.8682},{-102.253,21.8682},{-102.253,21.8682},<<3>>,{-102.252,21.8673},{-102.253,21.8672},{-102.253,21.8671}}],<<1>>] is not a correctly specified region.      And if I test for a region with `RegionQ[r]` I obtain `true Also if I try to plot the region discretizing with `DiscretizeRegion[r]` I obtain:               DiscretizeRegion[RegionIntersection[Polygon[{{-102.251, 21.8628}, {-102.252, 21.8628}, {-102.252, 21.8631}, {-102.251, 21.8631}, {-102.251, 21.8628}}],Polygon[{{-102.253, 21.8671}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8682}, {-102.253, 21.8681}, {-102.252, 21.868}, {-102.252, 21.8678}, {-102.252, 21.8673}, {-102.253, 21.8672}, {-102.253, 21.8671}}]]]      So it seems that the resulting object from the Intersection is a region but it is not possible to compute anything on it. Following the examples on the Documentation I notice that using circles it behaves correctly and it is possible to compute on the intersection, however if the intersection is nothing (i.e. the two regions don't intersect) the object is still a region. I was wondering if there is a way of knowing that I have a null region. Of curse my first guess was computing the Area on it but for my polygons it is apparently impossible. Any thoughts on why regions behave like that? and on how to know if the Intersection region is a null region?


Loop integrals (quantum field theory)

I am attempting to compute the one loop contribution to the Higgs mass, and the one loop integral is somewhat difficult. I decided to try and get Mathematica to do it, to see if the answer can point me in the right direction. I inputted,               Integrate [(k^(d - 1)*(k^2 + p*k + m^2))/(((k - (x - 1) p)^2 +        p^2 (x - x^2 - 1))^2), {k, 0, Infinity}]      where the integration variable is $k$, and the rest are constants. Mathematica outputted, ![enter image description here](http://i.stack.imgur.com/Mfrqc.png) i.e. it simply wrote out the integral, and did not even attempt to compute it. Can someone tell me why it behaved like this; it's happened with other integrals in the past? How can I make it perform the integral (if it can)? It didn't even output an error message. PS: Please feel free to edit/improve the tags, the closest I found to integration was 'numerical integration.'


Deep Pattern matching with repeating arguments

I have a function that accepts a single argument that is described by the following grammar:               term := (Less | Greater | Equal | LessEqual | GreaterEqual)[Symbol,Number]      argument := term | Or[term,term,...]      The expressions are generated from operations like:               Reduce[x^2 -x -6x == 0, x, Reals] // FullForm     (* Or[Equal[x,-2],Equal[x,3]] *)      I want to use a pattern in the function definition to ensure that the argument is of the correct form and I want to convert the argument into the following form for use within the function:               List[term,...]      I am currently bogged down in pattern purgatory. I have tried all of the following and am confused by the results.               (* Test data *)     s = Or[Equal[x,-2],GreaterEqual[x,3]]      This pattern matched the test case. So far so good.               (* case 1 *)     s /. Or[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {2}     (* {2} V {2} *)      Let's see if we can capture the head in a variable. Yes, we can. I've got this figured out.               (* case 2 *)     s /. f_Symbol[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {Or} *)      Let's limit the pattern to a specific head instead of any symbol. This didn't match. I'm not clear on why.               (* case 3 *)     s /. f_Or[(Less | Greater | Equal | LessEqual | GreaterEqual)          [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* No Match *)      Maybe a different syntax will work. And it does, but I expected `{Or}` as a result.               (* case 4 *)     s /. f : (Or)[(Less | Greater | Equal | LessEqual | GreaterEqual)          [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {x == -2} V {x >= 3} *)      **Edit** : Some appropriately placed parens make a difference. I understand this result, but I still don't understand the previous one.               (* case 5)     s /. (f : Or)[(Less | Greater | Equal | LessEqual | GreaterEqual)         [x_Symbol, (_Integer | _Rational | _Real)] ..] :> {f}     (* {Or} *)      **End Edit** I am missing something important about how patterns/rules work. I would like to correct that gap in knowledge. And, secondarily, I'd like to get my function to only accept an appropriate argument and be able to convert the argument into the desired format.


solving for one solution to a system of polynomials

I'm trying to solve a system of equations:               Solve[ A1 D1 + E1 H1 == 0 && A2 D1 + A1 D2 + E2 H1 + E1 H2 == 0 &&            C1 F1 - E1 G1 == 0 && C2 F2 - E2 G2 == 0 && A1 - B1 + C1 == 0 &&             A2 - B2 + C2 == 0 &&  A3 - B3 + C3 == 0,                  {A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,E1,E2,F1,F2,G1,G2,H1,H2}]       Since we have more variables than equations, we have more than 1 solution satisfying the above equations but I don't want Mathematica to give me all possible solutions -- I would like just only one. **1\. How do I get Mathematica to give me just one possible solution?** One way I thought about doing this is to plug in random numbers such as `A2 = 1/2, B2 = 1, C2 = 1/2`, etc. so that all other variables are determined. But this isn't a very effective strategy in case the numbers I plug in do not satisfy all of the above equations. (One reason why I don't want all possible solutions to a system of equations is because suppose I am working with 30 equations and 80 variables. Then this is crashing Mathematica.)


Is Mathematica compatible with primusrun?

I use _Mathematica_ 9 on Ubuntu 12.04 LTS x86 (64-bit). My computer has an Nvidia graphics card, for which I installed `primus` and `bumblebee`. If anyone is in a similar situation, I would like to know if they have solutions to the following two related problems:   1. _Mathematica_ does not need OpenGL when it's not rendering any 3D graphics. For this reason I find it convenient to run the program without `optirun mathematica` or `primusrun mathematica` most of the time. However, I noticed that if I do make a `Plot3D` or related command, _Mathematica_ will crash. Is it possible to set the program up in a way so that it doesn't crash, but rather shows an error message, or just doesn't show output, if no 3D rendering is possible?   2. `primusrun` extends `optirun` functionality by saving power when the graphics card is not in use. I suppose that for this reason, if I'm not actively rotating a 3D graphic, it goes blank in a session of `primusrun mathematica` rather than `optirun mathematica`. When using the less efficient `optirun`, all functionality is available and runs as expected. Did anyone figure out a workaround for this? I'm asking on this site rather than AskUbuntu because the solution, if it exists, probably lies in changing _Mathematica_ preferences rather than `primus`'.


Stop Mathematica from giving imaginary solutions

I have the following equation: $$D=\frac{1}{64} \pi A ^3 B \sin \left(C\right)-\frac{1}{2} \pi A B \sin \left(C\right)$$ which I want to solve for $A$. The equation is cubic in $A$ so this should give me 3 answers and, potentially, imaginary parts to the answers. I know, from the physical meaning of the parameters, that all parameters ($A$,$B$,$C$ and $D$) are positive and real. My question is: how can I use `Solve` on this equation and make sure that there will be no imaginary parts popping up in the solution? I have used the suggestion by Chris and tried:               Solve[d == 1/64 π a^3 b Sin[c] - 1/2 π a b Sin[c], a, Reals]      but I still see that there is a $\imath\sqrt{3}$ term in the answer. Why does this still appear?


Why this code is considerably slower in version 9?

I have a `Mathematica` code for computing and plotting the density which corresponds to a given potential. The following code was written few years ago using version 5.2 of the `Mathematica`. Recently, I tried this code in the latest version 9 and I observed something very disturbing. Using version 5.2 it needs about 5.5 sec in order to produce the contours. On the other hand, in version 9 I have to wait about a minute (ten times longer than in 5.2!) using of course the same PC. Why this is happening? Do I have to make any modification to make it more compatible with version 9? Here is the code:               Clear["Global`*"];     Off[General::spell];          Vn = -(Mn/Sqrt[r^2 + z^2 + cn^2]);     Vd = -(Md/Sqrt[b^2 + r^2 + (a + Sqrt[h^2 + z^2])^2]);     Vh = v0^2/2*Log[r^2 + β*z^2 + ch^2];     Vt = Vn + Vd + Vh;     Vr = D[Vt, r];     Vrr = D[Vt, {r, 2}];     Vzz = D[Vt, {z, 2}];     ρ = 2.325/(4*π*100)*(Vrr + Vr/r + Vzz);     ρr = ρ /. {z -> 0};          Mn = 400; cn = 0.25;     Md = 5000; b = 6; a = 3; h = 0.2;     v0 = 20; β = 1.3; ch = 8.5;     ρ0 = ρr /. {r -> 8.5};          Print["-----------------"]     Print["ρ0 = ", ρ0]     Print["-----------------"]          S0 = ContourPlot[ρ, {r, -20, 20}, {z, -20, 20}, Contours -> 10,      PlotPoints -> 200, ImageSize -> 550]


Confirming the existence of a function related to a matrix

Is it possible to get an answer to the following question in _Mathematica_? Let $M$ be a $n$ by $n$ matrix, is there a function $m:\mathbb{N}\times \mathbb{N}\rightarrow \mathbb{Z}$ such that $m_{ij}=m_{ji}$ and $m_{ij}=m_{i+2,j+2}$ for all $i$ and $j$. I am new to _Mathematica_ and interested whether such existential, abstract expressions can be solved in _Mathematica_.


Get the last line from each of a large number of files, transform them, and write all results to a single new file

I have _several hundreds_ of .csv files that are _not logically named_ (contains numbers, characters, and special characters), all _stored in a directory_. Each file has large but _unequal number of rows and columns_. I do not need any information other than the last line of each file. What would be an efficient way to use _Mathematica_ to get the last line from each file, and summarize them to a new .csv file with the file name as the tag ? @WReach suggested this, but I am not sure how to proceed, especially given the irregular titles.


Showing a rectangular plot on an almost-closed sphere

I am currently teaching some students about the "point at infinity", and how it allows us to treat circles and lines as "the same", etc. I would like to kind of _show_ this happening with a series of three images:   1. The usual, $x$-$y$ plane plot of some function (say $y=x^3$)   2. That plot, on the surface of an **incomplete** sphere: that is, a sphere with a disk removed (the gluing isn't finished yet).   3. The plot on a complete sphere (bonus points if the ends of the cubic join together!) Now, I have been playing with `Texture` for the last 90min or so, and while I think I can eventually get it to do what I want for step 3., I don't see how to get it to work for step 2. The problem is, when I do an incomplete sphere (I have been using a RegionFunction), the Texture is distorted by this. In fact, the distortion is quite nasty (I am always completely confused by TextureCoordinates). Is there a way to do this in a nice way? I am open to any suggestions! **EDIT** : here is a picture of what I mean by "incomplete sphere": ![enter image description here](http://i.stack.imgur.com/2LD9A.jpg) **2nd EDIT** : here is a picture of what I had in mind (for step 3 anyway): ![enter image description here](http://i.stack.imgur.com/Jr6PU.jpg) Code:               SphericalPlot3D[1, {theta, 0, Pi}, {phi, 0, 2 Pi},  PlotStyle -> Texture[p],              TextureCoordinateFunction -> ({#5, 1 - #4} &), Lighting -> "Neutral",             Mesh -> None, Axes -> False, Boxed -> False]      **3rd EDIT** : Sorry for the confusion, and multiple edits! When I say "that plot" on the surface of a sphere, I mean the graph, the axes, the tick marks, everything.


How to Plot Prism in Graphics3D

I want to create an image of a rectangular prism, but there is no built-in primitive for it. One method to display a prism is shown in whubers's answer to Mathematica for teaching orthographic projection. What are some alternative ways to display prisms using `Graphics3D`, either with polygons or as wireframe-type models? Assume that the prism cross section is defined by a list of points in the plane.


Guides for programming CDFs

Are there any tutorials for programming high-quality CDFs, like the interactive calculus textbook presented at wolfram.com? _Mathematica_ 's Help is extremely impressive but it really does not help much when it comes to low-level programming of the nicely typesetted documents. For example, after quite a long time I still sometimes stumble upon the output like > Consider the equation `Cell[BoxData[FormBox[(…), TraditionalForm]]]`. The > right side is… The question might seem unsuitable but I don't think it would be productive to ask questions about the various properties of `Cell`, `TextCell`, `TextData`, etc. instead, because the problem is clearly not that local. Creating practical and good-looking interactive documents involves the use of pretty special techniques, like defining different paragraph styles, setting in- document links, making layout independent of screen resolution and magnification, and so on—maybe even manual kerning presets. Some tasks (like printing inline equations, as in the example above) are so common that there must be a solid number of convenient solutions. I'm still not aware of any tutorial aimed at discussing these particular issues. And I am probably not the only one who is interested.


What's the wrong when I use NestWhileList?

_**Problem :_**   * A Happy number is a number that if one squares its digits and add them together, and then take the result and square its digits and add them together again and keep doing this process, one comes down to the number 1. Find all the Happy ages, i.e., happy numbers up to 100.* _**This is the problem the book gived,and the solution of author:_** Input:               f[1] = 1;     f[4] = 4;     f[n_] := f[Plus @@ ( IntegerDigits[n]^2)]     Select[Range[100], f[#] == 1 &]      Output:               {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100}      _**But I want to use a different method from the author_** _**My solution:_** Input:               Select[Range[100], NestWhile[Plus @@ (IntegerDigits[#]^2 &), # &, # != 1 &]]      Output: {} _**However,I cannot know where the wrong is?Can Someone help me ?Thanks!_**


Plot Ellipse based on EigenSystem

Please consider the following :               covMatrice = {{34.925, -10.21}, {-10.21, 22.462}};          COG = Mean@(Nfixations["d"][[1]])[[All, 1]];          fixations = {{19.4688, 17.4281}, {18.0563, 21.7156}, {13.0219, 24.7219},               {22.9594,25.5219}, {28.5406, 24.6719}, {27.0688, 17.1656},               {27.6781,16.325}, {28.9281, 10.7719}, {16.025, 13.6625},               {19.1313, 17.1094}};               With[{           eigVec = Eigenvectors[covMatrice],           eigVal = Eigenvalues[covMatrice]},           Graphics[{                     White, Rectangle @@ frmXY,                      Black, Disk[#, .5] & /@ fixations,                      Red, Line[(# + COG) & /@                                {eigVec[[1]]*eigVal[[1]]/5,                                 {0, 0},                                eigVec[[2]]*eigVal[[2]]/5}]}]]      ![enter image description here](http://i.stack.imgur.com/tvE61.png) How could I draw an ellipse representing on the EigenSystem given that Neither Disk or Circle enable to implement an "orientation" ? A rough example of my desired output as drawn using PPT : ![enter image description here](http://i.stack.imgur.com/r9MUF.png)


Compiled function error - nontensor object created

I'm trying to optimize code that uses Position MANY times. The following toy code works:               list1 = RandomInteger[{1, 10000}, 500000];     list2 = RandomInteger[{1, 10000}, {3, 500}];          test = ParallelTable[             Flatten[               Map[                 Position[list1, #] &, list2[[i]]               ]              ], {i, 1,  Length[list2]}];      My trouble begins because I have so much data to process. When I use my actual data in the code above, Mathematica takes 34 minutes to complete the computation. This is just too long to be practical, so I began exploring Compile. When I try this:                 test2 =          Compile[{{list1, _Integer, 1}, {list2, _Integer, 2}},            Table[             Flatten[                Map[                   Position[list1, #] &, list2[[i]]                ]             ], {i, 1, Length[list2]}]];             wow = test2[list1, list2]           CompiledFunction::cflist: Nontensor object generated; proceeding with uncompiled evaluation.       You can see that Mathematica complains. My questions are:   1. How can I debug what the problem is in the Compiled statement above? I really don't know how to start figuring out the problem.   2. Is there an obvious alternative to using Position that itself would be faster than Position? I am not new to Mathematica, but I admit to being completely new to compiling code. Any thoughts?


Simpler way to repeat an execution with 2D points?

q has the coordinates of quadrilateral. I can get the output below with brute- force but I want to find a simpler solution, perhaps something like `f<-q[[1;;2]]`. **Initializations**               f[x_, y_] = {{1, 2}, {3, 4}}.{x, y} + {5, 6};     q = {{1, 1}, {3, 1}, {3, 2}, {1, 2}}      **Want: better way for this, perhaps in some matrix form?**               f[1, 1]     f[3, 1]     f[3, 2]     f[1, 2]


What does it mean when a function is defined with two pairs of brackets

I have noticed a function defined as such:                f[x_][y_] := expr;      How is the argument y in 2nd pair of brackets being used? What is the difference from defining a function this way:                f[x_, y_] := expr;


DynamicModule, SaveDefinitions and global functions

* * * ### Unfortunately, I had not checked stackoverflow, because there, the exact same behavior was already reported. Please see the Q&A "SaveDefinitions considered dangerous". * * * Up-front, I'm on Ubuntu 12.04 with _Mathematica_ 9.0.1 and let's start with the questions:   * Should functions which are used in a `Manipulate` be local to this dynamic cell, when I `save them with`SaveDefinitions`?   * Is it OK, that after a kernel-restart `Manipulate` defines global functions? I noticed this behavior a while ago when something did not work as I expected it. Here is a small toy example. First we define a function, which (we assume we don't know this now) is not correct and will be fixed later:               f[x_?NumericQ] := "Wrong Implementation";      Now we make a small dynamic environment where we use this function and we save the definitions used there.               Manipulate[f[x] + x, {x, 0, 1}, SaveDefinitions -> True]      Sliding a bit around gives the correct output: ![Mathematica graphics](http://i.stack.imgur.com/Lg34w.png) Now, we notice our error in `f`, because (let's say) `f` is going to work even when we don't have numeric values. Therefore, we fix the pattern and evaluate               ClearAll[f]     f[x_] := "Correct Implementation!"      this redefinition is instantly shown in the `Manipulate`, which is kind of weird, because we explicitly told _Mathematica_ to save the definition and let me cite the documentation: `SaveDefinition`... > is an option to Manipulate and related functions that specifies whether > **current definitions** relevant for the evaluation of the expression being > manipulated should automatically be saved. ![Mathematica graphics](http://i.stack.imgur.com/NMk91.png) There is even more, because when you now `Quit[]` the kernel and then do nothing else that move the slider, you see that now the first definition is used again and the output changes to `"Wrong Implementation"`. This seems fine, because `Manipulate` finally remembers what is should have saved. However, this is not what broke my neck. What really took time to debug was that the wrong definition of `f` is leaked into the global context:               f[3]          (* "Wrong Implementation" *)      The problem back then, when I had this issue, was that although I evaluated the correct definition,               f[x_] := "Correct Implementation!"      the other one was used, because its pattern was more specific.               f[3]          (* "Wrong Implementation" *)      Any comments?


Is it possible to marginalize one or several parameters obtained from fitting procedure?

Statistical model analysis package has a few fitting functions. Their arguments are data points, fitting model and parameters in the fit. The result is a set of best values for parameters, which represent the `"BestFit"` to the data. However, one can also specify the `ConfidenceLevel` and obtain `"ConfidenceInterval"` for every parameter, or the total `"ParameterConfidenceRegion"` for all parameters. This region will be an **_n_** -dimensional ellipsoid, for the fit with **_n_** parameters. If you are not interested in one of parameters you could marginalize it, e.g. integrate the likelihood function over all values of that parameter, ending up with **_n-1_** parameters. If you could do this for all but one parameter you would reach to the same `"ConfidenceInterval"` that Mathematica has calculated for that parameter. But if one could do this for only **_p_** parameters, one would end up with **_n-p_** parameters and the `"ParameterConfidenceRegion"` would be **_n-p_** dimensional ellipsoid. Marginalization in terms of `"CovarianceMatrix"` is very simple - remove row and column that correspond to the parameter you want to marginalize. Now I don't know how to get `"ParameterConfidenceRegion"` from this modified `"CovarianceMatrix"` and I don't know if Mathematica has something for parametric marginalization implemented.


How to avoid an expensive subset of a Manipulate computation when dependent variables have not changed?

I have a `Manipulate` where a portion of the calculation that ends up displayed is dependent on a subset of the `Manipulate` control variables. It would make sense to cache that portion of the computation, only updating it if those controls are altered. Here's an example to illustrate:               ClearAll[preCalculateStuff]     preCalculateStuff = (#1  #2 ) & ;          Manipulate[ DynamicModule[{f},       f = preCalculateStuff[a, b];       Plot[(f t) Sin[  t + r ], {r, 0, 2 Pi}]],      {{a, 0.5}, 0, 1},      {{b, 0.5}, 0, 1},      {{t, 0.5}, 0, 1} ]      My real `preCalculateStuff` builds a big table, each element requiring a 4x4 `Eigensystem` call. I'd like to restrict that calculation to only do it when the control variables it is dependent on change. I've been pointed to `TrackedSymbols :> {var1, var2}` as a mechanism to avoid re-evaluation of the display. However, I still want to re-evaluate the display here (when any variable changes, including any that I would track), so it's not obvious to me how that would be applicable (unless it was to implement a `calculate` button, which wouldn't be terribly elegant).


How to control the speed in Manipulation

As the title says, I want to control the speed when I use `Manipulate`. I have the following piece of code               Clear["Global`*"];     Manipulate[     V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}];     Vyy = D[V, {y, 2}];     Vzz = D[V, {z, 2}];     ρ = 2.325/(4*π*100)*(Vxx + Vyy + Vzz);     ρxy = ρ /. {z -> 0};     ρxz = ρ /. {y -> 0};     ρyz = ρ /. {x -> 0};          M = 9500; a = 3; h = 0.15; λ = 1.1;          Syz = ContourPlot[ρyz, {y, -30, 30}, {z, -30, 30}, Contours -> 20,      ContourStyle -> Black, PlotPoints -> 50,      RegionFunction -> Function[{y, z}, ρyz < 0],      PerformanceGoal :> "Speed"],     {b, 0, 10, 0.1}]      My problem is that when I evaluate this in order to see what happens when the value of b changes the contours are plotted too fast without any order. Let me be more specific, the slider corresponding to b changes very fast and at any time it shows contours for completely random values of b. What I want, is to start the "animation" and be able to see in smooth and slow motion all the situations from b=0 up up b=10 using step 0.1 Many thanks in advance. **EDIT**               plots = Table[     V = -(M/Sqrt[b^2 + x^2 + λ*y^2 + (a + Sqrt[h^2 + z^2])^2]);     Vxx = D[V, {x, 2}]; Vyy = D[V, {y, 2}]; Vzz = D[V, {z, 2}];     ρ = (2.325/(4*Pi*100))*(Vxx + Vyy + Vzz);     ρxy = ρ /. {z -> 0};     ρxz = ρ /. {y -> 0};     ρyz = ρ /. {x -> 0};     M = 9500; a = 3; h = 0.15; λ = 1.1;     ContourPlot[ρyz, {y, -50, 50}, {z, -50, 50}, Contours -> 20,      ContourStyle -> Black, PlotPoints -> 50,      RegionFunction -> Function[{y, z}, ρyz < 0],      PerformanceGoal :> "Speed", FrameLabel -> {"y", "z"},      RotateLabel -> False,      FrameStyle ->       Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotLabel -> Row[{"b = ", b}],      LabelStyle ->       Directive[FontSize -> 17, FontFamily -> "Helvetica"],      ImageSize -> 550], {b, 0, 10, 0.1}];


Get the correct position of a label on a vertical gauge

I am trying to have the value for a vertical slider display next to the indicator arrow for a vertical slider. However, my attempt is slightly wrong; the coordinates are scaled to the entire frame of the vertical slider (and not the coordinates), so at the minimum and maximum values, the location of the label is slightly off. How can I get this to work correctly? When I don't use Scaled, the label goes way off of the vertical slider, but when I do used it, it scales to the wrong values. Code:               Manipulate[      Grid[{        {         Style[" Sample ", 12, Bold, Underlined]},        {VerticalGauge[length, {0, 100},          GaugeFaceStyle -> LightGray,          GaugeLabels -> Placed[Automatic, Scaled[{0, length/100}]]          ]         }        },       Alignment -> Center],      {length, 0, 100}      ]      ![Imgur](http://i.imgur.com/uoYfVhh.gif)


RegionPlot is producing odd gaps, even for simple functions. Is there an option to prevent this?

When I use `RegionPlot` to plot the region between two functions, I get strange gaps in the resulting figure. Is there a way to prevent this from happening? * * * For example,               RegionPlot[x^2 < y && y < x^4, {x, -3, 3}, {y, 0, 3}]      produces the following strange result: ![enter image description here](http://i.stack.imgur.com/u6MvY.png)


Combining Two Plots to Create a Zoomed Callout

I want to combine two images to create a zoomed callout, as illustrated below. ![zoom callout](http://i.stack.imgur.com/pIFi6.png) The plot on the right is the zoomed in version of the boxed area on the left. The dotted lines connect the corresponding box corners. I would like to be able to change the location and size of the zoom callout (the right plot) as well as which dotted lines are shown. This is the code I used to make the plots:               bigplot = ContourPlot[x^2 - y^2 == 1/10000, {x, -1, 1}, {y, -1, 1}, ContourStyle -> Directive[Red, Thick], Frame -> None];     xrange = {-1/10, 1/10};     yrange = {-1/10, 1/10};     rect = Graphics[{EdgeForm[Directive[Black, Thick]], Opacity[0], Rectangle[Sequence @@ Transpose[{xrange, yrange}]]}];          combined = Show[bigplot, rect]     zoomedplot = ContourPlot[x^2 - y^2 == 1/10000, {x, xrange[[1]], xrange[[2]]}, {y, yrange[[1]], yrange[[2]]}, ContourStyle -> Directive[Red, Thick], FrameTicks -> None, PlotRangePadding -> None]      I think a solution would use `Inset`. However, I do not understand how the _pos_ argument works.


Has Mathematica a function to compute the Smith Normal Form?

The Smith normal form is a matrix that can be calculated for any matrix (not necessarily square) with integer entries. See Wikipedia for a more elaborate description. **Has Mathematica a function to compute the Smith Normal Form ?** If not, is there an easy way to compute it in Mathematica?


Why are numeric division and subtraction not handled better in Mathematica?

There is something that has been troubling me for a while. At least in version 7, the performance of `a / b` and `a - b` is not equivalent to, and significantly inferior to, `Divide[a, b]` and `Subtract[a, b]`, despite the fact that these are treated as equivalent in the documentation. As a terse code fanatic it chafes me to have to write out the longer forms, but that is only the beginning of my concern, because the latter, faster forms are transparently converted into the former, slower forms. Examples from the documentation for `Divide`: > x/y or Divide[x,y] is equivalent to x y^-1. > > Divide[x,y] can be entered in StandardForm and InputForm as x ÷ y, x > `Esc`div`Esc` y or x \\[Divide] y. Proof that these statements are false:               {a, b} = List @@ RandomReal[{-50, 50}, {2, 1*^7}];          Do[a/b, {50}]          // Timing // First     Do[a b^-1, {50}]       // Timing // First     Do[a\[Divide]b, {50}]  // Timing // First     Do[Divide[a, b], {50}] // Timing // First      > >     2.262 >   >     2.231 >   >     2.184 >   >     0.437 >   `Divide[a, b]` is _not_ evaluated in the same manner as the rest. Similarly for subtraction:               Do[a - b, {50}]          // Timing // First     Do[a + (-1 b), {50}]       // Timing // First     Do[Subtract[a, b], {50}] // Timing // First      > >     3.651 >   >     3.65 >   >     1.404 >   Although the examples above use packed arrays (see Why does list assignment with a packed array result in unpacked values? for an explanation of `List @@`) the same performance differential exists with unpacked lists. One can see with `Trace` that the short forms induce additional operations:               a = Range[1, 2];     b = Range[3, 4];          a/b          // Trace     Divide[a, b] // Trace      > >     {{a,{1,2}}, {{b,{3,4}}, 1/{3,4}, {1/3,1/4}}, {1,2} {1/3,1/4}, {1/3,1/4} > {1,2}, 1/3,1/2}} >   >     {{a,{1,2}}, {b,{3,4}}, {1,2}/{3,4}, {1/3,1/2}} >                 a - b          // Trace     Subtract[a, b] // Trace      > >     {{a,{1,2}}, {{b,{3,4}}, -{3,4}, {-3,-4}}, {1,2} + {-3,-4}, {-3,-4} + > {1,2}, {-2,-2}} >   >     {{a,{1,2}}, {b,{3,4}}, {1,2} - {3,4}, {-2,-2}} >   Note the false equivalence in this output; the fast `Divide` and `Subtract` operations are formatted as `{1,2}/{3,4}` and `{1,2} - {3,4}`, yet these slow forms are not part of their evaluation process. More problematic is when this false equivalence changes evaluation. For example, if you try to work symbolically with `Subtract` and `Divide` in an evaluated expression and use the result these faster forms are replaced with the slower ones:               expr = Divide[x, y] + Subtract[x, y];     fn = Function[{x, y}, Evaluate @ expr]     fn // FullForm      > >     Function[{x, y}, x + x/y - y] >   >     Function[List[x,y], Plus[x, Times[x, Power[y,-1]], Times[-1,y]]] >   Note also that `Divide` and `Subtract` are stripped when converting forms in the Front End (menu **Cell** > **Convert To** ) so even without evaluation these operators may be lost. ### Therefore I have these questions:   * Why are these operations universally treated as equivalent when they are clearly not programmatically equivalent?   * Why does _Mathematica_ not include optimization for cases of numeric division and subtraction to eliminate the additional evaluation steps?   * Is there a practical way to add global optimizations to automatically convert these operations to the fast forms before numeric evaluation?   * Failing the above, what is the best way to work symbolically with actual division and subtraction operators for the sake of performance?   * Is internally representing division and subtraction as multiplication and addition really the only mathematically valid design option? Couldn't these instead be first-class operators that are recognized as equivalent to `Times` and `Plus` _for the purpose of pattern matching_ but not _converted into_ `Times` and `Plus` (which introduces additional `Times` and `Power` operations)?


Switching off Dynamic updating on a cell by cell basis

Is there a simple way to switch off `Dynamic` evaluation for a particular cell? I usually delete the cell if it disturbs other evaluations or affects the performance too dramatically.


NSolve missing solutions in Mathematica 10

Running Mathematica 8.0.4 and 10.0.0 on a Windows 8.1 machine. Processed the same code with both kernels: `k = .2; NSolve[Rationalize[2 r^2 - .2 r^(k + 2) - 1 == 0], r, Reals]` The version 8 kernel returns two values as expected: `{{r -> 0.742979}, {r -> 100000.}}` The version 10 kernel returns only the first value by default. The second value doesn't appear as a solution until setting `WorkingPrecision` to at least 28. The same behavior occurs for other values of `k`: the version 10 kernel needs massaging to return values the version 8 kernel finds by default. What would cause this?


Plotting a Partially Filled Ellipse

I would like to plot a partially filled/shaded ellipse. The code below shades the whole ellipse. However, I only want to shade the part of the ellipse to the right of the vertical line where x > cutscore.               Needs["MultivariateStatistics`"]          cutscore = 0.5;      data1 = RandomVariate[MultinormalDistribution[{0, 0}, {{1, 0.6}, {0.6, 1}}], 500];     ellipse1 = EllipsoidQuantile[data1, 0.5];     e1 = Graphics[ellipse1];     line1 = Graphics[{Line[{{cutscore, -1.3}, {0.5, 1.5}}]}];     show1SEL = Show[e1, line1, Axes -> {True, False}, AxesOrigin -> {-2, -2},                 PlotRange -> {{-2, Automatic}, {-2, Automatic}}];     show1SELfilled = show1SEL /. Line[x_] -> {Green, EdgeForm@Thin, FaceForm[Opacity@.2], Polygon[x]}


Implicit Interpolating function in Mathematica and its explicit form in small sections

I have a set of points $\\{x_i,y_i\\}$ that represents a closed curve. I want to find a function $F(x,y)$ such that $F(x,y) = 0$ gives the needed curve and $F(x,y) \ne 0$ outside the curve. For example, suppose I am given a set of points that forms a circle:               n = 16;     points = Drop[Table[{Cos[2 i Pi], Sin[2 i Pi]}, {i, 0, 1, 1/n}], -1] // N;      I use the `Interpolation[..]` Mathematica function:               args = Join[Table[{points[[i]], 0}, {i, Length[points]}], {{{0, 0}, -1}}];     F = Interpolation[args];      Here I have added a new point $(0,0)$ with value $-1$ in it to my set of points to give "a depth" to $F(x,y)$. First question. Is that solution right? Can I be sure that my $F(x,y) \ne 0$ on non-curve points if I add "an inner" point with non-zero value to my set? What solution is more preferable? Also I have a second (and main) question. Due the peculiarity of my problem I need an explicit expression for my curve in a given section. In other words I want to have an expression for my curve in terms $y = f(x)$ or $x = f(y)$ (does not matter) between near points. I need this $f$ and its derivative $f'$. Thereby $f$ should be an InterpolatingFunction object too (but one- dimensional). Using `Solve` on `F` from previous example does not give a result. How to get $F$ and $f$ (between given near points)? **Update** : In my example $F(x,y) = x^2+y^2-1$ and I can single out two explicit fucntions: $f_1(x) = \sqrt{1-x^2}$ where $x > 0$ and $f_2(x) = -\sqrt{1-x^2}$ where $x \leq 0$. Equations $y=f_1(x), y=f_2(x)$ and equation $F(x,y)=0$ represent the same curve (a circle). This is what I need: implicit function $F(x,y)$ and a set of explicit functions $f_i$. Also I can single out another explicit functions: $f_1(y) = \sqrt{1-y^2}$ where $y \leq x$ and $y \geq -x$; $f_2(x) = \sqrt{1-x^2}$ where $y > x$ and $y \geq -x$; $f_3(y) = -\sqrt{1-y^2}$ where $y > x$ and $ y < -x$; $f_4(x) = -\sqrt{1-x^2}$ where $y \leq x$ and $y < -x$. Together they form a circle. **Update 2** : The given curve is closed and has no self-intersections. Locally $F(x,y)=0$ can be expressed as $y=f(x)$ or $x=f(y)$. This is what I need. I try Solve function but it does not give result for interpolating $F(x,y)$. Instead it gives an error: _"Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system"_


Unify the sampling of NIntegrate[ {f, g, h} w ]

I'm trying to numerically integrate a function which has a vector-valued slow part and a much faster component which is shared by all the components, i.e. an integral of the form $$ \int_a^b\begin{pmatrix}f(x)\\\ g(x) \\\ h(x)\end{pmatrix}w(x)\,\text dx. $$ Because `NIntegrate` is nicely Listable on its first argument, I can feed it a list-valued argument without a problem. However, it appears to be doing each component as a completely separate integral, which results in a lot of work being re-calculated. For example, the (simplified) example integral               samplePointsList = Reap[         NIntegrate[          {x, x^2, x^3} Cos[10 x + Cos[x]]          , {x, 0, 5}          , EvaluationMonitor :> Sow[x]          ]         ][[2, 1]];      gives the sample point diagram (through `ListPlot[Transpose[{samplePointsList, Range[Length[samplePointsList]]}]]`) ![enter image description here](http://i.stack.imgur.com/FuIiD.png) It is clear that the kernel is doing the initial sampling, and then the further refinements, separately for each component. While the required sample points are not identical, there is a lot of shared work and I feel there is a fair bit of room for optimization there. I am aware that, since the sampling requirements of each component are slightly different, binding them completely will require more evaluations in some components than would be necessary. (For instance, in the example above, the extra detail required by the first component around $2\leq x\leq 3$ would be slowed down slightly if it was required to also calculate the second and third components there, though they do not require it.) However, the components in my case are similar enough that I do not think this would be an issue. Is there a way to force Mathematica into this sort of separation of the integrand and unification of the sampling? If not, is there a way to make it aware of the previously calculated values and sampling points which will speed up the process?


Sorting non-numerical lists

The `Sort` function will by default sort from lowest to highest.               In[1]:= Sort[{3, 1, 4}]     Out[1]= {1, 3, 4}      However, if the list contains non-numerical values, it will sort it incorrectly               In[2]:= zeroes = {2 Pi - 2 ArcTan[Sqrt[2 + Sqrt[5]]],         2 ArcTan[Sqrt[2 + Sqrt[5]]], 2 Pi + 2 ArcTan[Sqrt[2 + Sqrt[5]]]};          In[3]:= zeroes // N     Out[3]= {4.04615, 2.23704, 8.52022}          In[4]:= Sort[zeroes] // N     Out[4]= {4.04615, 2.23704, 8.52022}      One could use the `Greater` function as a parameter to Sort and then reverse the input               In[5]:= Reverse@Sort[zeroes, Greater] // N     Out[5]= {2.23704, 4.04615, 8.52022}      There is no `Lesser` function in Mathematica, but there must be a better way to do this, without converting the data to floats.


How to map vertex points from the surface of a straight pipe onto 2D plane. The 3D surface points of the straight pipe can be found here: data Working code:               file = "http://pastebin.com/H9y9SqYy";     dat = Import[file, "Table"];     Graphics3D[Point@dat, Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/rP8YS.png) One can imagine as a simple straight cut (anywhere) on the circumference of the pipe. I want to get something like this: ![enter image description here](http://i.stack.imgur.com/VT1gk.png)


How would I enable the Evaluate in place item of the Evaluate menu?

I would like to be able to suppress multiple outputs when a cell is evaluated. Is there a way to enable the "Evaluate in place" menu item of the Evaluate menu?


Copying Greek text from notebooks as unicode

> **Possible Duplicate:**   >  How to "Copy as Unicode" from a Notebook? How can I copy Greek text from notebooks as proper Unicode that can be pasted into other applications? If I type some Greek text into a notebook, and then try to paste it elsewhere, it ends up as a set of character names in Mathematica's notation. The screenshot below illustrated the problem. ![Mathematica graphics](http://i.stack.imgur.com/YqVrc.png) It doesn't really matter if the Greek text is typed elsewhere, then pasted into Mathematica, or if it's typed directly into Mathematica: when copying _from_ Mathematica, Greek letters are converted into character names. If you don't have a Greek keyboard layout installed, this can be useful for testing. **Use case:** analysing Greek text and copying results from a notebook.


Removing In/Out Labels before printing

I know that I can close a notebook and open it again in order to remove the In/Out labels. What I would like to know is if there is another easy way of removing these labels without having to close the notebook. Actually I just want to hide them from my printouts. It seems to me like it should be a printing option, but I can't find it.


Scan vs Map vs Apply

I cannot understand the difference between `Apply`, `Scan`, and `Map`. I have tried to play with these function by the codes below:               f[x_] := x^2      * * *               Map[f, {{a, b}, c}]      Output:               {{a^2, b^2}, c^2}      * * *                Apply[f, {{a, b}, c}]      Output:               f[{a, b}, c]      * * *               Scan[f, {{a, b}, c}]      There is no output for this one. The function of `Map` is understandable. But I cannot get the purpose of `Apply` and `Scan`. What are the differences between these three function?


What is the most efficient way to add zeros to end of a number?

Beside `*10^n`, is there a faster way to add thousands of zeros to end of a number? **Updated** Timings:               In[230]:= First[Timing[prime*10^100000000]]          Out[230]= 3.625          In[25]:= First[      Timing[FromDigits[        Join[IntegerDigits[prime], ConstantArray[0, 100000000]]]]]          Out[25]= 7.547      **Updated** According to Mr.Wizard answer:               In[46]:= First[Timing[2213*1*^200000000]]          Out[46]= 0.015 (* The real timing on the clock is 5 seconds *)          In[45]:= First[Timing[2213*10^200000000]]          Out[45]= 5.11          In[3]:= First[Timing[ToExpression["2213*1*^200000000"]]]          Out[3]= 5.078      But the strange thing is that by using special `1*^` notation, the reported timing is almost zero while by clock it takes roughly the same time of `10^n`. Maybe `Timing` function doesn't take Mathematica built-in notations into account.!! **Updated 2** Yet The fastest method to beat native `*^10` adding zero method is by shifting, even though the improvement is very tiny.               In[16]:= First[Timing[1223*10^100000000]]          Out[16]= 2.625          In[17]:= First[Timing[BitShiftLeft[1223*5^100000000, 100000000]]]          Out[17]= 2.547


Why function is evaluated backward?

I have a simple function: `f[x0_,y0_]:= Module[{x=x0,y=y0},For[i=0,i<2,i++;Print[x],Print[x+y]];]` So when I call it:   `f[2,3]` I get: > 5   >  2   >  5   >  2 Why not: > 2   >  5   >  2   >  5 as expected? Also my indentation of - or + don't seem to format?


Converting string representation of boxes into explicit boxes

It is very easy and convenient to write textual labels as `Strings` in the WYSIWYG mode. For example, I define a short form describing a linear model: `"2D3O"`, which means "two descriptors of type D and tree descriptors of type O". Everything is good so far. Now I wish to add superscripts and use standard palette to add them. I get ![screenshot](http://i.stack.imgur.com/FoiFh.png) Looks nice. But at some point I have a lot of such labels and wish to apply some formatting to all of them at once. For example, I wish to make all the digits `Bold` and all the letters `Gray`. `FullForm` shows internal structure and I see the string representation of boxes: ![screenshot](http://i.stack.imgur.com/mp7Na.png) This is not a format easy to deal with. The tutorial explains how to convert ordinary boxes to its string representation using `ToString`. But what is the general way to convert string representation of boxes into explicit boxes?


Plotting Fourier spectrum versus frequency of a signal

I have looked around here, and i am sure this has been answered, but i don't understand it. The thing is, I have taken a introductory signal processing course, and we had to use Mathematica, and i had no previous experience in Mathematica, so this made a lot of things hard for me. Now i need to understand how to visually present the spectral content of a sampled signal. So i try something simple,               sampls = Table[Sin[n*(2 \[Pi])/1000*4], {n, 0, 2000}];      where we can assume that the sampling period is 1/1000s and we have a sinus with a frequency of 4 Hz. This signal is sampled for 2 seconds, meaning we get 8 periods of the signal. ![Plot of samples](http://i.stack.imgur.com/P5GBm.gif) Now my naive attempt is to do this (as i saw something like this in some example somewhere):                ListLinePlot[Abs[FourierDCT[sampls]], PlotRange -> {{0, 100}, {0, 30}}]      Now i end up with this: ![output from above statement](http://i.stack.imgur.com/yd0rb.gif) which i can't make any sense out of... What does it mean? My dream is to be able to plot frequency on the x-axis and amplitude on the y-axis, so that i could present the teacher with a nice narrow peak with height 1 right above 4 on such a plot. My mathematical knowledge is rather weak, i'm sorry to say, so be gentle with me and explain as concrete as possible. This is not primarily a mathematics course.


What is the fastest way to split a number into parts?

I have very large numbers (million digits). number = A*10^partlen + B As of now, I split the numbers by this way:                TotalLen = IntegerLength[a];       partlen = IntegerPart[TotalLen/2];      Print[First[Timing[A = IntegerPart[number/(10^partlen )]]]];      Print[First[Timing[B = Mod[number, 10^partlen ]]]]      And the timings for a 6 million digits number are:               4.703          0.36      Converting the number to strings and rebuilding the parts is even slower than this. Is there any faster way?


Appearance in Checkbox does not work

I'm experiencing strange behavior in `Checkbox` with `Appearance`:               Table[Checkbox[Appearance -> a], {a, {Tiny, Small, Medium, Large}}]      (Copied from the help file) doesn't give me any difference in size. Screenshot: ![checkbox sizes screenshot](http://i.stack.imgur.com/77k73.png) `CheckboxBar` has the same behavior. _Mathematica_ seems to ignore the `Appearance` setting. I'm running mma 8.0.4.0 on Ubuntu 12.10 (64-bit). **Question: Is this a bug or just a non-existing but nonetheless documented feature?**


Partial differential equation: unexpected result from changing boundary region size

I am trying to solve a PDE for heat diffusion, but I have a problem with the boundary region. When I change the boundary region size, the estimation of temperature increases even when no other parameter is changed. Here is my code. Boundary region [-10, 10] in x and y               eq1 = Derivative[0, 0, 1][f][x, y, t] -         0.14*(Derivative[2, 0, 0][f][x, y, t] +            Derivative[0, 2, 0][f][x, y, t]) == Exp[-(x^2/(2^2) + y^2/(2^2))]          ic = {f[x, y, 0] == 24};     bc = {f[-10, y, t] == 24, f[10, y, t] == 24, f[x, -10, t] == 24,         f[x, 10, t] == 24};     sol1 = NDSolve[{eq1, ic, bc},        f, {x, -10, 10}, {y, -10, 10}, {t, 0, 1200}]      Boundary region [-40,40] in x and y               Plot[Evaluate[{f[0, 0, t] /. sol1[[1]], u[0, 0, t] /. sol2[[1]]}], {t,        0, 1200}, PlotRange -> All, Frame -> True]          Plot[Evaluate[{f[x, 0, 1] /. sol1[[1]],         u[x, 0, 1] /. sol2[[1]]}], {x, -10, 10}, PlotRange -> All,       Frame -> True]      ![Mathematica graphics](http://i.stack.imgur.com/L8bSR.png) Time history of heat in the interior at (0,0) ![Mathematica graphics](http://i.stack.imgur.com/XVDtQ.png) Spatial distribution of heat at t = 1 and y = 0 for x in [-10, 10]


Sum over binary digits of integer

This might seem like a simple enough question but Mathematica seems to simplify inadequately here:   How would you sum over the digits of an arbitrary binary number?   I already tried this:               Total[IntegerDigits[j, 2]]      which immediately simplifies to an incorrect $j+2$   In fact all               Total[IntegerDigits[j, n]]      simplify to $j+n$   After that, I tried this:               Sum[i, {i, IntegerDigits[j, 2]}]      which simplifies to another incorrect               1/2 IntegerDigits[j, 2] (1 + IntegerDigits[j, 2])      Is there any way, I can prevent these erroreous simplifications?   I need a solution that will work if I use it in another sum which, I ultimately hope, simplifies to something correct. If you want to see what I need this for, it's for another now solved problem on Mathematics StackExchange.


How to color separate a colored-in-pencil drawing?

I'd like to pick out just the "pencil" color in some drawings done by a young member of the household (he'd like to print out copies of these pictures and distribute them to his class mates on the last day of school, but has already colored them). I tried `Binarize`, which allows me to craft a color selection function, picking levels of each of Red, Green, or Blue. For example:               Clear[ girl, boy ] ;     boy = Import[ "http://imgur.com/mRRhOgo.jpg" ]     girl = Import[ "http://imgur.com/Q5ReXSX.jpg" ]     Binarize[ girl, #[[1]] > 0.8 & ]     Binarize[ girl, #[[2]] > 0.8 & ]     Binarize[ girl, #[[3]] > 0.8 & ]      The last works fairly well, but happens to leave a really dark section by the red belt. I figure it should be possible to code a color selection function that picks only things in the range of the gray pencil colored text, but I'd have to figure out what that color is first, and am not sure of a good approach to do that (other than sampling specific pixel values). I'd imagine this problem could be solved by sorting the image points by color and picking the dominant ones. Then find the "gray colors" or ranges of those grays, and finally coding an image function selection for binarize to pick that color or range of colors. However, it's not clear to me exactly how to go about doing that. EDIT: It looks like http://mathematica.stackexchange.com/a/5415/10 provides reasonable looking instructions on how to pick out just one color, so the problem may be reduced to just finding that "pencil" color. I've tried the Manipulate sliders in some of the other answers for that question, but find them very slow to update ( especially that of http://mathematica.stackexchange.com/a/5407/10 ) EDIT2: I see http://mathematica.stackexchange.com/a/4795/10 provides a locator based way of picking a color, which can probably be used to solve the find the "pencil" color part of the problem (although I'm still not sure how various darknesses of the pencil lines would be dealt with).


A debug utility to print or extract intermediate data from a program

Is there a way to print variables using their names, or to extract the corresponding information for later analysis ?


Position of axes labels

I have a 2D parametric plot like the following:               ParametricPlot[       {Sin[t], Cos[t]}, {t, 0, 2 \[Pi]},       Frame -> True, AxesLabel -> {x, y}, AxesStyle -> Arrowheads[0.04], PlotRangePadding -> 0.2     ]      ![wrong labels](http://i.stack.imgur.com/AYko2.jpg) But I would like the axes labels `x, y` to be positioned besides the arrowheads (i.e. `y` left of the vertical arrowhead and `x` just below the horizontal one). Since I can't use the frame as a replacement for the axes (as the axes are in the middle, not at the edge), I believe I cannot use the approach suggested in this question. How could I achieve this?


Solving Coulomb Integral

I am trying to solve so-called Coulomb Integral of two Gaussians:               Integrate[Exp[(-b1 (-c1 + x1)^2 - b2 (-c2 + x2)^2)/Sqrt[(x1 - x2)^2]], {x1, -Infinity,      Infinity}, {x2, -Infinity, Infinity}],      where $b1$ and $b2$ must be positive parameters, and $c1$ and $c2$ any real parameters. The denominator seems to be very nasty so I could not solve the integral. Any ideas how to tackle this problem?


Dashed mesh behind 3D object

I am trying to create a simple, almost transparent 3D sphere with a mesh that is made of solid lines if they are on the front surface (i.e. if they are directly visible) and of dashed lines if those lines happen to be in the back of the sphere (i.e. not directly visible). I cannot think of an easy way of doing it without involving an explicit calculation of what part of the sphere is directly visible, given the viewpoint, and what part is not... Any ideas?


Evaluating InterpolatingFunction returned by NDSolve is very slow starting from some arguments

I use this code to solve a PDE:               a = 20;     F[x_, t_] = f[x, t] /. First@NDSolve[{D[f[x, t], x, x] == I D[f[x, t], t],          f[-a, t] == 0,          f[a, t] == 0,          f[x, 0] == Sin[Pi/a (x - a)]},          f[x, t], {x, -a, a}, {t, 0, 700}, MaxStepSize -> 0.005 a]      It gives the correct solution for all `t` until about 650. But if I take `t` higher, see what happens:               AbsoluteTiming[Table[F[x, 650], {x, -a, a}];]     AbsoluteTiming[Table[F[x, 695.1], {x, -a, a}];]      > {0.000925, Null} > > {2.382157, Null} Threshold for `t` appears to be about $666.6$. It appears to be orders of magnitude slower at evaluating the interpolating function. What's the reason for this? **EDIT** : Using `NDSolve` option `InterpolationOrder -> All` works around this.


How to keep some of the results of the NestList

I'm using some iterative arithmetics to calculate wave propagation with the help of NestList. I have to use a small step size for iteration to guarantee the accuracy, which lead to too much data (e.g, 10^6 points) for further plotting, and the results consumes too much memories. Is there any clever way to cope with it? I didn't intend to use loops. This is a simplified example:               NestList[Sin, 1, 10^6]      One of my idea is to use `Sow` and `Reap`. But I've no idea to integrate them with `NestList` or `Nest` Any idea???


String pattern search and replacement -- it works, but produces error messages only the first time it is called

I defined a function in _Mathematica_ to process a pre-generated string. More specifically, I'd like to process some parts of C codes generated from MMA. Basically what my function does is to expand the `pow` function in C, so it involves finding a string pattern and replacing it. I know using MMA is not the best way to solve this problem, but unfortunately the language I'm most familiar with is MMA...Anyway, here's my function:               ExpandPowInCode[code_] :=        StringReplace[code, Shortest["pow(" ~~ x__ ~~ "," ~~ y__ ~~ ")"] ->          If[StringMatchQ[x, ___ ~~ "+" ~~ __] ||             StringMatchQ[x, ___ ~~ "-" ~~ __],            Nest[StringJoin["(" <> ToString[x] <> ")", "*" ~~ #] &,              "(" <> ToString[x] <> ")", ToExpression[y, InputForm] - 1],            Nest[StringJoin[x, "*" ~~ #] &, x, ToExpression[y, InputForm] - 1]]]      It works as I expected, namely expanding , for example, `"pow(x,2)"` into `"x*x"`. The `If` condition will help when dealing with plus/minus sign in the first argument of `pow`. For example,               ExpandPowInCode["pow(a x+b,3)"]      > `"(a x+b)*(a x+b)*(a x+b)"` However, at the first time I executed `ExpandPowInCode`, I always got the following error messages: > `StringMatchQ::strse: String or list of strings expected at position 1 in > StringMatchQ[x,___~~+~~__]. >>` > > `StringMatchQ::strse: String or list of strings expected at position 1 in > StringMatchQ[x,___~~-~~__]. >>` Although `ExpandPowInCode` still gave me the correct result, the appearance of error messages was really annoying...Moreover, when I executed the function again later, the error messages no longer appeared as if everything were correct. Has anyone ever met this odd situation?


Fixed color scale in multiple density plots with Fixed PlotLegends scale

From the great answer of Mr. Wizard, I would like to learn how to implement the associated PlotLegends scaled too. Here is the simplest example with PlotLegends, which does not look to be scaled:               data = {{{2, 4, 5, 4}, {3, 3, 7, 2}, {7, 2, 6, 5}, {7, 4, 8, 2}},              {{2, 1, 7, 9}, {3, 2, 1, 8}, {3, 3, 9, 7}, {0, 9, 7, 9}},              {{2, 2, 9, 0}, {5, 7, 0, 9}, {6, 9, 1, 9}, {5, 3, 8, 8}}};          Table[ListDensityPlot[Rescale[data[[i]], {0, 9}],      ColorFunctionScaling -> False, Mesh -> All,      ColorFunction -> "TemperatureMap", PlotLegends -> Automatic], {i, 1, 4}]      The first legend shows a different scale from the other three.


How do I choose only one branch of ArcTan?

I have a problem concerning `ArcTan` drawing a graph using `ListPlot`. I import a table of data:               a = Import["D:\2_b=10a.txt", "Table"];      Then I write:               ListPlot[Table[{i*0.005 Pi, -ArcTan[(a[[i]][[1]] -         a[[i - 1]][[1]]), (a[[i]][[2]] - a[[i - 1]][[2]])]}, {i, 2, 401, 1}]], PlotRange -> {{0, Pi}, {-4, 4}}]      The returned graph looks like ![this](http://i.imgur.com/lBZ0jLt.png) I know from the nature of my calculations that the function must be continuous on the interval $[0,Pi]$, but at $3Pi/4$ the `ArcTan` function goes to another branch, since `ArcTan[x,y]` chooses a quadrant. How could I possibly try to move the bottom part of the plot up by Pi, so the function is smooth and continuous? I tried defining a function               myArcTan[x_] := Piecewise[{{ArcTan[x] + Pi, x < 0}, {ArcTan[x], x > 0}}];      but it doesn't work. Thank you very much.


choosing the fastest way of finding position

I have this list `{1,7,8,10}` for instance. and a second list which is always smaller or equal to the first one say `{10,7}`. How can I find the position of the elements of the second list in the first list: the answer to above example is `{2,4}`. but I want the answer in this form: `{0,1,0,1}` which implicitly gives `{2,4}`.


Equating coefficients in a non-power-series equation

How can I use _Mathematica_ to equate coefficients in a non-power-series equation? For example, I would like to take an equation like the following: $$af_x+\frac{b}{2}f_xf_y+chf_x=f_x+e^af_x+3f_xf_y+2bhf_x$$ and produce the following system: $$a=1+e^a$$ $$\frac{b}{2}=3$$ $$c=2b$$ **EDIT:** This is a rather small example. If possible, I would prefer a solution that requires minimal human inspection of the original equation. The equations I will be working with will have many, perhaps hundreds of partial derivative terms, and it would be unfeasible to do things like individually pick them out. Ideally, I would like to specify only the unknowns I am interested in (in this case, {a, b, c}) and let _Mathematica_ take it from there.


How to simulate the response of a linear parametric varying system in Mathematica?

Consider the following system \begin{align} \dot{x}(t)&=\sum_{i=1}^{2}\rho_{i}(x(t))\left[A_{i}x(t)+B_{i}u(t)\right]\\\ y(t)&=Cx(t) \end{align} with:               a1 = {{-3, 2}, {-0.25, 1}}     a2 = {{-1.9, -0.4}, {-2.24, -4.7}}          b1 = {{0.25}, {1}}     b2 = {{-2.5}, {1}}          c = {{1, 0.5}, {0, 1}}      where $$\rho_1(x_1(t))=\frac{1-\tanh(x_1(t))}{2},\quad\rho_2(x_1(t))=1-\rho_1(x_1(t))$$ How do I build the state-space LPV system? The response, for example, to a sinusoidal input? I want to translate this code from MATLAB to _Mathematica_               A(:,:,1)=[-3 2; -0.25 1];     A(:,:,2)=[-1.9 -0.4 ; -2.24 -4.7];     B(:,:,1)=[0.25;1] ; B(:,:,2)=[-0.25; 1];     C=[1 0.05; 0 1];%     xx=[0.1; 0]; %initial conditions     mus(1,:)=[0.5 0.5 1]; %initial rhos          %%simulation loop          for k=1:tmax/Te              %% System             t(k+1)=t(k)+Te; %%time vector;              mus(1)=(1-tanh(xx(1,k)))/10  ;  % weigting functions         mus(2)=1-mus(1);              u(k+1)=10*sin(t(k)); %%input         Aa=mus(1)*A(:,:,1)+mus(2)*A(:,:,2);         Ba=mus(1)*B(:,:,1)+mus(2)*B(:,:,2);              %%Euler to solve the ODES         xx(:,k+1)=xx(:,k)+Te*(Aa*xx(:,k)+Ba*u(k) );         y(:,k+1)=C*xx(:,k+1);  %output     end          plot(t,mus,t,mus(:,1)+mus(:,2) );     plot(t,y);


Efficiently determining if a morphological component overlaps a polygon with vertices at real number coordinates

I have a list of morphological components $m$, a set of vertices for a polytope $P$ (at real number coordinates), and I'd like to be able to calculate a list of morphological components $m'$ that anywhere overlap the area of $P$. I can do this by approximating each pixel as a point, and calculating a winding number for these points with respect to $P$ to determine if they fall within the polygon's area. However, this is hardly an efficient strategy, and it's not as exact as I would like. My hope is to have a scheme to detect if the polygon crosses _any_ square bright pixel region. Is there a clever way to do this that works very quickly?


How to tell mathematica not to resolve stiffness issues

Very often I solve partial differential equations that are nonlinear and could be up to 4th order. In these cases, it is usual for the solution determined by `NDSolve` to be stiff during a later stage. What I suspect `NDSolve` does in this case is to resolve the stiffness until the error/local accuracy is very poor. That is when it quits the problem and gives you an Interpolating function polynomial. Whilst using the BDF method to MaxOrder of 1 for instance, is there someway to tell Mathematica to quit as soon as stiffness is encountered in the solution so that I save time? I don't want to resolve the stiff portion and just stop my solution just as it gets stiff. The below example looks like a mess in plain text but it copies fine. It gets stiff at t=4806. However, is lots of problems, NDSolve lingers at the time at which stiffness is achieved to try and resolve the features that I would like to circumvent completely. I will obv. look into the stiffness switching stuff again. ## Example               {xMin,xMax}={-4\[Pi]/0.0677,4\[Pi]/0.0677};          k=0.0677/4;          TMax=5000;          uSolpbc[t_,x_]=u[t,x]/.NDSolve[{\!\(     \*SubscriptBox[\(\[PartialD]\), \(t\)]\(u[t, x]\)\)==-100\!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\(u[t, x]\), \(3\)]\      \*SubscriptBox[\(\[PartialD]\), \(x, x, x\)]u[t, x])\)\)+1/3 \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\(u[t, x]\), \(3\)]\      \*SubscriptBox[\(\[PartialD]\), \(x\)]u[t, x])\)\)-5 \!\(     \*SubscriptBox[\(\[PartialD]\), \(x\)]\((     \*SuperscriptBox[\((     \*FractionBox[\(u[t, x]\), \(1 + u[t, x]\)])\), \(2\)]\      \*SubscriptBox[\(\[PartialD]\), \(x\)]u[t, x])\)\),u[0,x]==1-0.1 Cos[k*x],     u[t,xMin]== u[t,xMax],     Derivative[0,1]u[t,xMin]==Derivative[0,1]u[t,xMax],     Derivative[0,2]u[t,xMin]==Derivative[0,2]u[t,xMax],     Derivative[0,3]u[t,xMin]==Derivative[0,3]u[t,xMax]},     u,     {t,0,TMax},     {x,xMin,xMax},     MaxStepFraction->1/150][[1]]


Fitting parameters of user defined function returning discrete values

So, I'm fairly new to Mathematica (apologies in advance for the noobiness), and I'm having some problems regarding fitting the parameters of a user defined function to data. I'll give a representative toy example of what I'm trying to accomplish. Imagine that I have data that is comprised of two lists:               TestData = {       {1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15},       {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}     };      And I have a model/function that itself produces discrete data such as this. This function would be something like:               TestFunction[A_, B_] :=          Module[{results = {}, vec1 = {}, vec2 = {}},              For[i = 1, i < 18, i++, Do;                [vec1 = Append[vec1, (A - i)];                 vec2 = Append[vec2, (B + i)]]];             results = Append[results, vec1];             results = Append[results, vec2];             results]      Now, I want to find the parameters A and B that give the best approximation to TestData (i.e., such as the distance between TestData and the results of the function would be minimized). I tried looking into the FindFit and NonlinearModelFit functions, but these would seem to be more suited for continuous functions(?), so I'm not sure how to use it with a function that returns specific and discrete values. How would you go about solving this question? Thank you very much in advance.


How to print prime numbers

I want to know how can I print out a list of prime numbers. Should I use `For`, `Do`, `If`, maybe `Mod`, but If I can - no prime. How should I approach this problem ?


Filtering and Replacing outliers

I have a set of data that measurements of temperature vs time (date). It is easy to realize when the sensor went wrong as one might see a blip on the data. How to teach to Mathematica to: 1) Detect the "Blip" 2) Delete this Blip 3) Replace the corrupted point for one derived as the mean of the previous data (before the corrupted one) and the one after (after the corrupted one). Thanks in advance !!! I have tried to setup a test in which each pair of data were compared and if the difference between them was greater than 3 C (or 5C depending how rigorous you want to be). But my reasoning did not work properly. Thanks in Advance Ed The dataset is:               l = {{"2013-11-20 23:00:00", 23.52}, {"2013-11-21 00:00:00",        23.55}, {"2013-11-21 01:00:00", 23.62}, {"2013-11-21 02:00:00",        23.61}, {"2013-11-21 03:00:00", 23.53}, {"2013-11-21 04:00:00",        23.45}, {"2013-11-21 05:00:00", 23.52}, {"2013-11-21 06:00:00",        23.4}, {"2013-11-21 07:00:00", 24.02}, {"2013-11-21 08:00:00",        26.7}, {"2013-11-21 09:00:00", 27.54}, {"2013-11-21 10:00:00",        29.67}, {"2013-11-21 11:00:00", 28.3}, {"2013-11-21 12:00:00",        17.94}, {"2013-11-21 13:00:00", 27.42}, {"2013-11-21 14:00:00",        25.82}, {"2013-11-21 15:00:00", 24.61}, {"2013-11-21 16:00:00",        23.91}, {"2013-11-21 17:00:00", 24.58}, {"2013-11-21 18:00:00",        24.31}, {"2013-11-21 19:00:00", 23.18}, {"2013-11-21 20:00:00",        28.99}, {"2013-11-21 21:00:00", 22.56}, {"2013-11-21 22:00:00",        22.01}}      ![TempPlot](http://i.stack.imgur.com/Xy3mJ.jpg)


How to reconstruct a missing data point

In the output of a large computer simulation(thousands of cpus for 3 days), I found that one data point is missing in the result. Is it possible to reconstruct the missing value using the remaining data? Assumptions: The dynamics in the data is generally smooth and there is no shape feature in it. Here is the data:               data={-0.0949456,-0.2232,-0.15012,0.0364052,0.0841621,-0.0920731,-0.273141,-0.183935,0.0656169,0.140269,-0.0843562,-0.332979,-0.228146,0.0969235,0.208076,-0.0696226,-0.402307,-0.284266,0.128555,0.287427,-0.0454046,-0.479687,-0.353367,0.158121,0.377113,-0.00921489,-0.56245,-0.43569,0.182807,0.474626,0.0409945,-0.646659,-0.530218,0.199767,0.576109,0.106226,-0.727344,-0.634338,0.206674,0.676612,0.185864,-0.799108,-0.743778,0.202287,0.770614,0.277269,-0.856969,-0.852921,0.18688,0.85286,0.,-0.897303,-0.955487,0.162245,0.919149,0.475145,-0.91851,-1.04548,0.131507,0.967006,0.568474,-0.921269,-1.11803,0.0983087,0.995824,0.649178,-0.908188,-1.17004,0.0660878,1.00669,0.711966,-0.883046,-1.20025,0.0374795,1.00158,0.753415,-0.849936,-1.20902,0.0140558,0.983158,0.772116,-0.8123,-1.19776,-0.00394007,0.953394,0.768557,-0.772323,-1.16867,-0.0170188,0.914086,0.744676,-0.731382,-1.12393,-0.0260316,0.866382,0.703393,-0.689571,-1.06621,-0.0322879,0.811196,0.648481,-0.646799,-0.997935,-0.0368642,0.74929,0.583615,-0.602475,-0.921481,-0.0407482,0.681664,0.513284,-0.555671,-0.839684,-0.0446284,0.609182,0.440653,-0.507031,-0.755086,-0.0489018,0.533683,0.369238,-0.456793,-0.669996,-0.0537497,0.457136,0.301312,-0.405981,-0.586799,-0.0589172,0.381381,0.238713,-0.355861,-0.507526,-0.064281,0.308536,0.182517,-0.30782,-0.433796,-0.0694734,0.240373,0.133182,-0.263169,-0.366831,-0.0741541,0.178336,0.0906948,-0.222976,-0.30744,-0.0780402,0.123434,0.0547048,-0.187986,-0.25604,-0.0809698,0.0762321,0.0246802,-0.158568,-0.212644,-0.0828802,0.0368173,0.};      Also from other output information, I can determined that the problem data is at the index 51, which is set to 0 in the above. So is it possible to reconstruct that value? * * * Here is my try: I use the wavelet transform to identify the abrupt changes in the data, and manually adjust the data value, until I get a relative smooth wavelet transform.               Manipulate[      data1 = data;      data1[[51]] = data[[51]] + Abs[Mean[{data[[50]], data[[52]]}]]*x;      cwd = ContinuousWaveletTransform[data1,         GaborWavelet[10], {Automatic, 12}];      values = Abs[cwd[All, "Values"]];      ListDensityPlot[values, ColorFunction -> "TemperatureMap",        PlotRange -> {All, {0, 50}, {0, 0.1 Max[values]}},        ClippingStyle -> Automatic, InterpolationOrder -> 0]      ,      {x, -10, 30, 1}      ]      ![enter image description here](http://i.stack.imgur.com/hKSUz.gif) Form above I determined by eye that when x=17 the wavelet is smoothest. So the missing data I get is 0.377765. And here is a plot of the data and the wavelet transform after the fix ![enter image description here](http://i.stack.imgur.com/cegjj.png) ![enter image description here](http://i.stack.imgur.com/TVe3b.png) **Question** :   1. What are the general ways of reconstruct missing data?   2. Are there other methods to reconstruct the missing data, without looking by eye?


Navier–Stokes equations

how write Stokes equation in mathematica? the Stokes equation is in in this link http://en.wikipedia.org/wiki/Navier- Stokes_Equations


Release the web camera after using CurrentImage[]

`CurrentImage[]` will capture an image from the webcam. It is even possible to create a live video in the notebook using               Dynamic@CurrentImage[]      After using this function even a single time, Mathematica will not switch off or release the webcam any more, making it impossible to use the webcam from other programs on some systems. How can I switch off / release the webcam from Mathematica, without quitting Mathematica completely?


Total weight of a graph

I need to find the total weight of an `WeightedAdjacencyGraph`. I have a graph in that form               a = WeightedAdjacencyGraph[{...},{...},{...}....etc]      How can I find its total weight?


Rearrange graph

I have to rearrange graph described by               j = {1 -> 2, 2 -> 3, 3 -> 1};      appling some function to all vertices on the right so rearrange[j] output should give me               {1 -> f[2], 2 -> f[3], 3 -> f[1]}      I guess I can use ReplaceAll, but can't guess how.


Extra factors appear when evaluating Euler integrals

**Note: this is fixed in version 9.** * * * When I perform the double integral in _Mathematica_ ,               Integrate[(x (1 - x))^z (y (1 - y))^z, {x, 0, 1}, {y, 0, 1}]      which should give $$B(z+1,z+1)^2 = \frac{\Gamma(z+1)^4}{\Gamma\left(2(z+1)\right)^2}$$ where $B(x,y)$ is the Beta function and $\Gamma(z)$ is the Gamma function because the integral is a product of two Beta functions, I instead get this ratio of Gamma functions _times the extra factor $(-1)^{2z}$_. What is going on here? To make matters stranger, if I do the integral instead using two nested calls to Integrate (one to integrate out $x$ and one to integrate out $y$), I get the ratio of Gamma functions without the incorrect extra factor.


What does "suitable for symbolic manipulation" in the documentation mean?

This question is related to this other one I posted on Stack Overflow some time ago. There, in a beautiful answer, acl (with some unhumble editing done by me) showed that the derivative of `IntegerPart` is calculated numerically by a centered difference method of eighth order. If you read the help for `IntegerPart[]` you'll find: > Mathematical function, suitable for both symbolic and numerical > manipulation. At that time I assumed it was just a documentation (or program) bug. I revisited the problem today because I needed to solve an equation that can be tracked down to something like:               Reduce[IntegerPart@x == x, x, Reals]     (*     -> Reduce::nsmet: This system cannot be solved with the methods available to Reduce. >>     *)      So again, Mma's failure to "symbolically manipulate" the `IntegerPart[]` function is bothering me. And this time, the derivative calculation is not the issue. All these functions `{IntegerPart, FractionalPart, Ceiling, Floor, Round, PrimePi}` share the > Mathematical function, suitable for both symbolic and numerical > manipulation. legend in their help reference. Look at their derivatives:               f = {IntegerPart, FractionalPart, Ceiling, Floor, Round, PrimePi};     GraphicsGrid[      Partition[        Plot[{#[u], D[#[x], x] /. x -> u}, {u, -1, 3},             PlotLabel -> Style[Framed[Hyperlink[#, "paclet:ref/" <> #] &@ToString@#], 16,                               Blue, Background -> Lighter[Yellow]]] & /@ f,        2],       Frame -> All]      > ![Mathematica graphics](http://i.stack.imgur.com/OpUIg.png) Moreover, the help file for `NextPrime[]` doesn't state anything about its symbolic manipulation suitability, and the help for `HeavisideTheta[]` says: > HeavisideTheta can be used in integrals, integral transforms and > differential equations. and its derivative is evaluated as `DiracDelta[]`. When you plot these functions you get: > ![Mathematica graphics](http://i.stack.imgur.com/yQMuy.png) So it seems that from the whole set, only `HeavisideTheta` is treated symbolically. However, when you try:               Reduce[HeavisideTheta@x == 1, x, Reals]     (*     -> Reduce::nsmet: This system cannot be solved with the methods available to Reduce. >>     *)      So the "symbolical manipulation" is not there (or so it looks like). So the question is: **What does it mean for a _Mathematica_ function to be "suitable for symbolic manipulation"?**


Strange Behavior when making Equal Listable in Pick

While trying to make this problem more efficient I tried different methods and dabbled with making `Greater` and `Equal` `Listable`. To my surprise, while `Greater` worked as expected, `Equal` on the other hand showed a strange behavior. Let's dig deeper: First let's look at `Greater`               Pick[#, DivisorSigma[1, #] > 2 #] &@Range[6]      Gives the error:               Pick::incomp: Expressions {1,2,3,4,5,6} and {1,3,4,7,6,12}>{2,4,6,8,10,12} have incompatible      shapes. >>      Now we make `Greater` `Listable`               SetAttributes[Greater, Listable]      And we can now evaluate the above command successfully               Pick[#, DivisorSigma[1, #] > 2 #] &@Range[20]      > {12, 18, 20} Okay, let's move on to `Equal`               Pick[#, DivisorSigma[1, #] == 2 #] &@Range[8]      > Sequence[] We now make `Equal` `Listable`               SetAttributes[Equal, Listable]     Attributes[Equal]      > {Listable, Protected} Now let's try again:               Pick[#, DivisorSigma[1, #] == 2 #] &@Range[8]      > Sequence[] Hmmm, what's going on here? Well, let's explicitly provide the list and see what happens:               Pick[{1, 2, 3, 4, 5, 6, 7, 8},       DivisorSigma[1, {1, 2, 3, 4, 5, 6, 7, 8}] == 2 {1, 2, 3, 4, 5, 6, 7, 8}]      > {6} Interesting, this works! okay now let's textually substitute using `With`, this should technically be the same thing right?               With[{p = Range[8]}, Pick[p, DivisorSigma[1, p] == 2*p]]      > Sequence[] I guess not. Finally, let's look at `Trace`. I'll shorten the input list here. First with explicit input of list:               Pick[{4, 5, 6}, DivisorSigma[1, {4, 5, 6}] == 2 {4, 5, 6}] // Trace      ![Mathematica graphics](http://i.stack.imgur.com/lKQal.png)               Pick[Range[4, 6], DivisorSigma[1, Range[4, 6]] == 2 Range[4, 6]] // Trace      ![Mathematica graphics](http://i.stack.imgur.com/FlHwM.png) We see that only in the explicit case does `Equal` act `Listable` What is going on here? Sorry about the tiny images.


How to get complete Documentation Center graph of guide pages?

On the very last image below you can see a typical path of walking through Documentation Center guide pages. **What is the best way to get the graph data and visualize the whole structure of these connections starting from the main table of contents page?** An obvious thing to do is to look for example into directory:               SetDirectory["C:\\Program Files\\Wolfram\\Research                   \\Mathematica\\8.0\\Documentation\\English\\System\\Guides"]          FileNames[] // Column      ![enter image description here](http://i.stack.imgur.com/FvyYQ.png) But I am not sure what is the next most efficient way to analyze the connections. **A walk through guide pages** ![enter image description here](http://i.stack.imgur.com/FhhTh.png) **\------------ UPDATE: image from @Leoind data ------------**               style = {VertexStyle -> White, VertexShapeFunction -> "Point",        EdgeStyle -> Directive[Opacity[.3], Hue[.15, .5, .8]],        Background -> Black, EdgeShapeFunction -> (Line[#1] &),        ImageSize -> 500};          gr = Graph[Union[Sort /@ data], style]      ![enter image description here](http://i.stack.imgur.com/UG4un.png) The origin of self-loops was explained by @R.M in his comment. Almost all guide pages have their own URL at the top navigation bar. Here is the final graph with removed self-loops:               am = AdjacencyMatrix[gr];(am[[#, #]] = 0) & /@ Range[Length[am]];     AdjacencyGraph[am, style]      ![enter image description here](http://i.stack.imgur.com/3nA8O.png)


Evaluating function only when its optional argument is numeric

I want to have the argument 'a' for myf2 in form of optional argument, but at the same time I need to evaluate the function only if 'a' is Numeric, see also my previous question.               Options[myf2] = {"a" -> 1};     myf2[b_?NumericQ, opts : OptionsPattern[]] := Module[{y, x, a},        a = OptionValue["a"];        If[NumericQ[a], First[y /.NDSolve[{a y'[x] == b y[x] Cos[x + y[x]], y[0] == 1},             y, {x, 0, 30}]][10]]        ];          datamyf2 = {#, myf2[1, #] + 0.01 RandomReal[]}&/@Range[0.5, 1.5,0.1]          model = NonlinearModelFit[datamyf2, myf2[b, "a" -> a], b, a]      When I tried to add the NumericQ test for 'a' in myf2, the problem is that it returns Null upon evaluating with symbol 'y' {myf2[1, "a" -> y]}, instead of leaving it unevaluated at all (as for the case when 'a' was specified as regular argument with a_?NumericQ) How can I than specify that it should have numeric value for 'a' in the option? Thanks!


Artistic image vectorization

The question is **how can we use Mathematica to create vectorized versions of low-resolution images?** The goal is to get an image suitable for quality printing at any resolution. Since "true" vectorization performed by various specialized software is a tough problem, I suggest to consider "artistic" approaches, which produce inexact, but beautiful version of the original. Colored implementations are highly appreciated.


Evaluator option for Mathematica Scripts

I have mathematica with many additional kernels besides Local ( e.g., core1, core2, core3, core4 ... ) added through Kernel Configuration Options. I have been running multiple copies of a simulation (mycalculation.nb) in these different cores. The kernel for each notebook was set using this function:               SetOptions[EvaluationNotebook[], Evaluator -> "corei"];      where corei is core1, core 2, .. etc. So all kernels run in parallel without interfering with each other. Now I am trying to automate this and use Mathematica Scripts to run each kernel with my code converted into Input Form (mycalculation.m). When I do that, the above line gives this error message since the "Evaluator" seems to be defined for front end and notebook interface only:               FrontEndObject::notavail: A front end is not available; certain operations require a front end.      Note that my code in "mathematica scripts" form works fine when I skip the "Evaluator" definition. Is there a corresponding option that I can put in the file (mycalculation.m) or in the command line, which is;                MathKernel -noprompt -run "<<mycalculation.m"      so that I can tell MathKernel to execute the rest of the code not in the local kernel but in some other kernel. I could not find it myself.


File output and race conditions

Is it possible to know when Mathematica is done writing a file? I'm looking to automate something and I'm wanting to have Mathematica put it in a file using `Put[]`, and maybe also `Export[]`. I need to know that the file is complete before dealing with it outside Mathematica, but I don't want to have to exit Mathematica first. How can I be **_sure_** that Mathematica is done writing the file? Any solution is on the table, from waiting for Mathematica to reprompt, to relying on a metafile. I'd like to avoid writing additional data to the file if at all possible, though.


Using FindInstance to Prove No Solutions Exist

For a small amount of background, I am currently working on an undergraduate research project in Combinatorial Geometry and I'm working on a case analysis for embedding spherical simplicial 2-complexes in $\mathbb{S}^2$ and looking at their properties as they relate to tuples of spheres in arbitrary sphere packings. If that made no sense, no problem. I want to show that there does _not_ exist a solution to the equation:               a + b + c + d + e + f + g + h + i == 16 π - 33 ArcCos[1/3] - ω      where               ω = π - 4 ArcCos[1/3] +      2 ArcCos[(2 (1/2 + 1/8 (-1 - 3 Cos[4 ArcCos[1/3]])))/Sqrt[     3 (1 - 1/16 (1 + 3 Cos[4 ArcCos[1/3]])^2)]]      With some bounds on $a,b,c,d,e,f,g,h,i$. I have tried inputting this into Mathematica as follows (with $\omega$ defined in a previous command)               FindInstance[         a + b + c + d + e + f + g + h + i == 16 π - 33 ArcCos[1/3] - ω &&          ArcCos[1/3] < a < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < b < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < c < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < d < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < e < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < f < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < g < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < h < 2 π - ArcCos[1/3] &&          ArcCos[1/3] < i < 2 π - ArcCos[1/3],          {a, b, c, d, e, f, g, h, i}, Reals     ]      It returns an input of `{}` which means that _Mathematica_ couldn't find any solutions. This is a very good thing for me, but how can I formalize the fact that no such solutions exists other than "Mathematica couldn't find any solutions using the `FindInstance` command"?


How to make a list/matrix out of an expression?

I would like to make a matrix out out of the following expression: $$ (\Omega^2 (2 d\theta^2 + d\phi^2 - d\phi^2 \cos(2 \theta) \coth(\chi)^2) + (2 d\Omega^2 + (2 d\theta^2 + d\phi^2 - 2 d\chi^2) \Omega^2) \textrm{csch}(\chi)^2)/(2 \Omega^2) $$ so that I get for the 11-components all terms that belong to $d\Omega^2$, for the 22-component all the terms belonging to $d\chi^2$, etc. (As there are no 'cross-terms', the matrix in this case should be diagonal). How do I go about this in _Mathematica_? * * * Code for copying:               (Ω^2 (2 dθ^2 + dϕ^2 - dϕ^2 Cos[2 θ] Coth[χ]^2) +      (2 dΩ^2 + (2 dθ^2 + dϕ^2 - 2 dχ^2) Ω^2) Csch[χ]^2)/(2 Ω^2)