title: Classifying poker hands by pattern matching

text: 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 *)


title: Tools for Stability/Automatic Error Analysis in Mathematica

text: 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.


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

text: `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?


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

text: 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.


title: How to remove ConditionalExpression from output

text: 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]


title: Converting a nested for loop from MATLAB

text: 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;


title: Debugging Mathematica Code

text: 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?


title: How do I invoke the default complexity function?

text: 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!


title: Definite and Indefinite integral give different results for piecewise function

text: 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?


title: Considerations when determining efficiency of Mathematica code

text: 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)


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

text: 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


title: Find limit of Interpolated function

text: 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.


title: Simplifying expression on power

text: 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.


title: single root of a cubic function

text: 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


title: How do I manipulate a 3D point plot?

text: 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?


title: SetterBar divider style in Manipulate on a Mac

text: 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`?


title: integration on real domain only!

text: 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] >


title: Trouble fitting an explicitly complex model with the TransformedFit package

text: 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.


title: How to efficiently find positions of duplicates?

text: 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 *) >


title: Dynamic application of several polynomials

text: 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;


title: Rotation matrix $\to$ quaternion

text: 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 |


title: Block diagonal matrix

text: 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.)


title: Using PlotLegends

text: 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.


title: Morphing Graphics, color and location

text: 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.


title: How can I find the Fourier series from discrete data?

text: 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.


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

text: 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.


title: Citation of the algorithms used in FindGraphCommunities

text: 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.


title: Parallelization of distinct array write access from subkernels

text: 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.


title: Constrain movement of Locator (increased t-value)

text: 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!


title: Ordering oscillators with negative powers: Infinite loops

text: 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.


title: What is my problem with MeshFunction?

text: 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?


title: How to make Mathematica script executable?

text: 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"


title: Running "Animate" Using a Button

text: 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.


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

text: 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)


title: Displaying the roots of a complex function using ListCurvePathPlot

text: 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.


title: How to start Mathematica kernel without loading init.m?

text: 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`?


title: Gradient from Vectors type

text: 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?


title: Simplify doesn't simplify HypergeometricPFQ with exact arguments

text: 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?


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

text: **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?


title: Applying Labeled Option to Multiple Options

text: 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.


title: PlotStyle with Table

text: 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?


title: How to make a stereogram in Mathematica?

text: 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)


title: Numerical integration of Hankel functions

text: 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.


title: Speed up iterated manipulations of a graph / table

text: 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}]


title: How to plot two sets of data on one ListLinePlot

text: 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?


title: Finding eigenvalues of a $1500\times1500$ matrix

text: 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_?


title: How to move differentation before the integral?

text: 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


title: Solving a nonlinear PDE with Mathematica10 FEM Solver

text: 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 π}        ];


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

text: 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`?


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

text: 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.


title: How to create function that classifies sample data

text: 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,...}.


title: Approaches For Creating Cycle Plots in Mathematica

text: 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.


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

text: 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:


title: function returning 0

text: 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]


title: Use Pattern with Vectors in Assumptions

text: 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]`.


title: Export an image as a double precision TIFF

text: 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.


title: How to blend two photos in Mathematica?

text: 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


title: Solve gives solution with ComplexInfinity -> number

text: 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?


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

text: 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}}}} >


title: Matrix manipulation

text: 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.


title: Adding contour lines to a 3D plot?

text: 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)


title: Slide show - how to autorun manipulate

text: 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.


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

text: 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.


title: How to create new "person curve"?

text: 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.


title: Make a text with a transparent background in Graphics

text: 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?


title: Numerical Integration with InverseErfc

text: 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.


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

text: 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)?


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

text: ========== 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?


title: DownValues Type Access and Timing

text: 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**


title: FontSubstitutions: how do they work?

text: 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?


title: Check that a relational expression is true for all complex numbers

text: 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)?


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

text: 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?


title: How to programatically save a notebook created by CreateDocument

text: 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?


title: cannot open WSMLink

text: 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?


title: Distance between two line segments in 3-space

text: 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?


title: Reshape vectors exactly like in MATLAB

text: This gives a 64×1 column vector in _Mathematica_ :               F := Flatten[ArrayFlatten[     ArrayFlatten[      Table[Subscript[f, i, j, k, l, m,        n], {i, 0, 1}, {l, 0, 1}, {j, 0, 1}, {m, 0, 1}, {k, 0, 1}, {n,         0, 1}]]]] // MatrixForm      as `F=(1:64)'` does in MATLAB. In MATLAB, `reshape(F,16,4)` gives a 16×4 matrix, where _column_ 1 is the first 16 elements of `F`, column 2 the 17th to 32nd, etc. In _Mathematica_ , the best equivalents for reshaping seem to be the top two answers here. But when I apply either of these commands, I do not get a 16×4 matrix that's constructed like `reshape` in MATLAB. Instead I get a 16×4 matrix where _row_ 1 is the first four elements of F, etc. I have tried adding transpose operations in every location imaginable, and still can't get my _Mathematica_ output to match the MATLAB. I've also tried wrapping `List[]` around the definition of `F` to make `F` appear like a row instead of a column, but everything I do seems to not work. Any help is much appreciated!


