title: How to linearize an expression automatically?

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


title: Solving an algebraic equation with one or more constraints?

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


title: How can I make a plot of the Higgs potential?

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


title: Extract memoized results in the form of a rule

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


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

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


title: Matrix algebra vs. PrincipalComponents and Varimax/Oblimin

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


title: How to reset the $ModuleNumber?

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


title: Putting large amounts of data inside a self-contained Manipulate

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


title: Application on systems of equations

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


title: GridGraph layout with added edges

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


title: Command Completion

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


title: Hex Representation in Mathematica and Python

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


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


title: FindFit giving weird values on a logistic equation

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


title: Is the MaximalBy function still used

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


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

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


title: Introducing new variables implicitly

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


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

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


title: Simplify symbolic expression in terms of constants

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


title: Reducing Output length by introducing new variables

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


title: Replace expressions with symbols

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


title: Rewriting one expression using a variable representing another expression

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


title: Breaking up long equations in TeXForm

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


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

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


title: Awkward Two-Point Boundary Value ODE

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


title: Replacing one element of list

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


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

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


title: How to paint part of DateListPlot?

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


title: Constructing election cartograms?

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


title: Table not working with Plot

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


title: Rules governing Plot line generation

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


title: Bit Operations -- Force Binary Bit Representation

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


title: Determine if solution to linear system exists

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


title: Create a table with inline conditions

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


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

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


title: Import values from tab separated file, change decimal point?

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


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

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


title: Don't pollute outside context when solving equation from the outside

