Coordinates for multiple countries

I am trying to plot polygons for multiple countries, say `"UnitedStates"` and `"Canada"`. US data is generated thus:               coordsUS = CountryData["UnitedStates", "Coordinates"]      and Canadian data thus:               coordsCanada = CountryData["Canada", "Coordinates"]      I want to pass the combination of these two lists into the routines on this page. I cannot figure out how to combine these two lists into a single list of the same structure. The structure is:               {{{a,b},{c,d},{e,f}}}      I know how to combine lists of the following form:               {{a,b},{c,d},{e,f}}       but the extra depth is confounding me. I try putting the latter into a list thus:               l = {{a,b},{c,d},{e,f}}      z = {l}      but that does not work. `AppendTo` does not work either. Help is appreciated. Thanks! -Tony


Is it possible to use infix notation ~ for functions with one argument or more than 2 arguments?

According to a Mathematica textbook, we can write `N[x,n]` by using infix notation as `x ~ N ~ n`. How about other functions with one argument or more than 2 arguments, is it possible?


How can I add a background to a stylesheet?

In version 9 we can set the background to an image, however I'd like to save this into a stylesheet that can be installed.


How to turn a random graph into a matrix

I have constructed a random graph with Mathematica using the `RandomGraph` command. Now I would like to convert this graph to a matrix, but I don't know how. The command `//MatrixForm` just shows the same with "//MatrixForm" so that doesn't help to much either.


Texture mapping and resizing a sphere primitive in Mathematica