title: Forcing evaluation of ArgMax

text: How to force evaluation of `ArgMax` before its output gets used in `Solve`? Background: I'm trying to solve for the Nash equilibrium in various games using Mathematica. As a minimal example, I tried a Cournot competition game that I can solve by hand. It should be simple: for each of two players use `ArgMax` to find the optimal action given some conjectured action by the other player, then equate the chosen action to the conjectured action for each player and use Solve to find the equilibrium actions. The code I tried is               $Assumptions = {p, qa, qb, qachosen, qbchosen} >= 0     p[qa_, qb_] := 1 - qa - qb     qachosen[qb_] = ArgMax[qa*p[qa, qb], qa]     qbchosen[qa_] = ArgMax[qb*p[qa, qb], qb]     Solve[{qachosen[qb] == qa, qbchosen[qa] == qb}, {qa, qb}]      The output gives the warning > Solve::dinv: "The expression ArgMax[qa (1-qa-qb),qa] involves unknowns in > more than one argument, so inverse functions cannot be used" and does not give the answer. In the above example, ideally `qachosen` would become the function `(1-qb)/2`, `qbchosen` would be `(1-qa)/2` and the Solve output would be `qa=1/3, qb=1/3`. It seems forcing evaluation of `ArgMax` before applying `Solve` should do the trick, but `Evaluate[Argmax[...]]` returned the same thing as `ArgMax[...]`.


title: Solving an exponential inequality with parameters

text: Can I use _Mathematica_ for solving the inequality given below?               b^(x/2 - 3/2) - b^(ax) - 2c > 0      where b, a, c are the parameters. I want to find out for what range of x it is true. If it is possible, could you guide me on what I should try?


title: Find condition under which variables fall away

text: I have a somewhat lengthy expression, looking like               expr = 1 + x + b + Pi + 2*a      Is there some way of generating a relationship between `a` and `b` that makes the parameters fall away? In the example above, that condition could look like `a -> -b/2` or `2*a == -b`, because inserting that yields the new expression               expr2 = 1 + Pi      which is independent of both `a` and `b`. Note that the relationship contains only the two variables; it leaves the terms not involving them intact (namely `x`), in other words: `a` can depend only on `b` in the desired solution (if there is one of course). I tried my best using the usual suspects (`Reduce`, `Solve`, `SolveAlways`, ...), but couldn't come up with a solution. _Background:_ My expression is a physical quantity that has certain mathematical parameters left in it. Being physical, it may not depend on the choice of the leftover parameters, ergo these parameters are not independent of each other. I would like to get rid of these placeholders, and doing so will tell me something about the physics in the ansatz that lead to the whole calculation.


title: How do I mimic the functionality of "<>"?

text: The Cell expression for:               <>      is               Cell[BoxData["<>"], "Input"]      However similar expressions are parsed into RowBox(s), for example:               ><          Cell[BoxData[RowBox[{">", "<"}]], "Input"]      How do I get expressions like >< to act like <> does?


title: Map of all graphs obtainable with GraphData?

