GraphPlot not working properly

The code               e = {{Subscript["E",1,2],Subscript["E",2,3]} -> {Subscript["E",1,3]}};     v = {{Subscript["E",1,2]}, {Subscript["E",1,3]}, {Subscript["E",         2,3]}, {Subscript["E",1,2], Subscript["E",2,3]}};     GraphPlot[Join[e, #->#& /@ v], VertexLabeling->True,       EdgeLabeling->False, DirectedEdges->True, SelfLoopStyle->False,      VertexCoordinateRules -> ((#->{Length[#],Automatic})& /@ v)]      produces ![enter image description here](http://i.stack.imgur.com/1MzVq.jpg), but clearly my input also specifies a vertex $\\{E_{1,2}\\}$. Where is it?


How to determine coordinates of a shape in an image?

I have a pre-processed image, from which I have to get coordinates of some components. ![sample image](http://i.stack.imgur.com/xg4lA.png) There are 7 green components (pigs actually) that I have already isolated from an angry bird screen shot. So what I want is to locate those six components on the image. I tried               ImageValuePositions[u, RGBColor[1, 0, 0], .1]     { Mean[#1], Mean[#2]}& @@@ Transpose /@ FindClusters[%];     LocatorPane[ %, sample image]      But it doesn't work at all. Could anyone help me out? ![sample2](http://i.stack.imgur.com/ZZyLq.png) How should I figure this out?


Formatting plot of symmetric points differently to asymmetric points

From an array of numbers, I would like to determine (and then colour appropriately) which points are symmetric about a given axis (here, $x = 1/2$), and which are not. For example, form this:               ListPlot[{{1.5,1.5},{1,1},{1.5,-0.5},{-0.5,-0.5},{-0.5,1},{-0.5,1.5}},      PlotStyle -> Red]      I would like to achieve this:               Plot[{0}, {x, -2, 2}, PlotRange -> {-2, 2}, Epilog ->      {PointSize[Medium], Red,Point[{{{1.5, 1.5}, {-0.5, 1.5}, {1.5, -0.5}, {-0.5, -0.5}}}],     PointSize[Medium], Blue, Point[{{-0.5, 1}, {1, 1}}]}]      (Please excuse the clumsiness with which I code: I am very new to _Mathematica_.) I have looked at `Symmetric` in Wolfram Documentation, but it doesn't seem to cover this. I don't know of a method for selecting certain arrays and formatting them with one colour, then selecting a different set and formatting that with another colour, other than by doing it manually. Is there a way of automating this process? (My goal is to do this for arrays of over `1000` points, so sorting manually is not really an option!) # Update2 Data: array link # Update3 @Kuba, Using the code you provided in answer to my other post:               sol = Solve[N[Table[BernoulliB[n, z], {n, 1000, 1000}] == 0]];      would it be possible to find symmetric points? (And also format the plot: `AspectRatio -> Automatic, Plot Axis @ x = 1/2`, etc.?) # Update4 Note: So as not to mislead, I have included a corrected plot. The strange pattern produced without precision adjustment: ![enter image description here](http://i.stack.imgur.com/G3f5k.gif) is purely caused by numerical error (thanks to Antonio Vargas for pointing this out) - the corrected plot for n = 171 (n = 1000 is too much for my machine!), calculated to greater precision, looks like this: ![enter image description here](http://i.stack.imgur.com/DcbGs.gif) Plotted using Kuba's code:               sol = Solve[N[Table[BernoulliB[n, z], {n, 171, 171}] == 0, 50]];     point[x_?VectorQ] := {PointSize@.01, Red, Point[x]}     point[x : (_?VectorQ ..)] := {PointSize@.01, Blue, Point /@ {x}}     axis = 1/2;     point @@@ GatherBy[{Re@z, Im@z} /. sol,(*Round added*)     Round[{Abs[#[[1]] - axis], #[[2]]}, 0.001] &] //      Graphics[#, Frame -> True, GridLines -> {{axis}, None}] &


How can I add a tangent arrow at a certain point of a curve in a LogPlot?

How can I add an arrow at a certain point of a curve with the direction of the arrow tangential to that point? (Line are not straight in a log-plot.)               LogPlot[(1 - τ)^(-0.5),      {τ, 0, 1}, PlotRange -> {{0, 1}, {0.66, 20}},      Frame -> {{True, True}, {True, False}},      ImageSize -> 600,      PlotStyle -> {Directive[Black, Thick]},      BaseStyle -> {FontSize -> 30},      RotateLabel -> False,      AspectRatio -> 1      ]      ![enter image description here](http://i.stack.imgur.com/MAuZq.png)


BezierCurve in EdgeShapeFunction fails when used on multiedges graph

I would like to create a network graph with curved edges. To do this, I wrote this function:               edgeFun[pts_, e_] := Module[{controlPts},          controlPts = pts /. {a_, b_} :> {a, {a[[1]] + .1 b[[1]], a[[2]]},                                              {a[[1]] + 0.1 b[[1]], b[[2]]}, b};            BezierCurve[controlPts]     ];      With no multiedges the `edgeFun` function works fine:               pts = {1 -> 2, 2 -> 3, 3 -> 1};     Graph[pts, VertexLabels -> Placed["Name", Center], EdgeShapeFunction -> edgeFun]      ![Mathematica graphics](http://i.stack.imgur.com/NL3rJ.png) But when I want to create a network with multiple edges (note `1 -> 2` and `2 -> 1`, _Mathematica_ complains and the graph is pinked out:               pts1 = {1 -> 2, 2 -> 3, 3 -> 1, 2 -> 1};     Graph[pts1, VertexLabels -> Placed["Name", Center], EdgeShapeFunction -> edgeFun]      > >     Part::partd: "Part specification 0.496922[[1]] is longer than depth of > object" >   Does anyone know how to solve this problem?


Filtering elements from a list

Suppose that I have a list               {{{2, 1}, {4, 3}, {2, 4}}, {{2, 1}, {4, 3}, {3, 1}},      {{2, 1}, {2, 4}, {3, 1}}, {{4, 3}, {2, 4}, {1, 2}}}      I want to make a new list that only contains the entries for which the first component of each pair does not repeat itself. So for example, the element               {{2, 1}, {4, 3}, {2, 4}}      would be eliminated since `2` appears in the first component of both `{2,1}` and `{2,4}`. Likewise, `{{2, 1}, {2, 4}, {3, 1}}` will also be eliminated. Is there a simple condition I can use with the `Select` function to do this? Thanks in advance.


Standard errors for maximum likelihood estimates in FindDistributionParameters

I am trying to fit a non-standard PDF to data and `FindDistributionParameters` works great, and gives me the parameters of the distribution back using maximum likelihood, but I cannot find a way to get Mathematica to spit out the standard errors (or confidence intervals) for those estimated parameters. Anyone knows how to do it, or should I just go to a different program, i.e. MATLAB?


Swap two entries in a matrix

Is there a nice, simple script one can use to swap two entires in a matrix? For example, suppose we have the matrix below: $A=\begin{pmatrix}2 & 4 & 1\\\ 3 & 1 & 2\\\ 4 & 3 & 1 \end{pmatrix}$ Is there a script of the form `switch[A,a,b]`, which will swap all occurrences of $a$ in the matrix with $b$, and vice versa, and then update the matrix $A$ accordingly? So in this case the output of `switch[A,2,3]` would be: $A=\begin{pmatrix}3 & 4 & 1\\\ 2 & 1 & 3\\\ 4 & 2 & 1 \end{pmatrix}$ My own solution involves a lot of `If` and `For` functions, and will, I think, also run into the problems detailed here. I think it will work eventually (and I'd be happy to post what I have so far if people would like), but really I'm just wondering whether there's a simpler way to do this. Thanks!


How can I rationalize the denominator of an expression?

_Mathematica_ doesn't rationalize the denominator automatically, and I haven't found anything in the documentation about it. But I found an old post on MathGroup, which proposes a solution using `ComplexityFunction`. In very simple cases, it works fine, but it fails in more complex cases. Is there a better way to do it?


Distinguishing slots in a function mapping Position across a list

Suppose that I have a list `myList` that has more than one level. Here is an example of such a "data structure":               myList = {{10, "c"}, {20, "a"}, {30, "b"}};      Now suppose that I have a list of characters, called `charList`:               charList = {"a", "b", "c"};      I want to use `Position` to find the positions of the `charList` characters in `myList`. Of course, I can do this manually -- by calling `Position` for each character in `charList`:               Position[myList, _?(#[[2]] == "a" &), {1}, Heads -> False]     Position[myList, _?(#[[2]] == "b" &), {1}, Heads -> False]     Position[myList, _?(#[[2]] == "c" &), {1}, Heads -> False]      > {{2}} > > {{3}} > > {{1}} And, of course, I can shorten this process by using `Table` to call `Position` repeatedly:               Table[      Position[myList, _?(#[[2]] == charList[[i]] &), {1}, Heads -> False],      {i, 1, Length[charList]}]      > {{{2}}, {{3}}, {{1}}} But, is it possible to shorten the code even more by using `Map`? (I often find `Map` more convenient and easier to read than `Table`.) My initial thought was to do something like this:               Map[      Position[myList, _?(#[[2]] == # &), {1}, Heads -> False] &,     charList]      but I get undesired output: > {{}, {}, {}} I think that I have failed to distinguish between the two different `#` slots, which refer to two different things (they refer to different `&`s). How can I distinguish the two `#` so that I can `Map` `Position` across `charList`?


Fastest way to create a NxNxNxN dimensional matrix

I have a function that outputs a complex number               Func[x_,y_]:= blah blah;      I have constructed a table of all possible values of this function.               Bar = Table[Func[x,y],{x,1,N},{y,1,N}];      I do this so it can be faster accessed in the next step. I need to compute the following matrix/table of all possible values of two of these functions multiplied by each other.               result = Table[Bar[[x,z]] Bar[[y,w]], {x,1,N}, {y,1,N}, {w,1,N}, {z,1,N}];      And this actually takes quite some time, because this table would have around `150^4` entries for `N=150`. How can I speed this up? It currently takes around 1 hour using `ParallelTable`. What is the fastest way to make a table of this size and store it to memory to be accessed in a calculation? EDIT: `Bar` has the following symmetry:               Bar[[x,y]] = Bar[[y,x]]


Thread a function over a list and with a non-atomic 2nd parameter?

From the documentation, Thread's behavior on functions where the first parameter is a List and the second is an atomic expression, is this:               Thread[f[{a, b, c}, x]]           (* {f[a, x], f[b, x], f[c, x]} *)      If the second argument of 'f' is not atomic, it is possible to thread over its first argument {a,b,c} while treating the 2nd argument as if it were atomic? For example, consider:               M = Table[i + j, {i, 1, 3}, {j, 1, 2}]          (* {{2, 3}, {3, 4}, {4, 5}} *)      Then,               Thread[f[{a, b, c}, M]]          (* {f[a, {2, 3}], f[b, {3, 4}], f[c, {4, 5}]} *)      This is understandable because M is not atomic so For example:               g[p_, M_ /; Dimensions[M] == {3, 2}] := {p, M}      Threading over `g` Doesn't work as intended:               Thread[g[{a, b, c}, M]]          (* {{a, {2, 3}}, {b, {3, 4}}, {c, {4, 5}}} *)      Worse still, the result above is due to a coincidence: Length@M==3. If this is not the case, Thread returns an error:               Thread::tdlen: Objects of unequal length in f[{a,b,c},{{2,3,4,5},{3,4,5,6}}] cannot be combined. >>      I've also considered wrapping M in some variation of Hold, but none yield atomic expressions. Is there a way to force Thread to treat the 2nd argument of the function as atomic? The ultimate goal is to `SetAttributes` of the function to `Listable`.


Help with finding solution for utility function

I'm brand new to Mathematica and having trouble finding a solution for Lh based on the first order condition. I'm not sure if it is something I'm doing in Mathematica or something wrong with the equations. Any suggestions?               Utility[x_] = (((x - Eta)^(1 - Theta))/(1 - Theta))     Harvest[Lh_] = (Lh)^Beta     Livestock[Nt_] = Nt*(1 + b - Delta*(T*Nt)/(L - Lh))     constraint = P*Harvest[Lh] - Alpha*Livestock[N]     Langragian = Utility[Livestock[N]] + Lambda*constraint     {FOC1 = D[Langragian, Lh],       FOC2 = D[Langragian, Lambda]}     sols = Solve[{FOC1 == 0, FOC2 == 0}, {Lh, Lambda}]


Calculating the Mean of a Truncated Multinormal Distribution

First, I'm a little disappointed that Mathematica balks at:               Mean[TruncatedDistribution[{{0, Infinity}},MultinormalDistribution[{0}, {{1}}]]]      Second, is the numerical computation of means from truncated multinormal distributions so hard? Is anyone aware of a package that implements the algorithm of Leppard and Tallis (1989) (see here for FORTRAN code) or anything like it? **Edit** : rm asked for an example that fails to compute:               Mean[TruncatedDistribution[{{0, Infinity}, {0, Infinity}},          MultinormalDistribution[{0.5, 1.5}, {{1., 0.3}, {0.3, 1.}}]]]


How to get a rule for, e.g., (x + y) to apply to (-x - y), etc.?

For example, the substitution `(x + y) -> s` fails here:               In[1]:= (-x - y) /. (x + y) -> s          Out[1]= -x - y      Of course, I could try applying the rule `(-x - y) -> -s`, but this strategy becomes unwieldy in more complicated cases. At the very least it would require duplicating a lot of rules. For example, if the expression to be transformed were something like               (x + y)^2 + 2 (-x - y)      ...then I'd need to use something like               {(x + y) -> s, (-x - y) -> -s}      Is there a better way to transform the above expression to `s^2 - 2 s`?


How to quickly calculate intersections of filled curves?

I am trying to quickly calculate the intersection of polygons with more than 6,000 points. A compiled solution would be preferable. Here is one example of the problem:               o = First[            First[ImportString[              ExportString[               Style["O", Italic, FontSize -> 24, FontFamily -> "Times"],                "PDF"], "PDF", "TextMode" -> "Outlines"]]];          p = First[        First[ImportString[          ExportString[           Style["P", Italic, FontSize -> 24, FontFamily -> "Times"],            "PDF"], "PDF", "TextMode" -> "Outlines"]]];          Graphics[{EdgeForm[Black], ColorData["Crayola", "Sunglow"], {o, p}}]      Another:                   Module[{a = FilledCurve[{{Line[{{2, 3}, {0.8125, 0.625}}],           BezierCurve[{{0.6875, 0.375}, {0.375, 0.25}, {1.125, 0.25}},             SplineDegree -> 2],            BezierCurve[{{0.8125, 0.375}, {0.9375, 0.625}}],           Line[{{1.3125, 1.375}, {2.4375, 1.375}, {2.8125, 0.625}}],           BezierCurve[{{2.9375, 0.375}, {2.625, 0.25}, {3.625, 0.25}},             SplineDegree -> 2],            BezierCurve[{{3.3125, 0.375}, {3.1875, 0.625}}]},          {Line[{{1.875, 2.5}, {1.375, 1.5}, {2.375, 1.5}}]}}]},       Graphics[Table[{EdgeForm[Black], Hue[RandomReal[]],          Translate[Rotate[Scale[a, RandomReal[5]], RandomReal[2 Pi]],           RandomReal[20, {2}]]}, {30}]]]      **So in the problem is:** how to intersect of multiple (or two at a time) polygons (with or without) holes (and with up to 6000 points in their triangulations)? I have tried using the Weiler–Atherton clipping algorithm but my implementation was too slow (anything relying on bitmaps is too slow). Perhaps there is a solution that uses LibraryLink to harness a standard library? I found one here http://www.cs.man.ac.uk/~toby/alan/software/gpc.html ## Updates It was suggested in the comments that Graphics`Mesh` be used but this is way too slow in even 100 points and doesn't handle holes:               a = Polygon@RandomReal[1, {100, 2}];     b = Polygon@RandomReal[1, {100, 2}];     AbsoluteTiming[c = Graphics`Mesh`PolygonIntersection[a, b]]     Graphics[{Blue, a, Red, b, Yellow, Polygon /@ List @@ c}]      ![enter image description here](http://i.stack.imgur.com/nernU.png) Here is a sample input polygon for the letter G:                G = Polygon[{{-0.466796, -0.0328696}, {-0.466336, 0.0186753}, {-0.463089,         0.0682893}, {-0.459379, 0.100181}, {-0.451495,         0.146241}, {-0.444693, 0.175763}, {-0.432171, 0.21827}, {-0.422278,         0.245423}, {-0.411147, 0.271628}, {-0.39878, 0.296886}, {-0.37791,         0.332996}, {-0.362451, 0.355885}, {-0.345756,         0.377826}, {-0.327823, 0.398819}, {-0.300607,         0.426707}, {-0.281598, 0.443668}, {-0.251786,         0.466663}, {-0.231046, 0.480362}, {-0.198638,         0.498465}, {-0.176168, 0.508902}, {-0.141165,         0.522112}, {-0.116964, 0.529288}, {-0.0793649,         0.537605}, {-0.0534337, 0.541519}, {-0.013239,         0.544944}, {0.0144228, 0.545596}, {0.0521431,         0.544603}, {0.0973423, 0.540566}, {0.140374, 0.533423}, {0.181237,         0.523175}, {0.212366, 0.512741}, {0.249327, 0.496903}, {0.283288,         0.47845}, {0.310993, 0.459561}, {0.336333, 0.438254}, {0.359309,         0.414528}, {0.379921, 0.388384}, {0.398168, 0.359821}, {0.414052,         0.328839}, {0.427571, 0.295438}, {0.438725, 0.259618}, {0.444849,         0.234395}, {0.449921, 0.208096}, {0.309296, 0.208096}, {0.299494,         0.244597}, {0.29219, 0.264834}, {0.283819, 0.283824}, {0.267496,         0.312703}, {0.256279, 0.328367}, {0.243996, 0.342784}, {0.235215,         0.351703}, {0.221153, 0.364041}, {0.206024, 0.375133}, {0.189953,         0.385077}, {0.161346, 0.399325}, {0.14309, 0.406478}, {0.124015,         0.412584}, {0.0904026, 0.420435}, {0.0691431, 0.42375}, {0.0470644,         0.426018}, {0.00844619, 0.427471}, {-0.0284694,         0.425533}, {-0.0551123, 0.421535}, {-0.0892443,         0.412813}, {-0.121786, 0.400214}, {-0.152737,         0.383739}, {-0.182097, 0.363387}, {-0.209866,         0.339158}, {-0.235987, 0.311056}, {-0.248019,         0.295569}, {-0.259191, 0.279133}, {-0.269503,         0.261747}, {-0.278956, 0.243411}, {-0.291525,         0.214127}, {-0.298829, 0.193418}, {-0.305275,         0.171759}, {-0.313331, 0.137489}, {-0.321066,         0.0884734}, {-0.325362,         0.0356589}, {-0.32624, -0.0188127}, {-0.324105, -0.0667413}, \     {-0.319123, -0.112199}, {-0.311294, -0.155187}, {-0.300618, \     -0.195705}, {-0.294213, -0.215037}, {-0.28327, -0.242878}, \     {-0.270726, -0.269329}, {-0.25151, -0.302436}, {-0.235136, \     -0.325433}, {-0.216766, -0.346138}, {-0.196376, -0.3645}, {-0.173967, \     -0.380518}, {-0.149538, -0.394191}, {-0.123089, -0.405521}, \     {-0.104334, -0.411771}, {-0.0846818, -0.41698}, {-0.0535202, \     -0.422841}, {-0.0203389, -0.426357}, {0.0148622, -0.427529}, \     {0.0509528, -0.426065}, {0.0853497, -0.421672}, {0.118053, \     -0.414352}, {0.149062, -0.404104}, {0.171208, -0.394496}, {0.1924, \     -0.383241}, {0.212641, -0.370339}, {0.231928, -0.35579}, {0.250217, \     -0.339572}, {0.266916, -0.321406}, {0.281843, -0.301207}, {0.290811, \     -0.286611}, {0.302785, -0.263022}, {0.312987, -0.237399}, {0.321418, \     -0.209743}, {0.326054, -0.190175}, {0.331531, -0.159129}, {0.334198, \     -0.137302}, {0.336722, -0.102866}, {0.337421, -0.0787786}, {0.174296, \     -0.0787786}, {0.0111708, -0.0787786}, {0.0111708,         0.0393464}, {0.238983, 0.0393464}, {0.466796,         0.0393464}, {0.466796, -0.517529}, {0.377235, -0.517529}, \     {0.343661, -0.386923}, {0.320697, -0.411362}, {0.294314, -0.43722}, \     {0.26921, -0.459296}, {0.245385, -0.477589}, {0.222841, -0.492099}, \     {0.200503, -0.503935}, {0.174026, -0.515381}, {0.145794, -0.524995}, \     {0.108033, -0.534437}, {0.0758485, -0.539931}, {0.0331483, \     -0.544223}, {-0.0029876, -0.545596}, {-0.0362581, -0.545124}, \     {-0.0713561, -0.542341}, {-0.10544, -0.537172}, {-0.138509, \     -0.529619}, {-0.170564, -0.51968}, {-0.191371, -0.511729}, \     {-0.211727, -0.502717}, {-0.231632, -0.492646}, {-0.260644, \     -0.475551}, {-0.279422, -0.462829}, {-0.29775, -0.449047}, \     {-0.315626, -0.434205}, {-0.324396, -0.426386}, {-0.34277, \     -0.405934}, {-0.367955, -0.373398}, {-0.390289, -0.338633}, \     {-0.403595, -0.314218}, {-0.415633, -0.288813}, {-0.426404, \     -0.262417}, {-0.440185, -0.220965}, {-0.447788, -0.192092}, \     {-0.456817, -0.146926}, {-0.461252, -0.115577}, {-0.465529, \     -0.0666954}, {-0.466796, -0.0328696}}];


How can I remove a style from the list of available styles?

I have a stylesheet that has inherited some base definitions from another, but would like to "prune" the list of available styles, by removing or disabling1 some. Is there a way to do this? * * * 1\. This is not a question about how to _delete_ I style I've defined from my stylesheet, but how to _disable_ a style that my stylesheet has inherited.


Is there a way to base one style on another?

I'm setting up a stylesheet and and finding the process of defining related styles tedious and error prone. In particular, I have several related styles that need to have synchronized settings (e.g., such as "DisplayFormula" and "DisplayFormulaNumbered"). Is there a way to base one style on another, or perhaps simply to copy or duplicate an existing style as the starting point for another?


Execute code when file is modified

I have a function the takes some time to complete. The function imports data from a .csv, parses it, and plots certain vectors from there. The .csv is constantly being updated from an external program. Ideally, the file size of the .csv would be monitored and when it changes the function is run. Here's what I have so far (assuming the described function is `f`).               file = "testfile.csv"     Dynamic[         Refresh[          filesize:=FileByteCount[file];          data = Import[file, "CSV"];          f[data],TrackedSymbols:>{filesize},UpdateInterval->5]]      This works, but seems to run `f` every 5 seconds no matter if the file size has changed or not. This doesn't seem to be very efficient. Also, if I try to use inside `DynamicModule` it doesn't work at all. So, what's the best way to monitor and execute code on a file change?


Graph rendering not working as expected

I'm running the older Mathematica v6 which seems to go through the edges of graphs twice. Is this a bug? Is it fixed on the latest version? Please just try this command:               GraphPlot[{1 -> 2, 2 -> 3, 3 -> 1},       EdgeRenderingFunction -> (If[True, Print["e ", ##]; Black] &),       VertexRenderingFunction -> (If[True, Print["v ", ##]; Black] &)]                    v {0.496926,0.867793}11     e {{0.496926,0.867793},{0.999994,0.00354563}}{1,2}None{1,2}     e {{0.999994,0.00354563},{0.,0.}}{2,3}None{2,3}     e {{0.,0.},{0.496926,0.867793}}{3,1}None{3,1}     e {{0.496926,0.867793},{0.999994,0.00354563}}{1,2}None{1,2}     e {{0.999994,0.00354563},{0.,0.}}{2,3}None{2,3}     e {{0.,0.},{0.496926,0.867793}}{3,1}None{3,1}     v {0.496926,0.867793}11     v {0.999994,0.00354563}22     v {0.,0.}33


Package for voting systems

Is there a mathematica package that implements common voting systems (like IRV where voters will rank the candidates)?


Create triangular mesh from random list of points

I have a list of points. I would like to take these points and create a mesh of triangles from them, making sure triangles don't overlap. So here's a list of points:               p0 = Transpose[{RandomReal[{0, 10}, {100}], RandomReal[{0, 12}, {100}]}];     ListPlot@p0      ![enter image description here](http://i.stack.imgur.com/wJmc8.png) Now I've managed to take the first point in the list, find its two nearest neighbours and construct a triangle from this:               Graphics[{Thick, Red, Line[Append[Nearest[p0, p0[[1, All]], 3], p0[[1, All]]]]}]      ![enter image description here](http://i.stack.imgur.com/QVylR.png) What I'd not like to do is from this starting point keep connecting points to make a mesh where all the triangle corners are at one of the points and no triangles overlap. Any suggestions on how to do this? \-- _Below may be irrelevant_ \-- I imagine `DelaunayTriangulation` might come into this, however I'm not sure how. Also when I run it I don't understand what it returns:               DelaunayTriangulation[p0] // MatrixForm      ![image](http://i.stack.imgur.com/nKvTt.png)


Generating a "flare" effect in Graphics3D?

I'm attempting to indicate that there is a point-source of light at some position in a Graphics3D-generated image. Is there any built-in tool to do this? My patch-work solution thus far has been to imagine a sphere of radius $r$ centered at that point, and to generate a large set of diameter-length chords inside of the sphere. Surely there must be a better way that doesn't involve creating so many line or cylinder primitives?


Speed of convergence for NIntegrate

I'm trying to optimise numerically a function that entails computing the expected value of a truncated trivariate normal distribution and this is taking extremely long -I also get warned about `NIntegrate::slwcon` I've seen posts (such as this) about rewriting the problem as a differential equation, however I couldn't rewrite the problem successfully. Here's a simplified version of my problem (focusing on the expectation, which is what slows down the optimisation and produces `NIntegrate::slwcon` ):               JointD[X_,Y_,Z_]:= PDF[MultinormalDistribution[       {0,0,0}, {{1, 0.5, 0.5}, {0.5, 1, 0.5}, {0.5, 0.5, 1}}], {X,Y,Z}]          NIntegrate[X*JointD[X,Y,Z],{X, -∞, ∞}, {Y, 1, ∞}, {Z, 2, ∞}]


How do I define functions in TraditionalForm?

I'd like to be able to define functions (at least simple ones that _Mathematica_ can otherwise understand) using `TraditionalForm`; but this seems to require the use of an underscore. For example, I'd like to be able to have something like $$f(x) = x^2$$ correspond to               f[x_]:=x^2      but _Mathematica_ seems to require $$f(x\text{_}) = x^2$$ which goes a long way towards defeating the whole purpose. Is there, perhaps, a way to define some formatting that's less obtrusive, and more "conventionally notational" than the underscore that could correspond to the `TraditionalForm` underscore (and thus resolve any ambiguities)?


Why do I have to install my stylesheet each time I make changes to it?

I gather that it should be possible to preserve changes to a stylesheet by simply saving it, but this is not the behavior I'm getting with a stylesheet I've "installed" using the "Install Stylesheet..." button. In order to get any changes I've made to my stylesheet to persist, I need to install the stylesheet again. My saves (I have `Saveable` enabled for the stylesheet) seem to have no effect (the change indicator, doesn't even go away when I "save" it). Do "installed" stylesheets behave differently? Is my opened version of the stylesheet being saved somewhere else, perhaps?


How can I collect data for visualization of quick sort?

I know how to implement quick sort in Mathematica. But I don't know how to get the temp data for visualization, because I used recursion. I want the effect like this.               qsort[{}] = {};     qsort[{x_, xs___}] := Join[qsort@Select[{xs}, # <= x &], {x}, qsort@Select[{xs}, # > x &]];     qsort@RandomSample@Range@30


{Latitude, Longitude} to Transverse Mercator projection

I have a shapefile with the following `"CoordinateSystemInformation"`:               "PROJCS" -> {"NAD_1983_StatePlane_Illinois_East_FIPS_1201_Feet",     "GEOGCS" -> {       "GCS_North_American_1983",        "DATUM" -> {         "North_American_Datum_1983",         "SPHEROID" -> {"GRS_1980", 6.37814*10^6, 298.257}},        "PRIMEM" -> {"Greenwich", 0.},        "UNIT" -> {"Degree", 0.0174533}},      "PROJECTION" -> {"Transverse_Mercator"},      "PARAMETER" -> {"False_Easting", 984250.},      "PARAMETER" -> {"False_Northing", 0.},      "PARAMETER" -> {"Central_Meridian", -88.3333},      "PARAMETER" -> {"Scale_Factor", 0.999975},      "PARAMETER" -> {"Latitude_Of_Origin", 36.6667},      "UNIT" -> {"Foot_US", 0.304801}}      I would like to plot {Latitude, Longitude} points and overlay these images, but I am having trouble converting coordinates. The shapefile data contains coordinates in the vicinity of {1.16328*10^6, 1.89271*10^6}. (This is Chicago.) One point I would like to plot is {41.8713, -87.6737}.               GeoGridPosition[GeoPosition[{41.8713, -87.6737}], "TransverseMercator"]      gives the wrong coordinates:               GeoGridPosition[{-0.164851, 0.743066}, "TransverseMercator"]      As does               GeoGridPosition[GeoPosition[{41.8713, -87.6737}], "Mercator"]      which yields:               GeoGridPosition[{1.6114, 0.806147}, "Mercator"]      What am I doing wrong? It's not a question of reversed coordinates as in this thread.


Making code version aware

Mathics, a free Mathematica-compatible project has been recently launched. It provides a subset of the functions and capabilities of Mathematica at a slower pace. This opens us the tantalizing possibility to share our code even with people who do not have Mathematica on their computers. Since Mathics is currently supporting only a fraction of all Mathematica functions, it becomes important for our code to be able to discriminate whether it is run within Mathematica or Mathics. Is this possible?


How to apply restrictions to the "integrated" variable, when using NDSolve?

I have to integrate an energy along a path. I know the energy at the "beginning" of the path (`energy[0]`), and I can determine the energy change (gain and loss) along it (`energy'[x]`). But the values the `energy[x]` can have are restricted, since, along the path, the energy is always equal or above a certain value (`minimumEnergy[x]`). This minimum energy limits changes in an abrut manner, and only influence the values downward the path. If this would be done in a Euler step manner, it would be easy: starting from the beginning of the path, at each new step `energy[x]=Max[energy[x-step]+step*energy'[x-step], minimumEnergy[x]]`. How can I put this restrictions on `NDSolve`? I've tried to artificially change the `energy'[x]` equation so that it compensates the difference to have the `minimumEnergy[x]`, but this did not went well. Another problem that I have is that `energy'[x]` is based on the value of energy[x], and the equation has no real value for `energy[x] < minimumEnergy[x]`. I've tried to figure out how to implement it with StepMonitor, but came to no conclusion. The system is slightly complex to be placed here, and so I hope the above explanations are good enough for the understanding of my problem. The following code will not run. I just placed it here for a better understanding. I already implemented J.M. suggestion on the `EventLocator`.               ans = energy/. Flatten[NDSolve[         {             energy[outletChannelEnd] == minimumEnergy[flowrate] + bottomFunction[0],             energy'[x] == headLoss[flowrate, height4Head[flowrate, energy[x] - bottomFunction[x]]]         },         energy,         {x, 0, 241},          Method -> {             "EventLocator",             "Event" -> (energy[x] - (minimumEnergy[flowrate] + bottomFunction[x])),             "EventAction" :> (energy[x] = minimumEnergy[flowrate] + bottomFunction[x])         }     ]]      The result is as follows, where the blue line is the minimum energy, and the purple is the calculated one: ![enter image description here](http://i.stack.imgur.com/aOeZs.gif) EDIT: It correctly detects there is an event on the x=73 (I have asked for a print on the event actions), but it doesn't correct the `energy'[x]`


inequalities in equations and constraints

Say That I have the constraint:               .5<x1<x2<x3<x4<40      I want to use this constraint in a Nminimize function. It seems that mathematica runs into a problem when you have this. For example Nminimize will output an error saying that this function variable is not real for "-x2" but this constraint defines my variables all to be positive. So is there a better way to write this constraint?


How many triangles are there?

Some time ago I found a puzzle and it stopped my work until I solved it. ![](http://i.stack.imgur.com/7sTmp.png) One of the possible solutions: Let us sum upright and upside down triangles whose top lies in the $i$-th row. $$ N=\sum_{i=1}^n N_i^\Delta + N_i^\nabla. $$ For upright triangles we should multiply the number of possible sizes $n-i+1$ by the number of possible horizontal positions $i$ $$ N_i^\Delta = (n-i+1)i. $$ An upside down triangle with size $l$ at $i$-th row have $n-i-l+1$ positions and the size $l$ limited by $\min(i,n-i)$, therefore $$ N_i^\nabla = \sum_{l=1}^{\min(i,n-i)}(n-i-l+1). $$ Finally, we have $$ N=\sum_{i=1}^n\Bigl((n-i+1)i+\sum_{l=1}^{\min(i,n-i)}(n-i-l+1)\Bigr). $$ For $n=28$ rows we get $N=5985$ triangles. My question is: could you suggest a less trivial solution, which can reveal the power of the different sides of _Mathematica_? I mean look at this problem from different sides: finding a sequence, image-processing, finding a cycles in a graph and so on.


How to abort on any message generated?

Mathematica is a bit unusual as a programming language because it never stops on messages, regardless of whether the message is an error, a warning or just an informative message. It simply prints the message and continues with evaluation. This can cause an avalanche of messages and unpredictable behaviour (e.g. memory may get filled up, bringing the machine to a halt with swapping---this is what happened to me) **Is there a way to immediately abort when _any_ message is generated?** Requirements:   1. if a message would be printed, always abort.   2. if no message would be printed, don't abort.   3. do print the first message so I have a hint about what went wrong   4. the mechanism should work with parallel computations and should abort the full evaluation (i.e. main kernel and all parallel kernels) There are many ways to handle message printing, including `On`/`Off`, `Quiet`, and possibly others (such as setting some system options). The solution should work well with these. I am afraid manually handling all possible situations is too fragile (there's always a chance something got left out). I found a solution on MathGroup which aborts, but does not print the message. _I suspect there must exist a robust and simple solution because the Debug palette has a "Break on messages" option._


Create Slider to start/stop/move Point

I want to be able to start, stop, and move the dynamically moving point simultaneously in both animations. The "PlayPauseButton" in the animations only controls the given animation. Indeed, I want both animations to always by synchronized.               system = {x'[t] == 2 x[t] - 0.08 x[t] y[t], x[0] == 400,               y'[t] == -y[t] + 0.01 x[t] y[t], y[0] == 25};     sol = NDSolve[system, {x[t], y[t]}, {t, 0, 21.5}];     {x1[t_], y1[t_]} = {x[t], y[t]} /. Flatten[sol];          px4 = Plot[x1[t], {t, 0, 21.5}, PlotRange -> {0, 400}, PlotStyle -> {Black}];     py4 = Plot[y1[t], {t, 0, 21.5}, PlotRange -> {0, 400}, PlotStyle -> {Black, Dashed}];          Row[      {Animate[        Show[px4, py4,         Graphics[{PointSize[Large], Red, Point[Dynamic[{t, x1[t]}]],                    Point[Dynamic[{t, y1[t]}]]}]], {t, 0, 21.5,         AppearanceElements -> "PlayPauseButton"}, SaveDefinitions -> True,        AnimationRate -> 0.251, AppearanceElements -> "PlayPauseButton",         BaselinePosition -> Bottom],       Animate[        Show[ParametricPlot[{x1[t], y1[t]},{t, 0, 5.375}, AxesLabel -> {"Prey", "Predator"},                              AspectRatio -> 1, PlotRange -> {{0, 400}, {0, 80}}],              Graphics[{Red, PointSize[Large], Point[{x1[t], y1[t]}]}]],        {t, 0, 5.375, AppearanceElements -> "PlayPauseButton"},         SaveDefinitions -> True, AnimationRate -> 0.251,         BaselinePosition -> Bottom]}, Frame -> True, RoundingRadius -> 10]      The desired slider should fit into the frame space above the first "Animate". Perhaps I could have rewritten this code with Manipulate, but I don't know how to do that either.


How to make the computer consider two numbers equal up to a certain precision

My problem is that I have a matrix `A` and the computer says is not Hermitian (self-adjoint). Then I check which elements make `A` be not Hermitian by calculating:               B=A-ConjugateTranspose[A]      In case `A` is Hermitian, this difference should be zero. What I get is that `A` is not Hermitian, but the terms I get in matrix `B` all are smaller than `10^(-15)`. So how can I fix it at the beggining of the code, _Mathematica_ to consider two numbers equal, up to `10^(-10)` precision for example, that is it to consider: > 0.00000000010 = 0.00000000012 or saying it in an alternative way, I want _Mathematica_ to consider the following matrix Hermitian:               C={{0,I*1.1^(-10)},{-I*1.2^(-10),0}}      throughout the whole code.


using interpolation functions in ParallelMap

**Edit** _I am editing the question to give a simple workable example. It is at the bottom under the heading **Example**. The original question is now headed withe **Background**._ **Background** I am trying to calculate large tables with values taken from a normal distribution and an interpolation function (as well as a spherical coordinate). The interpolation function is b[j] below where j is an index denoting a certain interpolation function. The interpolation functions come from large arrays. I would like to calculate for different j in parallel since I have 30 different j to work with (j = 1..30). The problem I am seeing is that the parallel calculation is in fact much slower when the interpolation functions are present. The code is (which you will not be able to run since you don't have the bx,by,bz functions):                l = 0.2;      xEdge = 1990.;      yEdge = 1990.;      zBottom = 36.;      zTop = 126.;                dataMod[j_, rc_] := Module[{},           X = RandomReal[{rc, xEdge - rc}];      Y = RandomReal[{rc, yEdge - rc}];      Z = RandomReal[{zBottom + rc, zTop - rc}];           \[Phi]1 = RandomReal[{0., 2. \[Pi]}];      \[Theta]1 = RandomReal[{0., \[Pi]}];      y = RandomReal[{0., rc/l}];      d = l y;      dx = d Cos[\[Phi]1] Sin[\[Theta]1];      dy = d Sin[\[Phi]1] Sin[\[Theta]1];      dz = d Cos[\[Theta]1];           {y, \[Phi]1, \[Theta]1,      RandomReal[NormalDistribution[0., 1./2.]] + bx[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + bx[j][X + dx, Y + dy, Z + dz],      RandomReal[NormalDistribution[0., 1./2.]] + by[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + by[j][X + dx, Y + dy, Z + dz],      RandomReal[NormalDistribution[0., 1./2.]] + bz[j][X, Y, Z],      RandomReal[NormalDistribution[0., 1./2.]] + bz[j][X + dx, Y + dy, Z + dz]}      ];           data[j_, rc_, nMax_] := Table[dataMod[j, rc], {nMax}];      I would like to calculate the table for several different values of j. Here I use only 2 though in actuality, I will use 30:                list = Map[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      This took **6.6** seconds. On two kernels,                listParallel =       ParallelMap[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      took **119** seconds on two kernels. Why is this so much slower? Are the (10000) elements of the table being calculated in parallel or are j = 1 and j = 2 being calculated in parallel (which is what I was aiming for). I thought ParallelMap would calculate j=1 and j=2 in parallel (i.e. simultaneously so I would expect the time to be $\sim 3.3$ seconds). If I get rid of the interpolation functions,                dataMod[j_, rc_] := Module[{},           X = RandomReal[{rc, xEdge - rc}];      Y = RandomReal[{rc, yEdge - rc}];      Z = RandomReal[{zBottom + rc, zTop - rc}];           \[Phi]1 = RandomReal[{0., 2. \[Pi]}];      \[Theta]1 = RandomReal[{0., \[Pi]}];      y = RandomReal[{0., rc/l}];      d = l y;      dx = d Cos[\[Phi]1] Sin[\[Theta]1];      dy = d Sin[\[Phi]1] Sin[\[Theta]1];      dz = d Cos[\[Theta]1];           {y, \[Phi]1, \[Theta]1,      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]],      RandomReal[NormalDistribution[0., 1./2.]]}      ];      then                list = Map[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      takes 0.99 seconds. The parallel version had a modest speed-up                listParallel =       ParallelMap[data[#, 1., 1*10^4] &, Range@2]; // AbsoluteTiming      to 0.92 seconds which is at least not a lot slower as seen with the interpolation functions present. So why is it that the interpolation functions seem to present a problem for ParallelMap? Is there anything else obvious that I can do do speed this up (in reality nMax must be 1-100 million)? **Example** My question concerns using interpolation functions on multiple kernels with ParallelMap. Here is an example that I think illustrates my problem. Define the interpolation functions:                l = 0.2;      xEdge = 4.;      yEdge = 4.;      zBottom = 0.;      zTop = 4.;           {cx[1], cx[2], cx[3], cx[4]} =  Table[Interpolation[       Flatten[Table[{x, y, z, j*Sin[x y z]}, {x, 0, xEdge, 0.1}, {y, 0,         yEdge, 0.1}, {z, zBottom, zTop, 0.1}], 2]], {j, 1, 4}];      I now evaluate the interpolation functions at specific points governed by the following:                ffMod[j_, rc_] := Module[{},            X = RandomReal[{rc, xEdge - rc}];       Y = RandomReal[{rc, yEdge - rc}];       Z = RandomReal[{zBottom + rc, zTop - rc}];            \[Phi]1 = RandomReal[{0., 2. \[Pi]}];       \[Theta]1 =  RandomReal[{0., \[Pi]}];       y = RandomReal[{0., rc/l}];       d = l y;       dx = d Cos[\[Phi]1] Sin[\[Theta]1];       dy = d Sin[\[Phi]1] Sin[\[Theta]1];       dz = d Cos[\[Theta]1];            {cx[j][X, Y, Z], cx[j][X + dx, Y + dy, Z + dz]}       ];      I then want to make a large table of values (20000 here, but actually want to do for 1 million or more):                ffData[j_, rc_, nMax_] := Table[ffMod[j, rc], {nMax}];      for several different j.                ffList = Map[ffData[ #, 1., 2*10^4] &, Range@4]; // AbsoluteTiming      takes 8.9 seconds. In parallel on 4 kernels:                ffListP = ParallelMap[ffData[ #, 1., 2*10^4] &, Range@4]; // AbsoluteTiming      takes 17.6 seconds. How can I speed up the parallel version of this as I would expect that each kernel could operate on the 4 different j's?


Importing numerical values from a PDF file

I need the numerical values from pdf files like this one. ![Mathematica graphics](http://i.stack.imgur.com/xuZAG.png) When I use the usual `Import` command, the PDF imports, but pages of images. How can _Mathematica_ be used to import the numerical values from a PDF?


No builtin function for bitwise rotation?

There appears to be no builtin Mathematica function for bitwise rotation. Is that true? I suppose I can write my function:               ROR[x_, k_] := FromDigits[RotateRight[IntegerDigits[x, 2, 32], k]]      Obviously this will be a lot more inefficient than a builtin function because in machine code a rotate right is a single instruction. Is this my only option?


Visualize eigenvectors at specified points?

I am very new to Mathematica and I got stuck about visualizing eigenvectors 2D and 3D. I want to visualize my largest eigenvector field of tensor data(15x15). I wrote this code for instance :               points = {{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1,      2}, {2, 2}};          ListVectorPlot[{{{0, 0}, {1, 1}}, {{1, 0}, {1, 0}}, {{2, 0}, {0,      1}}, {{0, 1}, {1, -1}}, {{1, 1}, {1, 1}}, {{2, 1}, {-1, 1}}, {{0,      2}, {0, 1}}, {{1, 2}, {-1, 0}}, {{2, 2}, {0, -1}}}, VectorPoints -> points, FrameLabel -> {x, y}, PerformanceGoal -> "Quality", Epilog -> {Red, PointSize[Medium], Point[points]}]      But my vectors don't begin from the specified point. `ListVectorPlot` function locate the vector in the middle of the point. Do you think I have to use another function like `Arrow` and `Graphics`? In addition,I want to plot my second eigenvectors from the same point. For example, I have a matrix and its eigenvectors are {{1,1}, **{-6,5}** } or {{4,5},{-1,3}}. At the end I have to multiply these vectors with their eigenvalues({{2,4}}) and visualize like that. How can I do that at specified points at an order and different lenghts of vectors(multiply with eigenvalues)? Below you can find a basic example data,               datax = {{{{3, 4}, {4, 3}}, {{3, 4}, {4, 3}}, {{3, 4}, {4,       3}}}, {{{3, 6}, {6, 3}}, {{3, 6}, {6, 3}}, {{3, 6}, {6,       3}}}, {{{3, 5}, {4, 3}}, {{3, 5}, {4, 3}}, {{3, 5}, {4, 3}}}};     dataxv = Table[Eigenvectors[datax[[z, t]]], {z, 1, 3}, {t, 1, 3}];     dataxva = Table[Eigenvalues[datax[[z, t]]], {z, 1, 3}, {t, 1, 3}];      Thank you in advance.


How to implement Condition programmatically?

I am writing my own symbolic functions with custom symbolic properties. So often I wish to introduce some automatic simplifications or evaluations, which return the same head as it's argument. This means I can't use normal function definition to avoid infinite recursion. Suppose I with to create library for naive set theory. I am introducing `MySet` head to represent sets. For example, to create a set with `a`, `b` and `c` elements, I will write               MySet[a,b,c]      and Mathematica will reply               {a,b,c}      since I defined head `MySet` to be displayed in curly braces. Of course               MySet[a,b,c] // FullForm      will give               MySet[a,b,c]      Now suppose I wish to remove duplicates automatically, since sets do not care of duplicates. So that if I wrote               MySet[a,b,b,c]      Mathematica would reply               {a,b,c}      How to accomplish that? Currently I am writing two helper functions, like `HasDuplicates` and `RemoveDuplicates` and write something like that               MySet[x__] :=      MySet@@DeleteDuplicates[{x}] /;         HasDuplicates[{x}];      But this approach requires me to code nearly the same things in two places -- `HasDuplicates` and `RemoveDuplicates` functions. How to avoid this? Is it possible to write this in some following manner:               MySet[x__] := Block[{...},         (* search for duplicates and remove them *)         If[ someweremoved,              MySet[y], (* with removed duplicates *)             MySet[x] (* with no modifications *)         ];     ];      The problem is that I can't prevent infinite recursion here since `MySet` is called again and again in any case. Can I prevent recursion by force? I.e. tell somehow, that expression returning should not be reevaluated? Or may be I can implement `Condition` somehow in programming style? Or may be there is a way to code simplifications somehow? **UPDATE** The set is just a sample. My question is about general solution, suitable for ANY case of simplifications. The general sign of simplification is just was it done something or not. We can't assume we can compare some short list or count some.


Setting a binary operator Flat

I defined a binary operator in as the first statement in a new _Mathematica_ notebook.               {x1_, y1_} ⊕ {x2_, y2_} := Module[{}, Print["do anything"];]      where the code in the `Module` is somewhat more meaningful. My questions:   1. Why does this not show up in a `?Global`*` query?   2. How can I set the `Attributes` for this operation to be `Flat` so it is associative?   3. Do I need to use the `Notations` Package to do this "properly"?


how to get modify the following correlation matrix with a specific list of financial prices?

The following takes the last 5 members of the Dow Jones index and plots the correlation matrix of the last 5 years of daily prices:               mem = FinancialData["^DJI", "Members"];     findata =        FinancialData[#, "Price", {{2007}, {2012}, "Day"}][[All, 2]] & /@         mem[[-5 ;; -1]];     fincm = Correlation[Transpose@findata];          tb = Map[Item[NumberForm[#, 2],           Background ->            ColorData["TemperatureMap"][Rescale[#, {-1, 1}]]] &, fincm, {2}];     tb = Prepend[tb, mem[[-5 ;; -1]]];     tb = Join[List /@ Prepend[mem[[-5 ;; -1]], ""], tb, 2];     GraphicsGrid[tb, ImageSize -> 500, Frame -> All]      But what if I want to compare 5 specific equities instead from various listed exchanges; i.e CWC.L, CAP.PA, IFX.DE, ISYS.L and LAD.L? Anyone?


NDSolve fails for certain choices of parameters and solve range

I'm trying to solve a pair of coupled ODEs with NDSolve. I know roughly what the solution should look like (both should give periodic functions, pi/2 out of phase, the amplitude of which damp towards a common limiting value), but I am trying to work out what the limiting amplitude is for a range of parameters. For certain choices of parameters, the solution looks how I would expect, but for others the NDSolve sporadically takes very large steps and the output either diverges, becomes constant, or shows other noisy/glitchy behaviour. Changing the NDSolve range also makes these effects come and go, and reducing the MaxStepSize or changing the Working Precision to anything but 16 makes things worse - so I'm pretty sure this is a computational problem. I'm pretty new to Mathematica so this is probably something simple, but every suggestion I've seen in other posts (increasing workingprecision, limiting step size etc) has only made things worse so I'm a bit stumped!               ( _Define some constants_ )     wc0 = 0.9645*^8*B/mass /. {mass -> 40, B -> 1.845};     fc0 = wc0/2/[Pi];     ( _Define wz, w1, wc and wm as functions \     of trap voltage V_ )     wz[V1_] = Sqrt[4*0.9645*^8*1*V1/40/0.0189^2];     w1[V1_] = Sqrt[wc0^2/4 - wz[V1]^2/2];     wc[V1_] = wc0/2 + w1[V1];     wm[V1_] = wc0/2 - w1[V1];     ( _Want to find limiting value as these parameters are varied_ )     V = 244;     d = 100000;     rate = 2*^6;     rm0 = 5*^-6;     rc0 = 5*^-6;     ( _Solve for dynamics_ )     mysolve =        NDSolve[{           rc'[t]==rate*B/w1[V]^2/2/rc[t]-rate*wc[V]*A*rc[t]/w1[V]/2+d*rm[t],           rm'[t]==rate*B/w1[V]^2/2/rm[t]+rate*wm[V]*A*rm[t]/w1[V]/2-d*rc[t],            rm[0] == rm0, rc[0] == rc0} /. {B -> 3.4*^-4, A -> 3*^-3},           {rc[t], rm[t]}, {t, 0, 0.009}, MaxSteps -> Infinity           ];                              range = 1*^-6;     ( _Plot dynamics_ )     Plot[Evaluate[rc[t] /. mysolve], {t, 0.0, 0.008},       PlotRange -> {-range, range}, AspectRatio -> 0.25, ImageSize -> 800]     Plot[Evaluate[rm[t] /. mysolve], {t, 0.0, 0.008},       PlotRange -> {-range, range}, AspectRatio -> 0.25, ImageSize -> 800]                              ( _Find limiting value_ )     intmin = 0.004;     intmax = 0.008;     lrc = Sqrt[2*NIntegrate[Evaluate[rc[t]^2 /. mysolve], {t, intmin, intmax}]/(intmax-intmin)]     lrm = Sqrt[2*NIntegrate[Evaluate[rm[t]^2 /. mysolve], {t, intmin, intmax}]/(intmax-intmin)]                    (**)      The parameters listed above give a sensible result (first image) - but if, for instance, I change the NDSolve window to {t,0,0.004} or {t,0.04}, or change 'd=100000' to 'd=80000' (second image) it starts behaving strangely. Any help would be very much appreciated! ![Expected behaviour for settings listed above](http://i.stack.imgur.com/9dVN6.jpg) ![Glitchy behaviour when parameter changed \(here d=80000\)](http://i.stack.imgur.com/cp4Zf.jpg)


An ancient MIDI keyboard?

There is a demostration project http://demonstrations.wolfram.com/KeyboardAndComposer/ where you can compose Western music using a 97 keys simulated midi keyboard. I study eastern and ancient music and harmony. So I can not use SoundNote for this kind of music (where each note is represented as a fraction. Using middle Do as a base (i.e., `base = 260.741 Hz`), the next notes are represented by `re = 9/8 base`, `mi = 5/4 base`, `fa = 4/3 base`, `sol = 3/2 base`, `la = 3/2 9/8`, `si`=`3/2 5/4`) So my problem is to change the above keyboard so that   1. the keys have pitches defined using some fractions like the ones mentioned above   2. The user could simultaneously use his/her computer keyboard with the midi keyboard for music synthesis and polyphony. For example: While simultaneously pressing R on computer keyboard and midi button fa on the Mathematica Midi Keyboard the user could hear re + fa continuously (or at least as long as the R key and fa button are pressed.). But when R is released (and midi button fa is still pressed) only fa will be heard. Some help, please!


Alternatives to Mathematica

Inspired by the recent question Alternatives to LaTeX (currently 58 upvotes) on http://tex.stackexchange.com/: Are there any paid-for or open source alternatives to Mathematica which produce equal or even better functionality, specifically with regard to solving, manipulating and visualising algebraic expressions. Note: a similar question is Best open-source Mathematica equivalent, however this question is targeted at users of Mathematica.SE (and is five years in the future).


Automatic inverse for Lambert’s Azimuthal Equal-Area Projection

I’m interested in finding closed-form inverses for map projection equations in general (of course, this is not always possible). I’m hoping Mathematica can help me with some of the trickier ones. As a **practice run** , I thought I would try and use Mathematica to invert Lambert’s Azimuthal Equal-Area Projection. There are of course closed-form inverse equations on MathWorld, but I’m wondering how I would go about finding these using Mathematica. I’ve tried using `Solve` and `Reduce`, for example:               k = Sqrt[2/(1 + s1 Sin[y] + c1 Cos[y] Cos[x])]     Solve[{u, v} == {       k Cos[y] Sin[x],        k (c1 Sin[y] - s1 Cos[y] Cos[x])     }, {x, y}]      But no luck so far. Perhaps I need to specify more constraints? For example, I know that the longitude and latitude (`x` and `y` above) have:               -π ≤ x ≤ π     -π/2 ≤ y ≤ π/2      I wonder if eliminating variables might also help the solving routines.


Integration over a convex combination of a region: $\int_{\Omega} (w_1 z_1 + w_2 z_2)^{1-\sigma} d (z_1, z_2)$ where $\Omega = \{ z_1 + z_2 = 1\}$

Take $w,z\in R^{n}$. I am interested in integrating (as generically if possible) $$\int_{\Omega}(w \cdot z)^{1-\sigma} d z$$ Where the domain of $\Omega$ is $1$ dimension, and includes the convex combinations of $z$. i.e. $\Omega \equiv \\{z | \sum z = 1 \\}$ Obviously, for $n=2$, this is easy to rearrange: $$\int_{0}^{1} \left(w_1 z_1 + w_2 (1-z_1)\right) d z_1$$ $$ = \frac{w_2^{2-\sigma} - w_1^{2-\sigma}}{(\sigma - 2)(w_1 - w_2)}$$ And the mathematica code is:               Integrate[(w[1] z[1] + w[2] (1 - z[1]))^(1 - \[Sigma]), {z[1], 0, 1}] // FullSimplify      But it is a little harder to cheat like this as $n$ gets larger, and I am hoping for more general patterns. How would I set up the simple $n=2$ example using the convex combination directly? I tried things like: Integrate[(w[1] z[1] + w[2] z[2])^(1 - [Sigma]), {z[1], 0, 1}, {z[2], 1 - z[1], 1 - z[1]}] // FullSimplify Integration over a convex combination of a region: $\int_{\Omega} (w_1 z_1 + w_2 z_2)^{1-\sigma} d (z_1, z_2)$ where $\Omega = \\{ z_1 + z_2 = 1\\}$ ...but I couldn't get them to work.


Import symbolic variables from Matlab with MATLink

I'm trying to manipulate with Mathematica symbolic expression created in Matlab. I'm using the MATLink package, and I've succedeed in importing numerical variables, but not symbolic ones :               MEvaluate["syms g real"]     MEvaluate["syms l real"]     MEvaluate["u = g + l"]     MGet["u"]      will output :               u =      g + l % Matlab correctly defines the variable     {}    % Mathematica doesn t succeed in getting the variable      Anyone with experience in dealing with this ?


using 'steps' in Manipulate

I want to make a `3D` shape move through a specified graph; e.g. `y = Sin[x]`, such that it moves up and down.   My working so far has been to use `Manipulate`, and I think I want to use it with 'steps', as in the documentation, second one down, although I don't know how to use this.   Would this be the way, and if so how do I use it? Here is what I have so far:               Manipulate[Graphics3D[{Green, Cuboid[{0, 0, t}], Blue, Cuboid[{0, 0, 0}]}], {t, 0, 3}]      I think I want something like:               Manipulate[ Graphics3D[{Green, Cuboid[{0, 0, t}], Blue, Cuboid[{0, 0, 0}]}],                 {t, 0, 3, y = Sin[x]}]


Predictive interface eats my Esc key

After updating to version 9, I found the predict interface very helpful except there is a small problem always annoying me: Consider this: I have a list `abc = Range[1, 10];` and I want to take part of it `abc[[2]]`. For the `[[` and `]]`, I like to use the closer version of the bracket (`\[RightDoubleBracket]`) by press key `Esc`+`[`+`[`+`Esc` and `Esc`+`]`+`]`+`Esc`. ![enter image description here](http://i.stack.imgur.com/9y63p.png) In version 9, when I type `abc` I get this drop list of predictions, and the first `Eec` key goes to remove the drop list and the `[[` is not correctly typed: ![enter image description here](http://i.stack.imgur.com/cZYNW.png) ![enter image description here](http://i.stack.imgur.com/S4BDo.png) So it is possible to make the drop list automatically disappear once what I typed matches the exists variable, so that the first `Esc` key is not eaten by the drop list?


Elegant transformation of various rules to strings, {f[z_] -> y} becomes "f = @(z) y"

Assume that I have some function for transformation mathematica expressions to strings. For simplicity, just assume it is an identity:               mytostring[e_] := ToString[e]; (* In reality, much more complicated... *)      What I want to take various permutations of variadic rules syntax and apply this function to create a string for the function. e.g. assume my basic test is:               rulestostring[rule_????] := ???     testrules = {f[x,y] -> x, f[x_,y_] -> x, f[x,y] :> x, f[x_,y_] :> x};          (* Create a function rulestostring where all of these give the same output as a string:     ==>    "f = @(x,y) x"     Where the f is actually generated from mytostring[f], x is from mytostring[x], etc.     *)      I need it to support variadic arguments and a few other things:               otherrules = {f[x_] -> x, f[x[bar]] -> x[bar]};     (* ==>   {"f = @(x) x", "f = @(x[bar]) x[bar]"     where in reality both x[bar] would be transformed by mytostring     *)      (you can probably guess that what I am doing is extending the http://library.wolfram.com/infocenter/MathSource/577/ package to generate matlab functions. If anyone has an updated version of this package it would be appreciated)


CSS Selectors for Symbolic XML

_Symbolic XML_ is a convenient way of managing **XML** in _Mathematica_ , at least for casual use or small tasks. Here and elsewhere you can find examples of **XML** handling in _Mathematica_ , including **XSLT** / **XPath** emulations. In my opinion, however, if you must perform frequent searches, content extraction, or deep transformations, e.g., Web scraping, _Symbolic XML_ quickly becames clumsy and cumbersome to work with. If you have ever faced any kind of web programming, you're probably aware of the convenient **CSS Selectors** , the more common choice (being the other XPath) to tackle the aforementioned kind of problems. I'm curious, are there implementations of **CSS Selector** (and/or XPath) engines in _Mathematica_? If not, would be feasible/sensible to implement like capabilities in _Mathematica_? Or is it better to stick with ad-hoc queries and follow the examples approach? As elegant code is better than thousand opinions, we could illustrate the answers with this toy, greatly simplified, CSS Selector engine:                      **Pattern** | **Matches**                                                              | **Selector**     ---------------| -------------------------------------------------------------------- | ----------------                  * | any element.                                                         | Universal                  E | any E element (i.e., an element of type E).                          | Type          E.warning | any E element whose class is "warning".                              | Class             E#myid | any E element with ID equal to "myid".                               | Id                E F | any F element that is a descendant of an E element.                  | Descendant              E > F | any F element that is a child of an element E.                       | Child              E + F | any F element immediately preceded by a sibling element E.           | Adjacent Sibling              E ~ F | any F element preceded by an E element                               | General sibling             E[foo] | any E element with the "foo" attribute set (whatever the value).     | Attribute       E[foo="bar"] | any E element whose "foo" attribute value is exactly equal to "bar". | Attribute                    A selector is a chain of one or more simple selectors separated by combinators.     Combinators are: white space, ">",  "+", and "~". White space may appear between a combinator and the simple selectors around it.     A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or class selectors, in any order.     The universal selector may be omitted if followed by other simple selector components.     The simple selector matches if all of its components match.          Examples:     "*div" or "div", all elements with tag "div";     "div *", all descendants at any level of all div elements;     ".aClass+[attr=val]", direct descendants with attr equals val of elements with class aClass.      If you need a formal grammar, take a look to the W3C spec, but for this illustration I think that we can prescind of error handling or stringent processing. Then, given _context_ , any expression containing `XMLElements`, and _selector_ , a string compliant with the toy CSS grammar, implement **positionSelector[ _context_ , _selector_ ]** to return the positions (same format of `Position` built-in) of `XMLElements` matching selector:               xml = ImportString["<!doctype html>
Animals
", "XMLObject"];     positionSelector[xml, "body"]     positionSelector[xml, "*"]     Extract[xml, positionSelector[xml, "h1"]]          (* ==> {{2, 3, 1}} *)     (* ==> {{2, 3, 1, 3, 1}, {2, 3, 1}, {2}} *)     (* ==> {XMLElement["h1", {}, {"Animals"}]} *)          xml = ImportString["
Eh...
What's up, doc?up, doc?

Legen
--
Wait for it
--
Dary!

No.
I am your

 father.

", "XML", "NormalizeWhitespace" -> False];     result = positionSelector[xml, "div>span"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 2, 3, 1, 3, 1}, {2, 3, 1, 3, 2, 3, 1, 3, 3}, {2, 3, 1, 3, 2, 3, 1, 3, 5}} *)     (* ==>     XMLElement["span", {}, {"What's "}],      XMLElement["span", {"id" -> "def"}, {"doc?"}],      XMLElement["span", {"id" -> "def"}, {"doc?"}]}     *)          result = positionSelector[xml, "[class]>div"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 2, 3, 2, 3, 2}, {2, 3, 2, 3, 2}} *)     (* ==>      XMLElement["div", {"class" -> "dClass"}, {"Wait for it"}],      XMLElement["div", {"class" -> "cClass"}, {"--",      XMLElement["div", {"class" -> "dClass"}, {"Wait for it"}], "--"}]}]     *)          xml = ImportString["<!doctype html>
Animals

Lillith>

MaggieFatty
        ",      "XMLObject"];          result = positionSelector[xml, "h2+.dog"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 5}} *)     (* ==> XMLElement["h2", {"class" -> "animal dog mutt", "id" -> "maggie"}, {XMLElement["span", {"class" -> "christian Name"}, {"Maggie"}], XMLElement["span", {"class" -> "nick Name"}, {"Fatty"}]}]} *)          result = positionSelector[xml, "h2+#maggie"]     Extract[xml, result] // ColumnForm          (* ==> {{2, 3, 1, 3, 5}} *)     (* ==> XMLElement["h2", {"class" -> "animal dog mutt", "id" -> "maggie"}, {XMLElement["span", {"class" -> "christian Name"}, {"Maggie"}], XMLElement["span", {"class" -> "nick Name"}, {"Fatty"}]}]} *)          positionSelector[xml, "h1~.dog"]          (* ==> {{2, 3, 1, 3, 3}, {2, 3, 1, 3, 5}} *)          positionSelector[xml, "h1~b"]          (* ==> {} *)      To be clear, I'm not looking for a full-blown implementation, but strategies and idioms of how _Mathematica_ can resolve XML queries, and in which ways is _Mathematica_ better equipped for that than mainstream functional/imperative languages.


How do I map a Mollweide projection onto a sphere?

I have this Mollweide projection of the Earth circa 600 million years ago (http://jan.ucc.nau.edu/~rcb7/370moll.jpg).(1) ![Mollweide projection of the earth](http://i.stack.imgur.com/XkyQI.jpg) I want to map this onto a sphere. My results have big black splotches in the Pacific Ocean and the continents are distorted, because the code I used also mapped the black corners of the image to the sphere. I need to map just the central ellipse. What sort of code should I use? Perhaps I need to first convert the image to an equirectangular projection. (1) Image credit: Ron Blakey, NAU Geology


Opacity limitations?

Trying to make a better-looking globe model, I start off with something like this ![enter image description here](http://i.stack.imgur.com/ddScb.png) To enhance the 3D effect, I want the lines further from the eye to be "grayer" than the lines closer to the eye, as if there were a little fog inside the sphere. I thought I might get there by replacing the great-circles with semi- transparent wafers, but it didn't work. It seems as though I hit some kind of internal limit on the number of semi-transparent objects I can create before they become opaque. Here is the original code with polygonal great circles (minus the RGB-XYZ axes):               ClearAll[e, o, g, \[Epsilon]];     e[1] = {1, 0, 0}; e[2] = {0, 1, 0}; e[3] = {0, 0, 1};     o = {0, 0, 0}; g = 1.25; \[Epsilon] = 1/10000;     ClearAll[polycircle];     polycircle[n_: 360] :=        Line@Table[{Cos[2 \[Pi] i/n], Sin[2 \[Pi] i/n], 0}, {i, n + 1}];     ClearAll[globeGrid];     globeGrid[bands_: 6, figure_: polycircle[]] :=       {Table[         Scale[Translate[figure,  Sin[(k \[Pi])/2] e[3]],           Cos[(k \[Pi])/2]]         , {k, -((bands - 1)/bands), (bands - 1)/bands, 1/bands}]        , Table[Rotate[Rotate[figure, \[Pi]/2, e[1]], k \[Pi], e[3]]         , {k, 0, (bands - 1)/bands, 1/bands}]};     ClearAll[showFrames];     showFrames[figure_:polycircle[]] := Show[{           Graphics3D[{          Opacity[0.05], Sphere[], Opacity[1.0]          , globeGrid[6, figure]          }]   }       , Axes -> True       , PlotRange -> {{-g, g}, {-g, g}, {-g, g}}       , ImageSize -> Large];     showFrames[]      To improve it, I replace the polycircles with partially transparent wafers, which are very thin cylinders at low opacity:               ClearAll[wafer];     wafer[opacity_: 1/24] :=       {RGBColor[1, 0.71, 0]        , Opacity[opacity]        , Cylinder[\[Epsilon] {-e[3], e[3]}]        , Opacity[1]};      The results were disappointing               showFrames[wafer[]]      ![enter image description here](http://i.stack.imgur.com/6KVNx.png) **EDIT:** I tried a tube               polytorus[n_: 100] := Tube[polycircle[n], 0.01];     showFrames[polytorus[48]]      it's too slow to be interactive, but it has a better 3D effect. Still looking for a better answer. ![enter image description here](http://i.stack.imgur.com/ZFlZm.png)


Behavior of ValueQ inside a function

The following code               Cases[Function[{x}, x + 1], a_?ValueQ :> Hold[a], ∞, Heads -> True]      unexpectedly returns > {Hold[x + 1]} According to the manual, "ValueQ[expr] gives True if a value has been defined for expr, and gives False otherwise." In the example above, what is the expression that was assigned the value x+1?


Why can I still hear sound when the frequency of the periodic function inside Play is lower than the range of human ear?

This question is originally part of this question, but this issue seems to be different from the former one, so I think it's better to start another question for it. Usually, human can't hear sound with a frequency lower than 20 Hz, but what's confused is, the output of the following code can generate very slight shrieks, to be precise, two shrieks for every period, and the pitch of the sound will be lower with lower `SampleRate`:               Play[Sin[2 Pi t], {t, 0, 1}]     Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 4000]     Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      After some trial, I noticed that the frequency of the slight shrieks seems to be equal to the `SampleRate`, i.e.                 Play[Sin[2 Pi t], {t, 0, 5}, SampleRate -> 2000]      and                 Play[Sin[2000 2 Pi t], {t, 0, 1}, SampleRate -> 4000 2 Pi]      have same pitch. (Remember to regulate volume since the shriek generated by the former sample is really slight. ) It's probably another kind of artifact, but can someone explain it in detail? * * * ~~Some more information: the shrieks are at the position of peaks and valleys of sine wave i.e.               Play[Sin[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      has $2$ shrieks while               Play[Cos[2 Pi t], {t, 0, 1}, SampleRate -> 2000]      has $0.5+1+0.5$ shrieks.~~ * * * **Edit:** I should admit that I've misheard the position of the shrieks. With the code below, it's easy to distinguish that there's no sound at peaks and valleys:               Column[{Animate[Plot[Sin[2 Pi u], {u, 0, t}, PlotRange -> {{0, 5}, {-1, 1}}],                      {t, 0, 5}, AnimationRate -> 1, AnimationRepetitions -> 1],              EmitSound@Play[Sin[2 Pi t], {t, 0, 5}, SampleRate -> 2000]}]      I've posted the question in sound.SE and the answer I got there is in line with @CL.'s answer. Click here to read the answer (with a self-made video!).


How to sum matrix elements based on finding the first (and second) non-zero elements of each row?

I have a matrix: ![enter image description here](http://i.stack.imgur.com/omnrx.png) I would like to sum all the first non-zero elements of each row so that I get a value of $$25.5317 + 8.85471 + 6.90018 + 32.9436 + ... $$ and so on and simply ignore zero rows. Similarly I would like to do the same again for the second non-zero elements from each row so that I get: $$29.1235 + 11.0472 + 41.2639$$


ArcTan[z] and ArcTan[x,y], Restriction and Conversion

In _Mathematica_ there are two different forms for the arctangent (inverse tangent), namely               ArcTan[x,y]      which gives the arc tangent of $y/x$, taking into account which quadrant the point $(x,y)$ is in, and               ArcTan[z]      which gives the arc tangent $\tan^{-1}(z)$ of the complex number $z$. I am not sure about the exact conversion rule, but as far as I understand it is not simply               ArcTan[z] == ArcTan[x+I y] == ArcTan[x,y]      How do I restrict _Mathematica_ to use only one of the two forms for `ArcTan`, or convert between the two? **EDIT** Maybe I should elucidate on the problem at hand. I am trying to solve the equation $$ a \cos(x) + b \sin(x) = c $$ which can be done with the _Weierstrass substitution_ to yield $$ x_{\pm} = 2 \arctan\left[ \frac{b \pm \sqrt{a^2+b^2 - c^2}}{a+c}\right] $$ which is of the type `ArcTan[z]`. But if instead I use _Mathematica_               Solve[a Cos[x] + b Sin[x] == c, x]      Then I get an ugly expression of the type `ArcTan[x,y]`: $$ \arctan\left[\frac{a c-\sqrt{a^2 b^2+b^4-b^2 c^2}}{a^2+b^2},\frac{\frac{a \sqrt{-b^2 \left(-a^2-b^2+c^2\right)}}{a^2+b^2}-\frac{a^2 c}{a^2+b^2}+c}{b}\right] $$ How do I tell _Mathematica_ to convert this expression into an `ArcTan[z]` or vice versa? (I purposely neglected the periodicity of the solutions.) **EDIT 2** I just saw, that `Reduce` yields an `ArcTan[z]`. Where is the logic behind this?


Derivation after substitution not working

I have a code that will output an expression in form of a functions like this               (Λ[θ]^3 Ω[θ] - 4 (3 Derivative[1][Λ][θ] Derivative[1][Ω][θ] + Ω[θ] ( Λ′′)[θ]) -       4 Λ[θ] (Ω[θ] + 3 (Ω′′)[θ]))/(4 G J Λ[θ] Ω[θ]^3)      Now, I have functions $\Lambda(\theta)$ and $\Omega(\theta)$, that I'd like to replace with some values of theta. I tried with `->` and `:>` and none of the replacement rules will differentiate my replacement. I can differentiate the variables separately, and then specify replacement rule `Λ'[θ] -> value(θ)`, and then use `/. Derivative[1][Λ][θ]-> value[θ]`, but that seems kinda redundant. Why isn't _Mathematica_ doing it on it's own, recognising that it is the same expression, and just evaluating the derivative? This way _Mathematica_ is treating differentiated lambdas or omegas as something not connected to original lambda and omega. Why is this so, and can it be circumvented?


Why is my Dynamic expression so much slower than the same in Manipulate?

I'm trying to do some optimization based on interactive parameters, then compute and present stuff based on the optimized results. In trying to do that, I came across some strange behavior I can't figure out. When I write either:               Manipulator[Dynamic[y], {0, 1}]     Dynamic[NMinimize[(z - y)^2, z]]      or even:               DynamicModule[{y},       Manipulator[Dynamic[y], {0, 1}]       Dynamic[NMinimize[(z - y)^2, z]]     ]      it runs incredibly slower than:               Manipulate[       NMinimize[(q - p)^2, q]     , {p, 0, 1}]          The first two are much, much slower, to the point they slow down my whole session, and I can't figure out why. Any ideas on how to speed it up?


How to change the number of markers in Plots?

Two questions, but I am not sure whether they are already answered or not.   * How can I create `PlotMarkers` (in `ListLinePlot`) with less points (less markers)? Or markers with some intervals. I have tried the Mesh option, but it does not work; it messes up all the plots.    * Is it possible to create `PlotMarkers` for normal `Plot`, not `ListPlot`? One way is to export the data to the list, but I would like to do it directly. More information: Suppose `ListLinePlot` of a number of data lists with legends. based on the suggestions, I have changed my plots into this, but honestly I cannot understand how it works!               style = Sequence @@ {Frame -> {{True, False}, {True, False}},         FrameTicks -> {{0, 1, 2, 3}, {0, 0.4, 0.8, 1.5}, None, None},         FrameStyle -> Directive[Black, 16, FontSlant -> Plain],         LabelStyle -> Directive[FontSlant -> Plain],         AxesStyle -> Lighter@Gray, TicksStyle -> Black,         LabelStyle -> {GrayLevel[0], 14, FontSlant -> Plain,           FontFamily -> "Helvetica"}, ImageSize -> 300,         AspectRatio -> 1/GoldenRatio}            ListLinePlot[{c1, c2, c3, c4}, PlotRange -> Full,        Evaluate@style,        PlotLegends -> Placed[{Long, S_Short, Short, Flexible}, Below],        PlotStyle -> (Directive[            AbsoluteThickness[2], #] & /@ (ColorData[81] /@ Range[6])),        MeshFunctions -> {Abs[#1] &, Abs[#1] &, Abs[#1] &, Abs[#1] &},        Mesh -> 6, PlotMarkers -> {Automatic, 20},        MeshStyle -> {ColorData[81] /@ Range[6], ColorData[81] /@ Range[7],          ColorData[81] /@ Range[8], ColorData[81] /@ Range[9]}]      The output is something like this, where as you can see each Markers has all the colours together. How can I solve this problem and improve it? Another problem is the distribution of the Markers which is not good. ![the output!](http://i.stack.imgur.com/y53h9.jpg)


Question about Replacements and String Manipulations

I'm trying to get better at _Mathematica_ and in the book I'm using (by **Nancy Blachman** ) is the following question (which apparently was taken from another book: **_The Art and Science of C_** ) which reads: On a standard telephone keypad, the digits are mapped onto the alphabet (minus the letters Q and Z) as shown below:                       ABC     DEF      1       2       3     GHI     JKL     MNO      4       5       6     PRS     TUV     WXY      7       8       9      Write a function `phoneSpell` that generates all possible letter combinations that correspond to a given number, represented as a string of digits. For example, if you call `phoneSpell[652]`, your function should generate the 27 possible letter combinations corresponding to that prefix, namely               {"MJA", "MJB", "MJC", "MKA", "MKB", "MKC", "MLA", "MLB", "MLC",      "NJA", "NJB", "NJC", "NKA", "NKB", "NKC", "NLA", "NLB", "NLC", "OJA",     "OJB", "OJC", "OKA", "OKB", "OKC", "OLA", "OLB", "OLC"}      Note that if the argument passed to `phoneSpell` contains a 0 or 1, that position in the output should simply be displayed as that digit, since there are no letters that correspond to it. I've tried various things like first converting the number to a `String` using `ToString` and getting the `Length` using `StringLength`. I've tried a combination of `Outer` and `Tuples` to get the different combinations, but I'm not getting much luck. Any pointers in the right direction will be appreciated. Thanks.


How to deal with too much recursion

I have put together a very simple climate model based around four equations which define the state at time `t` based on time `t-1`, along with a initial state at time `t = 0`. The problem arises when I wish to evaluate, say, the temperature at year 2000 (`t = 2000`) or higher. I hit the recursion limit. I could keep increasing the `$RecursionLimit` all the time, but I wonder if there is a better way to deal with the problem?               ClearAll[timeStep, waterDepth, gramsPerM3ofWater, joulesPerCalorie,        joulesToHeatWater, solarConstant, albedo, boltzmanConstant,        emissivity, temp, heatContent, incomingFlux, outgoingFlux, flux];          (*Constants*)     timeStep = 31536000;(*One year in seconds*)     waterDepth = 4000.;     gramsPerM3ofWater = 1000000.;     joulesPerCalorie = 4.186;     joulesToHeatWater = waterDepth*gramsPerM3ofWater*joulesPerCalorie;     solarConstant = 1350.;     albedo = 0.3;     incomingFlux = solarConstant (1 - albedo)/4;     boltzmanConstant = 5.67*^-8;     emissivity = 1.;          (*Initial State*)     temp[0] = 0.;     heatContent[0] = temp[0]*joulesToHeatWater;     outgoingFlux[0] = emissivity *boltzmanConstant*temp[0]^4;     flux[0] = (incomingFlux - outgoingFlux[0])*timeStep;          (*Equations*)     heatContent[t_] := heatContent[t - 1] + flux[t - 1]     temp[t_] := heatContent[t]/joulesToHeat     outgoingFlux[t_] := boltzmanConstant*temp[t]^4     flux[t_] := (incomingFlux - outgoingFlux[t])*timeStep


Problem setting up C compiler on a Mac

This is a follow up to this question. I am using Mma 10 on a MacBook-Pro with OS-X Mavericks. After reading the documentation under CCompilerDriver/tutorial/SpecificCompilers I did the following:               Needs["CCompilerDriver`"];     CCompilers[]      ![enter image description here](http://i.stack.imgur.com/ZNCx5.png) The documentations says they are the compilers that _are found on my machine_ and that the CCompilerDriver package is automatically called when using CompilationTarget->"C" inside Compile. However, I can't get Compile working with CompilationTarget->"C". I also tried the Basic example in the documentation for CreateLibrary, and $Failed was returned. That means a suitable compiler could not be found. The documentation at CCompilerDriver/tutorial/SpecificCompilers also says, " Many Unix-type operating systems such as Linux or Mac OS X come with GCC already installed. If it is not present, then it can be added with a relatively simple configuration step." Can you help me with that _simple configuration step_?


Confusing ReplaceRepeated & Hold

I've been bootstrapping myself to the very alien world of Mathematica and there came my first WTF moment:               RRP[P_, O_, Phi_, L_, M_] :=       If[d <= L, O + l2*v0, {}] //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d  -> Norm[OP - v1],         l2 -> l1 + M Sqrt[L^2 - d^2]       };      What I wanted to achieve is to recursively apply these rules(which I felt similar to a context-free grammar) to form the desired expression. There was no cyclic dependency in the rules, nor were alternatives, so I kinda expected it to expand correctly. But it didn't! * * * Edit: I'm trying to calculate the position of the internal joint in a planar RRP linkage. Expressed in procedural language it's probably like this(pseudocode):               /* P: position of external R joint      * O: reference point of P joint      * Phi: direction of P joint      * L: length of the R-R bar      * M: +1/-1      */     function RRP(P, O, Phi, L, M){         OP=P-O;         v0=[cos(Phi), sin(Phi)];         l1=dot(OP, v0);         v1=l1*v0;         d=norm(OP-v1);         l2=l1+M*sqrt(L^2-d^2);         if(d<=L) return O+l2*v0;         else return [];     }      * * * Since I haven't figured out how to even _debug_ here, I tried to output intermediate variables(or non-terminals in CFG terminology):               RRP[P_, O_, Phi_, L_, M_] :=       {d, OP, v1, OP - v1} //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d -> Norm[OP - v1],         l2 -> l1 + M Sqrt[L^2 - d^2]         };     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      And it gave me this:               {{6, Sqrt[26]}, {-5, 1}, {-5, 0}, {{0, -5}, {6, 1}}}      `OP` and `v1` were as expected. But WTF was `OP-v1`? A _Matrix_? * * * I figure I can't do much with `OP` so I tried manually substituting `v1` in the `d->` rule:               RRP[P_, O_, Phi_, L_, M_] :=       {d, OP, v1, OP - l1*v0} //. {         v0 -> {Cos[Phi], Sin[Phi]},         OP -> P - O,         l1 -> Dot[OP, v0],         v1 -> l1*v0,         d -> Norm[OP - l1*v0],         l2 -> l1 + M Sqrt[L^2 - d^2]       };     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      Now it gives me the correct answer:               {1, {-5, 1}, {-5, 0}, {0, 1}}      * * * So now I'm VERY confused about this, I don't even know if I'm following the proper/idiomatic way of constructing complex functions, thanks to the arcane Help that came with Mathematica... Could anyone please either point out the problem, or kindly enlighten me on how I could construct a equivalent function in "The Mathematica Way"? * * * EDIT: After some lookup I figured out that the evaluation order for `OP - v1` was to blame. So I added `Hold[]` around the culprit and `//ReleaseHold` the whole thing after `//.` finishes building the expression. It works:               RRP[P_, O_, \[Phi]_, L_, M_] := (         If[d <= L, O + l2*v0, {}] //. {           v0 -> {Cos[\[Phi]], Sin[\[Phi]]},           OP -> P - O,           l1 -> Dot[OP, v0],           v1 -> l1*v0,           d -> Norm[Hold[OP - v1]],           l2 -> l1 + M Sqrt[L^2 - d^2]         }) // ReleaseHold;     RRP[{0, 1}, {5, 0}, 0, Sqrt[2], 1]      But I am still confused: Could I know where I need `Hold[]` when I _write_ the code, not as a workaround after I found out something wrong with it?


Finding the optimal teams ranking based on the table of match results

My original question was this: > So my task is to score all the possible rankings of the 14 SEC football > teams and find the best one, using who won in head-to-head games as the sole > criterion (so not factoring in strength of schedule or homefield advantage > yet). > > RandomSample[Range[14]] gives me one random ranking of the 14 teams, then I > score that ranking by seeing how many wins and losses it actually predicted. > For example, if "1" represents Missouri (miss) and "3" represents Georgia > (ga), then if the generated ranking has 1 listed before 3, that ranking gets > +1 to its ranking score, since Missouri beat Georgia this season. If 3 is > listed before 1, the ranking score receives a -1 to its score, for > incorrectly ranking those teams with respect to each other. And so on for > every head-to-head SEC match up from last year. In the code below, the 14x14 matrix is the head-to-head football results in the SEC from last year. For example, since "1" represents Missouri and "3" represents Georgia, the entry (1,3) and (3,1) both represent Missouri vs. Georgia. Since Missouri won, there's a 1 in that spot. The code checks which number is in each entry, then if the generated list has the winning team in front of the loser, the ranking score k receives one point, minus one if not. And it works for one list at a time. Now I need a way to apply that algorithm to all 14! possible rankings (Permutations[RandomSample[Range[14]]), find the one with the highest ranking score (k) and show that ranking. (14! is like 90 billion) Here's the code               x = ({         {0, 2, 1, 1, 1, 1, 1, 8, 0, 0, 1, 0, 1, 0},         {2, 0, 3, 2, 2, 6, 2, 0, 0, 0, 0, 2, 0, 2},         {1, 3, 0, 4, 3, 3, 3, 8, 0, 3, 0, 0, 0, 0},         {1, 2, 4, 0, 4, 4, 4, 0, 0, 0, 11, 0, 13, 0},         {1, 2, 3, 4, 0, 5, 5, 0, 0, 10, 0, 0, 0, 5},         {1, 6, 3, 4, 5, 0, 6, 8, 9, 0, 0, 0, 0, 0},         {1, 2, 3, 4, 5, 6, 0, 0, 9, 0, 0, 12, 0, 0},         {8, 0, 8, 0, 0, 8, 0, 0, 8, 10, 8, 8, 8, 8},         {0, 0, 0, 0, 0, 9, 9, 8, 0, 9, 9, 9, 9, 9},         {0, 0, 3, 0, 10, 0, 0, 10, 9, 0, 10, 10, 13, 10},         {1, 0, 0, 11, 0, 0, 0, 8, 9, 10, 0, 11, 11, 11},         {0, 2, 0, 0, 0, 0, 12, 8, 9, 10, 11, 0, 12, 12},         {1, 0, 0, 13, 0, 0, 0, 8, 9, 13, 11, 12, 0, 13},         {0, 2, 0, 0, 5, 0, 0, 8, 9, 10, 11, 12, 13, 0}        });          list1 = RandomSample[Range[14]];     rank = Ordering@list1;     k = 0;     For[i = 1, i < 15, i++,      For[j = 1, j < 15, j++,       Which[x[[i, j]] == i,        If[rank[[i]] > rank[[j]], k++, k--],        x[[i, j]] != (i || 0),        If[rank[[j]] > rank[[i]], k++, k--]]]]; k


Different results for MaximumLikelihood depending on method?

When I used this command:               EstimatedDistribution[data, BinomialDistribution[n, p],                           ParameterEstimator -> {"MaximumLikelihood", Method -> "NMaximize"}]       I get: `BinomialDistribution[12, 0.00842065]` with error message:               FindRoot::cvmit: Failed to converge to the requested accuracy or precision within 100 iterations      versus:               EstimatedDistribution[data, BinomialDistribution[n, p],                           ParameterEstimator -> {"MaximumLikelihood"}]      I get: `BinomialDistribution[4, 0.0252702]` What are actually the differences between the two commands? Which answer should I use?


Transform x-scale of data for e.g. MatrixPlot

I have to transform in a nonlinear way the x-scale of some data for a `MatrixPlot` (or `ReliefImage` or `ListDensityPlot` etc.). Let me give an example to explain what I try to do. I have following fake data:               fakeData=Table[BinCounts[RandomVariate[NormalDistribution[71,1.5],1000],{0,85,0.5}],{j,1,100}];      Which I can plot easily with e.g. `MatrixPlot[fakeData]`, which gives ![Output of MatrixPlot for fakeData](http://i.stack.imgur.com/orbzy.png) Or I can plot just one line of the fake data with `ListPlot[fakeData[[3]]]`, which gives ![Output of ListPlot for fakeData](http://i.stack.imgur.com/o59c5.png) But the xscale of the data is not correct and should be transformed. The initial scale is linear:               xScaleInitially=Range[Length[fakeData[[1,All]]]];      and the transformed scale should be something like, e.g.:               xScaleTransformed=1⁄((10+Sqrt[xScaleInitially]));      Then I can try to transform all my data with e.g.:               fakeDataTransformed=Table[Transpose[{xScaleTransformed,fakeData[[j]]}],{j,1,100}];      If I use `ListPlot[fakeDataTransformed[[3]]]`, I get for these data the result I want to have: ![Output of ListPlot for transformed fakeData](http://i.stack.imgur.com/Yekx6.png) But I cannot manage to use `MatrixPlot` or `ReliefImage` on these transformed data to get a picture similar to the first one above. Could somebody of you tell me how I can transform my data correctly, so that I still can have plots as with `MatrixPlot` or `ReliefImage` etc.? I would be very happy about every hint and help!


Using imported data in further calculations

I have quite a lot of data in an Excel file, which I have to use in further calculations. The transformation should map a data point with thre coordinates into a two coordinate result. Example: $(r,g,b)\mapsto(r/2 + g, r \, tan(\pi/3)/2)$. So far I have tried the following, but it doesn't work since the result is the same as the imported data.               coords[{r_, g_, b_}] := {r/2 + g, r Tan[Pi/3]/2};     data = Import["file.xlsx"]     coords[data]      ### Edit OK, i'm sorry for not posting the data earlier:               {{{"0.1", "0.65", "0.25"}, {"0.8", "0.1", "0.1"}, {"0.7", "0.15", "0.15"},        {"0.6", "0.1", "0.3"}, {"0.5", "0.2", "0.3"}, {"0.4", "0.1", "0.5"},        {"0.3", "0.3", "0.4"}, {"0.2", "0.1", "0.7"}, {"0.1", "0.8", "0.1"}}}


Mathematica 9, Mavericks, Java

I've been trying to get a clear story regarding the interaction of these three components before upgrading my system from Lion to Mavericks --- I can't afford a Mathematica disaster. What I think is the case is: 1\. Upgrading to Mavericks removes Java from the system (or perhaps installs Java 7). 2\. MMA 9 requires Java 6, and the MMA installer gives you an option to install (downgrade?) to Java 6. 3\. Once you have Java 6 installed, MMA works fine. Does that sound correct? Does Wolfram indeed support MMA 9 on Mavericks?


Is there a better way to get the eight points of intersection?

I want to get the eight points of intersection from the equations `2 Abs[x] + Abs[y] == 1` and `Abs[x] + 2 Abs[y] == 1`. To solve these equations, I tried               Solve[{2 Abs[x] + Abs[y] == 1, Abs[x] + 2 Abs[y] == 1}, {x, y}]      but could only get the four points. I then tried               y /. Quiet@Solve[#, y] /.         Abs[x_] -> {x, -x} & /@ {2 Abs[x] + Abs[y] == 1,  Abs[x] + 2 Abs[y] == 1}          p = ({x, y} /. Solve[y == #] & /@ {{1 - 2 x, (1 - x)/2}, {(1 - x)/2, (           1 + x)/2}, {(1 + x)/2, 1 + 2 x}, {1 + 2 x, -1 - 2 x}, {-1 - 2 x,            1/2 (-1 - x)}, {1/2 (-1 - x),            1/2 (-1 + x)}, {1/2 (-1 + x), -1 + 2 x}, {-1 + 2 x, 1 - 2 x}})~       Flatten~1      > {{1/3, 1/3}, {0, 1/2}, {-(1/3), 1/3}, {-(1/2), 0}, {-(1/3), -(1/3)}, {0, > -(1/2)}, {1/3, -(1/3)}, {1/2, 0}} It works, but I don't like it. Could you recommend a better method? ![enter image description here](http://i.stack.imgur.com/0GPLC.jpg)


EndOfFile error

I have a LARGE file (14.6 GB) that I want to separate into several smaller files. Because of its size, using Import/Export is not feasible, I think the most reasonable way of handling this would be using the file as a stream               stream = OpenRead[filepath]       then with               Read[stream, String]      I can select what I want, and hold the strings in a temporary list until that is large enough to warrant being exported and cleared. The problem is that when Read[stream,String] encounters ASCII character 0x1A, _Mathematica_ interprets it as an EndOfFile, even when it's not. Any suggestions to get around this? Edit: https://www.dropbox.com/s/sm51m2s19wtnoqa/allascii.txt is a text file with all ASCII characters, if read in as a stream, this error should be reproduced


Recently I have used Mathematica to simulate the concrete structure. The most important point is generate random concrete aggregate. As you know, concrete aggregate can be looked as a polyhedron. We can use ConvexHull to generate polyhedron.               Needs["TetGenLink`"];          data3D = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}};     Graphics3D[Point[data3D]];          {pts, surface} = TetGenConvexHull[data3D];     Graphics3D[GraphicsComplex[pts, Polygon[surface]]];      ![enter image description here](http://i.stack.imgur.com/SLdxs.png) Question 1: How to define two polyhedron intersect or not? I have written a Module, But its speed is very slow. Question 2: When the concrete aggregate become more and more in a cubic region, it is very difficult to add new aggregate in the region, How can deal with this problem ? The key is define the space relationship between line(segment) and plane(triangle):               HelenFormulaofTriangle[triangle_] := Module[        {a, b, c, p},             a = Norm[(triangle[[1]] - triangle[[2]])];        b = Norm[(triangle[[1]] - triangle[[3]])];        c = Norm[(triangle[[2]] - triangle[[3]])];             p = 0.5*(a + b + c);             Sqrt[p*(p - a)*(p - b)*(p - c)]             (*        triangle={{0,0,0},{1,0,0},{0,1,0}};        HelenFormulaofTriangle[triangle];        *)             ];                    PointInandOnorOut3DTriangle[point_, triangle_] := Module[        {},             If[         HelenFormulaofTriangle[{point, triangle[[1]], triangle[[2]]}] +            HelenFormulaofTriangle[{point, triangle[[1]], triangle[[3]]}] +            HelenFormulaofTriangle[{point, triangle[[2]], triangle[[3]]}] >           HelenFormulaofTriangle[triangle],         0,         1]                       ];                  triangle={{0,0,0},{1,0,0},{0,1,0}};        HelenFormulaofTriangle[triangle];        point={0,0,1};        PointInandOnorOut3DTriangle[point,triangle];      ![enter image description here](http://i.stack.imgur.com/Ka17C.png)


NDSolveValue: getting error concerning boundary values

I copied this code from the official website and I get an error when I evaluate it.               Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]     uval =        NDSolveValue[{         D[u[x, y], x, x] + D[u[x, y], y, y] == Exp[-(x^2 + 10 y^2)],          u[x, -1] == u[x, 1] == u[-1, y] == u[1, y] == 0},          u, {x, -1, 1}, {y, -1, 1}]      I get the error: > NDSolveValue::ivone: Boundary values may only be specified for one > independent variable. Initial values may only be specified at one value of > the other independent variable. >> Why is this happening? I copied it from: http://reference.wolfram.com/language/tutorial/NDSolvePDE.html I need this for an assignment, my problem is similar, but in this case I used the Laplace equation, but when I substitute my code I get the same error.


Intersection of two functions in SphericalPlot3D

How do I draw the intersection of these functions?               SphericalPlot3D[{Csc[ϕ], Sqrt[2]}, {θ, 0, 2 π}, {ϕ, 0, π},          BoxRatios -> {1, 1, 1}, AxesLabel -> {x, y, z}, Mesh -> None,          PlotRange -> {-1.5, 1.5}, PlotStyle -> Directive[Blue, Opacity[0.1]]]      ![](http://i.stack.imgur.com/C4IFa.png)


How to interpret an image histogram and plot histogram3D for an image?

I'm really finding many ambiguities in how I really should interpret the histogram of an RGB image? I could understand what the height denotes, but did not understand how the pixels get plotted on a single dimensional x-axis. Also, is it possible to plot the image onto histogram3D? I tried after converting it to separate RGB images but I get an error that says it is not able to calculate the "bins" the diagram. Thank you


Second derivative implicit differentiation using Wolfram Alpha input?

How would you perform second derivative implicit differentiation using Wolfram Alpha input? The reason that I'm using WA input is that it gives you step-by- step solutions and I'm a first year calculus student trying to figure things out. I've tried all of the obvious queries that I can think of without getting the desired results. If I type just the equation in it will give the results I'm seeking but without the step-by-step solution since it is not the primary output for the query. Here's an example of the results I get from just entering the equation x^2 + xy = 5 (w/desired result circled): ![equation results](http://i.stack.imgur.com/k9ZPt.png) *****P.S. Cross posted tocommunity.wolfram.com/groups/-/m/t/283665?p_p_auth=kD3FBYSv ***


How to write plain Greek in a text cell

If I create a text cell and type some greek text, most of the symbols are italics as if the cell had an _Input_ style. It doesn't happen with latin characters. I recollect that it is impossible to fix it, but I can't find the source where I read it. Perhaps someone knows a workaround ? The following screenshot is from _Mathematica_ 8/Linux. ![enter image description here](http://i.stack.imgur.com/0p2KG.png) **EDIT1** : I _just_ noticed that writing capital greek letters works fine (the letters are normal, not italics). The following screenshot is from _Mathematica_ 9.0.1/OSX Mavericks. ![enter image description here](http://i.stack.imgur.com/Qvxky.png) Does that piece of information ring any bells to anyone on what might be the underlying problem ? **EDIT2** : I also found this link describing a workaround by using custom modified unicode mapping files. I can't check it right now as I'm not near my Linux installation. **EDIT3** : I did try it though in _Mathematica_ 9.0.1/OSX (although the article talks about _Mathematica_ 7&8/Linux), and it works great! Here is the relevant screenshot: ![enter image description here](http://i.stack.imgur.com/qjjJx.png) **EDIT4** : As pointed out by @ybeltukov in comments, the workaround is to set the third column of `UnicodeFontMapping.tr` to 0 (zero) for Greek letters so that the default font is picked for them. **EDIT5** : This workaround doesn't anymore apply to _Mathematica_ 10\. I cannot find the `UnicodeFontMapping.tr` file.


Insert glyphs into a string using functional code

I asked this question few days ago: Replace For-loop with functional code Suppose I use strings instead of lists; for example               a = ToString /@ {123123, 112233};`      I want to insert first end of "4" to every possible position of given string. For elements in `a` , this give me               b = {4123123, 1423123, 1243123, 1234123, 1231423, 1231243, 1231234,           4112233, 1412233, 1142233, 112433, 112343, 1122334}       Now I Insert second end of "4" to given elements starting at first occurrence of "4". So, I get,               c = {       44123123, 41423123, 41243123, 41234123, 41231423, 41231243, 41231234,       14423123, 14243123, 14234123, 14231423, 14231243, 14231234,       12443123, 12434123, 12431423, 12431243, 12431234, 12344123, ...     }      Is there a method to insert elements into a string without splitting the string into a list of characters, (as done in Mr.Wisard's answer for the same question involving lists. See above link). This is what I came up with:               a = ToString /@ {123123, 112233};            Clear[f];       f[x_] := StringInsert[a, "4", x];       len = StringLength[         a[[1]]];(*Every string in set "a" has same length*)       b = Flatten[Map[f, Range[len + 1]], 1];            Clear[pos];       pos[x_] := Flatten[StringPosition[x, "4"], 1][[1]];       c = Map[pos, b];            result = {};       Do[Clear[g];         g[x_] := StringInsert[b[[i]], "4", x];         AppendTo[result, Map[g, Range[c[[i]] + 1, 8]]];, {i, 1, Length[b]}              ];            Flatten[result] ];      Anny comment to improve this really appreciated.