**Background Info** In Mathematica, it's only possible to texture map a sphere through the use of `SphericalPlot3D` or `ParametricPlot3D`.               image = Import["MyTexture.jpg"]; (* Pretend this is something you'd use *)          sphere = SphericalPlot3D[1, {theta, 0, Pi}, {phi, 0, 2 Pi},       Mesh -> None, TextureCoordinateFunction -> ({#5, 1 - #4} &),      PlotStyle -> Directive[Texture[image]],      Lighting -> "Neutral", Axes -> False, Boxed -> False];      Now that's all nice and everything. But what if we want multiple spheres on the same exact image, each with an arbitrary size? To position a single sphere is simple:               s1 = Graphics3D[      Translate[First@sphere, {3, 2, 1}],      Lighting -> "Neutral"]      Then you just position each sphere and `Show` them together:               Show[{s1, s2}, PlotRange->{{-5, +5}, {-5, +5}, {-5, +5}}]      * * * **The Issue** That's great and all, but **what if you need each sphere to be a distinct size**? Positioning and sizing regular `Sphere[]` primitives is easy and built directly into their definition. But if I want the same for a _textured_ sphere, I have to jump through all these hoops. Furthermore, it's not obvious how I can achieve this. Any ideas on how I can achieve arbitrary placement and sizing of _textured_ spheres?


Optimizing a simple calculus using a list of matrices - Repeated dot product between a vector and a list of matrices

I want to make the following operation : $$ \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 \end{bmatrix} \mathbf A_1 \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 \end{bmatrix} \mathbf A_2 \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \end{bmatrix} = \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 \end{bmatrix} \begin{bmatrix} 0&1\\ 1&1 \end{bmatrix} \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 \end{bmatrix} \begin{bmatrix} -1&0\\ 0&0 \end{bmatrix} \begin{bmatrix} q_1\\ q_2 \end{bmatrix} \end{bmatrix} = \begin{bmatrix} \dot q_1\\\dot q_2 \end{bmatrix} + \begin{bmatrix} {q_1}^2 + q_2(q_1+q_2)\\ -{q_1}^2 \end{bmatrix}$$ I also want to put the two $\mathbf A_1$ and $\mathbf A_2$ matrices inside a list of matrices `A` in mathematica. So I started creating my list of matrices `A` and did the following :               A={{{0, 1}, {1, 1}},{{-1, 0}, {0, 0}}};     res={{q1, q2}.A[[1]].{q1, q2},{q1, q2}.A[[2]].{q1, q2}};     final={q1p,q2p}+res;      Now, my question : is there a way to optimize the calculation of `res`? The goal is to avoid calling `A[[1]]` and `A[[2]]` independently each time. The perspective is to extend the `A` list to a list of dimension $n \gt 2$ (something like this) : $$ \begin{bmatrix} \dot q_1\\\dot q_2 \\ \vdots \\ \dot q_n \end{bmatrix} + \begin{bmatrix} \begin{bmatrix} q_1 & q_2 & \cdots & q_n\end{bmatrix} \mathbf A_1 \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ \dot q_n \end{bmatrix} \\ \begin{bmatrix} q_1 & q_2 & \cdots & q_n \end{bmatrix} \mathbf A_2 \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ \dot q_n \end{bmatrix} \\ \vdots \\ \begin{bmatrix} q_1 & q_2 & \cdots & q_n \end{bmatrix} \mathbf A_n \begin{bmatrix} q_1\\ q_2 \\ \vdots \\ q_n \end{bmatrix} \end{bmatrix}$$


Using mouse back/forward buttons in Mathematica's help system

I have a generic mouse with back/forward buttons. Those buttons are recognized by the system - I can use `xev` to see that they generate events for buttons number 8 and 9. I am so used to using them for web browsing, that I sometimes end up pressing them when I'm browsing through Mathematica's help system. Is there some way to bind those buttons to the back/forward functions in the help system? I looked around in the settings but haven't found anything. I'm using Mathematica 8.0 in Linux, if this is relevant. Any ideas?


ToDiscreteTimeModel fails following video

Following the systems-modeling video here at about 15 min, 20 seconds in, the presenter (Bob Sanhedrick, I think) shows a model for an "Asteroids-game"-like 2D spacecraft. The model is trivial:               dynamics = {m x''[t] == u1[t], m y''[t] == u2[t]}      or, in state-space form:               spacecraft = StateSpaceModel[       dynamics,        {x[t], y[t]},       {u1[t], u2[t]},       {x[t], y[t]},       t]      > >     {{{0, 1, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 0, 0}}, >      {{0, 0}, {1/m, 0}, {0, 0}, {0, 1/m}}, >      {{1, 0, 0, 0}, {0, 0, 1, 0}}, >      {{0, 0}, {0, 0}}} >   The next step is converting it to a discrete-time model (15:52 in the video):               spacecraftD = ToDiscreteTimeModel[spacecraft, 1, Method -> "ZeroOrderHold"]      This fails (even in the downloaded copy of the video's notebook -- it's not my typo): > >     During evaluation of In[3]:= General::ivar: 0 is not a valid variable. > >> >     During evaluation of In[3]:= General::ivar: 0 is not a valid variable. > >> >     StateSpaceModel[{ >       {{1, 1, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}}, >       {{1/(2 m), 0}, {1/m, 0}, {0, 1/(2 m)}, {0, 1/m}}, >       {{1, 0, 0, 0}, {0, 0, 1, 0}}, {{0, 0}, {0, 0}}, >       Automatic}, >       $Failed, >       {\[FormalK]}, >       SamplingPeriod -> 1] >   Fortunately, I can copy out the failed model explicitly, leaving out the `Automatic`, and reproduce the rest of the demonstration verbatim: ![enter image description here](http://i.stack.imgur.com/mDtz4.png) The question is "why did this fail, and what can I do to fix it." I read the documentation for `TransferFunctionModel` and tried a number of hacks, to no avail. I'd like to know this so that as I go to more advanced models I don't get stuck with something that doesn't have so obvious a workaround.


How to draw a plane parallel to one of the coordinate planes?

Sorry for the fact that I ask actually the same question on three different stackexchange sites (stackoverflow, mathematics and now here), but I need to find an answer to my problem as quickly as possible. The question is how to draw a 3D plot of functions: $$ y + 5 = 0 \\ x + 2y = 0 $$ The first one is a plane parallel to the $oxz$ plane. If anyone has an answer to this, please provide some explanation, not just `Plot3d[y + 5, {x, -20, 20}, ...]`. Thank you.


LF line break instead of CR+LF when exporting text files on Windows

I want my program to always save a text file with unix-style `LF` line breaks (even when _Mathematica_ runs on Windows). But the way the built-in `Export` command works depends on the operating system. For example the following code:               testFile = "newlinetest.txt";     testStringList = {"abc", "abc"};     Export[testFile, testStringList, "List"];     BinaryReadList[testFile]      Linux or Mac OS gives exactly what I want: > {97, 98, 99, 10, 97, 98, 99} Windows adds an extra `CR` symbol: > {97, 98, 99, **13** , 10, 97, 98, 99} Is there a normal way to save text files with unix-style newline on Windows?


ListPlot with high precision

I have a list of numbers, e.g. `{{1.,0``27.698970004336022},{2.,0``27.698970004336015}}` but usually much longer, suitable for `ListPlot`. `ListPlot` however does not display anything, even if I reduce `PlotRange` manually. Obviously the numbers are too small for `ListPlot`. The numbers do indeed represent only noise, the relative deviation of two numerical computations at different precision. I do this because I want a visual ipression of the numerical error of a computation depending on one parameter. Can I give an argument to `ListPlot` or similar in order to force it to display the small numbers and, if not, how can I compactly multiply the second elements in the list by a suitable number to scale the plot range to `0...1`?


Composition of functions using slots

Apolgies if this has been asked and answered, but I'm not even sure what to search for. I have two functions defined as follows:               F[n_]:=Max[Select[Divisors[n],#<=Sqrt[n]&]];     P[n_] := Select[Range[1, 1000], F[#] == n &];      I have two questions:   1. I have read the _Mathematica_ help page on the `#` symbol, and I think I understand most of that. I do not, however, understand what `#` and `&` do in this specific context.   2. How can I write `P[n_ ]` using a single line of code? It doesn't work if I simply copy and paste the definition for F into the definition of P:              P[n_] := Select[ Range[1, 1000], Max[Select[Divisors[n],#<=Sqrt[n]&]] == n &]


Mathematica 10 crashes on copy/paste

Mathematica 10 crashes in the following (simple) situation:               FormulaLookup["gas"]      This command will produce a long list of possible formulas. Then I type the following command below the list (and not run it)               FormulaData[]      When I copy one of the formulas produced by the FormulaLookup command and paste it in the square brackets of the FormulaData command Mathematica crasches. It happens only if the formula list is very long (as in looking for "gas") and not always but almost always. Can someone check if that's a Mathematica bug or some specific problem with my machine? (I'm on windows 8.1).


Classifying poker hands by pattern matching

I am working on this question posed in a _Mathematica_ course revised in 1998. Here are the instructions: > **Poker Hands** > > You are to define and show working examples of a function "`poker[]`". The > function "`poker[]`" should take five integers, each between 1 and 13, and > output the best poker hand. (True poker experts should note that we are > ignoring suits for simplicity.) > > The possibilities from best to worst are: "Five of a kind", "Four of a > kind", "Full house" (three cards of one kind and two of another), "Straight" > (five consecutive, distinct cards), "Three of a kind", "Two pair", "Pair", > and "High card" (the case in which none of the above apply). > > Examples: `poker[1, 2, 1, 2, 1]` should return `"full house"`; `poker[1, 1, > 3, 4, 4]` should return `"two pair"`. > > Hint #1: There are many combinations of two of a kind: the pair might be in > the first two cards, the second two cards, the first and third, and so on. > To deal with this, consider sorting the five arguments before sending them > to a second function with particular pattern definitions. > > Hint #2: Use multiple definitions for this second function, along with > pattern matching. Here are sample definitions for two hands. >   >   >     poker[a_,a_,a_,a_,a_]:="Five of a kind" >   >     poker[a_,a_,a_,b__]:="Three of a kind" >     (* the name b is unnessary, although the BlankSequence is not *) >                 Clear[poker]     poker[0,0,0,0,0];     poker[a_?NumberQ,b_?NumberQ,c_?NumberQ,d_?NumberQ,e_?NumberQ]:=Sort[poker[a,b,c,d,e]]     poker[a_,a_,a_,a_,a_]:="Five of a kind"     poker[b_,a_,a_,a_,a_]:="Four of a kind"     poker[a_,a_,a_,a_,b_]:="Four of a kind"     poker[b_,b_,a_,a_,a_]:="Full House"     poker[a_,a_,a_,b_,b_]:="Full House"       poker[a_,a_,a_,b_,c_]:="Three of a kind"     poker[b_,c_,a_,a_,a_]:="Three of a kind"     poker[b_,a_,a_,a_,c_]:="Three of a kind"       As is evident from the from the error messages and incorrect answers below, I have made a/some mistake(s), even the outputs that correctly identified the "hand" added `Sort[]` to the output. I had at first thought that "hands" were only identified when the four or three similar cards (in the case of Full House) were at the beginning of the sort, however that theory was disproved once the Three of a kind hands were inspected. I have not defined the rest of the "hands" because it became evident that I had made a mistake in the definitions I had already written.               poker[3, 3, 3, 3, 3]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Five of a kind"] -- correct *)          poker[3, 2, 2, 2, 2]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Four of a kind"] -- correct *)          poker[3, 3, 3, 2, 3]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Three of a kind"] -- should be "Four of a kind" *)          poker[1, 2, 1, 2, 1]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Full House"] -- correct *)          poker[1, 2, 2, 2, 1]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Three of a kind"] -- should be "Full House" *)          poker[1, 2, 1, 3, 1]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Three of a kind"] -- correct *)          poker[2, 1, 2, 3, 2]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Three of a kind"] -- correct *)          poker[3, 3, 1, 3, 2]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> Sort["Three of a kind"] -- correct *)          poker[4, 1, 5, 3, 2]     (* (prints) $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>      -> poker[1, 2, 3, 4, 5] -- correctly not identified *)


Tools for Stability/Automatic Error Analysis in Mathematica

I have a longer analytic expression in several variables containing special functions and others. Does Mathematica bring tools - or are there any packages - to examine the stability when I evaluate the expression numerically. I want to understand for which variables the accuracy of the numerical result is lowest in order to see how I can rewrite the expression to improve the result at finite precision. Note that the goal is not to obtain a high accuracy result by telling Mathematica to use more digits. I rather want to have an expression which evaluates accurately using a relatively small number of digits. Since it is not obvious how to achieve this because of the length of the expression I would like to have some help from Mathematica telling me how to optimize the expression.


Bold face formatting for vectors instead of overarrows like latex \mathbf{}?

`OverVector` can be used to make a symbol look like a vector in text sections of documents. I happen to like bold symbols for vectors better, as in latex `\mathbf{x}` output. I've found that I can do, say, `Style[x, Bold]`, but this is actually a very subtle seeming change, and I find it hard to actually notice the difference. Perhaps this is because the default font picked for variables is something quite different from what one gets with `\mathbf`. If this is just a font issue, what's a good font for this sort of output (i.e. like `\mathbf{x}`), and how would it be selected? Also, the `Style` function applies to expressions, whereas I want it to apply to just particular variables (i.e. leaving scalars in regular font), so that when they are used in input, the output comes out in the desired way. Is there a mechanism to declare a variable, and have specific style settings associated with it, so that it is displayed in the desired way?


How can I force points in a list to have distinct x values?

I have a list of points that may be used for linear interpolation using `Interpolation` and need to ensure that no two points have the same $x$ value, since, if they do, `Interpolation` reports errors: ![enter image description here](http://i.stack.imgur.com/gSEgZ.png) Ideally I'd like to simply tweak such points just enough, that their control points don't shift visibly, but that they satisfy `Interpolation` (e.g. by adding a very small number to one of the offending points). Alternatively, perhaps a different _Mathematica_ interpolation function or different options for `Interpolation` avoid this error. I've tried randomizing the points a bit, using various methods, but I get strange behavior, including briefly jagged plots (e.g. when changing settings for `iorder`) and eventual unresponsiveness of the control points (they just won't move).               Manipulate[      (*pts = MapAt[# + RandomReal[NormalDistribution[0, 10^-4]] &,         pts, -1];*)      (*pts={RandomReal[{#[[1]]-.0001,#[[1]]+.0001}],#[[2]]}&/@pts;*)          Plot[Interpolation[Prepend[pts, {0, 0}], InterpolationOrder -> iorder][x], {x, 0, 1}],      {{pts, {{.2, .1}, {.4, .2}, {.6, .3}, {.8, .25}, {1, 0}}}, Locator},      {{iorder, 3, "InterpolationOrder"}, Range[3], SetterBar}]      In context, I switch among even more curve fitting methods (e.g. Bezier, etc.), so dropping points is not an option, nor is moving them perceptibly, or skipping them.


How to remove ConditionalExpression from output

I need define the function with parameter so I could directly generate a power series expansion. The problem is that in some cases ConditionalExpression appears in output. Here is my code:               S[x_, l_] :=        (C[1] +           Integrate[            E^(2 Sum[t^i/i, {i, 1, l - 1}])*(1 - t)^2*              Sum[(l - i*2)*t^i, {i, 1, l - 1}]/((t - 1)*t^l),             {t, 1, x}])*        x^(l - 1)*E^(-2 Sum[x^i/i, {i, 1, l - 1}])/(1 - x)^2;           Table[S[x, i], {i, 2, 3}] // TableForm     CoefficientList[Series[S[x, 2] , {x, 0, 3}], x]     CoefficientList[Series[S[x, 3] , {x, 0, 3}], x]     CoefficientList[Series[S[x, 3][[1]] , {x, 0, 3}], x]


Converting a nested for loop from MATLAB

In MATLAB I have the following series of nested `for` loops that update a matrix. (It's not my code, but someone else's that I'm trying to replicate - I don't know why `i` starts at 0, for example, and I don't think it needs to, since `k` can be specified by the user.)               [n,d] = size(var1);     for i = 0:k         for j = 0:k             var1(i+1,d-j) = var1(i+2,j+2);         end     end          for i = 0:k         for j = 0:k             var1(n-i,j+1) = var1(i+2,j+2);         end     end          for i = 0:k         for j = 0:k             var1(n-i,d-j) = var1(i+2,j+2);         end     end      `k` is some variable that is less than both `n` and `d`. In terms of size, `k` is about 100 and `n` and `d` are about 1000. I've had a look over the Q&A - Alternatives to procedural loops and iterating over lists in Mathematica - for avoiding/rewriting nested loops. However, I'm not sure what to do to apply that guidance here. I think I'm being confused by the reference to `(i+1,d-j)`. The non-Mathematica part of me wants to use nested `For[]`s and `Part[]`s, but that can't be the best/fastest/most efficient way, certainly with the sequence of them shown above. Here's a basic example...               var1 = RandomInteger[{0, 5}, {1000, 1000}];     {n,d} = Dimensions[var1];     k = 100;


Debugging Mathematica Code

In various integrated development environments, such as Microsoft Visual Studio, there is an integrated debugger where you can step through code sections, examine the state of variables and figure out where things are going wrong. With more complex Mathematica programs a debugger would be an extremely valuable asset. I was wondering what people use to debug Mathematica programs? Is Wolfram Workbench the only/best solution?


How do I invoke the default complexity function?

Documentation on `ComplexityFunction` says: > With the default setting `ComplexityFunction->Automatic`, forms are ranked > primarily according to their `LeafCount`, with corrections to treat integers > with more digits as more complex. I need to use this default function on its own, not in `Simplify` or `FullSimplify`. Can I invoke it from my code? If no, could you give me a custom function that behaves as close to the default function as possible? Thanks!


Definite and Indefinite integral give different results for piecewise function

I have the following function: $$ f(q,y)= \begin{cases} \tfrac{11720+p}{37791360} & -11720<p<-7720 \\ 0 & \text{True} \end{cases} $$ where $p = 443\ y-777600\ \sin^{-1}\left(\frac{q \lambda }{4 \pi }\right)$. _Mathematica_ Code:               f[q_,y_]=Piecewise[               {{(11720+443 y-777600 ArcSin[(q λ)/(4 π)])/37791360,                 -11720<443 y-777600 ArcSin[(q λ)/(4 π)]<-7720}},                 0]      Now, if I take an indefinite integral over `y`,               weird[q_, y_] = Integrate[f[q, y], y]      which gives $$ g(q,y)= \begin{cases} \frac{293 y}{944784}+\frac{443 y^2}{75582720}-\frac{5}{243} y\ \sin^{-1}\left(\frac{\text{qy} \lambda }{4 \pi }\right) & -11720<p<-7720 \\ 0 & \text{True} \end{cases} $$ I can then evaluate this function at my endpoints `{-1,1}` to get the definite integral. However, I could also have _Mathematica_ run the definite integral directly.               weirder[q_, y_] = Integrate[f[q, y], {y, -1, 1}]      which gives ![something really big](http://i.stack.imgur.com/cEpwf.png) Plain Text Version:               \[Piecewise]    (293-19440 ArcSin[(q \[Lambda])/(4 \[Pi])])/472392             907/86400<ArcSin[(q \[Lambda])/(4 \[Pi])]<=1253/86400     (1/33483144960)(-111170729+29544134400 ArcSin[(q \[Lambda])/(4 \[Pi])]-1209323520000     ArcSin[(q \[Lambda])/(4 \[Pi])]^2-12006144000 I Log[4     \[Pi]]-604661760000 Log[4 \[Pi]]^2+12006144000 I Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]+1209323520000 Log[4 \[Pi]] Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]-604661760000 Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]^2)  7277/777600<ArcSin[(q \[Lambda])/(4 \[Pi])]<=907/86400     (1/33483144960)(147938569-37142841600 ArcSin[(q \[Lambda])/(4 \[Pi])]+1209323520000 ArcSin[(q \[Lambda])/(4 \[Pi])]^2+18226944000 I Log[4 \[Pi]]+604661760000 Log[4 \[Pi]]^2-18226944000 I Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]-1209323520000 Log[4 \[Pi]] Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]+604661760000 Log[I q \[Lambda]+Sqrt[16 \[Pi]^2-q^2 \[Lambda]^2]]^2)   1253/86400<ArcSin[(q \[Lambda])/(4 \[Pi])]<12163/777600     0   True      This result, depending on my value of `q`, is different that the result given by the indefinite integral. Specifically of note are the log terms, which did not appear in the indefinite integral. Why is the definite integral different from subtracting the end points of the indefinite integral? Which of these results should I trust?


Considerations when determining efficiency of Mathematica code

I have two segments of code that do the same thing and I want to determine the which is more efficient. What are the considerations when determining efficiency of Mathematica code?   * Correctness/Equality of code segments   * `AbsoluteTiming` vs `Timing` ... **Why?**   * Clearing the cache   * Memory footprint (speed vs size) ... **Any suggestions on how to measure this?**   * **More?** Any useful packages out there to assist in this? * * * **Hypothetical Code Segment 1**               numbers = {}; For[i = 0, i < 100, i++, AppendTo[numbers, i]]; numbers      * * * **Hypothetical Code Segment 2**               Range[0, 99]      * * * **Testing Code**               (* Test Equality *)     Print["Equality: ",          numbers = {}; For[i = 0, i < 100, i++, AppendTo[numbers, i]]; numbers ==          Range[0, 99]]          (* Timing Comparison *)     iterations = 10000;          times = Map[{           AbsoluteTiming[            numbers = {}; For[i = 0, i < 100, i++, AppendTo[numbers, i]]; numbers            ][[1]],          AbsoluteTiming[            Range[0, 99]            ][[1]]          } &, Range[1, iterations]];     {times1, times2}  = Transpose[times];          PrintStats[times_] :=           Print["Sum: ", Fold[Plus, 0., times], "  Min: ", Min[times],        "  Max: ", Max[times], "  Mean: ", Mean[times], "  StdDev: ",        StandardDeviation[times]]          PrintStats[times1];     ListPlot[times1, PlotRange -> All]     Histogram[times1]          PrintStats[times2];     ListPlot[times2, PlotRange -> All]     Histogram[times2]      _Results:_ ![enter image description here](http://i.stack.imgur.com/vVfC1.png)


How to turn a set of strings which represent a list into a 2D list

I have a set of data read in from a larger CSV file. I want it to match the format I have from another analysis. It is structured as a series of strings with letters and numbers Here it is copy-pasted from Mathematica               {"{H, 1}", "{H, 2}", "{H, 3}", "{Mg, 1}", "{Mg, 1}", "{Mg, 1}", "{C, \     1}", "{C, 1, H, 1}", "{N, 1}", "{N, 1, H, 1}"}      I want to convert it to:               {{"H", "1"}, {"H", "2"}, {"H", "3"}, {"Mg", "1"}, {"Mg", "1"}, {"Mg",        "1"}, {"N", "1"}, {"N", "1", "H", "1"}}      I've tried `Read` and `StringToStream` but I haven't been able to do what I need. * * * I've also solved it. I wasn't on the right track, once I looked at the simple string manipulation tools after posting the question the solution jumped out at me.               data = Map[StringTrim[#, ("{" | "}") ...] &, data];     data = Map[StringSplit[#, ","] &, data]     data = StringTrim/@data


Find limit of Interpolated function

I have an interpolated function               f = Interpolation[data]      I would like to calculate limits such as               Limit[(f[1.5 + h] - f[1.5])/h, h -> 0]      I just get errors.


Simplifying expression on power

I want to understand the behavior of Mathematica for the following code.               E^(-m0 + e1/2 + 1/2 (-e1 - e2) + e2/ 2 + (e1 + e2)/2) /. {Power[E, a___] -> Power[E, Expand[a]]}      I expected to see               E^(-m0 + e1/2 + e2/2)      but instead, Mathematica returns               E^(-m0 + e1/2 + 1/2 (-e1 - e2) + e2/ 2 + (e1 + e2)/2)      Why is it? If there is any suggestion, could you reply to me? Thanks a lot.


single root of a cubic function

As it can be shown that the function **f(x)=3x^3-9x+1** has a single root in the interval abierto (0,1). Try to solve using Newton Raphson method, but that is more than a demonstration calculation


How do I manipulate a 3D point plot?

I currently have a recursion done in 3D. At the moment, I am able to manipulate the points, but I cannot use "Joined->True" to connect them Currently this is what I have               z[1, t_] := {1, 1, 1};     A3[t_] := {{1, -t, 0}, {t, 1, -t}, {0, t, t + 1}}     W[t_] := Inverse[(IdentityMatrix[3] + A3[t])];     z[n_Integer, t_] /; n > 0 := W[t].z[n - 1, t];          Manipulate[      ListPointPlot3D[Table[z[n, t], {n, 1, 10}], Mesh -> Full,        Joined -> True, PlotRange -> All, InterpolationOrder -> 1], {t, 0,        1}]      Any idea on how to connect the points?


SetterBar divider style in Manipulate on a Mac

MMA 9.0.1 MacOSX "Mavericks". This issue is apparently mac specific. The issue of this post is illustrated here, for example. In a `SetterBar` control straight out of a `Manipulate`, there are no dividers, though the default appearance in other contexts is to have them. I prefer to have them and don't know why that design decision has been made, but anyway. I found a simple way to restore them using the `Paneled` option for `Manipulate` (which happened to produce other beneficial styling effects):               Manipulate[       Panel@view, {{view, 3, "Fruit:"},          {1 -> "Apples", 2 -> "Pears", 3 -> "Medlars"}, SetterBar},        AppearanceElements -> None, Paneled -> True]          Manipulate[       Panel@view, {{view, 3, "Fruit:"},          {1 -> "Apples", 2 -> "Pears", 3 -> "Medlars"}, SetterBar},        AppearanceElements -> None,  Paneled -> False]          Panel@     Manipulate[       Panel@view, {{view, 3, "Fruit:"},          {1 -> "Apples", 2 -> "Pears", 3 -> "Medlars"}, SetterBar},        AppearanceElements -> None, Paneled -> False]      ![Output of code above](http://i.stack.imgur.com/aEZo5.jpg) My question: is there a better way to get the dividers back from within a `Manipulate`?


integration on real domain only!

i am trying to integrate a real valued function. For some reason, _Mathematica_ gives an answer in the complex domain. I'd be grateful for your answers. Here is the integral:               Integrate[(-(Cos[b*s] - (2*Sin[b*s]*(a*D - b*C))/(a^2 + b^2))/E^(a*s))^2, {s, 1, ∞},        Assumptions -> Element[s, Reals]]      _Mathematica_ produces the following: > >     ConditionalExpression[1/4 >         (1/a + 1/(2 a - 2 I b) + 1/(2 a + 2 I b) + (-1 + E^(-2 a))/a + >         (-1 + E^(-2 (a + I b)))/(2 (a + I b)) + >         (-1 + E^(-2 a + 2 I b))/(2 a - 2 I b) - >         (2 (b C - a D)^2 E^(-2 (a + I b)) (-2 b^2 E^(2 I b) + >           a^2 (-1 + E^(2 I b))^2 + I a b (-1 + E^(4 I b))))/(a (a^2 + > b^2)^3) + >         (4 (b C - a D) E^(-2 a) (b Cos[2 b] + a Sin[2 b]))/(a^2 + b^2)^2), >       Abs[Im[b]] < Re[a] && Re[a] > 0] >


Trouble fitting an explicitly complex model with the TransformedFit package

This is follow up from a previous question in which @Oleksandr R. suggested the use of a package he developed for splitting a model and data into real and imaginary parts to avoid a problem with FindFit when it encounters complex solutions. I eventually had success with fitting the model in the previous question but now I have moved on to a more complex model and I'm getting an error I don't know how to interpret. The model is called qres and is defined as:               Clear[ns, ns\[Infinity], m, A, \[CapitalDelta]E, T, a, b, p, qst, \     qobs, R]     \[Theta] = ns/ns\[Infinity];     b = A*Exp[\[CapitalDelta]E/(R*T)];     p = (b/(\[Theta]^-m - 1))^(1/m);          qst = R*T*     Log[Psat[T]/b^(1/m)*(\[Theta]^m/(1 - \[Theta]^m))^((m - 1)/m)] +      R*T*Z[T] + \[Lambda]p;          qobs = FullSimplify[Integrate[qst, ns]]*.039;          qres = qobs - (513.4933382*ns - 98.64056065*ns^2);      Several variables are dependent functions of ns and T:               R = 8.314;     Psat[85.] = 78896.59231;     Psat[100.] = 323767.1859;     Psat[120.] = 1213037.739;     Psat[140.] = 3168227.12;     Z[85.] = -1.584*10^-13*p^2 - 3.494*10^-7*p + 1;     Z[100.] = -6.147*10^-14*p^2 - 2.185*10^-7*p + 1;     Z[120.] = -2.519*10^-14*p^2 - 1.264*10^-7*p + .9997;     Z[140.] = -4.203*10^-21*p^3 + 3.235*10^-15*p^2 - 8.985*10^-8*p + 1;     \[Lambda]p =      Piecewise[{{6540.2, Re[p] <= 68890.88832}},      3.74853*10^-35*p^6 - 3.91100*10^-28*p^5 + 1.60666*10^-21*p^4 -      3.33138*10^-15*p^3 + 3.74416*10^-9*p^2 - 3.12419*10^-3*p +      6723.71];      By choosing values for T and ns as well as guessing at the model parameters ns[Infinity], m, A, [CapitalDelta]E I can see that various parts of the model return the expected numerical results:               T = 140; ns = .5; ns\[Infinity] = 1.3052144404401276; m = \     0.33692827685320603; A = 2907.997380634411; \[CapitalDelta]E = \     -4579.218711936131;     Psat[T]     p     Z[T]     \[Lambda]p     qobs     qres     Clear[T, ns, ns\[Infinity], m, A, \[CapitalDelta]E]       The data to fit the model to are:               Data = {{0, 85, 0}, {0.131592244`, 85, 3.209459459`}, {0.230286428`,      85, 2.432432432`}, {0.255592629`, 85,      2.027027027`}, {0.382123633`, 85, 0.033783784`}, {0.426409484`,      85, -0.743243243`}, {0.516246497`,      85, -1.047297297`}, {0.60102227`,      85, -1.689189189`}, {0.642777502`,      85, -0.540540541`}, {0.749063545`, 85,      0.168918919`}, {0.760451336`, 85, -0.472972973`}, {0.762981956`,      85, 0.27027027`}, {0, 100, 0}, {0.074653293`, 100,      1.689189189`}, {0.111347284`, 100, 1.689189189`}, {0.127796314`,      100, 1.689189189`}, {0.212572087`, 100,      0.033783784`}, {0.269511039`, 100, -1.081081081`}, {0.29481724`,      100, -1.790540541`}, {0.408695144`,      100, -4.189189189`}, {0.523838358`,      100, -5.810810811`}, {0.536491458`,      100, -6.013513514`}, {0.551675179`,      100, -6.081081081`}, {0.58710386`,      100, -6.317567568`}, {0.632655021`, 100, -6.621621622`}, {0, 120,      0}, {0.072122672`, 120, 0.033783784`}, {0.127796314`,      120, -0.878378378`}, {0.258123249`,      120, -1.891891892`}, {0.260653869`,      120, -5.304054054`}, {0.29481724`,      120, -5.574324324`}, {0.349225572`,      120, -6.722972973`}, {0.356817432`,      120, -8.378378378`}, {0.361878672`,      120, -8.344594595`}, {0.372001153`,      120, -8.986486486`}, {0.415021694`,      120, -10.91216216`}, {0.430205415`,      120, -10.70945946`}, {0.474491266`,      120, -12.16216216`}, {0.526368978`, 120, -13.51351351`}, {0, 140,      0}, {0.051877712`, 140, -0.912162162`}, {0.080979843`,      140, -1.385135135`}, {0.111347284`,      140, -2.668918919`}, {0.116408524`,      140, -2.804054054`}, {0.158163755`,      140, -4.391891892`}, {0.169551546`, 140, -5}, {0.187265886`,      140, -5.878378378`}, {0.248000768`, 140, -8.918918919`}};      I have installed Oleksandr R.'s "TransformedFit" package and tried to use it to fit the function qres to the data:               ComplexFit[Data, qres, {{ns\[Infinity], 1.3052144404401276}, {m,      0.33692827685320603}, {A,      2907.997380634411}, {\[CapitalDelta]E, -4579.218711936131}} , {ns,      T}]      I get the error message:               FindFit::nrlnum: "The function value {0.,-69.0731+0.0051321\ (12314.5 +706.69\ (1. +Re       [Plus[<<2>>]])),-115.452+0.00898117\ (11880.9 +706.69\ (1. +Re[Plus     [<<2>>]])),<<45>>,0.,0. +0.0051321\ (0. +706.69\ Im[Times[<<2>>]+Times[<<2>>]]),<<46>>}      is not a list of real numbers with dimensions {96} at {TransformedParameter     $11,TransformedParameter$15,TransformedParameter$12,TransformedParameter         $16,TransformedParameter$13,TransformedParameter$17,TransformedParameter     $14,TransformedParameter$18} = {1.30521,0.,0.336928,0.,2908.,0.,-4579.22,0.}."      I would be grateful for any suggestions.


How to efficiently find positions of duplicates?

Is there an efficient way to find the positions of the duplicates in a list? I would like the positions grouped according to duplicated elements. For instance, given               list = RandomInteger[15, 20]      > >     {3, 3, 6, 11, 13, 13, 11, 1, 2, 3, 12, 8, 9, 9, 4, 15, 5, 6, 9, 12} >   the output should be               positionDuplicates[list]      > >     {{{1}, {2}, {10}}, {{3}, {18}}, {{4}, {7}}, {{5}, {6}}, {{11}, {20}}, > {{13}, {14}, {19}}} >   Here's my first naive thought:               positionDuplicates1[expr_] :=       Position[expr, #, 1] & /@ First /@ Select[Gather[expr], Length[#] > 1 &]      And my second:               positionDuplicates2[expr_] := Module[{seen, tags = {}},       MapIndexed[        If[seen[#1] === True, Sow[#2, #1],           If[Head[seen[#1]] === List, AppendTo[tags, #1];            Sow[seen[#1], #1]; Sow[#2, #1]; seen[#1] = True,            seen[#1] = #2]] &, expr]       ]      The first works as desired but is horrible on long lists. In the second, `Reap` does not return positions in order, so if necessary, one can apply `Sort`. I feel the work done by `Gather` is about what it should take for this task; `DeleteDuplicates` is (and should be) faster. * * * Here is a summary of timings on a big list.               list = RandomInteger[10000, 5 10^4];     positionDuplicates1[list]; // AbsoluteTiming     positionDuplicates2[list] // Sort; // AbsoluteTiming     Sort[Map[{#[[1, 1]], Flatten[#[[All, 2]]]} &, Reap[MapIndexed[Sow[{#1, #2}, #1] &, list]][[2, All, All]]]] // AbsoluteTiming (* Daniel Lichtblau *)     Select[Last@Reap[MapIndexed[Sow[#2, #1] &, list]], Length[#] > 1 &]; // AbsoluteTiming     positionOfDuplicates[list] // Sort; // AbsoluteTiming (* Leonid Shifrin *)     Module[{a, o, t}, Composition[o[[##]] &, Span] @@@ Pick[Transpose[{Most[ Prepend[a = Accumulate[(t = Tally[#[[o = Ordering[#]]]])[[All, 2]]], 0] + 1], a}], Unitize[t[[All, 2]] - 1], 1]] &[list]; // AbsoluteTiming (* rasher *)     GatherBy[Range@Length[list], list[[#]] &]; // AbsoluteTiming (* Szabolcs *)     Gather[list]; // AbsoluteTiming     DeleteDuplicates[list]; // AbsoluteTiming      > >     {40.186208, Null} (* my #1) >     {0.681758, Null} (* my #2) >     {0.214085, Null} (* Daniel Lichtblau *) >     {0.115021, Null} (* Szabolcs's suggested improvement of my #2 *) >     {0.041038, Null} (* Leonid Shifrin *) >     {0.027409, Null} (* rasher *) >     {0.010322, Null} (* Szabolcs's answer *) >     {0.007948, Null} (* Gather - for comparison purposes *) >     {0.000199, Null} (* DeleteDuplicates *) >


Dynamic application of several polynomials

I know how to get the 'resulting image' (y) from the application of a certain function (f) (here represented as the coefficients of a polynomial) over a certain interval (x):               x = Range[27000]/27001.;          f = {25.62, -38.43, 21.81}/9;          y = Map[f[[1]]*#^3 + f[[2]]*#^2 + f[[3]]*# &, x];          ListPlot[y]      How do i get the 'resulting images' from the application of several polynomials (represented as its coefficients) over a certain interval (x)? Considering the representation of those several polynomials to be something like:               polynomials = Map[     {9 + #[[1]] - #[[2]], -#[[1]], #[[2]]} &,     Flatten[Outer[                 List,                 {23.75, 28.02, 32.29, 36.56, 40.83, 45.1, 49.37, 53.64, 57.91, 62.18},                 {13.48, 15.9, 18.33, 20.75, 23.17, 25.6, 28.02, 30.44, 32.87, 35.29}                 ],             1]     ]/9;


Rotation matrix $\to$ quaternion

I found a very good link about quaternions in _Mathematica_ , but I don't know how to create a quaternion from a rotation matrix. Can anyone help me, please? ### Update I need this: > A rotation may be converted back to a quaternion through the use of the > following algorithm. The process is performed in the following stages, which > are as follows: > > Calculate the trace of the matrix T from the equation:                 T = 4 - 4x^2  - 4y^2  - 4z^2         = 4( 1 - x^2  - y^2  - z^2 )         = mat[0] + mat[5] + mat[10] + 1      > If the trace of the matrix is greater than zero, then perform an "instant" > calculation.                 S = 0.5 / sqrt(T)       W = 0.25 / S       X = ( mat[9] - mat[6] ) * S       Y = ( mat[2] - mat[8] ) * S       Z = ( mat[4] - mat[1] ) * S      > If the trace of the matrix is less than or equal to zero then identify which > major diagonal element has the greatest value. > > Depending on this value, calculate the following: > > Column 0:                   S  = sqrt( 1.0 + mr[0] - mr[5] - mr[10] ) * 2;         Qx = 0.5 / S;         Qy = (mr[1] + mr[4] ) / S;         Qz = (mr[2] + mr[8] ) / S;         Qw = (mr[6] + mr[9] ) / S;      > Column 1:                   S  = sqrt( 1.0 + mr[5] - mr[0] - mr[10] ) * 2;         Qx = (mr[1] + mr[4] ) / S;         Qy = 0.5 / S;         Qz = (mr[6] + mr[9] ) / S;         Qw = (mr[2] + mr[8] ) / S;      > Column 2:                   S  = sqrt( 1.0 + mr[10] - mr[0] - mr[5] ) * 2;         Qx = (mr[2] + mr[8] ) / S;         Qy = (mr[6] + mr[9] ) / S;         Qz = 0.5 / S;         Qw = (mr[1] + mr[4] ) / S;      > The quaternion is then defined as:                  Q = | Qx Qy Qz Qw |


Block diagonal matrix

Suppose I have 4 matrices: A, B, C, D, and I want to form a block diagonal matrix from these sub-matrices, i.e. it would look like               MatrixForm[{{A, B}, {C, D}}]      How can I do that? (If I use my above code, A,B,C,D will be perceived as entries and not matrices.)


Using PlotLegends

Please don't answer this with "Just trash `PlotLegends`" or anything like that as I have tried homebrew solutions. I keep running into problems which I can't debug as I'm not super familiar with _Mathematica_. However, to my question: If I have a `ListPlot` with say 6 lists, I can use `PlotLegends -> {x_1, x_2, x_3, x_4, x_5, x_6}` to label each individual one as `x_1, ..., x_6`. However, `x_1` and `x_2` (though different plots) correspond to the same data set (in the experiment I'm doing) and I have them labeled with alternating filled and empty markers (filled triangle/open triangle) and the same color. So what I want is x_1, x_2 with filled/empty triangle and line all colored blue   x_3, x_4 with filled/empty square and line all colored red   x_5, x_6 with filled/empty diamond and line all colored green That is -ftri-etri- (in blue) Set 1   -fsq-esq- (in red) Set 2   -fdi-edi- (in green) Set 3 Is there a way to make a legend that has a line with the filled AND empty marker on it, which I can label TOGETHER giving only 3 entries in the legend? If that makes sense? Sorry if that's confusing.


Morphing Graphics, color and location

I would like to make a small animation : **1-We start with a random distribution of gray points :**               Graphics[{               Black, Rectangle[{-2, -2}, {2, 2}],               Gray,Point /@ RandomReal[{-2, 2}, {4000, 2}]},               PlotRange -> {{-2, 2}, {-2, 2}}]      ![enter image description here](http://i.stack.imgur.com/Yol5O.png) **2-Then I would like that those points progressively color themselves to obtain the following** :               Graphics[{               Black, Rectangle[{-2, -2}, {2, 2}],               Pink,Point /@ RandomReal[{-2, 2}, {1000, 2}],               RGBColor[.4, .4, 1],Point /@ RandomReal[{-2, 2}, {1000, 2}],               Green,Point /@ RandomReal[{-2, 2}, {1000, 2}],               Yellow,Point /@ RandomReal[{-2, 2}, {1000, 2}]},               PlotRange -> {{-2, 2}, {-2, 2}}]      ![enter image description here](http://i.stack.imgur.com/w3a0W.png) Ideally : -the points progressively adopt the color. All at the same time, at the same rate (2 seconds ?) -OR each points suddenly change color but just 100 at a time. **3-Finally, once the point are colored i would like to see them move, to join their piers like such :**                normalRDN[μ_, σ_, No_] :=      RandomVariate[NormalDistribution[μ, σ], No]               Graphics[{       Black, Rectangle[{-2, -2}, {2, 2}],       Pink,Point /@ ((normalRDN[#, .5, 1000] & /@ {-1, -1})\[Transpose]),       RGBColor[.4, .4, 1],Point /@ ((normalRDN[#, .5, 1000] & /@ {-1, 1})\[Transpose]),       Green,Point /@ ((normalRDN[#, .5, 1000] & /@ {1, -1})\[Transpose]),       Yellow,Point /@ ((normalRDN[#, .5, 1000] & /@ {1, 1})\[Transpose])},       PlotRange -> {{-2, 2}, {-2, 2}}]      ![enter image description here](http://i.stack.imgur.com/WWCBL.png) I am not sure of the means available for doing such animations, thus my illustrative codes might not be relevant.


How can I find the Fourier series from discrete data?

I would like to define the function with Fourier series when I just have discrette data. (I don't have a specific function). I can draw the graph using the data, but I don't have a idea how can I get this function. The plot is a periodic. I want to obtain a function that will work like a Fourier series expansion. How can I define such a function? Graph ![enter image description here](http://i.stack.imgur.com/KoApA.png) Horizontal-axis is Time. Vertical-axis is Space.


Roughly how many times per day may WolframAlpha[] be used?

The integration of Wolfram|Alpha seems to be one of the (many!) major features of _Mathematica_ 8. Earlier I was reading this Wolfram Blog archive and noticed quite a few articles talking about the use of this API. But what finally got me to ask my first Stack Overflow question was reading the top ranked answer on this question which uses the programmatic interface to Wolfram|Alpha. There is, to my knowledge, no published information on how much _Mathematica_ users are allowed to use this service.


Citation of the algorithms used in FindGraphCommunities

For my research work I need to put a comparison of different community detection algorithms. Instead of implementing all those algorithms once again, I would like to use the methods already provided by Mathematica. Would anyone help me in figuring out the different algorithms used in FindGraphCommunities. I found there are 6 methods to get the community structures. Among the 6, the method "Centrality" possibly use the same algorithm by Girvan and Newman in 2002 with edge betweenness centrality. And the method "Modularity" works similar to the algorithm proposed by Newman and Girvan in 2004. However, there are different version of the same kind of algorithms in the literature. I would like to put proper citations for these algorithms. How could I find the details of the implementations of all 6 algorithms. Please provide me with the information. Also, please provide me with the link of full documentation of the Function FindGraphCommunities with all the options available to each method. I could not able to find options in the reference documents. Thank You.


Parallelization of distinct array write access from subkernels

I'm working on an implementation of a multivariate FFT, which is (or at least should be) highly parallelizable due to the row-column-algorithm. However, i can't figure out how to implement that. The serialized idea looks like the following               MFFTs[dims_,data_] := Block[{e,f,locdat=data},       If[Dimensions[dims] == {1}, Return[Fourier[locdat]];       , (*else: row column*)         Do[locdat[[e,All]] = Fourier[locdat[[e,All]]], {e,1,dims[[1]]}];         Do[locdat[[All,f]] = Fourier[locdat[[All,f]]];,{f,1,dims[[2]]}];         Return[locdat];       ]     ];      which would take on a sample of e.g. $2^{14}$ data points on a grid of $4\times2^{12}$ samples (quite anisotrope) about `0.089` seconds. Note that the operations in the first loop work on complete distinct sets of data. After that the second `Do`-Loop does also never write on an array entry twice. So that should be parallelizable quite far. However even for that short set of data the code               MFFTp[dims_, data_] := Block[{e, f, locdat = data},       If[Dimensions[dims] == {1},Return[Fourier[locdat]];       ,       locdat = ParallelTable[Fourier[a],{a,locdat}];       Do[locdat[[All, f]] = Fourier[locdat[[All, f]]];, {f, 1, dims[[2]]}];       Return[locdat];      ]     ];      would need about `0.0549` seconds (running on 4 subkernels). Do you know a way to do something similar with the second one (or in more dimensions that would be encapsulated `Do`s) ? Any Usage of `ParallelDo` would require to `SetSharedVariable` the `locdat`, which kills any timing due to synchronization (about `4` seconds in this example using 4 subkernels). Due to the distinct write access it would be nice to be able to write in parallel onto an array in the Master kernel or something like that. ### Edit: Update One little improvement - at least limited to the 2D-FFT is using twice the command `locdat = Transpose[ParallelTable[Fourier[a],{a,locdat}]];` to perform the FFT on each row and column. That won't work for a 3DFFT though. And it doesn't improve the timing that much. As @Ajasja pointed out the bottleneck is the collection of the results, so some kind of `Parallelwrite` would be really great.


Constrain movement of Locator (increased t-value)

Continuing with the code at the end this topic, I am now searching for a way of constraining the movement of the locator so that it doesn't "jump" from one "part" of the graph of f to another. So, if for example the graph of f has an intersection, as in               f[t_] := {Cos[5 t], Sin[4 t]}      then, I'd like the locator to be constrained for increased values of t, so that it "simply" continues the graph of `f` without "jumping" `t`-values. Now, I thus tried, instead of using `fvalues` as defined in the earlier link, to use something like this               Table[{t, f[t]}, {t, 0, 2, 0.1}];      and then to sort it accordingly with               SortBy[fff, Function[f0, Norm[f0[[2]] - #]]      but when I insert this into the second argument of the `Dynamic` of the `Locator`, the constrained movements don't change... Any help, as always, very much appreciated!


Ordering oscillators with negative powers: Infinite loops

I have been working with ordering of oscillators for example $[a,a^\dagger]=1$ and I have a fairly stable code. I have needed to use inverse oscillators for example expressions like $a^m (a^\dagger)^{-n}a^k$ but they are not hard to order because $[a,f(a^\dagger)]=f'(a^\dagger)$. However now I have expressions like $a^{-m}(a^\dagger)^{-n}a^{-k}$. If I attempt to normal order them, the solution is an infinite series (Rosenbaum, D.M.: J. Math. Phys. 10, 1127 (1969)) but if I choose a particular type of ordering, I get a finite series: $$ [a^{-m},(a^\dagger)^{-n}] = \sum_{k=1}^m (-1)^{k-1} k! \binom{m}{k} \frac{\Gamma(n+k)}{\Gamma(n)\Gamma(k+1)} a^{-1} a^{-(m-k)} (a^\dagger)^{-(n+k)} a^{-1} $$ which holds for all positive integer $m$ and $n$. Now if I plug this expression into Mathematica I get an obvious infinite loop because it will keep trying to normal order it i.e. all $a^\dagger$'s to the left and all $a$'s to the right. Is there a way I can tell Mathematica to order it in this particular form for negative integer powers of $a$ and $a^\dagger$ so I get a finite sum? Edit1: The function and the code is too long to paste so here is the pastebin link for the full code. Edit2: Since the code is too long, I will try to explain the gist of the problem as short as I can. I have written a function which when it sees a term like $aa^\dagger$ will change it to $1+a^\dagger a$ because of the commutation relations. This I achieve by something as follows:               func(left___,a,a^\dagger,right___):> 1+ func(left,a^\dagger,a,right)      Now similar to this, I tell the function to do this:               func[left___, InveP[m_, p], InveX[n_, x], right___] :> func[left, InveX[n, x], InveP[m,p],right] - func[left, Sum[(-1)^(k - 1) k! Binomial[m, k] (Gamma[n + k]/(Gamma[n] Gamma[k + 1])) func[InveX[1 + m - k, x], InveP[n + k, p], InveX[1, x]], {k, 1, m}],right]      where `InveX[n,x]` is the operator that represents $(a^\dagger)^{-n}$ and `InveP[n,p]` is the operator that represents $(a)^{-n}$. Now when I do `func[InveP[1,p],InveX[1,x]]` it should give me `InveX[1,x] InveP[1,p] + InveP[1,p]InveX[2,x],InveP[1,p]` according to the commutation relations. But the problem is that now the function will try to order the second term again since I am using `FixedPoint` in the definition of function to make sure everything is properly ordered. And this is why I get infinite loops.


What is my problem with MeshFunction?

I want plot the max value in a sine plot. We can use the following code               Plot[Sin[x], {x, 0, 50}, Mesh -> {{.99}},        MeshFunctions -> {#2 &},        MeshStyle -> {PointSize[Large], Red}]      Why can't `Mesh -> 1` be used to plot the red point? But in a mathematics way, I want to use this code               Plot[Sin[x], {x, 0, 50},        Mesh -> {{1}},        MeshFunctions -> {Boole[(Cos[#] == 0) && (-Sin[#] < 0)] &},        MeshStyle -> {PointSize[Large], Red}]       You can see the `MeshFunction` doesn't work? Why? Then I try some other test. For example,I want to emphasize the point above 0.5 to draw on Red. I use this code               Plot[Sin[x], {x, 0, 50},        Mesh -> {{1}},        MeshFunctions -> {Boole[Greater[#2, 0.5]] &}]       It doesn't work again. So I guess the equation `PrimePi[z] == 2` will give `2 <= z < 3`. To see whether this region can plot in `MeshFunction`, I tried the following:               f[x_, y_] := (x^2 + 3 y^2)*E^(1 - x^2 - y^2)          Plot3D[f[x, y], {x, -2, 2}, {y, -2, 2},        Mesh -> {{1}},        MeshFunctions -> {PrimePi[#3] &}]       ![Mathematica graphics](http://i.stack.imgur.com/DU9XG.png) You can see the plot is weird. So what is my problem with `MeshFunction`? Can I use `MeshFunction` to plot the maximum value in a plot?


How to make Mathematica script executable?

I have the following Mathematica script               #!/global/common/carver/usg/mathematica/8.0/bin/MathematicaScript -script          (* generate high-precision samples of a mixed distribution *)     Print /@ RandomVariate[MixtureDistribution[         {1,2},         {NormalDistribution[1,2/10],          NormalDistribution[3,1/10]}],         10,  WorkingPrecision -> 10]      in the file named test.m. I am running it on the cluster and It works if I run it as math -script test.m. But I'd like to make this script executable. I tried "chmod a+x test.m" but it's not working. I get the error message: command not found after I enter "./test"


Running "Animate" Using a Button

I made the button below for launching an `Animate`, but it doesn't work at all! Why?               Button["Plot", Animate[Plot[k x, {x, 0, 3}], {k, -2, 2}]]      Thanks in advance.


How can I add row and column header images to my TableForm output?

I am experimenting with the Eigenfaces algorithm and have my notes and experimental data collected in a Mathematica notebook. The result of an experimental run is a table of scores, where the smallest score corresponds to the best match of the facial signatures in the database. For example, a test run that matches three "unclassified" face images against a database that contains nine signatures produces a 3x9 list of scores like the following:               {{127.579, 99.0273, 29.9504, 34.6636, 18.359, 76.6986, 118.535, 87.1991, 110.594},      {190.249, 155.089, 75.9139, 118.029, 100.344, 22.9319, 28.5625, 13.7456, 36.53},      {102.811, 80.8411, 58.3028, 26.0953, 31.6592, 107.468, 148.969, 117.58, 142.881}}      I display this in `TableForm` to make it easier to read. I would like to add a column of headers to the resulting table so that each column is headed by the image that generated the signature at that column in the database. And likewise, I would like to add row headers so that each row is headed by the face image that generated that row of scores. For added coolness, it would be nice to highlight the minimum in each row somehow in the output (such as rendering it in a different color). I suspect Mathematica can do all of this but I'm at a loss as to exactly how. Any suggestions? UPDATE: Here is an example of the output formatted using the accepted answer below: ![Example](http://i.stack.imgur.com/0nqcm.jpg)


Displaying the roots of a complex function using ListCurvePathPlot

I have the following algorithm:               B[z_] = ((z*(z - 0.5)*(z + 0.5)*(z + 0.3))/((1 - 0.5*z)*(1 +                0.5*z)*(1 + 0.3*z))) // Rationalize[#, 0] & // FullSimplify;     For[n = 1, n < 5, n++,          roots = {Re[z], Im[z]} /. Solve[B[z] == (I^n), z];          g[n_] := Plot[            Graphics[{AbsolutePointSize[8], {Lighter[Gray], Circle[]}, {Blue,                Tooltip[Point[#], #] & /@ roots},               First@ListCurvePathPlot[roots, PlotStyle -> Blue], Frame -> True,               FrameLabel -> {"Re[z]", "Im[z]"},               PlotLabel -> ("Roots of " <>                  ToString[B[z] == 1, TraditionalForm] <> "\n")},              Axes -> True], {x, -2, +2}];          Print[g[n]]]      The `For` loop is working, but I want to embed all of the graphics in one graphic.


How to start Mathematica kernel without loading init.m?

Is it possible to start Mathematica kernel from UNIX command line without having the init.m loaded, but not by simply deleting or commenting out it before hand? If this is a Mathematica script, is it possible to have the script run and by pass the initialization of running `init.m`?


Gradient from Vectors type

I'm working with `Vectors` type in `Mathematica` 9. For this purpose I use the following command:               Assumptions = v ϵ Vectors[3]      Now I want to find gradient from the next vector expression: $\vec{v}/\mid \vec{v}\mid$, but the usual `Grad` function doesn't work with `Vectors`. I tried this:               Grad[v/Norm[v], v]      Question: Is it possible to find `Grad` or at least `Norm` from variables of `Vectors` type?


Simplify doesn't simplify HypergeometricPFQ with exact arguments

Consider a series: $$\sum_{t=0}^\infty \frac{8^{-11-2t}(22+4t)!}{t!(11+t)!(11+2t)!(32+t)}$$               Sum[(8^(-11 - 2 t) (22 + 4 t)!)/(t! (11 + t)! (11 + 2 t)!) 1/(32 + t),{t,0,Infinity}]      I enter it into Mathematica, and get the following: $$\frac{26880307030942914706481517908268600094665992\sqrt2}{2617883526123366341980485070559163273300330975\pi}\tag1$$               26880307030942914706481517908268600094665992 Sqrt[2]/(2617883526123366341980485070559163273300330975 Pi)      So far so good. Now I change $32$ to `q` and get the new answer: $$\frac{88179{\;}_3 F_2\left(\frac{23}4,\frac{25}4,q;12,q+1;1\right)}{1073741824q}\tag2$$               88179 HypergeometricPFQ[{23/4, 25/4, q}, {12, 1 + q}, 1]/(1073741824 q)      OK, not bad. Let's now do `%/.q->32`. But... it remains in almost unchanged form of $$\frac{88179{\;}_3 F_2\left(\frac{23}4,\frac{25}4,32;12,33;1\right)}{34359738368}\tag3$$ I now try doing `Simplify`, `FullSimplify`, but it doesn't change. I tried checking $(1)$ and $(2)$ for equality with `==`, and still got unevaluated expression. Using `Reduce` over it gave me `True` with strange problem of > Reduce::ztest1: Unable to decide whether numeric quantity /* difference of > LHS and RHS multiplied by denominator */ is equal to zero. Assuming it is. > >> Still, computing difference between ${}_3 F_2\left(\frac{23}4,\frac{25}4,32;12,33;1\right)$ and $\frac{923600316834709429658044469155615723122343517467181056\sqrt2}{230842351450032320669497193036836458276349885044525\pi}$ with `N[...,30]` gives me almost zero ($10^{-74}$), so this function indeed must be simplifiable. So, how do I convince Mathematica to simplify such hypergeometric function expressions?


What is the equivalent of a prototypical Manipulate in lower level functions?

**Background:** In the Mathematica tutorial 'Dynamic Interactivity' I read that there is a way of developing GUIs in Mathematica that do not use `Manipulate`. I want to investigate this further. **Question:** What is the equivalent of `Manipulate[i,{i,1,5,1}]` in 'lower- level' Mathematica functions?


Applying Labeled Option to Multiple Options

First post. Hope it's not ignorant. I am trying to label several data points so I can label them properly on a `ListLinePlot`. I know I can label plots if I am generating data, but I am dealing with experimental data. The end goal is to be able to graph the points, and have everything labeled properly. I am trying to figure out how not to do this the "dumb" way. Here's what I want to label:               litValues =        {"Literature Values (kcal/mol)",         123.34, 214.97, 191.35, 259.66, 335.15, 314.03, 401.75, 497.27};     plot =        ListLinePlot[{Delete[litValues, 1]},          AxesLabel -> {"Atomic number", "Ionization Energy (kj/mol)"}]      If my tone is wonky, excuse me -- I am very tired.


PlotStyle with Table

I want to create a plot style with a table and manipulate the variables in the plot style.               Menge = {g, h};     Manipulate[       Plot[{0.5 x + 1, x}, {x, -1, 5},         PlotStyle -> Table[Opacity[Menge[[i]]], {i, 1, Length[Menge]}]],     {g, {1, 0}},      {h, {1, 0}}]      This code won't work. But when i create the table and simply copy the output it works.   Can someone help me out?


How to make a stereogram in Mathematica?

Given a background and a pattern jpg files, is there a quick and easy way to produce a stereogram by using Mathematica? The following picture was produced from Photoshop, spent about half an hour. ![enter image description here](http://i.stack.imgur.com/7ntt4.jpg) Here is the background tile for creating the blank background below: ![enter image description here](http://i.stack.imgur.com/YTCXr.jpg) and here is a blank background picture of pebbles: ![enter image description here](http://i.stack.imgur.com/rqnWv.jpg)


Numerical integration of Hankel functions

I would like to know how to perform numeric integration for the following type of integrals in _Mathematica_.   For the following integrand, we can not get the symbolic result.               NIntegrate[ y * Integrate[ 1/x * HankelH1[1, k*x] * HankelH2[1, x/k], {x,1,y}],                {y, 1, 2}]         The aim of the integration is to find the real and imaginary parts of the result. Your views and inputs are greatly appreciated.


Speed up iterated manipulations of a graph / table

I am trying to generate a version of Watts' model of cascading shocks to a network following the discussion on p. 20-25 of this article. The basic premise is to use the `RandomGraph` function to generate a graph, then create a table of characteristics on from `VertexList`. The values in the table (`x`) are the vertex number, the 'persuadability' of the vertex, and the current state (0,1). Everyone is at 0 to start, and we put in an initial shock of 5 vertices going from 0 to 1. Then if the ratio of neighbours who are 1s is above the 'persuadability' number, that neighbour changes its state from 0 to 1. **UPDATE 2** The code below does what I want, in that it iterates the cascade and records each step, and also does it for different initial system shocks. The code does most of what I originally asked about - > Ultimately I would like to be able to do the following: > >   1. Use the code to store a table of `x` tables at each iteration. This > could be used to animate the graph later (using > `HighlightGraph[SubGraph[...]]`). > >   2. Use the code to simulate various random shocks on the same graph by > iterating until the table `x` does not change. > >   3. Maybe a nice `Manipulate` interface at some point. > > However, the evaluation takes about 20 minutes, and it also iterates a fixed number of times `iter` instead of sufficient for convergence. So I have some specific questions.   1. Why is the assignment `record[[l]]=x` necessary in the `Table` loop?   2. How can I get the `Table` to iterate till `record[[l]]==record[[l-1]]`? (Mike suggests `FixedPointList`, but I can't seem to get the syntax to work)   3. How can I write the `Do` loop with the `If` statement so I can use `ParallelDo` or similar? (much like the answer here, but with conditions from two lists)   4. What are some other ways to speed this up generally? **UPDATE 3** This part of the code takes about half a second (which seems slow, since it is called every iteration, or 750 times)               nextn = Table[               Drop[VertexList[NeighborhoodGraph[y, neighbourVL[[i]]]], 1], {i,                 1, Length[neighbourVL]}];      This generates a table with each row a list of neighbours of the vertexes in the list neighbourVL. Is there a way to get this list with a faster method? Thanks everyone.                 (* Note 20min evaluation time *)          y = RandomGraph[{100, 150}];     edges = EdgeList[y];     nodes = Partition[        Flatten[Riffle[VertexList[y], Table[{RandomReal[0.7], 0}, {100}]]],         3];     iter = 15;     record = Table[0, {iter}];          output = Table[             shock = Transpose[{RandomSample[Range[100], 5], Table[3, {5}]}];        x = ReplacePart[nodes, shock -> 1];             Table[         converted = Cases[x, {_, _, 1}];              neighbourVL =           Flatten[Table[            Drop[VertexList[NeighborhoodGraph[y, converted[[i, 1]], 1]],              1], {i, 1, Length[converted]}]];              (* Vertex list of neighbours' first neighbours to be evaluated     with If function *)              nextn = Table[           Drop[VertexList[NeighborhoodGraph[y, neighbourVL[[i]]]], 1], {i,             1, Length[neighbourVL]}];              (* Number of neighbours of vertex 1's first neighbour who are 1s *)                  neighbourcount =           Table[Table[            Count[x, {Take[nextn[[i, j]]], _, 1}], {j, 1,              Length[nextn[[i, All]]]}], {i, 1, Length[nextn]}];              threshold =           N[Total[neighbourcount, {2}]/            Table[Length[nextn[[i, All]]], {i, 1, Length[nextn]}]];              Do[               If[threshold[[i]] > x[[neighbourVL[[i]], 2]],             x = ReplacePart[x, {neighbourVL[[i]], 3} -> 1]];, {i,            Length[nextn]}];                   record[[l]] = x              , {l, 1, iter}]             , {50}];               Histogram[Total[output[[All, -1, All, -1]], {2}]]          Manipulate[      Table[HighlightGraph[y,         Subgraph[y, Cases[output[[j, i]], {_, _, 1}][[All, 1]]]]       , {j, 1, 6}], {i, 1, iter, 1}]


How to plot two sets of data on one ListLinePlot

I have two sets of x,y coordinates, and want to plot them both on the same graph. With one set, List1 $= \{ \{ x_1, y_1 \}, \{ x_2, y_2 \},\{ x_3, y_3 \}, \cdots \}$ I can use `ListLinePlot[List1]`. But with a second list, List2 $= \{ \{ u_1, v_1 \}, \{ u_2, v_2 \},\{ u_3, v_3 \}, \cdots \}$ I assumed I'd be able to use something like `ListLinePlot[List1,List2]`, but this seems reserved for when the lists have only one of the coordinates: $\{ x_1, x_2, x_3, \cdots\}$. The data in `List1` has to be connected via a line, as does the data in `List2`, but they mustn't be joined together (i.e. I can't amalgamate them into one list). Anyone know how I can plot both sets on the same graph?


Finding eigenvalues of a $1500\times1500$ matrix

I need to find the eigenvalues of a $1500\times1500$ real symmetric matrix given by $A_{i,i+1}= A_{i+1,i}=-1$ and also $A_{1,N=1500}=-1$ (this is because of a periodic boundary condition used) and all other off-diagonal elements are zero. Also the diagonal elements are non zero, unequal real numbers. According to what you said my matrix is sparse and numeric. How do I do this in _Mathematica_?


How to move differentation before the integral?

I have quite a lot expressions that need to be integrated after switching the integral sign with differentation operator. The additional problem is that the bounds are dependent to one of the variables. So I need to use: $\int_{a(y)} ^{b(y)} {\frac{\partial f(x,y)}{\partial y}}=\frac{\partial}{\partial y} \int_{a(y)} ^{b(y)} f(x,y) dx- \frac{db}{dy}f(x=b,y)+\frac{da}{dy}f(x=a,y)$ How do I achieve this in Mathematica? For now Mathmatica just writes output:               Integrate[D[f[x, y], y], {x, a[y], b[y]}]      in the symbolic form. How do I workaround this? Of course I can write my own function, but I wonder iw Mathematica has some built in functionality I require. Regards


Solving a nonlinear PDE with Mathematica10 FEM Solver

I am trying to solve a system of coupled nonlinear PDEs in a rectangular region with the new FEM solver in Mathematica 10. However, I come across an error stating > NDSolveValue::femnonlinear: Nonlinear coefficients are not supported in this > version of NDSolve. Is there any workaround? I find it hard to believe that this task should not be possible. Do I have to adjust the method of the solver? Here is my complete code:               Ω = Rectangle[{0, 0}, {2, 2}];     pdes={        \!\(     \*SubscriptBox[\(∂\), \(t\)]\(u[t, x, y]\)\) -           Inactive[Laplacian][u[t, x, y], {x, y}] ==          0.6 u[t, x, y] - v[t, x, y] - u[t, x, y]^3,        \!\(     \*SubscriptBox[\(∂\), \(t\)]\(v[t, x, y]\)\) -           Inactive[Laplacian][v[t, x, y], {x, y}] ==          1.5 u[t, x, y] - 2 v[t, x, y]        };     c = {        (** ic **)        u[0, x, y] == Exp[-5 ((x - 3/2)^2 + (y - 3/2)^2)],        v[0, x, y] == Exp[-5 ((x - 1/2)^2 + (y - 1/2)^2)]        (** blank bc = noflux **)        };     {usol, vsol} = NDSolveValue[{pdes, c},        {u, v},         {x, y} ∈ Ω,        {t, 0, 2 π}        ];


Properly ordering the output of FileNames for a directory consisting of files with consecutive integer names

Say I have a number of files in a directory at some location (C:\dir1\dir2\dir3...), and I pull an array of strings corresponding to the file names with the command:               fileList = FileNames["*", "C:\\dir1\\dir2\\dir3"]      Here, the files are named with consecutive integers (`1` through `N`) and the output is automatically sorted like the following:               C:\dir1\dir2\dir3\10.tif     C:\dir1\dir2\dir3\11.tif     C:\dir1\dir2\dir3\12.tif     C:\dir1\dir2\dir3\13.tif     C:\dir1\dir2\dir3\14.tif     C:\dir1\dir2\dir3\15.tif     C:\dir1\dir2\dir3\16.tif     C:\dir1\dir2\dir3\17.tif     C:\dir1\dir2\dir3\18.tif     C:\dir1\dir2\dir3\19.tif     C:\dir1\dir2\dir3\1.tif     C:\dir1\dir2\dir3\20.tif     C:\dir1\dir2\dir3\2.tif     C:\dir1\dir2\dir3\3.tif     C:\dir1\dir2\dir3\4.tif     C:\dir1\dir2\dir3\5.tif     C:\dir1\dir2\dir3\6.tif     C:\dir1\dir2\dir3\7.tif     C:\dir1\dir2\dir3\8.tif     C:\dir1\dir2\dir3\9.tif      For any value `N`, is there an ordering function `p` I can apply to `fileList` (using `Sort[fileList,p]`) to arrange the entries in fileList to obey to proper integer ordering of the file names? Can I supply this ordering function directly to `FileNames`?


Using "Raw MathLink Connections" to create a "Kernel Object"

Mathematica 8.0.0: I am stuck trying to get a Mathematica Mathlink connection from my Windows computer working that should connects to Linux over network (or vice versa) and then launches a Kernel on the remote end (which I want to use to do some calculations on my Windows PC or vice versa). For local connections it works on both operating system and I can use this Mathlink connection to launch a Kernel:               Needs[ "SubKernels`LinkKernels`"]     kernel = FileNameJoin[{$InstallationDirectory, "MathKernel.exe"}];     link = LinkLaunch[kernel <> " -subkernel -mathlink"]          LaunchKernels[link]      I have already tried to create MathLinks on one computer (let's say IP: 192.168.1.1) where the kernel is launched with:               (*Computer which creates the remote link*)     kernel = LinkLaunch[First[$CommandLine] <> " -mathlink"];         LinkRead[kernel];         LinkWrite[kernel, Unevaluated[$ParentLink = LinkCreate["8000", LinkProtocol -> "TCPIP"];]]      But I cannot access this link when I use:               (*Computer which wants to use the remote link*)     link = LinkConnect["8000@192.168.1.1", LinkProtocol -> "TCPIP"]     LinkRead[link]     LinkRead[link]     LinkWrite[link, Unevaluated[$ProcessID]]     First[LinkRead[link]]      Somehow I am also missing authentication informations for the computer which wants to connect in my code but I did not get an example which shows me where to state these credentials.


How to create function that classifies sample data

I want to create expression, that classifies samples ( 4 weather features -> decision). Example training data: ![enter image description here](http://i.stack.imgur.com/XUkx3.png) For the values that i have data for, I can use rules:               fs = {        {0, 0, 0, 0} -> 1, {2, 1, 0, 0} -> 1, {2, 2, 1, 0} -> 1, {0, 2, 1, 1} -> 1,        {1, 2, 1, 0} -> 1, {2, 1, 1, 0} -> 1, {1, 1, 1, 1} -> 1, {0, 1, 0, 1} -> 1,        {0, 0, 1, 0} -> 1, {1, 0, 0, 0} -> 0, {1, 0, 0, 1} -> 0, {2, 2, 1, 1} -> 0,        {1, 1, 0, 0} -> 0, {2, 1, 0, 1} -> 0};     {2, 1, 0, 1} /. fs      Alternatively I can use table/hashmap:               fs[{0, 0, 0, 0}] = 1;     fs[{2, 1, 0, 0}] = 1;     (*etc.*)     fs[{2, 1, 0, 1}]      How can I compute an estimation decision based on closest* existing sample element(s)? > closeness can be defined by any distance function ex: {euclidean > distance,hamming distance,...}.


Approaches For Creating Cycle Plots in Mathematica

I am trying to create a cycle plot in _Mathematica_ , and I am having a hard time finding the right approach to create the visualization. Can anyone give me a few pointers as to how to approach the problem? `ListPlot` seems to be the right way to go, but I have to manually add a placement for the x-axis and it is not ideal. This is what I have done with simulated data:               monday = {{1.1, 3}, {1.2, 3}, {1.3, 2}, {1.4, 1}};     tuesday = {{2.1, 4}, {2.2, 4}, {2.3, 3}, {2.4, 3}};     wednesday = {{3.1, 6}, {3.2, 4}, {3.3, 3}, {3.4, 3}};     thursday = {{4.1, 6}, {4.2, 5}, {4.3, 5}, {4.4, 4}};     friday = {{5.1, 10}, {5.2, 10}, {5.3, 9}, {5.4, 8}};     saturday = {{6.1, 12}, {6.2, 10}, {6.3, 8}, {6.4, 8}};     sunday = {{7.1, 11}, {7.2, 9}, {7.3, 7}, {7.4, 6}};          ListPlot[{monday, tuesday, wednesday, thursday, friday, saturday, sunday},     Joined -> True,     Mesh -> All,     Frame -> True,     FrameTicks -> {{Automatic, All},     {{{1, "Monday"}, {2, "Tuesday"}, {3, "Wednesday"}, {4,        "Thursday"}, {5, "Friday"}, {6, "Saturday"}, {7, "Sunday"}},      None}}]      I do have David Park's Presentations package, and it seems that may be an effective tool for this problem, but I have not really used it very much.


How to grab output from evaluating input cells in a generated notebook

The notebook expression resulting from ...               nb = CreateDocument[ExpressionCell[Defer@Random[], "Input"]];     FrontEndTokenExecute[nb, "EvaluateNotebook"];     NotebookGet@nb      does _not_ include the output of `Random[]` as I might have expected from the `FrontEndTokenExecute` command. Instead `NotebookGet@nb` acts as if `FrontEndTokenExecute` was _not_ evaluated despite its execution in the frontend? I guess this is due to the separation/communication between the frontend and the kernel but can output from evaluations in a generated notebook be grabbed in a single kernel call? See answer below:


function returning 0

Why is my function returning 0?               In[95]:= n = 25;     r[x_, y_] = Sqrt[x^2 + y^2];     \[Theta][x_, y_] = ArcTan[x, y];     f[y] = Piecewise[{{100, 0 <= y <= 1}, {0, -1 <= y <= 0}}];          In[109]:=      c = Table[(2*l + 1)/2*         Integrate[f[y]*LegendreP[l, 0, y], {y, -1, 1}], {l, 0, n}];          In[100]:=      T[x_, y_] =       Parallelize[       Sum[c[[n]]*r[x, y]^l*LegendreP[l, 0, Cos[\[Theta][x, y]]], {l, 0,          n}]]          Out[100]= 0      I don't understand why `T[x,y]` is returning only 0. * * * **Edit 2:** So if I start `l` from 1 and add in `c[[0]]` manual to the sum the code works but something is still going wrong. The top of northern hemisphere is supposed to be held at 100 and the southern hemisphere is supposed to be held at 0. When I plot this for different n, the temperature distribution switches to 100 on the top to 100 on the bottom and similarly for 0. And the 100 on the top is always chopped out. This is n = 25 and n = 23, respectively.               DensityPlot[T[x, y], {x, -1, 1}, {y, -1, 1},       ColorFunction -> "Rainbow",       RegionFunction -> Function[{x, y}, 0 < x^2 + y^2 < 1]]      ![enter image description here](http://i.stack.imgur.com/2rnuq.png) ![enter image description here](http://i.stack.imgur.com/UrVR7.png) What am I doing wrong? Why is 100 chopped off, why is it flipping position at different n, and why do I have to add in `c[[0]]` instead of letting it integrate l = 0 and summing at l = 0? If n is too large, then the image is: ![enter image description here](http://i.stack.imgur.com/0hOb3.png) Edit 3: Here is the code I am using. Try n = 25, n = 35, and n = 50 to see what happens.               n = 35;     r[x_, y_] := Sqrt[x^2 + y^2];     \[Theta][x_, y_] := ArcTan[y, x];     f[x_] := Piecewise[{{100, 0 <= x <= 1}, {0, -1 <= x <= 0}}];          c = Table[(2*l + 1)/2*         Integrate[f[x]*LegendreP[l, 0, x], {x, -1, 1}], {l, 1, n}];          T[x_, y_] =        50 + Sum[c[[n]]*r[x, y]^l*LegendreP[l, 0, Cos[\[Theta][x, y]]], {l,           0, n}];          Plot3D[T[x, y], {x, -1, 1}, {y, -1, 1}, Mesh -> None, Boxed -> False,       ColorFunction -> "Rainbow",       RegionFunction -> Function[{x, y}, 0 < x^2 + y^2 < 1],       PlotRange -> All]          DensityPlot[T[x, y], {x, -1, 1}, {y, -1, 1},       ColorFunction -> "Rainbow",       RegionFunction -> Function[{x, y}, 0 < x^2 + y^2 < 1],       PlotRange -> All]


Use Pattern with Vectors in Assumptions

I had a problem using `Pattern` with `Vectors` in `Assumptions`. Here's how I use `Pattern` in `Assumptions`:               (* Input := *) Simplify[Element[y[i], Anything], Element[y[_], Anything]]     (* Output:= True *)      _Mathematica_ does assume that any variable matching `y[_]` is an element of `Anything`. However, if I replace `Anything` by `Vectors[n]`, _Mathematica_ no longer assumes that:               (* Input := *) Simplify[Element[y[i], Vectors[n]], Element[y[_], Vectors[n]]]     (* Output:= Element[y[i], Vectors[n, Complexes]] *)      in which I expect to get an ouput of `True`. So where is the problem? * * * Update: The problem exists only in v9, in which `Vectors` is introduced as a built-in function. (Thanks Māris Ozols for clarifying it.) Below Michael E2 gave a solution, replacing `Element[y[_], Vectors[n]]` by `HoldPattern@Element[y[_], Vectors[n,Complexes]]`. This partially solves the problem, but it is not what I want, because it does not really assume `y[_]` is a vector. See the following code.               (*Input := *) $Assumptions = {HoldPattern[Element[y[_], Vectors[n, Complexes]]],                     Element[x[1], Vectors[n]], Element[z[_], Vectors[n]]};     (*Input := *) Simplify[{Element[y[i], Vectors[n]], Element[x[1], Vectors[n]],                     Element[z[i], Vectors[n]]}]     (*Output:= {True, True, Element[z[i], Vectors[n, Complexes]]}*)     (*Input := *) TensorRank /@ {y[i], x[1], z[i]}     (*Ouput:=  {TensorRank[y[i]], 1, TensorRank[z[i]]}*)      Above only `x[1]` behaves as a vector, but `y[i]` and `z[i]` not. `HoldPattern` only makes `Element[y[i], Vectors[n]]` true, but will not make `y[i]` a vector. I want `y[i]` to behave like `x[1]`.


Export an image as a double precision TIFF

I would like to save an image as a double precision TIFF image. I have looked and tried many things but no luck. I have been able to import a double precision TIFF from IDL and found that the data was double precision. So the problem is on the export side.               data = RandomVariate[NormalDistribution[], {4, 4}]     pic = Image[data, "Real"]     ImageData[pic]     Export["Real_tiff.tiff", pic]     Import["Real_tiff.tiff", "Data"]      If you run this code you will find that the data is non-integer until it is read back in.


How to blend two photos in Mathematica?

The following two photographs _forest_ and _tiger_ were blended into one with `screen` blending mode in Photoshop. How to accomplish the same result in Mathematica? ![enter image description here](http://i.stack.imgur.com/8MxSm.jpg) Images:1 2


Solve gives solution with ComplexInfinity -> number

I am trying to solve a cumbersome equation using               Simplify[Solve[(d*Cos[Φ]/Sqrt[x (x + J2) (x + J3) (x + J4)])*(1/            x + 1/(x + J2) + 1/(x + J3) +            1/(x + J4) + (x + J2) (x + J3) (x + J4) +            x*J2 (x + J3) (x + J4) + x*J3 (x + J2) (x + J4) +            x*J4 (x + J2) (x + J3)) + x*k0 + k1 + x*k1 + k2 == 0]]      When I plug this into Mathematica 9 I get               {{k2 -> -k0 x - k1 (1 + x) +          d Sqrt[x (J2 + x) (J3 + x) (J4 + x)] (-3 - 1/(            x^2 (J2 + x) (J3 + x) (J4 + x)) +             x (1/(J2 + x) + 1/(J3 + x) + 1/(J4 + x)) - (            1 + 1/((J2 + x) (J3 + x) (J4 + x)^2) +              1/((J2 + x) (J3 + x)^2 (J4 + x)) +              1/((J2 + x)^2 (J3 + x) (J4 + x)))/            x) Cos[Φ]}, {ComplexInfinity ->         x (J2 + x) (J3 + x) (J4 + x)}}      Does anyone know what it means for "ComplexInfinity-> x"? How can complex infinity approach a number? Is this some sort of asymptotic statement?


Generating the set of all three-dimensional binary arrays distinct under rotation and reflection?

How can I automatically generate all possible three-dimensional binary arrays of size $(x_1 \times x_2 \times x_3$) where each array is distinct from all others with respect to rotation and reflection operations around any axis? Is there a straightforward way to do this in Mathematica v9.0? For three-dimensional arrays, rather than using nested lists, perhaps it would be better to use the form: `{{data1, {x1,y1,z1}},{data2, {x2,y2,z2}},{data3, {x3,y3,z3}},...}`. So an example of the set of all three-dimensional array of dimensions $(x_1 \times x_2 \times x_3)$, where $x_1 = x_2 = x_3 = 2$ would be:               coordinateArray = Tuples[{0, 1}, 3];     bitArray = Tuples[{0, 1}, 8];          arrayList = Array[{} &, Length[bitArray]];          For[i = 1, i <= Length[bitArray], i++,       arrayList[[i]] = Partition[Riffle[bitArray[[i]], coordinateArray], 2];     ];      The set of all such three-dimensional arrays of dimensions $(x_1 \times x_2 \times x_3)$, where $x_1 = x_2 = x_3 = 2$ is given by `arrayList` of length (here) $2^8 = 256$:               arrayList      > >     {{{0, {0, 0, 0}}, {0, {0, 0, 1}}, {0, {0, 1, 0}}, {0, {0, 1, 1}}, {0, > {1, 0, 0}}, >       {0, {1, 0, 1}}, {0, {1, 1, 0}}, {0, {1, 1, 1}}}, >      {{0, {0, 0, 0}}, {0, {0, 0, 1}}, {0, {0, 1, 0}}, {0, {0, 1, 1}}, {0, > {1, 0, 0}}, >       {0, {1, 0, 1}}, {0, {1, 1, 0}}, {1, {1, 1, 1}}}, >      ..., >      {{1, {0, 0, 0}}, {1, {0, 0, 1}}, {1, {0, 1, 0}}, {1, {0, 1, 1}}, {1, > {1, 0, 0}}, >       {1, {1, 0, 1}}, {1, {1, 1, 0}}, {1, {1, 1, 1}}}} >


Matrix manipulation

Thank you for looking and answering this question. I am trying to create a new matrix from an old one. Meaning, I have a original matrix that's 20x20. I want to keep the first five lines of the matrix, then from line 6-10 I want to take every other line, meaning line 7 and 9 would be deleted, but also column 7 and 9 need to be deleted. Then from line 11-20, I want to take every 3 lines, so the rows and columns need to be deleted accordingly.


Adding contour lines to a 3D plot?

I am having trouble getting contour lines on a 3D plot (ListPlot3D). I have tried ListContourPlot3D, but that gives me a really weird looking graph with a ton of dfferent levels. What I would like is to get Contour lines on my ListPlot3D so it looks like a topo-map or something. As of now I have a contour map and a 3D plot - in essence I would like to combine them. Here is what the notebook currently looks like: ![enter image description here](http://i.stack.imgur.com/lN9mH.png)


Slide show - how to autorun manipulate

Is there a way to automatically run a manipulate command when you move to a slide ? I am trying to create a presentation and i have a number of slides which have use manipulate and i want these to run/loop when this slide is showing ? Thanks David.


What is the best way to make a plot complete with legends so it is exported-ready for Word?

I want to put my Plot output into an MS Word document without having to edit it in Corel first, so I want to export it ready for Word in vector format complete with legends, expressions, axes, and frames. Is it possible to do that in _Mathematica_ 9? After getting `Plot` output, what procedure should I follow to put it into Word? I want the best quality figures in my Word document with thin colored lines. Here is example of what I to do when I have many curves on one plot, using dashed and dotdashed combination.                 Plot[{Sin[x], Sin[2 x], Sin[3 x], Sin[4 x], 1/x}, {x, 0, 2 Pi},          PlotLegends -> "Expressions"]      I look forward to seeing your examples of multi-curve plots that are Word export-ready.


How to create new "person curve"?

Wolfram|Alpha has a whole collection¹ of parametric curves that create images of famous people. To see them, enter `WolframAlpha["person curve"]` into a Mathematica notebook, or `person curve` into Wolfram|Alpha. You get a mix of scientist, politicians and media personalities, such as Albert Einstein, Abraham Lincoln and PSY ![people](http://i.stack.imgur.com/iDgwn.png) The W|A parametric people curves are constructed from a combination of trigonometric and step functions. This suggests that the images might have been created by parametrising a sequence of contours... which is backed up by some curves being based of famous photos, e.g., the W|A curve for PAM Dirac is clearly based on the Dirac portrait used in Wikipedia. Here's a animation showing each closed contour as the plot parameter $t$ increases by $2\pi$ units: ![Animated Abe](http://i.stack.imgur.com/rHIJT.gif) Since the functions are so complicated, I can't believe that they were manually constructed. For example, the function to make Abe's bow tie is (for $8\pi < t < 10\pi$) ![{x,y}=...](http://i.stack.imgur.com/1cN3f.png)   The full parametric curve for Abe has 56 such curves tied together with step functions and takes many pages to display. So my question is, how can I use _Mathematica_ to take an image and produce a good looking "people curve"? Answers can start from line art and just automatically parametrise the lines or they can start from a picture/portrait and identify a set of contours that are then parametrised. Or any other (semi)automated approach that you can think of. ¹ At the time of posting this question, it has 37 such curves.


Make a text with a transparent background in Graphics

Code first               Graphics[{Thick,       Yellow, Disk[{0, 1}],       Text[Style["abcdeffsgg", 16, Black,          Background -> Transparent], {0.85, 0.65}]       }]      Using Background->Transparent, I expect that the background color of the text is transparent so I thought it should be yellow inside the circle and nothing outside the circle. However, Mathematica does not generate the output in that way. How do I make the text's background inherently transparent?


Numerical Integration with InverseErfc

I am trying to numerically integrate an equation that involves InverseErfc (embedded in the copula defined). The equation looks like the following: $$ \int_0^T \int_0^\infty \int_0^\infty e^{-Ab(s)x-Ar(s)y}\ f(x)\ c(F(x),G(y))\ g(y)\ dx\ dy\ ds\, $$ The function $\ f(x)$ and $\ g(x)$ are the density functions of $\ F(x)$ and $\ G(x)$ respectively, whereas the function $\ c(F(x),G(y))$ represents the copula chosen (in this case it's student-t copula). When combined, the student-t copula function with exponential marginals are called upon in MMA as GGE[Theta_,Alpha_, Beta_] in the program code.               (** Defining values of parameters & expressions **)     cr = 0.5; ar = -1; br = 0; Sigmar = 0.5; Gammar = 1; r0 = 0.0153; Betar = 100;      cb = 0.1; ab = -1; bb = 0; Sigmab = 0.05; Gammab = 1; b0 = 0.04; Betab = 200;     Theta = 0.5; T = 1; Rho = 4; DoF = 3;           compr = Sqrt[(cr ar)^2 + 2 (Sigmar Gammar)^2];      compb = Sqrt[(cb ab)^2 + 2 (Sigmab Gammab)^2];          Ar[s_] := (2 r0 (1 - Exp[-s compr]))/((compr - cr ar) + (compr + cr ar) Exp[-s compr]);      Ab[s_] := (2 b0 (1 - Exp[-s compb]))/((compb - cb ab) + (compb + cb ab Exp[-s compb]);          (** Define the copula - Student-t copula with exponential margins **)     GEE[Theta_, Alpha_, Beta_] := CopulaDistribution[{"MultivariateT", {{1, Theta}, {Theta, 1}},      DoF}, {ExponentialDistribution[Alpha], ExponentialDistribution[Beta]}];          (** Obtaining the density function of the above copula and its Laplace transform **)     GumExpExp := PDF[GEE[Theta, Betab, Betar], {x, y}];     P[u_, v_] := LaplaceTransform[GumExpExp, {x, y}, {u, v}]          (** The following is the expression I would like to calculate **)     chat = NIntegrate[P[Ab[s], Ar[s]], {s, 0, T}]      I have been running the code for 8 hours and up till now there is no output. Can someone please point out what is the mistake or give me a different idea on how to obtain the numerical answer? Your help is much appreciated.


Defining a function by pieces using list of interpolated functions in order to use `FindRoot`

I have two lists with the interpolated functions               list1 = {InterpolatingFunction[{{a1, b1}},<>], InterpolatingFunction[{{a2, b2}},<>],       InterpolatingFunction[{{a3, b3}},<>], InterpolatingFunction[{{a4, b4}},<>]}      which I will think as $\mbox{list1} = \{f_1(x),f_2(x),f_3(x),f_4(x)\}$, and               list2 = {InterpolatingFunction[{{c1, d1}},<>], InterpolatingFunction[{{c2, d2}},<>],       InterpolatingFunction[{{c3, d3}},<>], InterpolatingFunction[{{c4, d4}},<>]}      which I will think as $\mbox{list2} = \{g_1(x),g_2(x),g_3(x),g_4(x)\}$. What I need is to define $$ f(x) = \begin{cases} f_1(x) & a_1 < x < b_1 \\ f_2(x) & a_2 < x < b_2 \\ f_3(x) & a_3 < x < b_3 \\ f_4(x) & a_4 < x < b_4 \end{cases} \quad \mbox{and} \quad g(x) = \begin{cases} g_1(x) & c_1 < x < d_1 \\ g_2(x) & c_2 < x < d_2 \\ g_3(x) & c_3 < x < d_3 \\ g_4(x) & c_4 < x < d_4 \end{cases} $$ in order to find _a_ root of the equation $$ f(x) - g(x) = 0 $$ using the code               FindRoot[{f[x] - g[x] == 0},{x,x0}]      where the intervals $(a_i,b_i)$, $(c_i,d_i)$ are are well ordered (i.e. $a_1 < b_1 < a_2 < b_2 < ... < b_4$), and $x_0 \in [\min(a_1,c_1),\max(b_4,d_4)]$. Here is an example:               list1 = Interpolation /@ Table[{2 i + k, Tan[k]}, {i, 1, 3, 2}, {k, -(\[Pi]/2) + 0.1,       \[Pi]/2 - 0.1, 0.1}];          list2 = Interpolation /@ {Table[{i, i (i + 1/2) (i - 4)}, {i, -2, 5, 0.1}],        Table[{i, 5 (i - 8)}, {i, 6, 9, 0.1}]};          x0 = RandomReal[{-2, \[Pi]/2 - 0.1 + 8}];      In this case, $\mbox{list1} = \{f_1(x),f_2(x),f_3(x)\}$ and $\mbox{list2} = \{g_1(x),g_2(x)\}$. I don't mind if no solution can be found for some $x_0$; what I don't want is to obtain spurious solutions due to extrapolation, or other gimmicks _MMA_ might be using to "glue" the interpolated functions. In this particular example, the root $x \sim 9.43$ would be spurious, since neither $f$ nor $g$ are defined there. $\hskip1.5in$![enter image description here](http://i.stack.imgur.com/BXEMo.png) Thanks for your time. **EDIT** Using @b.gatessucks suggestion, if I define               f[x_] := Piecewise[{{list1[[1]][x], -(\[Pi]/2) + 0.1 < x < \[Pi]/2 - 0.1},        {list1[[2]][x], -(\[Pi]/2) + 0.1 + 4 < x < \[Pi]/2 - 0.1 + 4},         {list1[[3]][x], -(\[Pi]/2) + 0.1 + 8 < x < \[Pi]/2 - 0.1 + 8}}];          g[x_] := Piecewise[{{list2[[1]][x], -2 < x < 5}, {list2[[2]][x], 6 < x < 9}}];      then               sols = Union[x /. FindRoot[f[x] == g[x], {x, #}] & /@         Table[i, {i, -2, \[Pi]/2 - 0.1 + 8, .1}], SameTest -> (Abs[#1 - #2] <= 10^-6 &)]      returns some spurious solution: $\hskip1cm$![enter image description here](http://i.stack.imgur.com/x1nKo.png) Is there a way to automatically drop such solutions (for example generating the grid only where both `f` and `g` are defined)?


How to find all symbols in an expression and perform an operation on them?

========== motivation =========== Suppose, for example, I have an incoming expression like                m = (3-I)x + 4(x y)/(Cos[y])      I want to find all the symbols in the expression ("x" and "y" in this case) without a priori knowledge of what symbols may appear in m.   Perhaps then I want to do something to the symbols, for example, transform each symbol #:               # -> u*#        i.e. I want to obtain from m:               (3-I)u x + 4(u^2 x y)/(Cos[u y])        In this case, I can take this result, expand in u and unitize to get:               Series[(3-I)u x + 4(u^2 x y)/(Cos[u y]), {u,0,1}]/.u->1        a series expansion to first order in both x and y, where terms x^2, y^2, **_and x y_** are dropped. ============================================================== This is just one example though, in general, I want to know how to find the symbols in an expression and do something to them. I've tried things similar to                test = Expand[# /. Not@NumericQ :> ReplaceAll[#, z -> u z]] &;             (5-3 I)x + 2 y^2 //test        But this just returns the input unchanged, I would like it to return                (5-3 I)u x + 2 u^2 y^2        Any help?


DownValues Type Access and Timing

I definitely use so much DownValues structure for some many applications like to replace some common structures in a some way. It seems that DownValues is so fast for access, and set. My question is about complexity under DownValues usages. For take to consideration: Suppose that, I can store in a DownValues **Data** relations between names of persons (short and long text_String) and Choices of whatever (List) such that I could have $n = 10000000$ of these relations and I want to search for names, and likely other operations like add choices for a specific person. I've reading and It seems like DownValues structure has a pattern matching algorithm based on rules to access correctly to values. So I should say that:   * Searching or accessing to specific key is O(n).    * Create a new register, relations is O(1).   * Modify register to set will be O(1) But, I really concern about that, I used DownValues with a lot of data, and definitely it seems, that above statements are wrong. But, I don't find in the documentation comments about it. I'm thinking that in a low-level, DownValues use some king of hashing functions to indexing, in the example case, strings, because it's seems to access be in O(1)(?) or some BST to execute a search with pattern? I don't know. So, I share my doubts about it, and maybe help to others beginners to pay attention a this absolute useful data structure, **DownValues**


FontSubstitutions: how do they work?

I'm puzzled by `FontSubstitutions`. The help says this: > FontSubstitutions is an option for Style and Cell that gives a list of > substitutions to try for font family names. I typed this:               Options[Style, FontSubstitutions]      with the result: > Options::optnf: FontSubstitutions is not a known option for Style. >> OK. So I try the example instead:               Options[$FrontEnd, FontSubstitutions]      and get a list of rules:               {FontSubstitutions -> {"Helv" -> "Helvetica", "Arial" -> "Helvetica",        "Times New Roman" -> "Times", "Courier New" -> "Courier",        "Lucidabright" -> "Times", "Charter" ->  "Helvetica",       "Lucidatypewriter" -> "Courier", "Fixed" -> "Monaco",       "AGaramond" -> "Times", "Avant Garde" -> "Helvetica", "Bodoni" -> "Times",      "Bookman" -> "Times", "Caslon 3 Roman" -> "Times", ...      (Some of these rules are a bit strange - almost like misspellings...) In the tutorial _tutorial/TextAndFontOptions_ , I read: > In addition, you can set FontSubstitutions to be a list of rules that give > replacements to try for font family names. So my interpretation of this is that, when you supply a string for `FontFamily`, _Mathematica_ will, on failing to find any kind of matching font for that string, see if there's a rule for it, and then use the equivalent font given by that rule. However, I've not yet managed to make it happen. Here I try Bodoni. It's not currently active (and the basic face is called Bodoni Book anyway), so it should be substituted by Times. But it appears as Lucida Grande.               Style["The quick brown fox", 60, FontFamily -> "Bodoni"]      ![font substitutions](http://i.stack.imgur.com/JGs0T.png) and I couldn't get any of the rules to be applied. I also tried setting a paragraph of text in a particular font (the terrible Dom Casual, which has a rule replacing it with Helvetica), then closing Mathematica, de-activating the font, then re-opening Mathematica and the document. The paragraph's font reverted to ... Lucida Grande. So, does anyone know how `FontSubstitutions` works?


Check that a relational expression is true for all complex numbers

How can I use _Mathematica_ to check if a statement like $$\left| \frac{\sqrt{1+2z}-2}{2z-3} \right| \le 1$$ is true for all complex numbers $z$? Also, how can I use _Mathematica_ to check such a statement for a subset of the complex numbers (for example, all complex numbers with imaginary part less than zero)?


Custom (physics) dictionary for mathematica (used for word-processing, spell checking)

Is there a dictonary available that contains physics slang like spinor, vacua, gauge etc.?? How would one integrate such a file (or a simple text file containing the words) into the front-end without too much of a hassle?


How to programatically save a notebook created by CreateDocument

I've already written code that generates about 20 notebooks using "CreateDocument" and I was wondering if there exists a method to automatically save them. Is there an easy way to create a notebook and save it programatically, i.e. without manually saving the notebook?


cannot open WSMLink

I'm evaluating Wolfram SystemModeler and I want to explore its capabilities together with Mathematica. Unfortunately, I don't manage to get WSMLink working. In the notebook I'm using I typed               Needs["WSMLink`"]      and pressed Shift+Enter. Mathematica gives me this error message: > Get::noopen: Cannot open > C:\Users\Carlo\AppData\Roaming\Mathematica\Applications\WSMLink\Config.m. > WSMLink::cconf: -- Message text not found -- > (C:\Users\Carlo\AppData\Roaming\Mathematica\Applications\WSMLink\Config.m) I'm new to Mathematica and I don't know where I can start fixing my problem. I checked and the file C:\Users\Carlo\AppData\Roaming\Mathematica\Applications\WSMLink\Config.m does not exist on my computer. Do you have any idea how to fix this?


Distance between two line segments in 3-space

I need to compute the distance between two line segments in a project. After googling, I found this algorithm and used it to implement a _Mathematica_ version:               distSegToSeg[{p1_, p2_}, {q1_, q2_}] :=       Module[{small = 10^(-6), u, v, w,               a, b, c, d, e, D,               sc, sN, sD,               tc, tN, tD},         u = p2 - p1;         v = q2 - q1;         w = p1 - q1;         a = u.u;         b = u.v;         c = v.v;         d = u.w;         e = v.w;         D = a*c - b*b;         sD = D;         tD = D;         If[D < small,            sN = 0; sD = 1; tN = e; tD = c,           sN = b*e - c*d;           tN = (a*e - b*d);           If[sN < 0,              sN = 0.0; tN = e; tD = c,             If[sN > sD, sN = sD; tN = e + b; tD = c;]]];         If[tN < 0,            tN = 0;           If[-d < 0,              sN = 0,             If[-d > a,                sN = sD,                sN = -d; sD = a]],           If[tN > tD,              tN = tD;              If[-d + b < 0,                sN = 0,               If[-d + b > a,                  sN = sD,                  sN = -d + b; sD = a]]]];         sc = If[Norm[sN] < small, 0, sN/sD];         tc = If[Norm[tN] < small, 0, tN/tD];         N[Norm[w + sc*u - tc*v]]     ]      The code is not in good _Mathematica_ style, and it's very slow. Do you have any idea to make this faster? Do you have a better way to compute the distance between two line segments in 3D?