title: Find the centre of FindGeometricTransform

text: I'm interested in using `Solve[]` to find the centre point of rotation (as an $x,y,z$ coordinate point) and axis of rotation (as a vector) from a `TransformationFunction` obtained by using the `Mathematica` function `FindGeometricTransform`. eg:               pts1 = {{-21.365, -1.61273, 2.41973}, {-41.0366, -4.33682, 4.78811},             {-18.1104, -20.673, 7.53}, {-19.804, 3.79904, 21.6102}};          pts2 = {{-17.9409, -3.2446, -7.46078}, {-35.9907, -7.76684, -14.7927},             {-14.3971, -22.658, -4.21113}, {-25.7926, -1.61099, 10.8609}};      `FindGeometricTransform` gives the transformation:               t = FindGeometricTransform[pts2, pts1][[2]]      I posted a similar thread at Mathforum under the topic: How to calculate the 3-D centre point of rotation given the angle of rotation and got the answer: > Then Solve will give you the fixed point, i.e. the centre of rotation: >   >   >      {x, y, z} /. Solve[t[{x, y, z}] == {x, y, z}, {x, y, z}][[1]] >   But when I try and use this get the following message: > During evaluation of In[928]:= RowReduce::luc: Result for RowReduce of badly > conditioned matrix > {{-0.438289,-0.152175,-0.114141,1.80057},{-0.196422,-0.022041,0.0708135,0.32083},{-0.12289,0.142966,0.458519,0.443714}} > may contain significant numerical errors. >> >   >   >     Out[928]= {-5.22037*10^14, 1.37944*10^15, -3.42994*10^14} >   the output is also wrong as the answer should be close to my guesstimate of:               approxCenterOfRotation = {0.05418732005730931`,1.3533759077820666`, -0.1590650885642857`}      However, for some reason I cannot reply to the post on Math Forum to get say that this solution didn't work. This problem can be visualised with the following (NB: I calculated the `axisOfRotation` vector using a different method [i.e. not using `Solve]`, but am still interested in a method using `Solve` to calculate this if possible...):               axisOfRotation(*normalised*) = {0.347494, -0.904472, 0.247341}          viewVector = axisOfRotation*100          Show[          Graphics3D[{Black, PointSize[0.01], Point[approxCenterOfRotation]}],          ListPointPlot3D[{pts1, pts2, t /@ pts1},PlotStyle -> PointSize[0.01]],          Graphics3D[{Blue,Line[{{pts1[[1]], pts1[[2]]}, {pts1[[1]], pts1[[3]]}, {pts1[[1]],       pts1[[4]]}}]}],          Graphics3D[{Purple,Line[{{pts2[[1]], pts2[[2]]}, {pts2[[1]], pts2[[3]]}, {pts2[[1]],pts2[[4]]}}]}],          Graphics3D[{Brown,Line[{{(t /@ pts1)[[1]], (t /@ pts1)[[2]]}, {(t /@ pts1)[[1]], (t /@pts1)[[3]]}, {(t /@ pts1)[[1]], (t /@ pts1)[[4]]}}]}],          Graphics3D[{Orange, Thick, Dashed,Line[{(approxCenterOfRotation +(axisOfRotation*20)),(approxCenterOfRotation + (axisOfRotation*-20))}]}],              PlotRange -> All, BoxRatios -> Automatic, AspectRatio -> Automatic,              Axes -> True, ImageSize -> 700, ViewPoint -> viewVector]      Any suggestions ? * * * Thanks for your solution Sjoerd C. de Vries, but I'm still having problems using it for a similar case:               pts1 = {{-4.1703933347009725`,          1.4117161073762858`, -1.9926556291047952`}, {-22.189270524165632`,          6.791481789144898`, -8.802808787459966`}, {-10.82311078603393`,      -17.22865684593722`, 0.8844690943141205`}, {-9.74367022928643`,          6.269145198021164`, 16.59077697323315`}};          pts2 = {{4.170393334702319`, -1.4117161073741804`,          1.9926556291087356`}, {-10.018009366114274`,          2.942544547202209`, -11.413672837383066`}, {-3.8405873454718273`,      -19.553858138726234`, 4.578554129848027`}, {-7.427598618275446`,          5.792664273078895`, 16.607151377933118`}};          t = FindGeometricTransform[pts2, pts1][[2]]          centreOfRotation = t[{0, 0, 0}]          rotMat = {t[[1, 1, {1, 2, 3}]], t[[1, 2, {1, 2, 3}]],        t[[1, 3, {1, 2, 3}]]}          {rotVec} = NullSpace[rotMat - Transpose[rotMat]];     rotVec          viewVector = rotVec*100          Show[      Graphics3D[{Orange, PointSize[0.02], Point[centreOfRotation]}],           Graphics3D[{Green, PointSize[0.025], Point[pts1[[4]]]}],      Graphics3D[{Green, PointSize[0.025], Point[pts2[[4]]]}],           ListPointPlot3D[{pts1, pts2, t /@ pts1},        PlotStyle -> PointSize[0.01]],       Graphics3D[{Blue,         Line[{{pts1[[1]], pts1[[2]]}, {pts1[[1]], pts1[[3]]}, {pts1[[1]],            pts1[[4]]}}]}],       Graphics3D[{Purple,         Line[{{pts2[[1]], pts2[[2]]}, {pts2[[1]], pts2[[3]]}, {pts2[[1]],            pts2[[4]]}}]}],       Graphics3D[{Brown,         Line[{{(t /@ pts1)[[1]], (t /@ pts1)[[2]]}, {(t /@ pts1)[[1]], (t /@               pts1)[[3]]}, {(t /@ pts1)[[1]], (t /@ pts1)[[4]]}}]}],      Graphics3D[{Orange, Thick, Dashed,         Line[{(centreOfRotation + (rotVec*20)), (centreOfRotation +      (rotVec*-20))}]}], PlotRange -> All, BoxRatios -> Automatic,       AspectRatio -> Automatic, Axes -> True, AxesLabel -> {"X", "Y", "Z"},       ImageSize -> 700, ViewPoint -> viewVector]      The orange point is the point calculated by `centreOfRotation = t[{0, 0, 0}]`, but looking at the graphic, the center point of rotation should lie closer to the two green points. Also, the axis of rotation (`rotVec`) looks incorrect. Any further suggestions?


title: How to evaluate an integral involving normal distribution

text: I want to compute the following integral, in which 5 can be replaced by any natural number. But I found Mathematica keep running forever and cannot evaluate it. I want to ask for some help.               Integrate[      Sqrt[5]/Sqrt[2 Pi] Exp[-5 x^{2}/2] 1/Sqrt[2 Pi] Exp[-y^{2}/2],       {x, -Infinity, Infinity}, {y, x - 1.96/Sqrt[5], x + 1.96/Sqrt[5]}]


title: Is there a function for falling factorial in Mathematica

text: If I had to construct a function for falling factorial in mathematica I'd do something like that (hope I'm not mistaken): > fallfact[x_,k_]:=$\prod_{j=0}^{k-1}(x-j)$ But is there a built-in function for falling factorial in Mathematica?


title: Convolve two sets of (x,y) data sets

text: I have two sets of data in the form               a={{.1,2},{.2,3},{.3,4},{.5,6}}          b={{0,8},{.1,4},{.2,7},{.3,1},{.5,10},{.6,3}}      Both data sets have even spacing, although the `b` dataset has significantly many more data points at higher and lower values of `x`. How do I convolve these data sets? `Convolve[a,b]` only works if I use just the `y` values of the datasets. Is there a way to convolve this data while still keeping these `x` values?


title: Recursion when randomizing elements in a list