text: I've been trying to put together an answer to another question, but I am stuck, so I decided to post this question instead. Mathematica contains (among its curated data) information on definition, embeddings, and many properties of around 7500 graphs. This is really a wealth of data, however, there are some problems that came with sheer size of information:   * It is difficult to provide the user means for, let's say, selecting a graph, or selecting a group of graph with desired features.   * It is difficult to know what really is in the database. For example, how many graphs are planar? How many are 3-chromatic? To address this issue, my idea is as follows: Create a rectangular map of graphs (that somewhat resembles "heatmaps"), where each graph is assigned a small cell (4x4, 5x5, or so pixels). The whole map should fit in a reasonable small portion of a computer screen. Each cell is colored by a property (user chooses which property) of each graph. (let's say the property could be number of vertices) ![enter image description here](http://i.stack.imgur.com/J7oAR.png) Than user hovers mouse pointer over the map, and gets more info on a particular graph, in this case Coxeter graph: (only default embedding is displayed in the picture, but there could be many other details there) ![enter image description here](http://i.stack.imgur.com/tfwJ2.png) * * * ## How should be the map colored? For detailed info on GraphData[], of course see GraphData[] documentation. Some ideas on candidates for map coloring: Boolean properties:               "Connected" connected     "Disconnected"  disconnected     "Planar"    planar      Numerical properties: (mostly integer numbers, but some could be non-integers, like Harary index)               "VertexCount"           total number of vertices     "EdgeCount"             total number of edges     "FaceCount"             total number of faces (for a planar graph)          "VertexConnectivity"        minimum vertex deletions to disconnect the graph     "EdgeConnectivity"          minimum edge deletions to disconnect the graph     "ConnectedComponentCount"   number of connected components          "ChromaticNumber"               chromatic number     "EdgeChromaticNumber"           edge chromatic number     "FractionalChromaticNumber"     fractional chromatic number     "FractionalEdgeChromaticNumber" fractional edge chromatic number          "BalabanIndex"      Balaban index     "CyclomaticNumber"  minimum number of edges to remove to turn acyclic     "DetourIndex"       detour index     "HararyIndex"       Harary index     "HosoyaIndex"       Hosoya index     "KirchhoffIndex"    Kirchhoff index     "KirchhoffSumIndex" Kirchhoff sum index     "StabilityIndex"    stability index      * * * ## Note Some other MSE questions and answers involving heatmaps: here, here, here. Sorry I can't include my code. But anyway it is not worth publishing, trust me. * * * ## Related visualization concepts Data points triangle: ![enter image description here](http://i.stack.imgur.com/zhT18.png) Parliament charts convey similar visualization concept: ![enter image description here](http://i.stack.imgur.com/csN8s.png) Treemaps use (on top of color) also size of rectangle as a visual code: ![enter image description here](http://i.stack.imgur.com/KEVLw.png) * * * ## Question Is this idea feasible at all? Or good? Please feel free to adjust it, if you maybe have a better solution for the same problem.


title: PlotLegends question

text: Two lists:               line = {{0, 2.15}, {0.05, 2.03}, {0.1, 1.94}, {0.2, 1.8}, {0.3,      1.68}, {0.4, 1.58}};     points = {{0.1009`, 1.206`}, {0.19455`, 1.4569`}, {0.3597`, 1.2315`}};      I'd like to plot the line with the points, and have a legend.               ListPlot[{line, points}, PlotRange -> {0, 2.5}, PlotLegends -> {"line", "points"}, PlotMarkers -> {" ", \[FilledSquare]}, Joined -> {True, False}]      ![enter image description here](http://i.stack.imgur.com/U0YDn.png) Why doesn't PlotLegends pick up the line? Any way around this, other than manually?


title: How to convert long integers in the expression into the products of their prime factors via Mathematica?

text: I have many of the following expressions created by `CForm` of _Mathematica_ :                24612842763116842319872/(5042560366642267*x - 256*(2446745837411900 + 4901398098088043*y - 144207654645973248*z));      Another example for testing:                (-524288*(29427736469514379027531261659072347 + 58899562724319710108573382000184640*y - 1732944474195510410991057714955859184*z))/ Power(5042560366642267*x - 256*(2446745837411900 + 4901398098088043*y - 144207654645973248*z),2)       What is the regular expression rule to use in _Mathematica_ in order to convert all the long integers into the product of their prime factors in _Mathematica_ by function below?               RegularExpression["regex"]      My thoughts are, first extract every long integer, and `FactorInteger` them to obtain all prime factors; then replace the original long integers with product of their prime factors. The target final expression should be usable immediately in C/C++. But I have no idea how to use the regular expression rule.