text: This code works fine only if `a` is not defined in the outside context:               getA[f_,total_]:=Module[{},         result=Solve[\!\(          \*SubsuperscriptBox[\(\[Integral]\), \(0\), \(255\)]\(f \[DifferentialD]i\)\)==total,a];          If[Length[result] == 0,Return[False]];          a/.First@result//N     ];     plotShow[f_,max_]:=Module[{},         a=getA[f,max];         If[!a,Return[]];         Print[f];         Plot[f,{i,0,255}]     ];          plotShow[i * a, 3500] (* => 0.107651 i      & a plot*)     (* Now showPlot has polluted the outside context with a = 0.107651 *)     plotShow[i * a, 3500] (* => Solve::ivar: "0.107651 is not a valid variable." *)      How can I make the function `plotShow` stop polluting the outside context?


title: Plotting several numerical solutions plus the analytic solution of ODE in one plot

text: I want to be able to plot several numerical solutions of an ODE plus its analytical solution in one plot in order to see how the numerical solutions converge towards the analytical one w.r.t. the number of steps. The methods I'm using is Euler's method for the equation $ y'(t) = 1-t +4y(t), y(0)=1$ The code I have so far is:               y[0]=1;     Do[y[n+1]=y[n]+0.01(1-0.01n+4y[n]), {n,0,99}]     y[100]      Is this doable? Thanks in advance for any help :)


title: How can I get the Predictive Interface to work in Slide Show environment?

text: It appears as though the predictive interface does not work in the Slide Show screen environment.


title: Opening .nb in other software or exporting to other languages

text: I am collaborating on a spare-time project with someone else that has access to Mathematica. I do not. He has supplied me with his notebook file. Is it possible for me to open, or import this file in any other piece of software? If not, are there any options to export from Mathematica to another format or language? I have heard that it is possible to export from a .nb file to C/C++ code, but I don't know if my co-conspirator can do this or what the best options are. For my specific case, export to C++ would be ideal.


title: How can I draw a picture like this?

text: How can I draw a picture like the following using _Mathematica_ 's graphics primitives? ![picture](http://i.stack.imgur.com/erDdu.jpg)


title: How could I implement the equivalent of NextPrime

text: I would like to know what an implementation of the function `NextPrime` would look like if it were implemented in _Mathematica_ 's core language.


title: Differential equations with a complex variable

text: Is Mathematica able to handle ordinary differential equations where the _variable_ itself is complex? I am looking for solutions of ODE systems of the form $$\left\\{ \begin{align} i\frac{da_1}{dt} &=E_1a_1(t)+\mu\cos(\omega t)a_2(t) \\\ i \frac{da_2}{dt}&=\mu\cos(\omega t)a_1(t)+E_2a_2(t), \end{align}\right.$$ and I need to use the analytical continuation of the solutions to a contour that consists of a number of straight-line segments on the complex plane. (Why? because of things like this.) My naive try would be               NDSolve[{           I a1'[t] == E1 a1[t] + μ Cos[ω t] a2[t],            I a2'[t] == E2 a2[t] + μ Cos[ω t] a1[t],            a1[0] == 1, a2[0] == 0},         {a1, a2}, {t, 0, I (2 π)/ω}];      (suitable parameters are $E_1=-1$, $E_2=-1/2$, $\mu=0.1$, $\omega=0.05$) but this simply causes an error               NDSolve::ndnl: "Endpoint 0. +125.664\ I in {t,0.,0. +125.664\ I} is not a real number"      I have looked online but I haven't found any good resources. Is this functionality natively available in Mathematica? Are there easily available add-ons that provide it? Or will I need to manually convert the ODEs into a chain of equations of a real variable?


title: shortcut key for traverse command history in a Mathematica session in a terminal?

text: I wonder what is the shortcut key for traverse command history (i.e. retrieve last, last last, ..., commands) in a Mathematica session in a terminal? If I hit the up/down arrow or pageup/pagedown, it will only show some incomprehensible codings of the keys. My OS is Ubuntu. Thanks!


title: How to make DocumentationTools palette useable?

text: I am writing the documentation for my package using Wolfram Workbench 2. But when I open DocumentationTools under Palettes, I get this unpolished piece of junk: ![enter image description here](http://i.stack.imgur.com/LqC1p.png) The top half is a total waste of space (it appears to be some kind of warning...), and the right-half of all the buttons are cut off by the completely fixed size of the window. **Option Inspector** refuses to respond to any changes made for Window Properties for "DocumentationTools". What can I do to make this more useable?


title: ParametricPlot3D creates a blank graphic in this case

text: I have been trying to evaluate the following code, but nothing happened. I don't see any result.               ParametricPlot3D[{v Cosh[u/v], v Cosh[u/v], u}, {u, -1, 1}, {v, -1, 1}]      What am I doing wrong?


title: Why can't I define vector v as having subscripted elements v_1, v_2, v_3...?

text: I'm a very beginner in Mathematica 8 programming. While trying to play a little with tensor analysis I encountered a problem. How to define for example vector in such manner: **v** ={$v_1,v_2,v_3$} For now I get the recursive definition, due to the situation in which the **v** variable is on the right-hand and left-hand sides.


title: Compiling Map over expression that yields a ragged array

text: I'm trying to speed up a function that looks in the neighborhood of each 3D point in a large dataset and finds all the points within 1 unit in each direction, x, y, z. I've started by using `Select` to find the points around a specified point and then `Map` this function over the dataset. First, lets make up some "data" and then define the `findpoints` function.               data = RandomReal[10, {10^4, 3}];          findpoints[data_, pt_]:= Block[{x = pt[[1]], y = pt[[2]], z = pt[[3]]},         Select[data,         x - 1 <= #[[1]] <= x + 1 && y - 1 <= #[[2]] <= y + 1 &&           z - 1 <= #[[3]] <= z + 1 &]     ]      Now lets map it over the random data.               Map[findpoints[data, #] &, data]; // AbsoluteTiming      This is quite slow, I gave up waiting, so I started by compiling the `findpoint` function.               findpointsC =        Compile[{{data, _Real, 2}, {pt, _Real, 1}},         Block[{x = pt[[1]], y = pt[[2]], z = pt[[3]]},          Select[data,           x - 1 <= #[[1]] <= x + 1 && y - 1 <= #[[2]] <= y + 1 &&             z - 1 <= #[[3]] <= z + 1 &]         ], CompilationTarget -> "C", RuntimeAttributes -> {Listable},         Parallelization -> True, RuntimeOptions -> "Speed"];          output= Map[findpointsC[data, #] &, data]; // AbsoluteTiming          (*{3.7542147, Null}*)      Much faster, great. Now I figured since compiling was so beneficial here and in other functions I found that by compiling the `Map` function I can gain some more speed, lets compile the whole thing.               mapfindpointsC =        Compile[{{data, _Real, 2}}, Map[findpointsC[data, #] &, data],         CompilationTarget -> "C", RuntimeAttributes -> {Listable},         Parallelization -> True, RuntimeOptions -> "Speed"];          mapfindpointsC[data]          (*CompiledFunction::cflist: Nontensor object generated; proceeding with uncompiled evaluation. >>*)      However, as per the error message, in this case the output is ragged.               TensorQ[output]          (*False*)      I've tried to flatten the output from map but nothing I can think of works. Is it possible to compile this expression.


title: Frontend coloring of Table[x, {x, 0, x}]

text: I have a small question about how the _Mathematica_ frontend colours in the variables that appear in (wrongly written) iterators. More specifically, I'm intrigued by the colour of the third `x` in iterators of the form               Table[x, {x, 0, x}]      which, as shown here, matches the first and second ones. This colouring of variables that are being iterated over is a very helpful feature in getting the iterators right and not using variables outside of their domain of definition; for example, the colours in               x Table[x, {x, 0, 5}]      make it abundantly clear that the `x` inside the `Table` will evaluate to a specific number, while the one outside it won't. However, an iterator of the form shown in the first code snippet above is incorrect and will usually return an error, so the colouring should reflect that and not put it in the same colour (pale blue for me) as iterated over variables. In a slightly more curious turn, I can think of one example where the first construction is valid, such as with               Module[{x = 5}, Table[x, {x, 0, x}]]      or simply               x=5;     Table[x, {x, 0, x}]      which indeed work, but the colour of the third `x` inside `Table[x, {x, 0, x}]` should match the first one (pale green and black, respectively, for me). Is this a bug, or simply a curious corner case?


title: Manually specifying distance metric to Nearest slows down calculation

text: Why does manually specifying the distance metric to `Nearest` slow down the calculation so much? This is relevant to my previous question. I've been using `Select` to find sets of points close to a center point but I figured that an alternative (although uncompilable) solution might be to use `Nearest` with the `ChessboardDistance`. However, I've found that if you specify the `DistanceFunction` to nearest you tremendously slow down the calculation by orders of magnitude, with the `ChessboardDistance` being the worst of the bunch by another order of magnitude. These results were observed in 1D, 2D and 3D with random data. I'm not sure what the effect, if any, of structured data would be. Here is the example code for 3D points. I will give all the timings below. I've simply created a set of 1000 points and computed the `NearestFunction` and then computed closest point in the first set of 1000 points to each point in a second set of another 1000 points.               data1 = RandomReal[10, {10^3, 3}];     data2 = RandomReal[10, {10^3, 3}];          nf1 = Nearest[data1];     nf1 /@ data2; // AbsoluteTiming          nf2 = Nearest[data1, DistanceFunction -> EuclideanDistance];     nf2 /@ data2; // AbsoluteTiming          nf3 = Nearest[data1, DistanceFunction -> ManhattanDistance];     nf3 /@ data2; // AbsoluteTiming          nf4 = Nearest[data1, DistanceFunction -> ChessboardDistance];     nf4 /@ data2; // AbsoluteTiming      Here are the timings:               nf1 {0.0160009, Null}          nf2 {1.1730671, Null}          nf3 {1.1720671, Null}          nf4 {26.4165109, Null}      Very similar timings were found for 1D and 2D so I won't list all of them here. The documentation says: If the elements are vectors or matrices of numbers, Nearest by default _in effect_ uses the metric `Norm[#1-#2]&`. So I tried to manually use `Norm[#1-#2]&` as the `DistanceFunction`.               nf5 = Nearest[data1, DistanceFunction -> (Norm[#1 - #2] &)];     nf5 /@ data2; // AbsoluteTiming      This is, surprisingly, even slower.               nf5 {3.9752274, Null}      I figured that maybe the default distance transform, even though it is given in the documentation, is compiled. Lets try that.               euclideandistanceC =        Compile[{{pt1, _Real, 1}, {pt2, _Real, 1}}, Norm[pt1 - pt2],         CompilationTarget -> "C", RuntimeAttributes -> {Listable},         Parallelization -> True, RuntimeOptions -> "Speed"];          nf6 = Nearest[data, DistanceFunction -> euclideandistanceC];     nf6 /@ data2; // AbsoluteTiming          nf6 {0.8990514, Null}      Better but still slower. What's going on? Why is the default method so much faster, and most importantly, how can I use other distance metrics without a huge performance penalty?


title: How to solve system of differential equations of arbitrary order (symbolic tensors)?

text: I am interested in solving systems of ODEs symbolicly, keeping things with arbitrary dimensions for clarity. For example, assume that $x, f(x) \in R^N$ and $A \in R^{N \times N}$, how do I solve $f'(x) = A \cdot x$ ? (of course, I am interested in much fancier equations) From the Mathematica documentation on symbolic tensors, it talks about differential operators but I can't figure out the notation. For example, I tried variations of the following, which didn't work:               $Assumptions = A \[Element] Matrices[{2, 2}, Reals] && x \[Element] Vectors[2, Reals] && f[x] \[Element] Vectors[2, Reals];     DSolve[ A . f[x] == D[f[x], x], f[x], x]      I also tried `Grad`, etc. but didn't work. Any ideas on whether this is possible?


title: Moving a locator based on the movement of another

text: My problem is: I want two `Locator`s to simulate a vector in the following sense: The first `Locator` is the base and the second the tip of the vector. When I move the tip, the base does not move (hence the vector changes). When I move the base, the vector is unchanged, and therefore the tip (and the `Locator`) moves. How can I achieve that? I have tried storing the previous value of the base and then test if the current value is different. And if so updated the position of the tip. I can however not make that work, when using 'Module'. I suspect that there is a more elegant solution.


title: DSolve is rejecting my description of a system of PDEs

text: I am trying to solve a system of partial differential equations using DSlove. But i get the input equations in return. Dsolve is not doing anything                pde4 = (2 Subscript[k, 3]*      D[Subscript[s, 1][x, t, o], x, x]) + ((2 G/r^2)*      D[Subscript[s, 1][x, t, o], o, o]) + ((Subscript[k, 1] + 2 G)/r)*     D[Subscript[s, 2][x, t, o], x, o] + (Subscript[k, 1]/r) D[      Subscript[s, 3][x, t, o], x] -      u*D[Subscript[s, 1][x, t, o], t, t] == 0              pde5 = 2 G*     D[Subscript[s, 2][x, t, o], x, x] + ((2 G + Subscript[k, 1])/r)*     D[Subscript[s, 1][x, t, o], x, o] + (2 Subscript[k, 2]/r^2)*     D[Subscript[s, 2][x, t, o], o, o] + (2 Subscript[k, 2]/r^2)*     D[Subscript[s, 3][x, t, o], o] -      u*D[Subscript[s, 2][x, t, o], t, t] == 0              pde6 = (Subscript[k, 1]/r) D[Subscript[s, 1][x, t, o],       x] + (2 Subscript[k, 2]/r^2)*     D[Subscript[s, 2][x, t, o], o] + (2 Subscript[k, 2]/r^2)*     Subscript[s, 3][x, t, o] + u*D[Subscript[s, 3][x, t, o], t, t] == 0              DSolve[{pde4, pde5, pde6}, {Subscript[s, 1], Subscript[s, 2],          Subscript[s, 3]}, {x, t, o}]      Output is this same thing again. I want a general solution with arbitrary functions. I will add boundary conditions later. Can i get output in a general form?


title: ListSurfacePlot3D generates ugly artifacts

text: I have a list of $\\{x,y,z\\}$ pairs representing points in $R^3$. For every unique value of $z$ there are many $\\{x,y\\}$ pairs defining a polygon/contour in that particular $z$-plane. My dataset looks like this:               Input:= Take[ptv, 3]     Output= {{61.52, -217.26, -80}, {63.48, -217.64, -80}, {65.43, -217.64, -80}}      These are coordinates of points residing on the $z=-80$ plane. There are other pairs for $z=-75$, $z=-70$, etc. Therefore `ptv` is of the form: ptv: {{$x_1$,$y_1$,-80}, {$x_2$,$y_2$,-80}, ..., {$x_k$,$y_k$,-80}, ..., {$x_1$,$y_1$,-75}, ..., {$x_m$,$y_m$,-75}, ...} My **goal** is to create a 3D surface where:   1. the points in every $z$-plane are connected into a polygon/contour and   2. the points in every $z$-plane are connected with their neighbors in the immediately above and below plane. I have achieved **1.** , via:               Graphics3D[Line[ptv], Point /@ ptv}]      The result looks like this: ![Plot1](http://i.stack.imgur.com/IF5Gk.png) If I, instead, use:               ListSurfacePlot3D[ptv, AxesLabel->{"x","y","z"}]      I get some ugly artifacts (edges at the boundaries of the volume) as shown here: ![Plot2](http://i.stack.imgur.com/SMwHg.png) Whereas, I was expecting a more "smooth" surface without any "openings". Any hints on:   1. Whether `ListSurfacePlot3D[]` is the proper function to use (i.e. in the documentation it is mentioned that `ListSurfacePlot3D[]` may "fold" over; perhaps this is why I'm experiencing these ruffles?) or   2. What other alternatives are there to consider ? **EDIT 1** : Minimally working example:               ClearAll["Global`*"];     ptv = Import["http://leaf.dragonflybsd.org/~beket/ag1", "Table"]     ListSurfacePlot3D[ptv, AxesLabel->{"x", "y", "z"}]      **EDIT 2** : I excluded random z-planes to explore the dependence of the produced surfaces on my dataset. There is considerable visual variability in the output, including some _very_ irregular images. Here is the code:               (* Identify the values of z-planes *)     planes = ({x, y, z} = #; z)& /@ ptv // Union;          (* Generate some random sequences with z-planes-to-be-excluded *)     excludedPlanes = Table[         RandomSample[planes, RandomInteger@{1, 4}],         {k, 1, 20}]] // Union // Reverse;          (* Filter data by discarding points residing on excluded planes *)     FilterData[p_] := Select[ptv,         Function[v, And@@(Unequal[v, #]& /@ p)][Last[#]]&]          (* Generate the 3D surfaces *)     ListSurfacePlot3D[#, AxesLabel->{"x","y","z"}]& /@ FilterData/@ excludedPlanes      And here is a screenshot: ![enter image description here](http://i.stack.imgur.com/Bs47c.png)


title: Can I stop edges in graphs from drawing on top of the vertices?

text: Consider the following               testadj = RandomVariate[BernoulliDistribution[0.15], {50, 50}];     AdjacencyGraph[testadj, VertexSize -> Large]      ![enter image description here](http://i.stack.imgur.com/I5Tc1.png) The nodes are almost completely hidden in the mess of edges. They can be made easier to see by making the edges fade into the background a little.               AdjacencyGraph[testadj, EdgeStyle -> Directive[Opacity[0.4], Gray],       VertexSize -> Large]      ![enter image description here](http://i.stack.imgur.com/OT77n.png) But we still have the problem that the lines draw over the top of the nodes. Is there a way to force the nodes to draw on top of the lines?


title: How to control Manipulate speed

text: I want to ask about how can we control `Manipulate` function so that it is not incrementing the step until the expression is calculated. I have the following simple code:               data = RandomReal[1, {100, 10}];     data2 = ConstantArray["Emp", {100, 10}];     Manipulate[           data2[[1 + IntegerPart[i/10.00000001], i - IntegerPart[i/10.00000001]*10]] =        data[[1 + IntegerPart[i/10.00000001], i - IntegerPart[i/10.00000001]*10]];            data2 // TableForm, {i, 1, 1000, 1}]      If you see when you click the `"PlayButton"`, the `Manipulate` jumps the step in non-sequential odder so that it is not calculating the expressions in sequential odder. I want to ask if there is any way to control the play action of `Manipulate` so that it is not moving to `i + 1` until it is calculated the expressions at `i`. ![enter image description here](http://i.stack.imgur.com/nnz6T.jpg)


title: Equation with complex numbers and 2 variables

text: I have an equation:                eq = 1 + ( 9 / ( s*(s + 9) ) )*( k/(s + b) ) == 0;      where `s == -2 + 2I` (`I` is the imaginary unit). I know it can be solved by separating into real and imaginary parts, substituting the value of `s` and then equating both equations to zero and solving the simultaneous equations to find the values of `b` and `k`. But how do I make _Mathematica_ do this for me cause it takes very long on paper. For those that have a similar problem, this worked for me:               FindInstance [{ComplexExpand[Re[eq]] == 0,  ComplexExpand[Im[eq]] == 0}, {k, b}, Reals]          {{k -> 9.04063, b -> 5.54344}}


title: fit a curve in a three dimensional space

text: I have a list of points of a curve in a three dimensional space, like               myData =     {{1.6251942652167208, 3414.632234882431, 3.248326448352207},       {0.195563463104691, 32.18966154343482, 1.1454060351007385},      {0.17904199044243319, 14.25108939238815, 0.9423477799753123},      {0.170816821901991, 8.653164633472851, 0.7958880823665402},        {0.15676037756308206, 5.631156542779637, 0.67467521725227},      {0.1548948722263085, 4.270874169070245, 0.6275611866853114},      {0.1876950201556172, 4.308999312640106, 0.6090637255823652},       {0.16188251254916763, 2.9764924022024317, 0.5292892925723116},      {0.17262610022897934, 2.739111371641244, 0.52653513586836},      {0.16954431585785373, 2.3070638999549393, 0.49560804724631763},       {0.2097961985882085, 2.6534757543854317, 0.5487657657669014},      {0.19081633352127408, 2.0852454796400357, 0.514435548916157},      {0.19563129613920563, 1.917093872159669, 0.4743406166681895},      {0.21254024573386504, 1.9251337728677473, 0.485236735240245},      {0.21896472970440534, 1.8147535334973488, 0.46531629302089494},      {0.20466136180653818, 1.513876366963674, 0.4249037110237554},      {0.21855394267841366, 1.519108716384235, 0.4380750296933395},      {0.23565318703002316, 1.5488572100526539, 0.44631964709969185},      {0.2380818528018018, 1.4529671243699986, 0.42553379428103266},       {0.2424842011874948, 1.389721482236748, 0.4345346021692877},      {0.2647317878191315, 1.4605691656957687, 0.43267419256049483},      {0.2632502748033041, 1.3557447019366855, 0.4286184053606104},        {0.27205729604073775, 1.334394688581283, 0.44259414855715523},      {0.2793705082711959, 1.302387809445032, 0.4336404208867536},      {0.2837573939406187, 1.2544604741697558, 0.42970441420505734},      {0.2948407139307023, 1.251503834903687, 0.4289108411034688},      {0.29600086351343347, 1.1920618765471473, 0.42889878404407833},      {0.29465197778349606, 1.1243426155800962, 0.4276172983591667},      {0.30183374846249794, 1.1064964396078605, 0.42772557494175767},      {0.30918455260251276, 1.0893160114201885, 0.4275101914583863},      {0.3170183678910846, 1.0761991260380923, 0.4251450946217794},      {0.3170471652361686, 1.028070998453355, 0.4231589533788725},      {0.33509119696542056, 1.062744456154385, 0.4233345521815623},      {0.32971337187673616, 0.9954325606304446, 0.4231326015290622},      {0.33595705730728015, 0.979557033300735, 0.4236769992893109},      {0.3436253098086924, 0.9714372846864234, 0.4241910609852374},      {0.34812463781047914, 0.949934939902976, 0.42012852465803996},      {0.3563732253707738, 0.9443465112229241, 0.4204752685781463},      {0.35992684291158533, 0.9221331266260643, 0.41804460944990646},      {0.36120796960334306, 0.893126929139083, 0.41819781912012344},      {0.3694695389695183, 0.8578713443146384, 0.4150160053145223},      {0.37334083248099226, 0.8414330588993054, 0.4145221485938744},      {0.3766063600562105, 0.8812611721272469, 0.45266007028291844},      {0.3835672074215254, 0.8426364383173903, 0.44224264257818485},      {0.3925576360242645, 0.8145071347303069, 0.441619765516166},      {0.3952083972535039, 0.7698172682169502, 0.4289584794098478},      {0.40767794715674194, 0.7561905560105875, 0.42830082380993906},       {0.4139609495348973, 0.7284690866030674, 0.42802517746189234},      {0.4199909107710205, 0.7017646393366863, 0.4245332938666336},      {0.42517695763043706, 0.6756040929172838, 0.41901542028878747},      {0.438909457948436, 0.6699655678281783, 0.41733783818556264},      {0.44563579799220726, 0.6499029238980055, 0.4129281969548992},      {0.4473498530318954, 0.6211332659501384, 0.4089614451608291},      {0.45464041389498117, 0.6051969313774956, 0.4050849964713832},      {0.46156953220721025, 0.5899702211293141, 0.4029806473833252},      {0.47141055300556484, 0.5805373200701324, 0.39970427922756985},          {0.4792326437523886, 0.5681016242905145, 0.39694835543120627},      {0.4853330654106727, 0.553725319161017, 0.393182829103135},      {0.49135512137375686, 0.5399417830238199, 0.3901371989617769},      {0.5006324150392757, 0.5320562690230357, 0.3875692692973447},      {0.5064951595246885, 0.5194105475320817, 0.3832282043244645},      {0.5115547319598217, 0.5062662671288428, 0.3811347260859499},      {0.51504804958564, 0.4917529304140576, 0.3775795425712839},      {0.5220718511737211, 0.48266019418477496, 0.37470445520090895},      {0.5312779766503062, 0.47705149397591645, 0.37098468508988963},      {0.5324554882538403, 0.4612891859386048, 0.36767364179185347},      {0.5377840374755473, 0.451700594900957, 0.3651018926671713},      {0.5450134070805016, 0.44432218995571343, 0.3621032659850748},      {0.5532192176564933, 0.438742917967833, 0.35988610407498006},      {0.5559200803701375, 0.4272035754877022, 0.3562923772639558},      {0.5632612273324766, 0.42125311233985596, 0.35442749937954365},      {0.5695771900612702, 0.4143325143071145, 0.35207878660073166}}      I want to find and plot a find of this curve in the space. I don't have a explicit form of the real function, but I know that it is regular enough to allow a polynomial expansion in the interval of interest. Is this possible?


title: Exporting a rasterized Row of Graphics

text: I'm running some code based on @R.M.'s answer to **this question** to create a couple plots side by side. I want to export the plots rasterized to a png. However, when I `Rasterize` the plot at a higher `RasterSize` or `ImageResolution` it splits the row on to two seperate lines. See the following simplified example below:               Rasterize[      With[{size = 250},        Row[Show[#, ImageSize -> {Automatic, size},            ImagePadding -> {{30, 15}, {40, 5}}] & /@ {Plot[           Sin[x], {x, -1, 1}], Plot[Sin[x], {x, -1, 1}]}]],       ImageResolution -> 200]      It looks like this: ![Mathematica graphic](http://i.imgur.com/C1yJ9.png) I want both plots on the same line but at higher resolution, like this: ![Mathematica graphic](http://i.imgur.com/nFb3e.png) What is going wrong?


title: Are there "All" and "Any" functions in Mathematica?

text: In Python, there is a function `all` which returns true if all of its arguments are true, and `any` which returns true if at least one of its arguments is true. I find these quite useful in functional programming. Given how much Mathematica encourages functional programming constructs, I was surprised not to find anything equivalent to these `all` and `any` functions in the documentation. Does Mathematica have equivalents to these functions, or some standard way to achieve the same effect? I can implement them myself as               AllOf[b_List] := Fold[And, True, b][[1]]     AllOf[b__] := Fold[And, True, {b}][[1]]          AnyOf[b_List] := Fold[Or, True, b][[1]]     AnyOf[b__] := Fold[Or, True, {b}][[1]]      (these may not be always correct, but they've worked for my purposes). But I would rather use something built-in if it exists.


title: Is my Mathematica 7.0 student version crazy?

text: der[x_]:=Piecewise[{{E^((-4 - 4*x - x^2 - Log[2]^2)/8)/(2^(x/4)*Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])] + Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 + Log[2])/(2*Sqrt[2])])), x >= 0}}, (2^(x/4)*E^((-4 - 4*x - x^2 - Log[2]^2)/8))/(Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])] + Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 + Log[2])/(2*Sqrt[2])]))]          pdf[x_]:=0.2015152271993863*DiracDelta[x] + Piecewise[{{E^((-4 - 4*x - x^2 - Log[2]^2)/8)/(2^(x/4)*Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])] + Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 + Log[2])/(2*Sqrt[2])])), x >= 0}}, (2^(x/4)*E^((-4 - 4*x - x^2 - Log[2]^2)/8))/(Sqrt[Pi]*(2*Sqrt[2/E]*Erf[Log[2]/(2*Sqrt[2])] + Erfc[(-2 + Log[2])/(2*Sqrt[2])] + 2*Erfc[(2 + Log[2])/(2*Sqrt[2])]))]          N[Integrate[der[x], {x, -Infinity, Infinity}]]     0.798485     N[Integrate[0.2015152271993863` DiracDelta[x], {x, -Infinity, Infinity}]]     0.201515     N[Integrate[pdf[x], {x, -Infinity, Infinity}]]     0.798485      EDIT (code part related to convolution)               Integrate[pdf[x - w] pdf[w], {w, -2, 2}, Assumptions -> x ∈ Reals && x ∈ Reals]      the last convolution involves a dirac delta as well as a continuous density. Both version 7 and 9 doesnt produce any solutions. Do you have any ideas to get a solution?


title: Maintaining stylesheet information in Cell[]

text: I am working on formatting a cell for a slideshow presentation format such that a graphics object occupies the left half of the cell and bullets or other items occupy the right. The ancient `AuthorTools` functions are not sufficiently documented for me to determine if this is possible with bilateral cells, but the first attempt below is my stripped down version of `ToBilateral`               CellPrint@Cell[BoxData@GridBox[         {{           Cell[BoxData[ToBoxes[Plot[Sin[x], {x, 0, 2 Pi}]]], "Output"],           GridBox[{             {Cell["section", "Section"]},             {Cell["subsection", "Subsection"]},             {Cell["item", "Item"]}             }, ColumnAlignments -> Left]           }}, ColumnSpacings -> 3, RowAlignments -> Top]]      gives the following output with the default stylesheet ![Mathematica graphics](http://i.stack.imgur.com/YFXDI.png) Boxing in Mathematica can leave you punch drunk very quickly, so I reverted to `Row` and `Column` to get this               Row[      {Plot[Sin[x], {x, 0, 2 Pi}, ImageSize -> 300],       Column[{         Style["section", "Section"],         Style["subsection", "Subsection"],         Style["item", "Item"]         }, Left, 2]       }, "\t"]      ![Mathematica graphics](http://i.stack.imgur.com/TGYmW.png) In both cases the dingbat for the item style gets eaten and there is no style indenting. I attempted to edit the stylesheet and navigate to the options inspector; however changes made there have no effect on the output of either of these code snippets unless the formatting change is related to font color, size, weight, etc. Oddly enough, the framestyle for a section does appear in the Cell snippet but not in the Row/Column snippet. To be clear, I'm looking for something like this: ![Mathematica graphics](http://i.stack.imgur.com/dbqUa.png) which I've only been able to obtain with the following code:               LoadMicrosoftPowerPoint[]     CutandPaste[]      so I'm looking for a better solution.


title: Can't create a simple CDF

text: I decided it was time I investigated CDFs, so I created the following simple `Manipulate` using Mathematica version 9.0.1.0:               Manipulate[      Plot[       Sin[a x], {x, 0, 2 Pi}       ],      {a, 1, 10},      SaveDefinitions -> True]      ![simple manipulate](http://i.stack.imgur.com/kpSYg.png) Then I selected File>CDF Preview>CDF Player ![file cdf preview](http://i.stack.imgur.com/n9PuG.png) which produced a new window: ![cdf preview](http://i.stack.imgur.com/TfhqT.png) Not very interesting (a bit like yesterday's paper — flat, lifeless, inactive), but perhaps that's what it's supposed to look like at this point. I pressed on, and used the wizard (File>CDF Export>Standalone...) to save a CDF version of the notebook. ![cdf wizard](http://i.stack.imgur.com/DDRzw.png) I put the new CDF file in a trusted directory, then opened the Wolfram CDF Player (version 9.0.1.0) and tried to open the file. Nothing happened - no console messages. I know that the CDF Player works, because I can open CDFs downloaded from demonstrations.wolfram.com. The CDF file itself can be opened in _Mathematica_ and works as expected. I tried opening it in CDF player with _Mathematica_ running, and also after quitting _Mathematica_. I also tried with CDFs made using File>SaveAs... -> CDF. I've read the CDF-tagged questions here, but can't find anything that addresses my basic inability to create a simple CDF.


title: webMathematica interface for Mobile apps

text: I was reading about webmathematica but it has mentioned that it is for websites and mobile apps depend on wolfram alpha to get its work done. But since exact mathematica code doesn't work in alpha, it obviously puts serious limitations regarding the granularity of computation needed as it is at mercy of database. So, is there some service that some app can be programmed that creates mathematica code based on parameters from front-end and it is sent as request object to some server where it can be computed and sent back as response object, hence giving the exact answer. In simpler words, Mathematica running on server and executing client's code.


title: Some boundary issue of Integration

text: When I try to solve the integration f(x) as following (type it in the Mathematica) $ f(x)= \frac{1}{π} \int_{-1}^{1} \frac{\sqrt{1-y^2}}{(y-x)}dy $, I met some boundary problems. I have searched some basic command like NIntegrate or PrincipalValue, but it dose not work. I think these commands just for finding a value of integration, but not for calculating a function. Can anyone provide any suggestion?


title: How to define custom operators

text: I am currently running _Mathematica_ 8 and I would like to know how to define custom operators. Let's say I define an operator called $\times$ where: $$a\times b = a+a\cdot b+b$$ I also want to know if it is commutative, associative, its inverse, identity and whether it is closed for Z. How would I do that in _Mathematica_.


title: How can I restore context menu functionality to a Manipulate that contains Locators?

text: Before adding a `Locator` to a `Manipulate`, I can easily print or export the result using a context menu: ![enter image description here](http://i.stack.imgur.com/D3zhJ.png) But after adding a `Locator`, I can't even get a context menu to appear. How do I enable graphics generated with `Locators` so that the context menu functionality is restored?                   Manipulate[          Show[ParametricPlot[BezierFunction[{{0, 0}, c1, {1, 1}}][x], {x, 0, 1}]],         {{c1,{.2, .2}}, Locator}]


title: How to convert a 2D image into a 3D graphics?

text: I have an image I would like to make into a `.dxf` and to do this I need a `Graphics3D` object. Is there anyway I can do this? Can mathematica somehow vectorize a 2D image? I tried saving the image as a PDF then `Export[path.dxf,Import[path.pdf]]` after saving `EdgeDetect[Image]` as a PDF but AutoCad said it was a bad DXF and did not accept it. Any solutions? Edit: Clarification: I have a 2d image that i want to put into the .dxf format which I believe is 3d. In order to do that Mathematica wants a Export[path.dxf,3DGraphics object]. It's a 2d image though. This is for importation into AutoCAD. It says malformed shape when i do Export[path.dxf,Image] since I assume Image is 2DGraphics object


title: Issues FindRootPlot command

text: I've had some fun playing around with `FindRootPlot` for a simple system of equations:               << Optimization`UnconstrainedProblems`     f[1] = Sin[x[1] + x[2]]     f[2] = Cos[x[1] - x[2]]     F = Table[f[i], {i, 1, 2}]          guess[1] = 1;     guess[2] = -1;          Xinsert = Table[{x[i], guess[i]}, {i, 1, 2}]          FindRootPlot[F, Xinsert, Method -> {"Newton",      "StepControl{"LineSearch","MaxRelativeStepSize" -> .1}}]      Which gives a plot ![Mathematica graphics](http://i.stack.imgur.com/rx4XJ.png) and the following:               {{x[1] -> 0.785398, x[2] -> -0.785398}, {"Steps" -> 5,"Residual" -> 5, "Jacobian" -> 4},      But when I tried applying it to a larger matrix it seems to no longer work. Given:               dim = 8;           test4 ={0.3125 z[5] + 0.4375 z[6] + 0.0706277 z[7] + 0.101342 z[8], 0.5 z[7] + 1.        z[8], -0.961887 z[1] - 1.35898 z[2] - 0.29427 z[3] - 0.415442 z[4], -3.30241 z[1] -      6.60482 z[2], -2.77806 z[5] - 3.90146 z[6] - 0.671632 z[7] - 0.943006 z[8] + 1.875      z[1] z[9] + 2.625 z[2] z[9] + z[3] (-1.83751 + 1.875 z[9]) + z[4] (-2.58057 + 2.625      z[9]), -1.95073 z[5] - 2.77806 z[6] - 0.471503 z[7] - 0.671632 z[8] + 1.3125 z[1]      z[9] + 1.875 z[2] z[9] + z[3] (-1.29029 + 1.3125 z[9]) + z[4] (-1.83751 + 1.875        z[9]), z[6] (-10.1813 - 2.54697 z[9]) + z[5] (-7.27566 - 1.83285 z[9]) + 2.42463      z[1] z[9] + 3.36932 z[2] z[9] + 1.01633 z[7] z[9] + 1.42194 z[8] z[9] + z[3]       (-2.74994 + 2.42463 z[9]) + z[4] (-3.84816 + 3.36932 z[9]), z[6] (-7.27566 - 1.83285      z[9]) + z[5] (-5.09064 - 1.27349 z[9]) + 1.68466 z[1] z[9] + 2.42463 z[2] z[9] +      0.710972 z[7] z[9] + 1.01633 z[8] z[9] + z[3] (-1.92408 + 1.68466 z[9]) +      z[4] (-2.74994 + 2.42463 z[9]), -1 + z[3]/2 + z[4] + z[5] + z[6]}      and               Esol2 = AppendTo[Esol, 1]          (* {-5.15989, 2.57995, 12.036, -5.01798, 0.391302, -0.357324,1.70608,          -0.85304, 1} *)      and               Dimensions[Esol2]          (* {9} *)      I can explain where `Esol` and `test4` come from if needed but I didn't want to clutter the post with too much information. For now I just want to point out that they are lists of length 9. Now I try to use `FindRootPlot`:               F = Table[test4[[i]], {i, 1, dim + 1}];          Dimensions[F]          (* {9} *)          Xinsert = Table[{z[i], Esol[[i]]}, {i, 1, dim + 1}]          (* {{z[1], -5.15989}, {z[2], 2.57995}, {z[3], 12.036}, {z[4], -5.01798},         {z[5], 0.391302}, {z[6], -0.357324}, {z[7], 1.70608}, {z[8], -0.85304}, {z[9], 1}} *)          Dimensions[Xinsert]          (* {9, 2} *)          FindRootPlot[F, Xinsert,Method -> {"Newton", "StepControl" -> {"LineSearch",        "MaxRelativeStepSize" -> .1}}]      **Which gives me an error about the number of equations not being equal to the number of variables**. But this makes no sense the length of `Xinsert` and `F` are clearly equal. Running the previous command also gives this:               FindRoot[Optimization`UnconstrainedProblems`Private`obj, {{z[1], -5.15989}, {z[2],          2.57995}, {z[3],12.036}, {z[4], -5.01798}, {z[5], 0.391302}, {z[6], -0.357324},         {z[7], 1.70608}, {z[8], -0.85304}, {z[9],1}}, {"Jacobian" -> {"Symbolic",      EvaluationMonitor :>      Sow[{{z[1],-5.15989},Optimization`UnconstrainedProblems`Private`obj},{Optimization`UnconstrainedProblems`Private`j$37945,Optimization`UnconstrainedProblems`Private`all$37945}]}, Method -> {"Newton", "StepControl" -> {"LineSearch", "MaxRelativeStepSize" -> 0.1}}, "StepMonitor" :> Sow[{{z[1], -5.15989},    Optimization`UnconstrainedProblems`Private`obj}, \     {Optimization`UnconstrainedProblems`Private`s$37945,           Optimization`UnconstrainedProblems`Private`all$37945}],        "EvaluationMonitor" :>         Sow[{{z[1], -5.15989},           Optimization`UnconstrainedProblems`Private`obj}, \     {Optimization`UnconstrainedProblems`Private`r$37945,           Optimization`UnconstrainedProblems`Private`all$37945}]}]


title: How can I visualize features found in an image?

text: I am using Mathematica to explore the face detection feature of Core Image on Mac OS X Lion. To do this I have an Objective-C program which captures images from the iSight camera, runs face detection and logs the coordinates of any detected features, and then saves the image to the clipboard. I then switch to Mathematica and paste the captured image into one variable, and copy-and-paste the logged feature coordinates into another. I've written a simple Mathematica function that can subsequently produce a "normalized" face image, but it would be helpful to be able to draw graphics on top of an image in order to visualize where features are and how they're oriented. When I naively try this I get the error: "Image is not a graphics primitive or directive." Is there a simple way to draw (or composite) graphics on top of an image?


title: Inverse Laplace transform

text: For this expression: $ (1 - Exp[-Sqrt[1+s] x])/(1+s)$ How to make the Inverse Laplace Transform analytically?               InverseLaplaceTransform[(1 - Exp[-Sqrt[1+s] x])/(1+s),s,t] does not directly give solution


title: Mathematica Complains about Non Symmetric Covariance matrix, when it's not the case

text: I was doing some fitting with Mathematica7 using NonlinearModelFit. It's quite long the program to do the fit and that's why I am not displaying here ... It goes ok, and I can get the fit parameters as well as the covariance matrix               In[81]:= {Subscript[a, 0], Subscript[a, 1]}/.fitCCBA34["BestFitParameters"]          In[78]:= fitCCBA34["CovarianceMatrix"]      When testing it is Symmetric, it goes ok, as should be by construction of the matrix:               In[80]:= SymmetricMatrixQ[b]      Out[80]= True      However, it turns out, that, when trying to get some Multinormal distribution of the parameters, it complains about the matrix which is non-symmetric ...               In[84]:= MultinormalDistribution[{Subscript[a, 0], Subscript[a,         1]} /. fitCCBA34[        "BestFitParameters"], {{fitCCBA34["CovarianceMatrix"][[1, 1]],         fitCCBA34["CovarianceMatrix"][[1, 2]]}, {fitCCBA34[          "CovarianceMatrix"][[2, 1]],         fitCCBA34["CovarianceMatrix"][[2, 2]]}}]          During evaluation of In[84]:= MultinormalDistribution::cmsym: The covariance matrix must be symmetric. >>          Out[84]= MultinormalDistribution[{0.275723,        0.246948}, {{0.00001521, -0.0000535383}, {-0.0000535383, 11.6061}}]      Of course, if now you do copy paste, it works perfectly, so I guess it's some numerical issue, any clue about how to fix this? I need to encode this inside a function rather than copy paste each time ... Thanks in advance!


title: Deleting a row or column of an adjacency matrix while maintaining the associated label

text: I am currently working with a weighted adjacency matrix for a directed graph, and it contains several 0 columns and rows. With the unaltered matrix, I am able to monitor the relations between vertices with,               TableForm[Normal @ WeightedAdjacencyMatrix[graph],          TableHeadings -> {a = VertexList[graph], a}]      This outputs a table with the corresponding vertex list labeling the rows and columns. I want to delete the 0 rows and columns while altering the labels to reflect the change. My matrix is currently $85\times 85$, and eliminating the necessary rows and columns reduces the size to $77\times 38$. I could theoretically go through by hand and track the eliminated entries, but that sounds way too time consuming for something that I'm sure has a simple solution. Any help is appreciated.


title: Splitting a list in which figures vary from negative to positive

text: Consider the following list:               data={4078, 256, -1266, -388, 1290, 1368, 1446, 1524, 2};      I would like to split any kind of such list always, when figures turn form negative to positive. In the case of `data` the result would be:               {{4078, 256, -1266, -388},{ 1290, 1368, 1446, 1524, 2}}      I tried it with               Split[%, #2>0 && #1<0 &]      but I got:               {{4078}, {256}, {-1266}, {-388, 1290}, {1368}, {1446}, {1524}, {2}}


title: Using RegionFunction on multiple plots

text: I realize that the `Plot` function can plot multiple functions of x at the same time, using `{ }`. I also know that the `RegionFunction` option is used to specify the particular region of the domain that you want plotted. My query is whether I can combine the two together and use different `RegionFunction`s on different functions of the same parent `Plot` statement, plotting multiple conditional functions rather than a whole domain: $$f(x) =\begin{cases} 2\sqrt{x} & \text{if } 0\leq x \leq1 \\\ 4-2x & \text{if } 1<x<2.5 \\\ 2x-7 & \text{if } 2.5 \leq x \leq 4 \end{cases}$$


title: Distorted graphics when using custom ticks and AspectRatio -> Full

text: I am having a problem using custom tick specifications along with `AspectRatio -> Full`.   The problem affects both `Ticks` and `FrameTicks`. An example of the problem:               x = MapThread[{#, #2, {0, 0.007}} &, {100 Range@5, {"One","Two","Three","Four","Five"}}];          p = ListPlot[Array[Log, 600], Ticks -> {x}, AspectRatio -> Full, ImageSize -> {250, 250}]      ![Mathematica graphics](http://i.stack.imgur.com/tEn1a.png) Giving an explicit AspectRatio produces the output I desire:               Show[p, AspectRatio -> 1]      ![Mathematica graphics](http://i.stack.imgur.com/zyqiS.png) A plot without the custom ticks is not distorted:               Show[p, Ticks -> Automatic]      ![Mathematica graphics](http://i.stack.imgur.com/4kekp.png) I wish to understand what is causing the problem and find a way to work around it _besides_ specifying a numeric AspectRatio. I could add a routine to calculate the aspect ratio from the image size but I would rather find a way to make `AspectRatio -> Full` work as intended.


title: Can we know the background code associated with basic mathematica functions

text: I wanted to know how computers calculate basic functions like `Sqrt` so first I checked how humans do it I found that they use something called "Newton's method" that is basically a iterative method to find the root of a number. that can be efficiently reproduced in Mathematica as:               SqRoot[x_, assump_, precision_] := N[Nest[(# + x/#)/2 &, assump, 21], precision]      `Timing` it for 2 gives:               In:= Timing[SqRoot[2, 1, 123]]     Out:= {1.75, 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492}      `1.75 Seconds` While using same precision with `Sqrt` gives:               In:=Timing[N[Sqrt[2], 123]]     Out:= {1.6237*10^-15,1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492}      `1.6237*10^-15 Seconds` Meaning Mathematica uses an entirely different operation to calculate the root of a number Like this there are tons of elementary functions like `Factorial` `Abs` `Solve` `Sin` `Cos` which result in similar fast results as compared to slower human results using slower loops and iterative methods. Where can we find a compendium of all the back code that supports these functions and makes them faster than actual procedure. P.S. This is related only to Mathematica based functions (not theoreticalcs.SE)


title: Using Mathlink with the cernlib FORTRAN package MINUIT

text: I could successfully use Mathlink to call a simple fortran subroutine. However, when I went to a realistic problem, I failed. To be specific, I want to fit a set of data with some function using the cernlib package MINUIT (for function minimization and error analysis). Then within FORTRAN, I can get the best parameter sets and their errors, and many more. Now, I want to plot some figures with the resulting best parameters in Mathematica. Of course, I can read the parameters by eyes... But it would be nice to do this with Mathlink. However, I failed. I created an executable, but it cannot be recoganized by Mathlink. Install simply hang until I aborted it. This is a bit strange, since the fortran code was successfully called in C when Mathlink was not using. Here is the shortened FORTRAN code, to be called `myprog.f`, (still somewhat lengthy) for a MINUIT example here:                 ! n is not used, just to give the Mathlink function an argument       subroutine myprog(n, fmin)        !program myprog         implicit none       integer SYSIN/1/, SYSRD/5/, SYSWR/6/, SYSPU/7/       integer n, ndat, npari, nparx, istat       real(8) fmin, fedm, errdef       external myfcn            !     initialize unit numbers       call mintio(SYSRD, SYSWR, SYSPU)       !driven card running the fit       open(unit=SYSRD, file='myprog.mincards', status='OLD')        !output, if commented out, the output will be written to terminal       open(unit=SYSWR, file='myprog.out', status='UNKNOWN')                  !     invoke minuit       call minuit(myfcn, 0)             ! current status of minimization       CALL mnstat(fmin, fedm, errdef, npari, nparx, istat)       end                 subroutine myfcn(npar, g, f, x, iflag, futil)       implicit none       integer npar, iflag, i, ndat, n       integer SYSIN/1/, SYSRD/5/, SYSWR/6/, SYSPU/7/       parameter (ndat=5)       real*8 f, g(*), x(*), xdat(ndat), ydat(ndat), edat(ndat), func,              &       answer/15.7/, rms, avg, diff, futil       !     Save all data that must be preserved between calls!       save xdat, ydat, edat         ! MUST            if (iflag .eq. 1) then       !     Initialization mode          do i=1,ndat             xdat(i) = i             ydat(i) = answer + i - float(ndat + 1) / 2.             edat(i) = 1.          end do       end if       !     compute LSQ       f = 0       do i = 1, ndat          f = f + (ydat(i) - func(xdat(i), x(1)))**2 / edat(i)       end do       end            function func(x, par)       implicit none       real*8 x, par(*), func       func = par(1)       end      The driven card _myprog.mincards_ , where the initial values of the parameters are set, contains               set title     Minuit data cards for myprog example program     parameters     1 'average' 0.0 1.0          set print 1     mig     mino     return     stop          The subroutine `myprog(n,fmin)` (fmin gives the minimized value of chi-square) can be successfully called in C with the following code               #include "stdio.h"     #ifdef __cplusplus     extern "C"{     #endif          double myprog(int n)      {       double fmin;         myprog_(&n, &fmin);       return fmin;     }          #ifdef __cplusplus     }     #endif          int main(void)     {     printf("%f\n", myprog());     return 0;     }      The result is 10. I thought as long as the FORTRAN subroutine can be called in C, one should be able to call it in Mathematica with Mathlink. Here is the C wrapper (I paste the complete code since it might be helpful to others):               #include "mathlink.h"          #ifdef __cplusplus     extern "C"{     #endif          double myprog(int n)      {       double fmin;            myprog_(&n, &fmin);       MLPutDouble(stdlink, fmin);       return fmin;     }          #ifdef __cplusplus     }     #endif          #if WINDOWS_MATHLINK          #if __BORLANDC__     #pragma argsused     #endif          int PASCAL WinMain( HINSTANCE hinstCurrent, HINSTANCE hinstPrevious, LPSTR lpszCmdLine, int nCmdShow)     {     char  buff[512];     char FAR * buff_start = buff;     char FAR * argv[32];     char FAR * FAR * argv_end = argv + 32;          hinstPrevious = hinstPrevious; /* suppress warning */          if( !MLInitializeIcon( hinstCurrent, nCmdShow)) return 1;     MLScanString( argv, &argv_end, &lpszCmdLine, &buff_start);     return MLMain( (int)(argv_end - argv), argv);     }          #else          int main(int argc, char* argv[])     {     return MLMain(argc, argv);     }          #endif      The Mathlink template file _myprog.tm_ is               :Begin:     :Function:       myprog     :Pattern:        Minuit[n_Integer]     :Arguments:      { n }     :ArgumentTypes:  { Integer }     :ReturnType:     Manual     :End:          :Evaluate: Minuit::usage = "Minuit[n] does fit using MINUIT. n can be an arbitary integer. This function returns the value of the least chi-square."      I use Windows 7 with MinGW. I wrote `math.bat` to create an executable for Mathlink               gfortran -c myprog.f     gcc -c callfmath.c -o myprogc.o     mprep myprog.tm -o myprogtm.c     gcc -c myprogtm.c -o myprogtm.o     gcc *.o libminuit.a libML32i3.a -lm -lpthread -mwindows -lstdc++ -lgfortran -o myprog_math     rm *.o      where `libminuit.a` is the library for MINUIT. But the generated `myprog_math.exe` does not do what I want. It does not create a link to Mathematica, and is not Mathlink-aware... If anybody can tell me what was wrong with the procedure, I would be appreciate it very much!!! EDIT: The MINUIT source files can be downloaded here, and libminuit.a made by gfortran.


title: How to peel the labels from marmalade jars using Mathematica?

text: How can I detect and peel the label from the jar below (POV, cylinder radius, jar contents are all unknown) ![enter image description here](http://i.stack.imgur.com/rfNu7.png) to get something like this, which is the original label before it was stuck on the jar? ![enter image description here](http://i.stack.imgur.com/FMALS.gif)


title: Tabs inside expression to format code

text: In a similar spirit to a question proffered several days back,and as that question stated, > Since the front-end is quite extendable my question is... Does the front end provide any way to use tabs in code? A bit trivial, I admit, but I for one would find it very useful to use tabs to align parts of different expressions or the layout of a `Grid` to make the code easier to read and debug. **Edit to original question follows:** I didn't realize until I saw Leonid's answer that what I thought I had asked and what everyone else thought I asked had little resemblance. What I'd like to do is perhaps simpler and maybe just sillier. A very simple example of a Grid[]                 Grid[{{"First" , "Second" , "Third", "Fourth", "Fifth" },       {"1st" , "2nd" , "3rd" , "4th" , "5th" }}]      What I'd like to see in either a StandardForm or InputForm styled cell would look like this: ![enter image description here](http://i.stack.imgur.com/jPJSI.png) I'd like the functionality of using a tab within any given line of code within any longer expression. This draws a bit on one of the useful features of "table oriented programing". I think this could make setting up complex Grid[]s or just reading complex code and functions easier and thereby facilitate more easily finding bugs and inconsistencies. I hope this makes the question clearer.


title: Simplification of a symbolic manipulation involving functions of more than one variable

text: I am facing the following problem.               f[x_,y_] = a[x] u[y] + b[x] v[y]      Now I can ask Mathematica to calculate               g[x_] = Integrate[ Expand[f[x,y]^2],y]      which it correctly shows. In the expansion we have an expression like               Integrate[ a[x]^2 u[y]^2 + 2 a[x] b[x] u[v] v[y] + b[x]^2 v[y]^2 , y]      Now in the output I want to replace               Integrate[u[y]^2,y]       by `I11` etc. Using `/.` did not do the job. Can anyone please enlighten me?


title: CompilationTarget->"C" crashes the kernel

text: **Major deviation from my original post** I realize that the long code I originally had was very discouraging to debug and did not attract any answers. So I have decided to revamp this question significantly (I hope this is acceptable). Please visit the edit history for older versions of this question. **Game Plan** I hypothesize that there are multiple errors in my script the is causing the kernel to crash. But since I can not identify them all at this time, I plan to identify one problem at a time, get solution, implement it in my code and repeat the process of identifying the next problem and posting it on this page, till all the issues are resolved. **Problem 1.** The following code compiles fine:               a=Compile[{{p1,_Real,0},{p2,_Real,0}},Max[0.,Min[p1,10.]-p2],RuntimeAttributes->{Listable}];          b=Compile[{{p1,_Real,0},{p2,_Real,0},{p3,_Real,0},{p4,_Real,0}},       Max[0.,Min[(20.-p1) 5.-p2-p3,10.]-p4],RuntimeAttributes->{Listable}];          ab=Compile[{{p1,_Real,0},{p2,_Real,0},{p3,_Real,0},{p4,_Real,0},{p5,_Real,0}},        Min[a[p1,p5],b[p2,p3,p4,p5]],RuntimeAttributes->{Listable},        CompilationOptions->{"InlineExternalDefinitions"->True}];          f=Compile[{},Module[{k0=Table[0.,{10}]}, ab[k0,k0,k0,k0,k0]],CompilationTarget->"C",       CompilationOptions->{"InlineExternalDefinitions"->True}];      But when I execute `f[]`, the kernel crashes. I am guessing, it is to do with mixing Scalars with Vectors in the `a` and `b` functions. But that is what I thought `Listable` takes care of. Any thoughts?


title: How do I solve a PDE with a strange boundary condition?

text: How do I solve the PDE with boundary value like this $$u(t,x,y)=0, \textrm{when } F(x,y)=0$$ using DSolve? As a specific example, I want to solve heat equation $$\frac{\partial u}{\partial t}=\alpha\left(\frac{\partial^2 u}{\partial x^2}+\frac{\partial^2 u}{\partial y^2}\right)$$ with a strange boundary condition $u(t,x,y)=0$ where $x^6+y^4=1$. (Or I want to solve it numerically with a strange closed curve.)


title: Complement change order of elements

text: Consider this example:               Complement[{a, y, c, d, e}, {a, c}, {d}]     (*{e, y}*)      I was expecting the result to be               (*{y,e}*)      why Complement reorder the resulted list? Any idea how to get the desired results using Complement? Thanks.


title: How to find rows that have maximum value?

text: Suppose if I have following list               {       {10,b,30},       {100,a,40},       {1000,b,10},       {1000,b,70},       {100,b,20},       {10,b,70}     }      How to find rows that have max value in 3rd column, in this case               {       {1000,b,70},       {10,b,70}     }


title: Minimum in a nested list

text: I have a nested list of {x,y,z} and I want to find out the values of x and y where z is minimum. I can write a nested For loop and do it               mya = {{0, 1, 10}, {1, 1, 20}, {0, 2, 5}, {1, 2, 15}}          For[i = 1, i <= Length[mya[[All, 3]]], i++,      If[mya[[All, 3]][[i]] == Min[mya[[All, 3]]], Print[mya[[i]]]]]      I get the desired output:               {0, 2, 5}      I know this problem is simple, but if someone can tell me a more elegant way to do it, it will be helpful as I wanna do it for a very large list.


title: Syntax highlighter shows error for Manipulate when it's inside a Block or a Module

text: I'm putting my new copy of Mathematica 10 through its paces and I noticed a weird change in the colouring scheme that I find very annoying, and I'd like to get some insight into why it's happening. The change happens, as far as I can tell, for variables that have been set in some scoping construct which are then used inside of a Manipulate command. Thus, for example, the code               Module[      {A = 1},      Manipulate[       Plot[        A Sin[k x]        , {x, 0, 20}        ]       , {k, 1, 10}       ]      ]      renders differently in the Mathematica 9 and 10 frontends: ![enter image description here](http://i.stack.imgur.com/j33Jq.png) Playing around in Edit > Preferences > Appearance > Syntax Coloring > Errors and Warnings, the error class that this is attributed to is > Variables that will go out of scope before being used though what that means exactly isn't very clear to me. Therefore, I have some questions:   * Is this in fact an incorrect usage? If so, why, and what alternative construct should I use? (I notice, in particular, that in version 10 the red colour is displayed for Block and Module but not for With.)   * Why did this only start happening in version 10? Which version is right?   * If this sort of code is OK, can I safely disable this sort of error marking? What risks does that entail?


title: Numerical solution NDSolve for SIR model

text: I'm trying to numerically solve the SIR model. This should be simple but I'm can't understand why this is not working:               b = 1;     g = 0.4;     NDSolve[      {S'[t] == -b *X[t] * S[t],       X'[t] == b*X[t]*S[t] - g*X[t],       R'[t] == g*X[t],       X[0] == 0.01,       S[0] == 0.99,       R[0] == 0},      {S[t], X[t], R[t]},      {t, 0, 20}      ]               {{S[t]->InterpolatingFunction[{{0.,20.}},<>][t],X[t]->InterpolatingFunction[{{0.,20.}}, <>][t],R[t]->InterpolatingFunction[{{0.,20.}},<>][t]}}


title: Rearrange cells without cut-paste

text: When working in a Mathematica notebook, I often want to reorder cells. Most of the time, I am adding cells at the bottom of the notebook, until I realize it may be better to insert this calculation at an earlier point, between existing cells. > Is there a convenient way to reorder cells in a Mathematica notebook without > having to cut and paste? Ideally, I would like to be able to drag cells by their bracket, possibly holding a modifier key. I've searched through the internet in general and this StackExchange in particular and come up with nothing.


title: Is there really a bug in the following code, taken from the reference documentation for PetersenGraph?

text: PetersenGraph[5, 2, EdgeLabels -> {8 \[UndirectedEdge] 9 -> "hello"}]      appears to evaluate perfectly, as expected, but in my version 9.0.1.0, the option `EdgeLabels -> {8 \[UndirectedEdge] 9 -> "hello"}` is marked in red (as well as the preceding comma), as if it is a syntax error. This happens for all predefined graphs I've tried so far. Either this is an interface bug, or I've managed to mess up my syntax highlighting somehow. Can anyone confirm or deny this behaviour?


title: How to change start and end date of DateListPlot with Manipulate?

text: Let's say I have a one dimension list `d` with length `L`. The $x$-axis in the plot starts from `{2013, 8, 28 + start}` and ends in `{2013, 8, 28 + end}`, and I want to change the `start` and `end` date with `Manipulate`. So               d[[1]] (*--> 2013/8/28*)          d[[2]] (*--> 2013/8/29*)      So I think it would be:               Manipulate[       DateListPlot[d, {{2013, 8, 28 + start}, {2013, 8, 28 + end}}],       {{start, 0}, 0, L},       {{end, L}, 0, L}     ]      But when I plot it, it gives me an error when `a>3` because the day of the date is greater than `31` (I think). How would be the correct way to do this?


title: Changing mouse appearance at notebook level

text: Ideally, I'd like to change the mouse pointer appearance(s) at notebook level, from a styleseet. However, I'd be satisfied only by changing its color. This is the main issue keepeing me away from dark themes: the pointer becomes hard to find. There seems to be an option "MousePointerAppearance" but I don't know how/if it works.


title: NDSolve`ImplicitRungeKuttaGaussCoefficients doesn't work

text: I am using Mathematica 9.0 on Ubuntu. I tried the first example from this documentation page, but it returns unevaluated:               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];          NDSolve`ImplicitRungeKuttaGaussCoefficients[4, 50]          (* ==> NDSolve`ImplicitRungeKuttaGaussCoefficients[4, 50] *)      What is the problem ?


Title says it all. How do I count a number of primes(say smaller than N) that does not contain 5?


title: Adding labels on ArrayPlot and coloring rows

text: I need to add lables on the right from ArrayPlot for each row and color the black square of each row depending on values from two list. Color list has a numbers in some range and should be mapped using Color Scheme.               s={{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 1, 1, 0}, {1, 1, 1, 1, 0, 1, 1, 1, 1, 0}, {1, 1, 1, 1, 0, 1, 1, 0, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 0}, {1, 1, 0, 1, 1, 1, 1, 0, 1, 1}, {1, 1, 0, 1, 1, 0, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 0, 1, 1}, {0, 1, 1, 1, 1, 0, 1, 1, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 0, 1, 1, 0, 1, 1, 0}};     ArrayPlot[s, Mesh -> True]     labels = {638/2835, 37/432, 3/40, 1/16, 1/14, 1/20, 1/16, 8/81, 1/14, 3/40, 37/432, 1/27};     colors = {0.00, 0.74, 0.79, 0.86, 0.81, 0.93, 0.86, 0.67, 0.81, 0.79, 0.74, 1.00};


title: Animate crashes Mathematica

text: I'm editing my post by giving all the code I have until now. I'd like to write a program which "unravels" randomly and piece by piece a given image. At the moment, I'm using an image randomly created with Image[] (endImage), and I'm starting with a grey background (whitePart and beginImage). I divide the image in partNumber x partNumber parts (here 10):               partNumber = 10;     allParts = Flatten[Outer[List, Range[1, partNumber], Range[1, partNumber]], 1];     endImage = ImagePartition[        Image@RandomReal[1, {400, 400}]        ,        400/partNumber];     whitePart = Image@Table[0.5, {400/partNumber}, {400/partNumber}];     beginImage = Table[whitePart, {partNumber}, {partNumber}];      (* After that, I create a random ordering of the unraveling of the parts with *)               replaceOrdering = RandomSample[allParts];      (* Then, a short function which replaces `beginImage` part number `indexNumber` with `endImage` part `indexNumber`: *)               replacePartWithNumber[tableOfParts_, indexNumber_] :=      ReplacePart[tableOfParts,       replaceOrdering[[indexNumber]] ->         endImage[[Apply[Sequence, replaceOrdering[[indexNumber]]]]]]      (* Creation of the list with recursion: *)               stage[1] = replacePartWithNumber[ beginImage, 1];     stage[n_] := replacePartWithNumber[stage[n - 1], n]      (* which finally gives the `Animate` command: *)               Animate[      ImageAssemble@stage[n]      ,      {n, 1, Length@replaceOrdering, 1}      , DefaultDuration -> 10      , AnimationRepetitions -> 1]      This works for values of `partNumber` till ca. 25. But with `partNumber = 40` or `=50`, Mathematica crashes immediately... Any idea why this is? Any help greatly appreciated!


title: Permuting elements within a list

text: I have               s = {2, 3, 5, 7, 1, 4, 6}  (* always with diffente elements in {1,2....7}*)     l = Length[s]     n = 3      and `n` tells us that we want to select 3 positions in the list `s`, and permute them within the full list. For example,               a = RandomSample[Range[l], n]      Suppose we obtain `a = {2, 6, 4}` and we apply a random permutation to these positions obtaining `{4, 6, 2}`. Then Position 2 goes to position 4   Position 6 goes to position 6   Position 4 goes to position 2 obtaining               s = {2, 7, 5, 3, 1, 4, 6}      What´s a simple (and comprehensible) way without using an auxiliary list. ### Edit After reading MrWizard an Yi-Wang answers: (I like the `s[[a]] =s[[b]]` of MWizard, and the use of permutations and rule of Yi-Wang, but I think that a simpler an more comprehensible way is               s = {2, 3, 5, 7, 1, 4, 6}     n = 3     Print["BEFORE -> ", s]     choice = RandomSample[Range[Length[s]], n]     choicepermuted = RandomSample[choice, n]     s[[choice]] = s[[choicepermuted]]     Print["AFTER ->  ", s]


title: How to get information during evaluation of a Mathematica script?

text: I have a Mathematica script               table=ParallelTable[f[u],{u,0,40,.5}]     Export["filename.csv",table]      that computes and exports a table of a rather complicated function f. I execute it using the "math -script table.m&" command. As it takes a very long time to calculate this table, I would like to abort the calculation. Is there any way, to obtain the information that has already been calculated so far?


title: CustomTicks - Changing NumberPoint -> ","

text: How can I change the number point from `.` to `,` in `CustomTicks` ? The _Mathematica_ built-in function               NumberForm[Plot[…],NumberPoint -> ","]      doesn't work any more, if you use e.g. `LinTicks`.


title: Is matrix multiplication automatically done in parallel in Mathematica 9?

text: In good old _Mathematica_ versions _(5.2, 6.0)_ , matrix multiplication was automatically done in parallel. For example, on an 8-core machine, define two square real matrices:               m1 = Table[Random[Real], {256}, {256}];     m2 = Table[Random[Real], {256}, {256}];      The total CPU time used in all cores to compute a dot product is:               Tsingle = Timing[m1.m2][[1]]      > 0.010999 Second The real time needed for the calculation is:               Tparallel = AbsoluteTiming[m1.m2][[1]]      > 0.001546 Second For large matrices, the ratio is almost equal to the number of cores (8):               Tsingle / Tparallel      > 7.114489004 Repeating the same calculation in newer _Mathematica_ versions _(8.0, 9.0)_ gives `Tsingle` equal to `Tparallel`, which seems to indicate that new _Mathematica_ versions dropped automatic parallelization of the _Dot_ command. Is this true?   I would be thankful if anyone can advise how to regain this functionality, i.e. compute `Dot` products in parallel (automatically or manually).


title: How could I make an Excel-like table?

text: I am looking to build a simple Excel type of a table with four columns. I have spent some time researching _Mathematica_ documentation, but haven't come across a way to implement that. Here is a picture of what I am aiming to achieve:   1. I'd like to be able to add new rows to this table by specifying frequency and probability values   2. I'd like the result to be a product of multiplication of freq. and probability.   3. I'd like to increment index as the new rows are added to the table and decrement when rows are deleted   4. I'd like to be able to remove rows by specifying an index number. Can somebody please point me in the right direction of where do I begin; e.g., _Mathematica_ docs or _Mathematica_ SE threads ) I would greatly appreciate any help! ![What I am looking to build:](http://i.stack.imgur.com/9oEdE.jpg)