text: I want to randomize certain elements of a list; Since the code               list = {a, b, c, d, e, f, g};     list[[{1, 3, 5}]] = RandomSample@list[[{1, 3, 5}]];     list      works fine, I was trying to see if I could speed up things a little bit and have only one call to `list[[{1,3,5}]]` using a pure function The code               list = {a, b, c, d, e, f, g};     (# = RandomSample@#) &[list[[{1, 3, 5}]]];     list      will trigger an infinite recursion. I know that the function evaluates the argument before passing to the function, but the infinite recursion still confuses me. Any thoughts? Thanks


title: Make Plot look like Bloomberg terminal

text: I've always wanted to make my financial `Plot`s look like a Bloomberg terminal. How would I go about making my chart look like one? I am talking specifically about the chart gradient background, the gradient plot fill, the dashed horizontal and vertical markers, and the markers on the right y axis. Here is the image I am using as a template: ![Bloomberg terminal](http://i.stack.imgur.com/H9RrG.gif) Any pointers would be appreciated!


title: Plotting the components of a function that returns a list in different colors without redundant evaluations of the function

text: I have a function `f` which takes a number as input, and returns a list of numbers (the length of the list is constant). `f` is hard to calculate (each evaluation takes a long time). I want to plot the different components of `f` in _different colors_. If I use this command:               Plot[f[x], {x, -2, 2}]      all the lines are drawn in the same color.   If I use this command:               Plot[{f[x][[1]], f[x][[2]], f[x][[3]]}, {x, -2, 2}]      (assuming the list has three components) the lines are drawn in different colors, but the function is called three times the necessary amount. Note that this is a numeric function, it cannot be evaluated with a symbolic argument (i.e. the function definition begins with `f[x_Real]:=`), so there is no use in using `Evaluate` like in this question.


title: vectorized operations is not efficient?

text: Consider the following example:               4.*Mean@Table[ Boole[Random[]^2 + Random[]^2 < 1], {10^6}] // AbsoluteTiming     (*{0.408023, 3.14105}*)          With[{n = 10^6},       4. Mean@Boole@Thread[(RandomReal[1, n]^2 + RandomReal[1, n]^2) < 1]] // AbsoluteTiming     (*{1.460084, 3.14276}*)      I expected the second method to be more efficient since it used vectorized operations, but it works slowly, and I don't know why. Is it possible to make it faster? I used Mathematica 9 on Windows 7.


title: Need to parallelize function f in a iteration

text: I don't have experience using Mathematica for parallel calculation. I need to do something simple to parallelize the calculation of f which is calculate each time n iterates:               f[k_] := Sum[r[j], {j, k}];     SetSharedFunction[f]           r[1] = 1;     f[1] = 2;          Table[r[n] = 2 r[n - 1] + f[n - 1], {n, 2, 4}]      Thanks for your help.


title: Item Resizing when using Locators

text: I am having some difficulty in resizing a Stream Plot when using locators: Whenever I try to resize the Stream Plot, one of the locators instead moves to the cursor.               Manipulate[{StreamPlot[{(      q1 (x - p[[1]]))/((x - p[[1]])^2 + (y - p[[2]])^2)^(3/2) + (      q2 (x - q[[1]]))/((x - q[[1]])^2 + (y - q[[2]])^2)^(3/2), (      q1 (y - p[[2]]))/((x - p[[1]])^2 + (y - p[[2]])^2)^(3/2) + (      q2 (y - q[[2]]))/((x - q[[1]])^2 + (y - q[[2]])^2)^(3/2)}, {x, 0,      10}, {y, 0, 10}, PlotRange -> {0, 10}]},      {{p, {1, 1}}, Locator}, {{q, {1, 1}}, Locator}, {q1, -4, 4}, {q2, -4,4}]      How can I rectify this behaviour?


title: Speeding up TIF import

text: After trying to import a $\approx 2$ GB TIF file with the Import command, I noticed that the process takes $\approx 15$ minutes or so, which seems excessive, especially when compared to other software packages. Attempting to load TIF files $>10$ GB in size can take over an hour. Surely there must be some trick to accelerate the import procedure? If not, can anyone explain to me why this is occurring? Perhaps it is generating an index of the individual images in some inefficient manner? I have a 64-bit system and I'm happy to use an arbitrary amount of memory - speed is what matters to me.


title: find connectivity

text: Imagine a chain of 20 rings, labeled by 1-20 sequentially. We want to make random size sets of numbers randomly chosen from these 1-20 rings. No duplicate numbers are allowed. Example of a set: $\{16,7,11\}$. We want to count the links between the members of different sets. Rules:   1. If we have got one number $N$ in set $A$ and next successive number $N+1$ exists in set $B$ this is called link of length $1$.   2. If the next successive number $N+1$ is not member of any set, we look for the closest successive number $N+m$ existing in other sets, so this is called a link of length $m$.   3. If the next successive number is also in the set $A$, then is a loop, we ignore it.   4. The two ends of the chain, if not member of any set, are dangled, we ignore it. Output = {the number of links of length i}. Example:               clusters = {{2,3,4}, {16,7,11}, {9,20,12,18}}      In `clusters` we have: 1 link of length 1 : `11-12` 3 links of length 2 : `16-17-18, 7-8-9, 9-10-11` 1 link of length 3 : `4-5-6-7` 1 link of length 4: `12-13-14-15-16` and `18-19-20` is a loop to same cluster and `1` is a free end so ignore them. How can I count the links to have:               out1 = {{1,length1}, {3,length2}, {1,length3}, {1,length4}}      Also we need to know the total number of links between two given cluster. for above example we will have:               out2 = {{cluster1-2, 1links},{cluster2-3, 5links},{cluster1-3,0links}}


title: Extracting only complete records from two data sets and combining them

text: I have two data sets:               data1 =     {       {{2004, 1, 1}, 28.0774}, {{2004, 1, 2}, 33.0775}, {{2004, 1, 3}, 33.6817},        {{2004, 1, 4}, 31.41}, {{2004, 1, 5}, 31.6763}, {{2004, 1, 6}, 28.255},        {{2004, 1, 7}, 29.4663}, {{2004, 1, 8}, 28.8583}, {{2004, 1, 9}, 27.3979},        {{2004, 1, 10}, 26.2367}, {{2004, 1, 11}, 25.9692}, {{2004, 1, 12}, 28.7213},        {{2004, 1, 13}, 27.405}, {{2004, 1, 14}, 27.6808}, {{2004, 1, 15}, 29.0129},        {{2004, 1, 16}, 28.65}, {{2004, 1, 17}, 27.6096}, {{2004, 1, 18}, 27.1733},        {{2004, 1, 19}, 30.3533}, {{2004, 1, 20}, 32.5442}, {{2004, 1, 21}, 35.2171},        {{2004, 1, 22}, 35.7233}, {{2004, 1, 23}, 31.0108}, {{2004, 1, 24}, 27.9142},        {{2004, 1, 25}, 26.8617}, {{2004, 1, 26}, 30.0146}, {{2004, 1, 27}, 30.4133},        {{2004, 1, 28}, 29.8754}, {{2004, 1, 29}, 29.8067}, {{2004, 1, 30}, 29.7713},        {{2004, 1, 31}, 27.4904}, {{2004, 2, 1}, 28.6221}, {{2004, 2, 2}, 30.9058},        {{2004, 2, 3}, 28.1475}, {{2004, 2, 4}, 27.0221}, {{2004, 2, 5}, 26.9771},        {{2004, 2, 6}, 26.5542}, {{2004, 2, 7}, 25.5142}, {{2004, 2, 8}, 25.7975},        {{2004, 2, 9}, 28.3658}, {{2004, 2, 10}, 30.0617}     }     data2 =     {       {{2004, 1, 2}, ""}, {{2004, 1, 5}, 33.71}, {{2004, 1, 6}, 33.54},        {{2004, 1, 7}, 33.57}, {{2004, 1, 8}, 34.27}, {{2004, 1, 9}, 34.38},        {{2004, 1, 12}, 34.92}, {{2004, 1, 13}, 34.26}, {{2004, 1, 14}, 34.62},        {{2004, 1, 15}, 33.61}, {{2004, 1, 16}, 35.16}, {{2004, 1, 19}, ""},        {{2004, 1, 20}, 36.21}, {{2004, 1, 21}, 35.53}, {{2004, 1, 22}, 35.12},        {{2004, 1, 23}, 34.94}, {{2004, 1, 26}, 34.41}, {{2004, 1, 27}, 33.99},        {{2004, 1, 28}, 33.63}, {{2004, 1, 29}, 32.86}, {{2004, 1, 30}, 33.16},        {{2004, 2, 2}, 34.02}, {{2004, 2, 3}, 34.2}, {{2004, 2, 4}, 33.06},        {{2004, 2, 5}, 33.26}, {{2004, 2, 6}, 32.49}, {{2004, 2, 9}, 32.91},        {{2004, 2, 10}, 34.03}     }      Sometimes values are missing and sometime both values and dates are missing. I need just the records that are complete and common to both data sets.               data = Transpose[{data1value, data2value}];     mixeddata = {{Date}, data1value, data2value};      How could I write the code for this?


title: Help to solve exponential equation over positive integers

text: I am trying to solve the equation $\frac{4}{9} = \big( \frac{1}{3} \big) ^n + \big( \frac{1}{3} \big) ^m $ with $n$ and $m$ both positive integers. I type into Mathematica the following In:= Solve[4/9 == 1/3^m + 1/3^n && m > 0 && n > 0, n, Integers] which spits out "Solve::nsmet: This system cannot be solved with the methods available to Solve." The solution to the problem is $n=1\:\&\:m=2$ or $n=2\:\&\:m=1$. How can I change my input to have Mathematica come up with this?


title: How do I test for the occurrence of an error message and act on it?

text: I want to see how well some curves fit a data set. If a curve doesn't fit after 100 iterations, I get the error `cvmit`. How do I test for and handle this error within my code?


title: Strange Behavior in Barchart LabelingFunction

text: BarChart formatting algorithm make me loose some time today in V10. Now, `LabelingFunction` do not work beyond some number of Labels. See example:               RandomSeed[1]     barchart[n_]:=         BarChart[RandomInteger[10,{n,3}]                 ,LabelingFunction->(Placed[#1,Center]&)                 ,AspectRatio->0.2,ImageSize->700                 ,ChartLayout->"Percentile"         ]          barchart[33]     barchart[34]      ![enter image description here](http://i.stack.imgur.com/kjN9m.png) After 33, labels disappear! Witch magic parameter can I change to get my labels back? The problem is the same in V10.0.0 for Mac and Win. I wrote to support. If I get some clue I'll post here.


title: How to properly substitute values into variables?

text: I have an array of functions in terms of a[0] through a[n] and I wish to replace the a[]'s with previously calculated values p[0] through p[n], as in below:               p = Table[Chop[NIntegrate[f[t]*wt[t]*Tn[t], {t, 0, 1}]/(Pi/2)], {n, 0, k}];     p[[1]] = p[[1]]/2;          s = Table[Coefficient[pmult[j], tstar[i], 1], {j, 0, k}, {i, 1, k}]          q3=s/.p      What is the best way of doing this? I have tried the Replace[], ReplaceAll[], and /. commands but none seem to be giving me what I want. I just want a[0] replaced with the number contained in p[0], a[1] replaced with p[1], etc. Thanks in advance!


title: Unknown limit of an array of area integrals

text: Could someone explain why Mathematica can't finish computing this limit (this is a limit of an array, when `n -> Infinity` (`n` is an integer), whose elements are area-integrals as shown):                Limit[Integrate[(x^(2n) + y^(2n)) Boole[x^(2n) + y^(2n) < 1], {x, -1, 1}, {y, -1, 1}], n -> Infinity]      In the case when `n=2`, the integral is `Pi/2`, for `n=4` it is `(2 Gamma[1/4] Gamma[5/4])/(3 Sqrt[\\[Pi]])` Thanx


title: Why is Query so much slower than Part?

text: Time for another of these(1),(2) as yet another new-in-10 function appears to have poor performance compared to older alternatives. This time: `Query` appears to be orders of magnitude slower than `Part` when used for simple extraction. For example:               Needs["GeneralUtilities`"]          x = RandomInteger[99, 1*^6];     spans = Span @@@ Partition[Sort @ RandomInteger[{1, 1*^6}, 5000], 2, 1];          Do[x[[s]], {s, spans}]      // AccurateTiming     Do[Query[s][x], {s, spans}] // AccurateTiming      > >     0.00447013 >   >     3.586205 >   Here `Query` is 800 times slower than `Part`. I know that `Part` is well optimized for packed arrays. Perhaps `Query` hasn't been similarly optimized yet. Let's try unpackable data:               x = "a" ~CharacterRange~ "z" ~RandomChoice~ 1*^6;          Do[x[[s]], {s, spans}]      // AccurateTiming     Do[Query[s][x], {s, spans}] // AccurateTiming      > >     0.0106673 >   >     3.594706 >   Alright, that seems to account for some of the difference as `Part` is only 337 times faster than `Query` here, but that is still a huge difference. The reason I was interested in `Query` is that by default it will not fail on out- of-bounds span ranges as `Part` will:               a = Range[9];          a[[5 ;; 11]]          Query[5 ;; 11][a]      > Part::take: Cannot take positions 5 through 11 in {1,2,3,4,5,6,7,8,9}. >> >   >   >     {1, 2, 3, 4, 5, 6, 7, 8, 9}[[5 ;; 11]] >   >     {5, 6, 7, 8, 9} >   It also returns a `Missing` expression for a single part that is out-of- bounds:               Query[12][Range@9]      > >     Missing["PartAbsent", 12] >   This feature is controlled by `PartBehavior`. Perhaps its overhead is high so let's turn it off and try again:               SetOptions[Query, PartBehavior -> None];     Do[Query[s][x], {s, spans}] // AccurateTiming      > >     3.568204 >   Well that doesn't seem to be the case. Thankfully Szabolcs's post in Why is Dataset upset by division by zero? made me take a look at the other options for `Query`. With `MissingBehavior` set to `Automatic` `Query` will apply special rules for certain operators when there are `Missing[]` expressions:               Query[Total] @ {1, 2, 3, Missing[]}       > >     6 >   This should have no role for `Span` however:               Query[2 ;; 4] @ {1, 2, 3, Missing[]}      > >     {2, 3, Missing[]} >   Let's turn it off and time again just to be sure:               SetOptions[Query, MissingBehavior -> None];     Do[Query[s][x], {s, spans}] // AccurateTiming      > >     0.355520 >   It seems we have found the cause of most of the slow-down, yet it makes no sense to me for this to have any effect as there is no special behavior to apply for `Missing` elements in a `Span` operation. With `FailureAction -> None` this comes down to `0.285016` second, or ~27 times slower than `Part` on unpacked data. ### Questions   1. Why would `MissingBehavior` affect the speed of a `Span` operation?   2. Why is `Query` still many times slower than `Part`, even with all special handling turned off?


title: Intersection of any triangle with a circle in Cartesian coordinates

text: I started a notebook dealing with metrics in a triangle and its intersection points by a circle. Up to know I reached the point of having plotted a triangle, a circle with an arbitrary centre and I know the coordinates where they intersect.   Before going further with adding more meaningful circles and more lines I would like to know if there is a better way of finding the coordinates of the points where the triangle intersects the circle.   Here is my code:               eqc[c_, r_] := {(x - c[[1]])^2 + (y - c[[2]])^2 -      r^2}  (*   c: {x,y} coord.centre  r: radius *)      a = {2, 4}; b = {7, 1}; c = {-1, -4}; (* triangle vertices *)     c1 = eqc[{5/2, 4/7}, 3]; (* expression for plotting the circle *)          fctline[a_, b_] :=      Reduce[Det[{{x, y, 1},  (*  Finds equation of a line between 2 points a{x,y} b{x,y) *)                  {a[[1]], a[[2]], 1},                 {b[[1]], b[[2]], 1}}] == 0, y];          lineA = fctline[c, b];  (* fct of line oposite vertex A *)     lineB = fctline[c, a];     lineC = fctline[a, b];          coordpts[c_, line_] :=      Module[{eqns},   (* module computing coords.      intersection of a line with a circle *)       eqns = {c == 0, y - line[[2]] == 0};       {x, y} /. Solve[eqns, {x, y}]];     trpts = Flatten[{coordpts[c1, lineA], coordpts[c1, lineB],      coordpts[c1, lineC]}, 1];          symbolsI = FromCharacterCode /@ (Range[Length@trpts] + 944);     symbolsV = {A, B, C};          plotA = Plot[{Transpose[(y /. Solve[# == 0, y]) & /@ c1]}, {x, -5,      15},  (* triangle to be added next step *)     PlotStyle -> {Black, Black, Black, Blue},     PlotRange -> {{-3, 8}, {-6, 6}}, PlotRangePadding -> 0.5,      AspectRatio -> Automatic,     Epilog -> {     {Red, PointSize[0.01], Point[trpts],      (Text[Style[#, 15], #2 + {-0.2, .2}] & @@@         Transpose[{symbolsI, trpts}])},     {Black, PointSize[0.001], Point[{a, b, c}],      (Text[Style[#, 20], #2 + {-0.3, .3}] & @@@         Transpose[{symbolsV, {a, b, c}}])}}]       To plot the sides of the triangle with lines strictly limited to the sides of the triangle I anticipated a rather repetitive process (ie plot nine segments of lines, six of them with a `Transparent` graphics attributes) but I found in Stack Exchange question 8199 a nice solution to deal with that with less code.               SetAttributes[splitplot, HoldAll];  (* thanks to Simon Woods *)     splitplot[pieces__] := Piecewise[{#}, I] & /@ Unevaluated@pieces     splitplot[{v_, c_}] := splitplot[{v, c}, {v, ! c}]     splitstyle[styles__] :=      Module[{st =      Directive /@ {styles}}, {{Last[st = RotateLeft@st], #}} &]          sideA = Plot[{splitplot[{lineA[[2]],        x < -1 || x > 7}, {lineA[[2]], -1 <= x <= 7}]} ,       {x, -2, 8},      PlotStyle ->      splitstyle[{Transparent, Black}, {Transparent, Black}, {Black}]];     sideB = Plot[{splitplot[{lineB[[2]],        x < -1 || x > 2}, {lineB[[2]], -1 <= x <= 2}]} ,       {x, -2, 8},      PlotStyle ->      splitstyle[{Transparent, Black}, {Transparent, Black}, {Black}]];     sideC = Plot[{splitplot[{lineC[[2]], x < 2 || x > 7}, {lineC[[2]],        2 <= x <= 7}]} ,       {x, -2, 8},      PlotStyle ->      splitstyle[{Transparent, Black}, {Transparent, Black}, {Black}]];          Show[plotA, sideA, sideB, sideC, Axes -> None, ImageSize -> 600]      As you can see I considered the triangle as a set of three lines. That's certainly not elegant but a triangle is not a locust of points than can be determined by a general function as for any conics, function that you can integrate or differentiate. There is perhaps a function for it in higher mathematics and if so may be a built-in (undocumented) in MMA is available.


title: Forcing Interpolation to be smooth at its boundaries

text: I'm looking at a piecewise function of two lines, which has a kink, such as:               f1[p_] := 1.41 * p + 2*^8;     f2[p_] := 1.45 * p + 1.9584*^8;     f3[p_] := Piecewise[{{f1[p], p <= 1.04*^8}, {f2[p], p > 1.04*^8}}];      I want to work with a function which is linear on both sides of the kink like above, but is smooth in a small region around the kink as an approximation to the above function. I'd like to use Interpolation[] to find a smooth function to approximate a region of width delta p around the kink, p = 1.04 * 10^8. However Interpolation can give me a function which will just introduce more kinks out the boundaries with f1 and f2. Is there a way I can enforce boundary conditions on Interpolation[] so that it can give me a smooth function in this region? Edit to clarify: The boundary I'm considering is arbitrary; it is just centered around 1.04*10^8. For example, I tried using a region of width .01*10^8 centered around this value, so my code was:               region = Interpolation[{{1.03*^8, f1[1.03*^8]}, {1.035*^8, f1[1.035*^8]}, {1.045*^8, f2[1.045*^8]}, {1.05*^8, f2[1.05*^8]}}];      But if you plot this, it will not be smooth with the rest of the function (i.e., it doesn't have a slope of 1.41 at p=1.03*^8, and 1.45 at p=1.05*^8. I want to enforce those slopes at those values, or any other arbitrary value).


title: Why does GraphicsGrid rescale 3d plots?

text: In the documentation for `GraphicsGrid`, it says > By default, GraphicsGrid will display graphics at their specified sizes So why does it rescale the 3d plots even if I have set the ImageSize option? For example:               GraphicsGrid@Table[Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}, ImageSize -> 200], {2}, {2}]      gives the scaled 3d plots, regarding I have set the image size ![enter image description here](http://i.stack.imgur.com/NhhWM.png) while it doesn't rescale the 2d plots ![enter image description here](http://i.stack.imgur.com/Yh4hf.png) So why does GraphicsGrid rescale 3d plots?


title: How to define a nestable Baseform function, BaseForm output becomes BaseForm input

text: Mathematica won't change a number's BaseForm recursively:               63969 // BaseForm[#, 16] & // BaseForm[#, 8] & // BaseForm[#, 2] &      Well, I inspected former answers, most of them treated formatting problems, but none of the anwers given treated the nestable aspect. Maybe I'm wrong, and I risk a duplicate. (1) I would like to have a nestable function which allows constructs of the form               63969 // base@16 // base@8 // base@2      This feature might be adopted advantageously within iterative functions : NestList, FoldList, ... * * * ## Edit1 To explain my interest for seamless changes of baseforms               2 ArcCot[GoldenRatio^2^^1111] == ArcCot[2^^1010101010]     2^^1010101010 // BaseForm[#, 4] &      ![curiousSinCosMindmap](http://i.stack.imgur.com/b70Ms.gif) * * * ## Edit2 I tried myself another approch, but it has an disadvantage: `HoldForm` isn't respected               ClearAll@base     base[b_] := Function[# // ReplaceAll[#, BaseForm[x_, _] :> BaseForm[x, 10]] & //           ToString // ToExpression // BaseForm[#, b] &]          testsuite = {5555, BaseForm[5555, 8], HoldForm@Plus[5000, 555],5*BaseForm[1111, 2]}     base@10 /@ testsuite


title: Is there a built-in function to map a list of heads to a list of data?

text: Assume that this built-in function is called `func`. What I want is               func[{f,g},{a,b,c}]      will return the following result:               {{f[a],f[b],f[c]},{g[a],g[b],g[c]}}      I can achieve this by defining a function myself:               myfunc[functions_List, data_] :=          Table[Map[fn, data], {fn, functions}];      But is there some built-in function to achieve the same result? (I have to admit that, after months intermittent reading of `The Mathematica Book` my knowledge is still very limited compared with what exist unknown in the sea.)


title: InputField as part of a Graphics

text: I am building a model for which the user can enter parameter values. I would like to create a "graphical layout" of the model in which I display several InputField-s to enter the numerical parameters, arranged to be shown at the appropriate x-y-locations in my "graphical layout". However, InputFields appear to become non-editable when part of a Graphics object. For example, the following works (of course):               InputField[Dynamic[x]]      However, the next command creates an InputField that cannot be accessed, although the dynamic value still correctly updates when you change the InputField created by the previous command:               Graphics[Inset[InputField[Dynamic[x]]]]      How can I place InputFields at specific coordinates in (or on top of) a Graphics?


title: Functions returns Command Completion Output

text: Is there a function that returns the output as if you invoked Command Completion. To help clarify I am looking for a function that returns the Cell Data as if you invoked `Ctrl`+`Shift`+`K`.


title: How do I append a graph to last column of a table?

text: rmsdata= Partition[ReadList["RMStabledata.txt", Number],29]        > >     {{0, 2.96142, 36.7357, 9.05539, 9, 0, 0, 1, 1, 0, 2, -1, 1, -2, 2, -4, >      2, -3, 1, -5, 1, -7, 1, -6, 0, -7, -1, -9, -1}, {1, 2.68942, >     30.2974, 8.24621, 8, 0, 0, -2, 0, -4, 0, -5, 1, -7, 1, -6, 2, -8, >     2, -9, 1, -10, 0, -8, 0, -7, -1, -8, -2}, {2, 3.04704, 38.8905, 10., >     5, 0, 0, 1, 1, -1, 1, -2, 2, -4, 2, -3, 3, -2, 4, -3, 5, -5, 5, -6, >     6, -7, 7, -6, 8}, {3, 2.0943, 18.3723, 4.24264, 14, 0, 0, 1, -1, >     0, -2, -2, -2, -1, -1, -2, 0, -1, 1, 1, 1, 0, 2, -1, 3, -2, 4, -3, >     3}, {4, 2.97999, 37.1979, 10., 9, 0, 0, 2, 0, 4, 0, 3, 1, 5, 1, 4, >     2, 5, 3, 7, 3, 8, 4, 9, 5, 7, 5, 8, 6}, {5, 2.48083, 25.7801, >     7.61577, 7, 0, 0, 2, 0, 4, 0, 3, 1, 2, 2, 0, 2, 1, 3, 2, 4, 4, 4, 6, >     4, 5, 3, 7, 3}}   >                 sortedrmsdata = SortBy[rmsdata, #[[5]] &]            xydata = Partition[Flatten[Take[sortedrmsdata, All, {6, 29}]], 2]            gridedvalues = Take[sortedrmsdata, All, {1, 5}]            col = {SpanFromBelow, SpanFromBelow, SpanFromBelow, SpanFromBelow,         SpanFromBelow, SpanFromBelow};            Table[AppendTo[gridedvalues[[i]], col[[i]]], {i, 6}]  grided = Prepend[       gridedvalues, {"Number", "RMS displacement", "Volume",         "RMS end-end", "Interactions", "Graph"}]            Grid[AppendTo[       grided, {SpanFromAbove, SpanFromAbove, SpanFromAbove, SpanFromAbove,         SpanFromAbove,         ListPlot[Partition[xydata, 12], Mesh -> All,          MeshStyle -> PointSize[Large], Joined -> True,          PlotLegend -> Take[sortedrmsdata, All, 1]]}], Frame -> All]      Worked:               col ={ListPlot[Partition[xydata, 12], Mesh -> All,      MeshStyle -> PointSize[Large], Joined -> True], SpanFromAbove, SpanFromAbove, SpanFromAbove, SpanFromAbove, SpanFromAbove};     gridedvalues = Take[sortedrmsdata, All, {1, 5}];Table[AppendTo[gridedvalues[[i]], col[[i]]], {i, 6}];     grided = Prepend[gridedvalues, {"Number", "RMS displacement", "Volume", "RMS end-end", "Interactions", "Graph"}];     Grid[grided, Alignment -> Center, Frame -> All]


title: Exporting graphics without X server

text: I have a Mathematica installation on a Linux server that is intended to be used for batch processing. Some of the things that will be processed will include rendering of graphics. However, if I use `Export["/file/name.gif", graphicsobject]`, Mathematica wants to connect to an X server. Yes, I can run Xvfb or similar, but this seems like inordinate overkill. Is this really the only option? Is there no way to get Mathematica to render to GIF (or PNG, or BMP, or TIFF, or whatever; I don't really care) without having an X server running? _**Update:**_ I just ran this small program without an X server available:               s=Graphics[Sphere[]];     Do[         Print[fmt];         TimeConstrained[             Export["/tmp/img-"<>fmt, s, fmt],               10, Print["Timeout"] ],       {fmt, $ExportFormats} ]      and found that the only files created that contained something other than just the text `Graphics[Sphere[0, 0, 0]]` or `-Graphics-` were DXF and JVX, both of which were very simple renderings without axes or labels or anything once anything remotely more complex was rendered.


title: Solving a linear fourth-order fractional integro-differential equation

text: **Definition:** A real function $f(x)$, $x>0$ is said to be in space $C_\mu$, $\mu\in \Bbb R$ if there exists areal number $p$ ($>\mu$), such that $f(x)=x^pf_1(x)$, where $f_1(x)\in C[0,\infty]$, and it is said to be in the space $C^m_\mu$ iff $f^{(m)}\in C_\mu$, $m\in\Bbb N$. The Riemann-Liouville integral fractional operator of order $\alpha\geq 0$, of function $f\in C_\mu$, $\mu\geq -1$, is defined as $$J^\alpha f(x)=\frac{1}{\Gamma(\alpha)}\int_o^x(x-t)^{\alpha-1}f(t)dt,\quad \alpha>0,x>0,$$ $$J^0f(x)=f(x). $$ The fractional derivative of $f(x)$ in the Caputo sence is defined as $$D^\alpha_{*x}f(x)=\frac{1}{\Gamma(m-\alpha)}\int_0^x (x-t)^{m-\alpha-1}f^{(m)}(t) dt $$ for $m-1<\alpha\leq m$. $m\in\Bbb N$ and $f\in C^m_{-1}$. I wanna solve the following linear forth-order fractional integro-differential equation $$D^\alpha_{*x}y(x)=x(1+e^x)+3e^x+y(x)-\int_0^x y(t)dt,\quad 0<x<1, 3<\alpha\leq 4,$$ subject to the boundary conditions $$y(0)=1,\quad y''(0)=2.$$ $$y(1)=1+e,\quad y''(1)=3e.$$ For instance, the exact solution, when $\alpha=4$ is $y(x)=1+xe^x$. The recursive Adomian decomposition algorithm is $$y_0=1+Ax+x^2+\frac{1}{3!}Bx^3+J^\alpha(x+xe^x+3e^x),$$ $$y_{n+1}=J^\alpha y_n(x)-J^\alpha\left(\int_0^x y_n(t)dt\right).\quad n\geq 0. $$ where the constants $A=y'(0)$ and $B=y'''(0)$ are to be determined. I don't know how to write the code.               a=4     DSolve[{1/Gamma[m - a]*     Integrate[(x - t)^(m - a - 1)*D[y[t], {t, m}], {t, 0, x}] ==      x (1 + Exp[x]) + 3 Exp[x] + y[x] - Integrate[y[t], {t, 0, x}],      y[0] == 1, y''[0] == 2, y[1] == 1 + E, y''[1] == 3 E}, y[x], {x,0,1}]


title: How to remove a break line in coding

text: MySum[p_List, iMin_] := Module[{printOuput, i, iMax},        iMax = iMin + Length[p];        printOuput = "";        For[i = iMin, i < iMax, i++,         printOuput =           printOuput <> " + " <> ToString[i, TraditionalForm] <>            " \[CenterDot] " <>            ToString[Part[p, i - iMin + 1], TraditionalForm]];        Print[printOuput <> " = "];        Sum[Part[p, i - iMin + 1]*i, {i, iMin, iMax - 1}]];     p = 1/7 {3, 2, 0, 2};     MySum[p, 0]      This is my code.   1. I would like to have it in one separate line.   2. I would also like to remove the first "+", So the output will look exactly like this: $$0 \cdot \frac{3}{7} + 1 \cdot \frac{2}{7} + 2 \cdot 0 + 3 \cdot \frac{2}{7}= \frac{8}{7}$$


title: Triple fractional part-related integral

text: The evaluation with _Maple_ suggests the triple integral is around $1$, but Mathematica tells   it's $0.0958758$. When using the code               N[Integrate[FractionalPart[x/y] FractionalPart[y/z] FractionalPart[z/x], {x, 0, 1}, {y, 0, 1}, {z, 0, 1}]]      it returns: "NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >> NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times. The global error is expected to decrease monotonically after a number of integrand evaluations. Suspect one of the following: the working precision is insufficient for the specified precision goal; the integrand is highly oscillatory or it is not a (piecewise) smooth function; or the true value of the integral is 0. Increasing the value of the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical integration. NIntegrate obtained 0.09587582633950331`and 0.004696948831748114` for the integral and error estimates. >>" I'd like to know if Mathematica's approximation is correct, and if there is a possible closed form.


title: How can I get the exact solution of this equation (inequality equation)?

text: I want to solve the equation and inequality equation $$\sqrt{8\cdot 16^x - \dfrac{1}{2}\cdot 9^x }= 3\cdot 4^x - 3^x$$ and $$\sqrt{8\cdot 16^x - \dfrac{1}{2}\cdot 9^x } \leqslant 3\cdot 4^x - 3^x.$$ The correct of the given equation is $$-\log_{\dfrac{3}{4}}\left (3+\dfrac{\sqrt{30}}{2}\right ).$$ I tried               Reduce[Sqrt[8 16^x - 1/2 9^x] == 3 4^x - 3^x, x, Reals]      > >     x == Root[{2 + Sqrt[2] 3^-#1 Sqrt[2^(4 (1 + #1)) - 3^(2 #1)] - >      6 E^(2 Log[2] #1 - Log[3] #1) &, 6.0734320063313606675}] >   With inequality, I tried               Reduce[Sqrt[8 16^x - 1/2 9^x] <= 3*4^x - 3^x, x, Reals]      > >     x >= Root[{2 + Sqrt[2] 3^-#1 Sqrt[2^(4 (1 + #1)) - 3^(2 #1)] - >      6 E^(2 Log[2] #1 - Log[3] #1) &, 6.0734320063313606675}] >   How can I get the correct solution?


title: How can I make a heatmap of a days in year?

text: I know Mathematica has a ListPlot for time series but does it have a function for visualizing a list of dates as a heat map like this: ![enter image description here](http://i.stack.imgur.com/1Og85.png) This idea is from D3, check it out here.


title: Since installing mathematica 9 I can't import certain tiffs

text: I have a notebook written in Mathematica 8 in which I imported Tiff images and everything worked fine. Since I installed Mathematica 9, I get the error:               In[14]:= Files[[1]][[1]]     Import[Files[[1]][[1]],"TIFF"]     Out[14]= Growth_1_130124_1353/Growth_1_130124_1353_T0001.tif     During evaluation of In[14]:= Image::imgcsmis: The specified color space ColorProfileData[<>,Description->sRGB IEC61966-2.1,DeviceColorSpace->RGB,IndependentColorSpace->XYZ] and the number of channels 1 are not compatible. >>     Out[15]= Image[RawArray[Byte,<1024,1360>],Byte,ColorSpace->ColorProfileData[<>,Description->sRGB IEC61966-2.1,DeviceColorSpace->RGB,IndependentColorSpace->XYZ],Interleaving->None]      How can I solve it? Cheers, Andrea


title: Moving the location of the branch cut in Mathematica

text: According to the documentation, _Mathematica_ chooses the branch cut for $\log(z)$ to lie along the negative real axis. It it possible to change this so that it lies along the positive axis or elsewhere in the complex plane?


title: Installing Mathematica's package in Linux

text: I copied the package folder (ProPac, http://www.pages.drexel.edu/~hgk22/software/ProPac/ProPac.html) in `$UserBaseDirectory/Applications` in Linux mint. But when I called it by               <<ProPac`      the ouput is               Get::noopen: Cannot open ProPac`. >>     $Failed      I tried install it from File menu but appears the same error. But in Windows OS I have no problem with installation of this package and using it.


title: Finding face vertices from the face adjacency graph

text: I have a question about face adjacency graphs. Suppose that I have an adjacency matrix               M = {{0, 1, 0, 0, 1, 1, 0, 0},           {1, 0, 1, 0, 0, 0, 0, 1},            {0, 1, 0, 1, 0, 0, 1, 0},           {0, 0, 1, 0, 1, 0, 1, 0},           {1, 0, 0, 1, 0, 1, 0, 0},           {1, 0, 0, 0, 1, 0, 0, 1},           {0, 0, 1, 1, 0, 0, 0, 1},           {0, 1, 0, 0, 0, 1, 1, 0}}      that is known to be a planar graph. So I use the command `GraphPlot[M]` and give vertex labeling. The result is ![enter image description here](http://i.stack.imgur.com/UlwEa.jpg) There are 5 faces in the figure (exclude the outer face). The set of vertices of the faces is `{{1,6,8,2}, {1,6,5},{4,5,6,8,7},{3,4,7},{2,3,7,8}}`. I don't know how to find this list of vertices automatically if I enter any adjacency matrix (I'm sure that all picked matrices are planar graphs due to `PlanarGraph[M]`)


title: NSolve: Mathematica 9 issue

text: In _Mathematica_ 8 the following expression evaluates and returns a result in terms of `InverseFunction`:               NSolve[Integrate[x^(1/2)/(Exp[x - μ] - 1), {x, 0, ∞}] == C, μ]      where `C` is a constant. But in _Mathematica_ 9 the expression does not evaluate: > NSolve::nsmet: This system cannot be solved with the methods available to > NSolve. >> Is this a bug, a regression, or a feature? And how can this equation can be solved in V9? Particular, trying to solve this:               NSolve[PolyLog[3/2, 20 x] == 2, x]      In _Mathematica_ 8 and _Mathematica_ 9 gives different results: _Mathematica_ 8 (correct result):               NSolve::ifun: Inverse functions are being used by NSolve, so some solutions may not be found; use Reduce for complete solution information. >>     {{x -> 0.05 InverseFunction[PolyLog, 2, 2][3/2,       2.0000000000000000000000000000000]}}      _Mathematica_ 9:               NSolve::nsmet: This system cannot be solved with the methods available to NSolve. >>     NSolve[PolyLog[3/2, 20 x] == 2, x]      * * * **UPD:** That's a confirmed bug with `NSolve`, that I already reported to developers of Wolfram Mathematica long time ago.


title: Why I get the "Set::write: "Tag Times in is Protected." error?

text: Why I get the error below with this code:               Needs["VectorAnalysis`"]          ρ = 1000;     g = 9.80665;     μ = 0.001;     p[x_, y_, z_, t_] = {x^2, Sqrt[y], -z, t^3};     f[x_, y_, z_, t_] = {-x^2, Sqrt[y]/2, z, t^2};          ρ Dt[v, t] = -Gradient[p] + μ Laplacian[v] + f      * * * ## Error:               Set::write: "Tag Times in 1000\ Dt[v,t] is Protected."


title: Why does WordData fail to find "PartsOfSpeech" when given a list of two words?

text: I have the following sample code.               StringSplit["a test string", " "]     Thread[WordData[%, "PartsOfSpeech"]]      The output I get is:               {a, test, string}     {{Noun, Preposition, Determiner}, {Noun, Verb}, {Noun, Verb}}      If I change `"a test string"` to `"test string"`, then my code fails, giving the following:               {test, string}     {}      Can anyone tell me why this is and how to solve it?


title: Is there a Break[] equivalent for short-circuiting in Table?

text: I am running _Mathematica_ 7. The following is admittedly a silly example, but suppose that I have a list `list` whose entries are either `True` or `False`. Suppose that I have some function `truthFun[]` which evaluates randomly to either `True` or `False`. I would like to call `truthFun[]` and print `False` until `truthFun[]` evaluates to `True` for the first time. One way to do this is using a `For` loop. We can exit the loop "early" using `Break[]`. (As the documentation states, `Break[]` exits the nearest enclosing `Do`, `For`, or `While` loop.) For example, the following works:               truthFun[] := RandomChoice[{True, False}]          For[i = 1, i <= 10^8, i++,        If[truthFun[] === False, Print[False], Break[]]];     Print["Finished"]      > False > > False > > Finished However, it is often recommended that _Mathematica_ users avoid using loops (which are relatively slow in _Mathematica_ , I think). Is it possible to accomplish the above using `Table`, which is probably faster? I tried the following, but unfortunately it appears that `Break[]` does not work with `Table`:               truthFun[] := RandomChoice[{True, False}]          Table[If[truthFun[] === False, Print[False], Break[]], {i, 1, 10^8}];      > False > > False > > False > > Hold[Break[]] Also, _Mathematica_ gives me this error message: > Break::nofwd: No enclosing `For`, `While`, or `Do` found for `Break[]`. Is there an analogue to `Break` in `Table`? Thanks for your time.


title: Using NumberString, DigitCharacter, or a similar directive to find all string representations of integers in a string

text: I have a text file containing many, many lines of text like `test` in the following:               test = "word  123  456    7890.000      0.12000";      I would like to extract all of the "string representations of integers." However, I need to be clear about what I would like. In `test` above, I would like the output to be:               {"123", "456"}      since I am only interested in _actual_ , _isolated_ (delimited by spaces) string representations of integers. Yes, `7890` is an integer, but in `test` above, it is not isolated, so I do not want my function to return it (since `7890.000` is a decimal). In the case of `test`, I could use this:               StringCases[test, Repeated[DigitCharacter, 3]][[1 ;; 2]]      which returns               {"123", "456"}      However, this is not general, because my string may contain more than two string representations of integers. So I would like my function to also take this input:               test = "word  123  456  123    7890.000      0.12000";      and return:               {"123", "456", "123"}      I have thought about using `StringSplit` followed by `ToExpression` and `IntegerQ`, but this seems like it would be very (unnecessarily?) complicated. Perhaps Mathematica has something better built in that I can use? Do you have any advice? Thanks!


title: Text to speech in notebooks?

text: Mac OS, MMA 10 -- I accidentally discovered that typing `Ctrl``V` between cells reads out the cell below, or, if you have text selected, reads out the text. `Ctrl``V` would be _Edit > Paste_ on Windows, so the text-to-speech feature would be triggered differently on Windows, if it's present at all. I know there is a global Mac text-to-speech function ( _System Preferences > Dictation & Speech_), but I have it turned off. Just to be sure, I changed the global Mac text-to-speech voice to "Vicky", but the voice in MMA stayed on "Alex." That is evidence that I'm triggering a MMA special. Where is this text-to-speech configured; in particular, can I change the keyboard shortcut for it? It would be nice to explore if it has any other configurable features. I trolled the menus and the _Preferences_ dialog box for a hint, but didn't find one. MMA has a `Speak` built-in function, but that appears to be something else altogether.


title: Read a binary file to an image in memory then analyze it

text: Is it possible to read a whole file (~100 MBs) into memory, and then use BinaryRead[] function on the data loaded into memory to read/cast it to the types I need with a proper StreamPosition pointer? I need this because the process is very slow if I do it directly to files, so I prefer to have all manipulations done in memory, especially that I require many memory accesses with many BinaryRead[] calls. Thank you for any efforts.


title: FiniteFields package is very slow. Any fast substitute for Mathematica?

text: I want to compute the inverse of matrix, say with dimensions $100 \times 100$, defined over a large finite field extension such as $GF(2^{120})$. I am using the package **FiniteFields** , but Mathematica's computation time is exponential with respect to matrix dimensions. The following code illustrates the problem:               << FiniteFields`;     Table[         With[{ext = 12},            First@AbsoluteTiming@                Inverse[                    Array[GF[2, ext][RandomInteger[{0, 1}, ext]] &, {n, n}]                ]         ],         {n, 1, 11}     ]      I am using an Intel Xeon X5680 @ 3.33GHz (64-bit OS) and Mathematica v8.0.4.0. I have received the following timing results:               {0.0030, 0.0080, 0.0210, 0.0630, 0.1860, 0.5110, 1.3350, 3.3840, 8.9340, 23.0090, 57.4660}      I believe the source of the problem is that the **FiniteFields** package defines many UpValues, DownValues and SubValues of `Times` and `Plus` for head GF and, consequently, the pattern matching of arguments is degraded. Does anyone know if a patch for the **FiniteFields** package or a faster substitute providing a similar interface? Many thanks!


title: SyntaxForm not correctly parsed by FrontEnd

text: When using `TagBox` with `SyntaxForm`, I noticed sometimes it is not well parsed by the `FrontEnd`. Here is a minimal example. First input               TagBox["f", "test", SyntaxForm -> "^"] // DisplayForm      Then copy the output `f` to new input, and do some prefix or postfix operations. There is an error message. A screenshot is attached. ![enter image description here](http://i.stack.imgur.com/9ooAD.png) To debug further, one note that where there is a problem, in the saved file the cell is broken into more than one `RowBox`, for example:               Cell[BoxData[      RowBox[{       TagBox[        TagBox["f",         "test",         SyntaxForm->"^"],        DisplayForm],        RowBox[{"//", "ToBoxes", " ",         RowBox[{"(*", " ",          RowBox[{         "this", " ", "f", " ", "is", " ", "copied", " ", "and", " ", "pasted",           " ", "from", " ", "the", " ", "above", " ", "line"}], " ",          "*)"}]}]}]], "Input",      CellChangeTimes->{{3.618418507443947*^9, 3.618418516513115*^9}},      EmphasizeSyntaxErrors->True]      I am using Mathematica 10.0 on Linux x64. I have also tried `SyntaxForm->"a^b"`, or other operators. None of them work well. Am I doing anything wrong or is it a bug? **Edit:** As @WReach commented, I should have provided more details about my goal, otherwise why not go without SyntaxForm? And here is what I wanted (still a simplified version of the realistic case): typeset derivative in a good- looking way. The simplest implementation is               MakeBoxes[d[f_], StandardForm] :=       TagBox[GridBox[{{"\[PartialD]", ToBoxes[f]}}], "d"]      However, if I evaluate               d[f]^2      > ∂ f² This is not what I want (it evaluates correctly but does not look correct). Instead I want `(∂ f)²`. Note that here I could use `RowBox` instead of `GridBox` and then there is no such problem. But I do need `GridBox` in the realistic case because it is more feature-rich (I could use `RowBox[{GridBox[...], ""}]` to replace `GridBox[...]` as a workaround. But I hope there is a cleaner and less hacky way). Also the `Notation` package is not powerful enough for my actual need so I want to do it myself. I think the logical move to solve this problem is to use `SyntaxForm`. Indeed, if I define               MakeBoxes[d2[f_], StandardForm] :=       TagBox[GridBox[{{"\[PartialD]", ToBoxes[f]}}], "d2", SyntaxForm -> "^"]          MakeExpression[TagBox[GridBox[{{"\[PartialD]", f_}}], "d2", ___],        StandardForm] := With[{g = ToExpression@f}, HoldComplete@d2@g]      I get the desired `(∂ f)²` appearance for `d2[f]^2`. However, now the problem that I have described appears. If I evaluate `d2[f]`, and copy the output to new input and use, say, post-fix form of operators, it ends up with an error.


title: Label cell goes away with SelectionEvaluate

text: When a given cell has a label (given with the CellLabel->"label" option of the cell), then this label disappears after calling               SelectionEvaluate[ nb ]      when the contents of the cell is selected. Why is that? Is it possible to keep the label after evaluating its content (without making a new cell, so not using the               SelectionEvaluateCreateCell[]      command? Thanks for all help!


title: Creating a function with integral zeroes of the 0th, 1st, and 2nd derivatives

text: I would like to be able to randomly generate functions, each of which satisfies   1. $f : [-10, 10] \rightarrow [-10, 10]$   2. All the zeroes, critical points, and inflection points have an integral $x$-value   3. Some of the critical points -- $x$-values where $f'(x) = 0$ -- are local extrema, but some aren't   4. Some of the zeroes are also at local extrema (like $x=0$ in the function $y=x^2$), and some aren't It's easy to draw such a function by hand and then define a piecewise function that looks similar. The hard part, for me, is finding an algorithm that generates these functions with some randomness. I was approaching this by taking functions of the form $y=a (x-b)^2 + c$ and gluing them together so that the points and derivatives match up. (If the second derivatives don't match up, that's ok -- my Mathematica method will still identify the "gluing" points as inflection points.) This works fine if I'm only worried about critical points and inflection points, but seems to become very difficult when trying to respect the zeroes condition. Can anyone think of a tractable algorithm for this? EDIT: the randomness needs to be present beyond just, say, a scalar multiple. The goal is to show graphs of these functions to students and ask them to visually identify zeros / critical points / inflection points, and so different functions should correspond to usefully-different problems.


title: Treat list as cyclic

text: I am considering the following case. Say that `T={p1,p2,p3}` represents a triangle. In addition, I want to parameterize the edges of the triangle `T`. What I currently do is:               edgesT = {        t T[[1]] + (1 - t) T[[2]],        t T[[2]] + (1 - t) T[[3]],        t T[[3]] + (1 - t) T[[1]]};      This seems to be very naive, and I would like to learn how can I improve this. One, somehow obvious, way would be to have a cyclic list. Thus the question's title. **Is there a (smart) way to treat a list as cyclic?** Obviously, `T[[i]] = pi` for `i={1,2,3}`. It could be useful, for example in the example above, to enter `T[[4]]` and expect to have `p1` as an output. Is there some way to do it? **If not, how can I improve the definition above?**


title: Relative performance of the Julia language

text: I was just reviewing the _Mathematica_ benchmark code linked from the Julia language home page http://julialang.org/. The stated goal of the benchmarks is to test the performance of specific algorithms, expressed in a _reasonable idiom_ in each language, and all languages use the same algorithm. In particular, the Fibonacci benchmarks are all recursive, and the _Mathematica_ code reads               ClearAll[fib];     fib = Compile[{{n, _Integer}},          If[n < 2, n, fib[n - 1] + fib[n - 2]],         CompilationTarget -> "WVM"     ];      Now, dynamic programming is certainly a _reasonable idiom_ in _Mathematica_ :               fib[n_Integer]:= fib[n]= If[n < 2, n, fib[n - 1] + fib[n - 2]]      and this dynamic _uncompiled_ code will be much faster than the benchmark code, especially for large n (unless the WVM compiler is smart enough to do automatic memoization). The test only computes fib[20] and it would be most interesting to try say fib[100] in the various languages (the times for R, MATLAB, and OCTAVE are excessive even for n=20). It would also be useful, I think, for better coding of all the benchmark examples, if someone has the time and energy ...


title: Efficient way to build a certain quadratic matrix

text: For odd `n` I'm looking for a short and swift way to construct with (f.e.)               n = 3      ![enter image description here](http://i.stack.imgur.com/Z2DHG.jpg)               n = 11      ![enter image description here](http://i.stack.imgur.com/VHDYp.jpg)               n=1111      ![enter image description here](http://i.stack.imgur.com/Vk3zT.jpg)


title: How to make an efficient difference of sets function?

text: How to write a nice code that removes all elements from given set A, that occur also in set B? I would like to use `DeleteCases[]` for this purpose, but have no good idea how to make it efficient.               SetDifference[A_,B_]:=DeleteCases[A, ??? ]      Or to find out if theres a ready to use function already, as in Lists as Sets there is nothing like that mentioned.


title: Zero-dimensional matrices

text: In a recent _Mathematica_ project, $(n \times 0)$- and $(0 \times n)$-dimensional matrices have suddenly become a frustratingly common edge case for me. For instance, consider the following two situations, both common in linear algebra programming:   1. Suppose we have a matrix $A$, presenting a linear transformation $\newcommand{\R}{\mathbb{R}}\R^n \to \R^m$. The kernel of $A$ is a particular subspace of the source, $\R^n$, and if $A$ has a kernel of dimension $d > 0$, then `NullSpace[A]` produces a new matrix presenting a map $\R^d \to \R^n$ whose image is $\ker A$. This mode of thought is very useful; it lets you, for instance, restrict the action of some other map $B: \R^n \to \R^l$ to the kernel of $A$ by multiplication: `B.Transpose[NullSpace[A]]`.   2. Suppose we have a pair of matrices $A$ and $B$, presenting a pair of linear transformations $\R^n \xrightarrow{A} \R^l \xleftarrow{B} \R^m$ with a common target. The _pullback_ or _generalized intersection_ of these two maps is defined to be the collection of pairs of vectors $(x, y) \in \R^n \times \R^m$ with $Ax = By$. This, too, is easy enough to model in _Mathematica_ : the `NullSpace` of the block matrix $\left[\begin{array}{c|c}A & -B\end{array}\right]$ splits into a block matrix itself $\left[\begin{array}{c}P \\ \hline Q \end{array}\right]$. The matrices $P$ and $Q$ present the "largest nontrivial" maps into $\R^n$ and $\R^m$ respectively with the property that $AP = BQ$. While the mathematics continues to make sense, both of these run into serious difficulties when $0$-dimensional vector spaces get involved. This happens all the time in both situations (and, generally, in any situation where you might be applying `NullSpace` to a matrix with trivial kernel): because _Mathematica_ models matrices as lists of lists (with some exceptions, like `SparseArray`s, which have to support conversion to lists of lists anyway), it has real trouble modeling an $(n \times 0)$-dimensional matrix. For instance, `NullSpace[ IdentityMatrix[n]]` returns `{}`, which at first glance is reasonable enough but is totally unsuited for uniformly handling the above procedures. The expression `{}` is not $(n \times 0)$-dimensional in any sense, and so matrix multiplication, transposition(, inversion in the case $n = 0$), and so on all balk at using this as input. This is surmountable, of course, by riddling my _Mathematica_ code with conditionals that check for this failure output and handle it separately. This is uglier than it sounds (and it already sounds ugly); oftentimes this means passing around extra information to keep track of the `n` involved, since it's not recoverable from `{}`. > **My question is:** Is there a cleaner solution than a sea of conditionals? > Is there an idiomatic way to model $(n \times 0)$- and $(0 \times > n)$-dimensional matrices in _Mathematica_ , ideally in a way that's near- > seamlessly compatible with standard routines like `Times`, `Transpose`, > `ArrayFlatten`, ...? (P.S.: I eventually intend to offer this thing I'm writing as a package, and so I'd prefer not to modify the behavior of built-in functions directly.)


title: Intersecting graphics

text: Does the _Mathematica_ graphics system have any concept of intersecting graphics? I've not found much in the documents so far. For example, if I want to show the intersection of two shapes:               Graphics[{Rectangle[], Disk[{0.2, 0}, .5]}]      ![graphics without intersection](http://i.stack.imgur.com/Or0Ov.png) I know I can use `Opacity`:               Graphics[{Opacity[0.8], Red, Rectangle[], Green, Disk[{0.2, 0}, .5]}]      ![graphic with intersection](http://i.stack.imgur.com/hEOji.png) But is there a way of specifying the colours of intersecting areas directly? It doesn't seem to be possible to 'address' the intersecting shapes any other way. In the same vein, is is possible to 'extract' the graphical intersection of arbitrary shapes, without returning to the original geometry and calculating it? Could you obtain this type of entity easily given the above specification (these are just examples...!): ![the intersection](http://i.stack.imgur.com/YwZZ1.png) I think it might be easier with raster images, but am interested for now in vector graphics.


title: GatherBy Option to group results?

text: How can `GatherBy` be programmed to take an option to group results as follows:               data = {T0->1993-09-29,T1->1993-10-04,T10->1993-09-29,T11->1993-10-01,T12->1993-10-02,T13->1993-10-04,T14->1992-10,T3->1991,T4->1991,T7->1992-10,T8->1992-10,T9->1993-09-26}      `Column@(data2 = GatherBy[data, #[[2]] & ])` gives:               {T0->1993-09-29,T10->1993-09-29}     {T1->1993-10-04,T13->1993-10-04}     {T11->1993-10-01}     {T12->1993-10-02}     {T14->1992-10,T7->1992-10,T8->1992-10}     {T3->1991,T4->1991}     {T9->1993-09-26}      It's desired to optionally group into lists based on the common right-hand sides: `Column[ ((First /@ #) -> #[[1, 2]]) & /@ data2]`, which gives:               {T0,T10}->1993-09-29     {T1,T13}->1993-10-04     {T11}->1993-10-01     {T12}->1993-10-02     {T14,T7,T8}->1992-10     {T3,T4}->1991     {T9}->1993-09-26      And to do this not just for `Rule` expression arguments but for any argument and `GatherBy` test functions.


title: Mathematica "prelude"

text: Is there any way to have the functions from a mathematica file be loaded on startup? For example, in this excellent answer, Jens helps me out and gives me some functions for creating legends for plots. Instead of loading a file with those functions in it every time I load mathematica, can I instead put all the functions in a file and have them load every time I load mathematica?


title: Print documentation (or front end) with all Openers open?

text: From the online reference: http://reference.wolfram.com/mathematica/ref/Opener.html a JS function javascript:open_ES() is invoked to open all Openers within a section. Note (1) this feature is absent in the built-in MMA documentation center; (2) even online it selectively opens the EXAMPLES section (for Opener). Often I need to quickly overview all the sections including More Information, Options, Properties & Relations &c. Is there a way to program the documentation or even the Front End that contains Opener and Toggler to map them all to True? Perhaps a palette selection.


title: Strange behavior when using Row with packed arrays

text: Today I lost a lot of time with a strange behavior and I narrowed it down to this small piece of code:               a = {1, 2};     ToString@Row[DeleteDuplicates[a], ","]     ToString@Row[Union[a], ","]      > >     "Row[{1, 2}, ,]" >     "1,2" >   Can someone explain this bizarre behavior? Is this a bug? This is interesting too:               a = {1, 2};     l1 = DeleteDuplicates[a];     l2 = Union[a];     l1==l2     s1 = ToString@Row[l1, ","]     s2 = ToString@Row[l2, ","]     s1==s2      > >     True >     "Row[{1, 2}, ,]" >     "1,2" >     False >   There is some "memory" in `l1` created using `DeleteDuplicates`. **UPDATE** This bug was fixed in V10.0.0


title: Wolfram language from batch or py

text: I would like to automate the commands in this website into a batch file, so when the batch file it runs these commands in sequence. http://community.wolfram.com/groups/-/m/t/157461 Do any of you have any ideas. I know that you can just type in wolfram in a batch file like this:               #!/bin/bash     wolfram      It will give you this output:               Wolfram Language (Raspberry Pi Pilot Release)     Copyright 1988-2013 Wolfram Research     Information & help: wolfram.com/raspi          In[1]:=      How would you enter commands in the In[1]:= from a batch script? Thanks in advance. Ahmad EDIT I think this could help from http://reference.wolfram.com/language/guide/RaspberryPi.html               wolfram -script file.wl


title: Plotting and ContourPlot

text: > Make a `Plot` and a `ContourPlot` that gives the same diagram and use > `ContourPlot` on a quadruple of equations to make ![plot](http://i.stack.imgur.com/GvFwc.png) I am thinking that I need to show a parabola reflected across the x-axis, and two sideways parabolas, but I don't know how to create this picture.


title: Show List of HighlightGraph Objects in Matrix

text: I'm new to _Mathematica_ and can't get my problem solved. I want to display a list of `HighlightGraph` objects in `MatrixForm` like `GraphicsGrid`. This is my current tryout create a 3xn matrix               GraphicsGrid[      Table[# &, {3}, {(Length[graphLst] / 3) + Mod[Length[graphLst], 3]}]      ] /@ graphLst      This is the output. > ![Output](http://i.stack.imgur.com/oLyr8.png) I can't figure it out how to get this thing going. Can you lend me some help?


title: Text with specified FontSize looks smaller than expected

text: The simplest way to see what the post's title is trying to convey is to evaluate:               {"-0.5",       Text[Style["-0.5", FontFamily -> $DefaultFont[[1]],                FontSize -> $DefaultFont[[2]]]]}      On my Windows 7 laptop, at least, the first `0.5` looks larger than the second one. (The first one looks "right" to me somehow). My understanding is that `$DefaultFont` specifies the default output font, so I'm puzzled by the obvious difference (illustrated by this example) between text using the default output font, and text using a font explicitly set to match `$DefaultFont` (i.e., the first and second elements in the output of the evaluation above). Clearly my understanding is wrong somewhere, but I can't figure it out. Ultimately, I'm looking for a reliable way to specify the font size and font family of text elements in `Graphics` generated by `Plot`, etc. FWIW, I'm using version 9.0.1.0.


title: Confused about scoping, not sure what to ask

text: I'm grading for a class using Mathematica right now, and one of the students ran into a weird issue. When he ran code like this:               examplefun[n_] :=         SetDirectory["/Users/"];         Module[{output = ""},         Do[output = output <> RandomInteger[{1, 4}], {i, n}];         Print[output]]      He get's an error: Do::iterb: "Iterator {i,n} does not have appropriate bounds. " But if he moves Module up:               examplefun[n_] :=         Module[{output = ""},         SetDirectory["/Users/"];         Do[output = output <> RandomInteger[{1, 4}], {i, n}];         Print[output]]      The error disappears. I'm not sure what the problem is, though I suspect it has something to do with scoping. Could someone provide me with some insight here? Thanks! Edit: Ohhhhhhhh, that makes sense! Thanks for the prompt responses, everyone! I hadn't considered that his code didn't use the proper syntax for a multi- line function since I haven't used multi-line syntax before. I've accepted an answer, but thanks for all the responses!


title: Eastern European alphabet conversion from nb to PDF

text: When converting Eastern European alphabet written article from .nb to pdf, certain letters convert to empty rectangle like shapes or constructs, also hacek like letters (č,ć,ž,š,""...). Has anybody suggestion how to correct this?


title: How do I type boxtimes?

text: How do I type boxtimes in Mathematica, for example $a\boxtimes b$? This symbol is used a lot in mathematics, but I found no corresponding part in Mathematica. In TeX form, I can type \boxtimes. Can I make one in Mathematica, and type it in a simple way, like the following?               \[EscapeKey]b*\[EscapeKey]


title: NMaximize with matrix input

text: I defined function `f[x_, fixed_] := {...}`. Here `x` is an $M\times N$ matrix. I want to maximize $f$ with respect to $x$. I have three questions:   1. By default, `NMaximize` treats all variables as real. How can I inform _Mathematica_ that $x$ here is a real matrix?   2. I tried `FindMaximum`, by typing `FindMaximum[f[x, fixed],{x}]`, with `x` as a matrix. The weird thing is that in the process of `FindMaximum`, my function `f` did not evaluate `x`; it just kept `x` as a variable name without content. How to understand and fix this thing? BTW, my function `f` is not in the global context but in a private context.   3. Indeed, the function $f$ here is an approximate of its theoretical counterpart $f_0$. And I know $f_0(x)$ is maximized when $x\in A$. Here $A$ is a subset in Euclid space. My actual aim is to approximate the set $A$. Let $x^*$ be the $\arg\max$ of $f$ found by `Mathematica` somehow. Intuitively, I want to keep all $x'$ such that $|f(x')-f(x^*)|<\epsilon$ for a chosen $\epsilon$. How can I achieve this goal? I noticed that `NMaximize` has a option called `StepMonitor`, which might help.


title: How can I draw a 3D cross-section of a 3-torus embedded in 4D Euclidean space?

text: I have a $3$-torus ($\mathbf S^1\times\mathbf S^1\times \mathbf S^1$) embedded in 4D Euclidean space. How can I draw the cross-section of this $3$-torus cut by a 3D Euclidean space in an arbitrary direction? The equations are: $$\begin{align*} x &= (r + (t + d\cos\,a)\cos\,b)\cos\,c\\ y &= (r + (t + d\cos\,a)\cos\,b)\sin\,c\\ z &= (t + d\cos\,a)\sin\,b\\ w &= d\sin\,a \end{align*}$$ where $x,y,z,w$ are the orthogonal coordinates in 4D space, $r,t,d$ are the radii of three circles, and $a,b,c$ denote the angles of the point with respect to the three circles.


title: Symmetrical image transformation for a kaleidoscope-type image

text: I've been trying to write a little kaleidoscope-type manipulate, using images rather than graphics, and using `ImageTransformation` as a way in. However, I'm starting to suspect that my approach isn't going to work. Before I abandon it, though, I thought I'd ask here if it can be rescued:               im = ImageResize[ExampleData[{"TestImage", "Mandrill"}], 100]          Manipulate[      ImageTransformation[          ImagePad[im, {{x, -x}, {-x, x}}, Padding -> "Reversed"],          Function[{pt}, {ArcTan[-#2, #1] & @@ pt, Norm[pt]}],         DataRange -> Automatic, PlotRange -> {{-2, 2}, {-2, 2}},         Padding -> "Reversed"], {x, 0, 100, 5}]      ![a manipulated mandrill](http://i.stack.imgur.com/F2VW6.png) While the results are OK, it isn't symmetrical, and I'm not sure that the transform can be corrected to make it so? (Strictly speaking this is a teleidoscope, rather than a kaleidoscope...)


title: Alternative ways to implement a triangular recursion

text: Triangular recursions are a class of algorithms that frequently turn up in computational mathematics. These recursions are expressible in the general form $$T_k^{(n)}=f(T_{k-1}^{(n)},T_{k-1}^{(n+1)})$$ for some function $f$ and initial values $T_0^{(n)}$. The "triangular" adjective is easily visualized if the $T_k^{(n)}$ are arranged in an array: $$\begin{array}{}T_0^{(0)}&T_1^{(0)}&T_2^{(0)}&T_3^{(0)}\\T_0^{(1)}&T_1^{(1)}&T_2^{(1)}&\\T_0^{(2)}&T_1^{(2)}&&\\T_0^{(3)}&&&\end{array}$$ Due to the nice theory behind triangular recursions, it is known that such algorithms can be implemented using only a one-dimensional scratch array instead of a two-dimensional array. So much for theory. I shall now give various examples of triangular recursions that occur in computational practice, as implemented in _Mathematica_ , with the underlying triangular recursion flanked by `(* ------ *)` comment lines. Here is the Akiyama-Tanigawa algorithm for the Bernoulli numbers, with the redefinition $B_1=\frac12$:               myBernoulliB[n_Integer] := Module[{atArray = 1/Range[n + 1]},            (* ------ *)       Do[        atArray[[j]] = j (atArray[[j]] - atArray[[j + 1]]),        {k, n + 1}, {j, k - 1, 1, -1}];       (* ------ *)            First[atArray]]          myBernoulliB /@ Range[0, 20]     {1, 1/2, 1/6, 0, -(1/30), 0, 1/42, 0, -(1/30), 0, 5/66}          BernoulliB[Range[0, 20]]     {1, -(1/2), 1/6, 0, -(1/30), 0, 1/42, 0, -(1/30), 0, 5/66}      Here's the Neville-Aitken algorithm for polynomial interpolation:               iPolyVal[pts_?MatrixQ, x_] := Module[{n = Length[pts] - 1, xa, ya, temp},       {xa, ya} = Transpose[pts];            (* ------ *)       Do[        temp = (x - xa[[j]])/(x - xa[[k]]) - 1;        ya[[j]] = ya[[j + 1]] + (ya[[j + 1]] - ya[[j]])/temp,        {k, n + 1}, {j, k - 1, 1, -1}];       (* ------ *)            First[ya]]          iPolyVal[{{0, 1}, {1/3, 1}, {1/2, 1/2}, {3/4, -1}, {1, 0}}, 1/4]     161/160          InterpolatingPolynomial[{{0, 1}, {1/3, 1}, {1/2, 1/2}, {3/4, -1}, {1, 0}}, 1/4]     161/160      Here's (a simplified version of) de Casteljau's algorithm for splitting Bézier curves:               bezierChop[BezierCurve[pts_?MatrixQ, opts___], u_?NumericQ] :=       Module[{n = Length[pts]},        BezierCurve[Transpose[            Function[{vec}, Block[{ta = vec},                  (* ------ *)             Do[              ta[[j]] = u ta[[j + 1]] + (1 - u) ta[[j]],              {k, n - 1}, {j, k, 1, -1}];             (* ------ *)                  ta]] /@ Transpose[pts]]]] /; 0 < u < 1          Graphics3D[{AbsoluteThickness[5],        BezierCurve[{{0, 0, 0}, {1, 1, 1}, {2, -1, 1}, {3, 0, 2}}],        Directive[Blue, AbsoluteThickness[3]],        Translate[        bezierChop[         BezierCurve[{{0, 0, 0}, {1, 1, 1}, {2, -1, 1}, {3, 0, 2}}],          1/3], {0, 0, 1/10}]}, Boxed -> False]      ![Bézier curve truncated with the de Casteljau algorithm](http://i.stack.imgur.com/gefrR.png) There are many more examples of situations that make use of triangular recursions, such as Romberg quadrature, divided differences for interpolating polynomials, the Levin transformation for summing series, the Cox-de Boor algorithm for B-splines... etc. Having shown that they are important, note that the common core of the algorithms that use triangular recursions is a double-index `Do[]` loop working on a preset scratch array, modifying elements as needed. That should be sufficient preamble. My question now is: **are there alternative methods (e.g. non-procedural methods) for implementing triangular recursions?**


title: How to correct my code for solving the Josephus problem?

text: ### Problem Decription Recently, I have been reading the book _Schaum's Outline of Mathematica (2nd Edition)_ , where I encounted the problem: > Flavius Josephus was a Jewish historian of the first century. He wrote about > a group of ten Jews in a cave who, rather than surrender to the Romans, > chose to commit suicide, one by one. They formed a circle and every other > one was killed. Who was the lone survivor? **The author's solution:**               list = Range[10];     While[Length[list] > 1, list = Rest[RotateLeft[list]]];     list      > {5} However, I know it is not efficient to use the procedural methods such as `Do`, `While`, etc. Rather, I want use a functional method like `NestWhile`, `Nest`, or `FixedPoint` to solve the problem. **My solutions:** Method 1:               list = Range @ 10;      NestList[Rest@RotateLeft[#] &, list, 9]      > >      {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, >       {3, 4, 5, 6, 7, 8, 9, 10, 1}, >       {5, 6, 7, 8, 9, 10, 1, 3}, >       {7, 8, 9, 10, 1, 3, 5}, >       {9, 10, 1, 3, 5, 7}, >       {1, 3, 5, 7, 9}, >       {5, 7, 9, 1}, >       {9, 1, 5}, >       {5, 9}, >       {5}} >   Furthermore,this method has a flaw that I must give the the number of iterations. In fact, sometimes that is unknown. Method 2:               list = Range @10;     FixedPoint[If[Length@# != 1 &, Rest @ RotateLeft[#] &], list]      Unfortunately, method 2 doesn't work. Method 3:                list = Range @ 10;      NestWhileList[Rest @ RotateLeft[#] &, list, Length@list != 1]      > >     {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}} >   So my question is: what is a good way to do it?


title: Use boundaries of one plot for another

text: I am writing some code in which I combine a `ParametricPlot[]` with a `RegionPlot[]`. _Mathematica_ is very good at figuring out appropriate bounds for the `ParametricPlot[]`, and I would like to reuse the same bounds for creating the `RegionPlot[]`. How can I tell _Mathematica_ to reuse the bounds?


title: Unexpected result for Coefficient[]

text: Is this just me being stupid, or is this a known bug in Mathematica?               Coefficient[2 x + 2 y, x + y]      gives 0, while               Coefficient[2(x + y), x + y]      gives 2. The documentation says that it should work whenever the expression is expanded or not... I can see the problem with Coefficient[x-y, x + y] but if all coefficients in _expr_ and _form_ are positive, then surely there is a well-defined largest number k, such that `expr-k*form` have non-negative coefficients? And this is what I'd expect.               Coefficient[expr,form]       EDIT: In my case,               PolynomialReduce[expr,{form},vars][[1,1]]      does the thing I want. This computes _k_ such that _expr-k form_ is minimal in some sense.


title: Variable scope similar to other languages

text: Mathematica, unlike many other languages, defines the variables in the global scope unless it is explicitly asked to define a variable in a local scope, _e.g._ , using `Module`, `With`, or `Block`. My question is how to define a scoping construct which defines the variables locally by default unless otherwise stated. For instance:               x = 1;     y = 1;     Scope[{x (* specify global variables here *) },       x = 2;       y = 2;       a = 0;       (* x and y both equal to 2 and a is 0 here *)     ]     (* x equals to 2, y equals to 1, a is undefined here *)      How can one define a function `Scope` as demonstrated above?


title: Volume within parameter space

text: Imagine a parameter space with variable `0<p<1`, `0<e1<1/2` and `0<e2<1/2`. There are certain conditions on the parameters in some situations. For example `p<e1` or `(p)(e1)/((p)(e1)+(1-p)(1-e2))<e1/e2` How can I determine the volume of the parameter space which satisfies these (and other) conditions? I would like to determine them algebraically, and not via a numerical simulation of plotting points within parameter space. I also do not want to solve any complex equations myself. I simply want a function which gives me the result easily. Does this exist? Update: The suggestion below works very well in many cases, however, I seem to have hit a problem. Try to evaluate: `NIntegrate[Boole[0<p<1&&0<e1<1/2&&0<e2<1/2&&e1<e2&&0<e3<1/2&&0<(e3-e2 e3-e1 p-e3 p+e1 e3 p+e2 e3 p)/((1-e1-2 e3+e1 e3+e2 e3) (-1+p))<1&&0<(-e1+e1 e3+e2 e3)/(1-e1-2 e3+e1 e3+e2 e3)<1&&40/100<(((e3-e2 e3-e1 p-e3 p+e1 e3 p+e2 e3 p)/((1-e1-2 e3+e1 e3+e2 e3) (-1+p)))(e3+p-2 e3 p)+(1-((e3-e2 e3-e1 p-e3 p+e1 e3 p+e2 e3 p)/((1-e1-2 e3+e1 e3+e2 e3) (-1+p))))(1-e3))],{p,0,1},{e1,0,1/2},{e2,0,1/2},{e3,0,1/2},WorkingPrecision->20]` This gives something like 0.036. Try now to weaken the condition by lowering 50/100 to 40/100. The results becomes 0....


title: Overscript distance

text: When I write:               Overscript[PQ, \[RightVector]],       the arrow is placed too close to the `P` and `Q`. Is there a way to modify the default distance used by `Overscript`?


title: Force Dispatch to generate dispatch tables

text: Dispatch creates hash tables only for lists of length larger than 3. Is there any way to force MMA to create hash tables even for lists of length smaller than 4?               Table[Head@Dispatch@Table[Rule[a[i], i], {i, n}], {n, 5}]     (* {List, List, List, Dispatch, Dispatch} *)


title: Why is ToRadicals[] not able to handle all cases? Is there a workaround?

text: The documentation for the function `ToRadicals` says: > ♦ There are some cases in which expressions involving radicals can in > principle be given, but `ToRadicals` cannot find them. I'm concerned only with cases where the argument to `ToRadicals` is a single `Root` object with a single polynomial function with integer coefficients and no parameters, and an explicit root index. * * * Here is an example when _Mathematica_ cannot find an expression in radicals:               ToRadicals[Root[-1 - #1^2 - #1^3 + #1^4 + #1^6 &, 2]]      But actually the expression exists: $$\frac1{\sqrt[3]{36}}\left(\frac3{\sqrt{\beta\phantom{.}}}+\frac\beta2\right),\ \text{where}\ \beta=\sqrt[3]{2\,\ \alpha}-8\sqrt[3]{\frac3\alpha\phantom{}},\ \alpha=9+\sqrt{849}.$$ * * * Another example is               ToRadicals[Root[6 + 25 #1 - 25 #1^3 + 5 #1^5 &, 5]]      where the expression in radicals is $$\sqrt[5]{\frac{-3+4\sqrt{-1}}5}+\sqrt[5]{\frac{-3-4\sqrt{-1}}5}$$ * * * What is the nature of this restriction? Is the problem known to be undecidable in general? Or is it extremely computationally expensive? Can we write an implementation of `ToRadicals` that is able to find an expression in radicals in all cases when it is possible? Or, at least, in much more cases then the built-in `ToRadicals` does?


title: Can Epilog be used with ParametricPlot3D

text: This command:               ParametricPlot3D[{Cos[t], Sin[t], t}, {t, 0, 2 \[Pi]},          Epilog -> {Arrow[{{0, 0, 0}, {Cos[\[Pi]], Sin[\[Pi]], \[Pi]}}]}]      Produces the message: > Coordinate {0, 0, 0} should be a pair of numbers, or a Scaled or Offset > form.


title: How can I use shared libraries in LibraryLink code and ensure Mathematica will find them?

text: I need to use shared libraries in some LibraryLink code. The shared library is installed in a custom location because it was also compiled by myself. When I try to load functions from the LibraryLink library, I get `LibraryFunction::libload` errors because Mathematica is not able to find the shared library. What is the solution to this problem?


title: Why am I getting a kernel crash on Chop?

text: First post, hopefully I figure out the formatting easily. Please forgive me if this posts ugly. I am having a (repeatable) problem where when I run my code everything works fast and the output is displayed but the program has some error in which it erases the kernel (maybe that's not the correct term). Basically all my variables reset and _Mathematica_ goes back to being as if I just opened the software. For context, this is the output of a secular variation model               (0.0057300369 - 0.0071475265 I) E^((-8.2717832*10^-25 +  6.6290151*10^-9 I) t) -     (0.0000981431 +  0.0001437239 I) E^((-3.7695835*10^-29 +  1.4229429*10^-9 I) t) +     (0.000072401667 -   0.000092434689 I) E^((0. +   2.6555734*10^-8 I) t) +     (0.000092742725 -   0.000015933052 I) E^((4.0245734*10^-26 + 3.1934271*10^-10 I) t)      Those real pieces in the exponential are really zero except for some numerical error. I want to `// Chop` it. When I do however, my machine makes a "dong" sound (standard Mac error sound) and _Mathematica_ or the kernel resets. I would guess it is repeatable for anyone else to try as well. I completely quit _Mathematica_. Reopen then copy paste the block above into a new window. A chop at the end of it has the same result. It spits out the right answer, but this is just a step in a loop, so I need all my variables and such to stay defined. Any reason someone can see that this is happening? ### Edit My guess is _Mathematica_ just needs a real component in the exponential. Don't know why, though. Take that bit above and use `// ComplexExpand //Chop` gives it in an equivalent form in sines and cosines.


How do I extract the middle element(s) of a given list? Here is some code that works, but seems a little too long:               extract[x_] :=            Part[x, If[IntegerQ[#], {#}, {Floor[#], Ceiling[#]}] & @ Median[Range[Length @ x]]]      Here is another, shorter routine, but for a list of even length, it only gives one value, not two. I think two values would be better for even lists:               extract[x_] := Part[x, Quantile[Range[Length @ x], 1/2]]      So is there concise, efficient code that will return two elements for a list of even length?


title: Creating a standalone (executable) from mathematica code

text: I have written a small mathematica code to input a ".csv" file and output the data in a specific format, in a ".txt" file. I would like to give this program as an executable to my friend as she doesn't have mathematica installed. I've seen how one creates ".exe" from mathematica. However the process doesn't seem to work for me. Can anyone kindly help. Here is the mathematica code:               content=Drop[Transpose[Import["~/Downloads/19162.csv"]],2];          sorted=GatherBy[DeleteCases[DeleteCases[Flatten[content],""],"="],StringTake[#,StringPosition[#,"="][[1]][[1]]]&];          tab=OutputForm[TableForm[sorted]];          Export["~/Downloads/19162.txt",tab]      I would like the executable to input a file (in ".csv") format and output the text file in the "~/Downloads/" folder (of course the choice of the folder isn't important here).


title: FillingStyle Thickness Distorting ListPlot image

text: I'm trying to create a histogram using `ListPlot` using the `Filling->Axis` and `FillingStyle -> {{LightGray, Thickness[.1]}}` as options. However, when I use this the columns are actually higher than the value in the lists. Below is an example                  n = 6;        p = 0.5;        (*calculate probabilities *)        list = Table[          c = Binomial[n, k];          d = p^k (1 - p)^(n - k);          {k, c* d}, {k, 0, n}]                  (*FillingStyle Thickness results in additional height being added to \        top of each column*)        ListPlot[(list),          Joined -> False,         Axes -> True,         FrameTicks -> {Table[i, {i, 0 , n, 1}],            Table[i, {i, 0, 0.3, 0.05}]},         FrameLabel -> {"Successes k", "Probability"},         Frame -> {True, True, False, False},         PlotStyle -> Automatic,         Filling -> Axis,         FillingStyle -> {{LightGray, Thickness[.1]}},         ImageSize -> 6*72 ]      Does anyone have a suggestion for a solution for this problem while still using `ListPlot`? Thanks, Mike


title: Not evaluating all cells unless I explicitly evaluate each one?

text: I'm running a Mathematica (version 8) notebook. In one of the first few cells, it is supposed to plot some data. It uses a couple functions that are defined in an above cell. If I do Evaluation-> Evaluate Notebook (which should evaluate the whole notebook, starting from the top, right?), it goes through and seems to evaluate it (the bars at the right turn from highlighted to regular as it goes down the notebook), but it doesn't produce the plot, or several other results that should output to the screen (they don't have a semicolon). However, if I go down from the top and manually hit shift+enter for each cell in order, it produces what it's supposed to. Am I doing something dumb? What's going on? Thanks!


title: Finding y given x from an interpolating function

text: I would like to put a dot on the point of a curve that has a specific y value but I don't know the x value. A simple example of my code is               eqns = {y''[t] + y[t] == 3 a Sin[y[t]], y[0] == y'[0] == 1};     pfun = ParametricNDSolveValue[eqns, y[1] + y[2], {t, 0, 5}, {a}];     Plot[pfun[a], {a, -2, 2}]      ![enter image description here](http://i.stack.imgur.com/kjNg7.png) So say I want to find the x at which y=3. How? Once I have the two coordinates I know how to add the dot. I guess I'm confused because the interpolating function gives you the y given the x, and I can't figure out how to do the inverse. Also any suggestions of tutorials on how to use interpolating functions would be great. Thanks!


title: Challenge: Creating Compilable Permutations Function

text: As Mathematica's implemented `Permuations` function is not compilable I tried to write my very own Permutations implementation, called `PermutationsNew`, which I want to compile later on. Unfortunately the only implementation I came up with so far uses recursive programming and looks like this:               PermutationsInternal = Function[{list, listfixed}, If[Length[list] == 1, Join[listfixed, list], Table[PermutationsInternal[Drop[list, {i}], Append[listfixed, list[[i]]]], {i, Length[list]}] ]];     PermutationsNew[list_] := Flatten[PermutationsInternal[list, {}], Length[list] - 2]      The implementation seems to work fine, but because of the recursive structure I cannot come up with any approach that can be compiled, because mathematica has trouble compiling the lists encountered in `PermutationsInternal`. Does anybody have an idea on how to compile the above approach or can offer me an idea for a different compilable solution?


title: How to transform the polynomial in this way?

text: I have two functions `f` and `g` and a polynomial                poly=p[1,1]+2*p[1,2]-3*p[1,3]-p[2,1]+p[2,2]-p[4,3]      and I want to transform the `poly` into                f[1,1]+2*f[1,2]+3*g[1,3]+g[2,1]+f[2,2]+g[4,3]      Generally, I want to transform $$poly = \sum (-1)^{\tau_{i,j}} a_{ij}*p[i,j]$$ into $$\sum_{\tau_{i,j}=0} a_{ij}*f[i,j] + \sum_{\tau_{i,j}=1} a_{ij}*g[i,j]$$ What's the most elegant and efficient way?


title: How can I change the keyboard shortcut for switching the active window?

text: The default keyboard shortcut (on Windows at least) for switching focus to the next window is Ctrl+F6, and for switching to the previous windows it's Shift+Ctrl+F6. How can I change this to Ctrl+Tab and Shift+Ctrl+Tab respectively (or some other pair of combinations which is not used by default)?


title: Use output from Plot3D as an object in Graphics3D that I can transform

text: I'm trying to draw up an optical system where I can show an example of wavefront error on an exit pupil. It would be great if I could take the results of a 3D function from Plot3D and use it as a graphics object that I could transform to fit into my Graphis3D drawing. Below is some code that does not work but it shows a very simple case of what I would like to be able to do.               pic = Plot3D[Sin[x] Sin[y], {x, -5, 5}, {y, -5, 5},              RegionFunction -> Function[{x, y, z}, x^2 + y^2 <= 20]];          Graphics3D[{Rotate[pic, \[Pi]/4, {1, 1, 1}],              Arrow[{{0, 0, 0}, {5, 5, 5}}]}]


title: How do I create an ellipse bubble chart?

text: I have some data that I would like to plot as a bubble chart. The data is formatted as {{val1_mean,val1_sd,val2_mean,val2_sd},{val1_mean,......}}. What I would like to do is plot a bubble chart where the x/y location of the bubble is val1_mean,val2_mean and the width/height of the bubble is val1_sd,val2_sd. So far I've been able to do circular bubble charts with the inbuilt function but am a bit lost as to how to make the bubbles ellipses instead of circles. Here's the code I've written so far;               bubleData={{1.88308*10^6, 1024.85, 149446., 6636.62}, {1.98345*10^6, 15022.5,      126966., 7071.75}, {1.94677*10^6, 9281.83, 131930.,      7435.15}, {1.88308*10^6, 1024.85, 127423., 8718.36}};     BubbleChart[bubbleData[[All, 1 ;; 3]],ChartStyle -> Directive[Opacity[0.5]]]      ![enter image description here](http://i.stack.imgur.com/iE8CY.png)


title: Arcs of rotation for angles

text: 1. How can I draw trigonometric angles of any radian measure associated with the unit circle, complete with the x-axis and y-axis?    2. How can I draw arcs of rotation inside positive or negative angles?   3. Is there a method for drawing arcs inside angles of more than one rotation? Here is a link showing what I would like to draw: http://hotmath.com/hotmath_help/topics/coterminal-angles.html


title: Efficient Data Entry / Manipulation with Many Datasets

text: I currently have a simple task of graphing many different datasets (26 here, with many different instances where I'll need to do, say, 26 different ones from the same template). I'm trying to minimize the amount of "name changing" I'll have to do manually, as the treatment of each dataset is virtually identical aside from the names and (obviously) individual data points being graphed. For example, I have a large table (specifically imported using ExcelRead with ExcelLink) with: `data = {{DataSetName1, m1, m2, m3,m4},{DataSetName2, m1, m2, m3, m4},...}` etc. for all 26 datasets and their measurements 1 - 4 as a function of time. Next I have to extract each datasets information individually using `time=[5, 10, 20, 1440]` for the time intervals my data is taken at, `DataSet1raw = Rest[Part[data, 2, 1;;5]` and then `DataSet1 = Transpose[{time, DataSet1raw}]` `DataSetList = {"DataSet1Name","DataSet2Name","...", "DataSet26Name"}` to finally yield the time-series `{{t1, m1},{t2, m2}, ...}` form and a list of the names of each set. Combining the list of time-series (& names respectively) to graph in thirds for ease of viewing, `AllSets = {DataSet1, DataSet2, ..., DataSet26}` `FirstCollection = Take[AllSets, 1;;9]` `SecondCollection = Take[AllSets, 10;;18]` `FinalCollection = Take[AllSets, 19;;26]` After doing this individually for 26 numbered data sets (such as NB1,NB2,NB3, etc., all of which contain name-specific components previously used), it is finally in the form where I can graph the datasets easily using: `ListLogLinearPlot[FirstCollection, Legending, etc.]` So, my question is a general one of how to optimize this process. Currently I'm leaning towards generalizing the terms like I've done above, and trying to use a simple process of "Specific name = generic name," but suspect my lack of general organizational Mathematica familiarity (and coding in general) has me complicating much of this process. Thank you for taking the time to respond! Update: After investigating further as to how to possibly simplify the process, I've at least found in the documentation a means of possibly doing the renaming of each drug iteration (26 times here) by a series of `ToString` and `ToExpression` functions, in case anyone else is facing a similar dilemma.


title: How do I draw a triangle given the lengths of the sides?

text: I know, of course, how to draw a triangle in the plane given the vertices:               Graphics[Polygon[{{1, 0}, {0, Sqrt[3]}, {-1, 0}}]]      But I'm not sure how to simply draw a triangle if all I care about is the length of the sides. (I'm happy to place one of the vertices at the origin and place one of the sides on the non-negative side of the x-axis, but that doesn't really matter.) Is there a straightforward way? This raises the additional question, "how do I draw a triangle in Mathematica, given three angles?" (Say I want to it to reside somewhere in the unit circle.)


title: How to import and visualize a network stored as an edge list in CSV file?

text: I'm extremely new to Mathematica, and I'm trying to import an edgelist representing a network, but I think I'm missing something major. **Here is my process so far just to import and visualize the data:**               SetDirectory["C:\\path\\to\\files"]     net = Import["data.csv"]     GraphPlot[net]      **The format of my data is as follows:**               A, B     A, C     B, D     C, E     C, F     C, G     D, F      I've imported a couple of different networks, and they all end up looking the same. I'm sure that I'm missing some major step, most likely in declaring that this is an edgelist.


title: What is the quickest way to convert a lot of SQLDateTime[] objects to DateLists

text: I often run database queries that return sets of {date, datum} objects. A hypothetical query looks like               testData = SQLExecute[commodDB, "select date,price from commoddb.tbcommodprices     where futurePrefix='XB'"];      and the results look like               {{SQLDateTime[{2005, 10, 3}], 188.88}, {SQLDateTime[{2005, 10, 4}],      184.53}, {SQLDateTime[{2005, 10, 5}],      176.5}, {SQLDateTime[{2005, 10, 6}],      172.}, {SQLDateTime[{2005, 10, 7}] . . . etc}      To do anything useful with these, I need to convert the SQLDateTime[] objects into Mathematica datelists. With the example above, this can be done with               Map[{#[[1]][[1]], #[[2]]} &, testData]      But this takes longer than I would like; I feel as though this conversion is trivial and should be basically instantaneous, but for typical queries (which admittedly return thousands of results), the conversion takes half a second or more. Can anybody suggest a quicker way to convert my SQLDateTime[]s into DateLists? Thanks.


title: How to calculate the following integral of the multiplication of two Bessel functions?

text: This integration has an analytical solution and its behavior is described by 1/r^2 function, but Mathematica gives some weird oscillating answer. Can anybody explain this and help me overcome this issue.               R  = 1500;     f[r_] := NIntegrate[BesselJ[2, r*k]*BesselJ[1, R*k], {k, 0, Infinity},AccuracyGoal -> 12]     sol = Table[Abs[f[r]]^2, {r, R, 2000, 10}];     ListLinePlot[sol, PlotRange -> All]


title: Implementing a safe ValueQ that does not evaluate its argument

text: _Mathematica_ has a built-in function `ValueQ`. Quoting the docs, > `ValueQ[expr]` gives `True` if a value has been defined for `expr`, and > gives `False` otherwise. > > ... > > `ValueQ` gives `False` only if `expr` would not change if it were to be > entered as _Mathematica_ input. This works nicely with symbols that only have `OwnValues`:               x = Print["boo!"]     ValueQ[x]          (* ==> True *)      It doesn't work so nicely with functions, though:               f[x_] := Print[x]     ValueQ[f[1]]          (*          1      ==> True     *)      This gives `True`, but also evaluates `f[1]` completely, printing `1`. This is clearly dangerous, and it is important to be aware of this. Unfortunately, the docs make no mention of this under the "Possible Issues" section! Why this happens is clear if we look at the implementation of `ValueQ` for non-symbols:               ValueQ[expr_] := ! Hold[Evaluate[expr]] === Hold[expr]      **Question:** Is it possible to implement a more robust version of `ValueQ`, which does not evaluate its argument in an unexpected an possibly dangerous way?


title: Efficient code for building a big list

text: I would like replace the following code               With[{n = 5},       Flatten[         Table[Join @@ NestList[Abs@Differences@# &, {a, b, c, d, e}, n - 1] // Evaluate,            {a, #}, {b, #}, {c, #}, {d, #}, {e, #}] &[n (n + 1)/2], n - 1]]; // AbsoluteTiming     (*{0.551032, 759375}*)      with this               With[{n = 5},       Join @@ NestList[Abs@Differences@# &, #, n - 1] & /@          Tuples[Range[n (n + 1)/2], n]]; // Timing      but the second method is much slower than the first. How can I make it fast?


title: Modified definition of Sin does not work in Plot

text: I don't know if this issue has been discussed before, if anyone know any related post, please let me know, thank you :) `Unprotect` the function `Sin` and create a new definition for it:               Unprotect[Sin];     Sin[x_] := x^2;      Because `x_` matches any expression, then I think (naively) the system definition of `Sin` would never be applied.               {Sin[2], Sin[1.2], Sin[Sin]}     (*        {4, 1.44, Sin^2}     *)      Every thing works as expected except for `Plot`:               Plot[Sin[x], {x, 0, Pi}]      ![enter image description here](http://i.stack.imgur.com/6XmSH.jpg) I think it's related to the internal computation of `Plot`, I checked the mass output of `Trace` and found nothing useful. I know it's stupid to modify a system symbol this way, but could you please give me some explanation? Thanks in advance.