title: How to construct a coordinate system that owns detailed calibration in the 3D enviroment?

text: **_Recently,I write a program to demonstrate the forward kinematics of the SCARA robot.The code showed as below:_** **Using this function to construct the`BigArm` and `SmallArm` of SCARA robot.**               KeywayGeometry[color_List, coordinate_List, length_, height_, radius_,                    rotation_List] := Block[     {KeywayGeometryResult},      KeywayGeometryResult =      {       Rotate[         {color[[1]], Dashed, Thick,          Line[{coordinate - {0, 0, 2}, coordinate + {0, 0, height + 2}}],          Line[{coordinate + {length, 0, -2}, coordinate + {length, 0, height + 2}}],          color[[2]],          Cylinder[{coordinate, coordinate + {0, 0, height}}, radius],          Cuboid[coordinate - {0, radius, 0}, coordinate + {length, radius, height}],          Cylinder[{coordinate + {length, 0, 0}, coordinate + {length, 0, height}}, radius]},         Sequence @@ rotation       ]      }     ]      **Main program**                Manipulate[      Block[           {CoodinateSystem, ModelCoodinateSystem, Base, BaseHeight = 14,            BigArm, BigArmLength = 35, BigArmHeight = 4, BigArmRadius = 2,            SmallArm, SmallArmLength = 20, SmallArmHeight = 4, SmallArmRadius = 2,            LiftMechanism, LiftMechanismHeight = 18, Wrist,px, py},         px = BigArmLength Cos[θ1] + SmallArmLength Cos[θ1 + θ2];         py = BigArmLength Sin[θ1] + SmallArmLength Sin[θ1 + θ2];       CoodinateSystem =          {           Sequence @@ Flatten@           ({#1, Arrowheads[.02], Arrow[Tube[#2]]} &@@@           {            {Lighter@Red, {{0, 0, 0}, {10, 0, 0}}},            {Lighter@Green, {{0, 0, 0}, {0, 10, 0}}},            {Blue, {{0, 0, 0}, {0, 0, 10}}}           }),           Lighter@Red,           Sequence @@            (Text[Style[#1, Bold, 12, FontFamily -> Times, Italic], #2] & @@@           {            {"x", {12, 0, 0}}, {"y", {0, 12, 0}}, {"z", {0, 0, 12}}           })          };       ModelCoodinateSystem =          {           Sequence @@ Flatten@           ({#1, Arrowheads[.02], Arrow[Tube[#2]]} &@@@           {            {Lighter@Red, {{0, 0, BaseHeight + BigArmHeight},             {10, 0,BaseHeight + BigArmHeight}}},            {Lighter@Green, {{0, 0, BaseHeight + BigArmHeight},             {0, 10, BaseHeight +BigArmHeight}}},            {Blue, {{0, 0, BaseHeight + BigArmHeight},             {0, 0, 10 + BaseHeight + BigArmHeight}}}           }),          };      Base =       {        RGBColor[1, .5, .5, .6],        Cylinder[{{0, 0, 0}, {0, 0, 2}}, 3],        Cylinder[{{0, 0, 2}, {0, 0, BaseHeight}}, 2]       };      BigArm =        KeywayGeometry[          {Red, Blue}, {0, 0, BaseHeight}, BigArmLength, BigArmHeight, BigArmRadius,                     {θ1, {0, 0, 1}, {0, 0, 0}}];      SmallArm =        KeywayGeometry[          {Green, Purple},{BigArmLength Cos[θ1], BigArmLength Sin[θ1],           BaseHeight + BigArmHeight}, SmallArmLength, SmallArmHeight, SmallArmRadius,          {θ1 + θ2, {0, 0, 1}, {BigArmLength Cos[θ1],            BigArmLength Sin[θ1], 0}}];       LiftMechanism =       {        Rotate[         Cylinder[         {{px, py, BaseHeight + BigArmHeight - d3},         {px, py, BaseHeight + LiftMechanismHeight + BigArmHeight - d3}}, 1],         θ1 + θ2, {0, 0, 1}, {px, py, 0}]       };      Wrist =       Flatten@({#1, Cylinder[#2, #3]} & @@@       {        {Green, {{px, py, BaseHeight + BigArmHeight - d3}, {px, py,            BaseHeight + BigArmHeight - d3 - .5}}, 2.5},        {Red, {{px + 2 Cos[θ1 +θ2 - θ4],py + 2 Sin[θ1 +θ2 - θ4],            BaseHeight + BigArmHeight - d3 - .5},          {px + 2 Cos[θ1 + θ2 - θ4], py + 2 Sin[θ1 + θ2 - θ4],            BaseHeight + BigArmHeight - d3 - 2}}, .5},        {Orange,          {{px + 2 Cos[θ1 + θ2 - θ4 + π], py + 2 Sin[θ1 + θ2 - θ4 + π],            BaseHeight + BigArmHeight - .5 - d3},          {px + 2 Cos[θ1 + θ2 - θ4 + π], py + 2 Sin[θ1 + θ2 -θ4 + π],            BaseHeight + BigArmHeight - 2 - d3}}, .5}       });      Panel[         Graphics3D[           Sequence @@ # & /@        {CoodinateSystem, ModelCoodinateSystem, Base, BigArm, SmallArm, LiftMechanism, Wrist},      BoxRatios -> Automatic, ImageSize -> 550, ViewPoint -> {80, -60, 15},       PlotRange -> {{-60, 60}, {-60, 60}, {0, 45}}],       Style["SCARA Model Demostration", FontFamily -> "SketchFlowPrint",Red, 15]]     ],      {{θ1, 20 \[Degree], "θ1"}, -100 \[Degree], 100 \[Degree]},      {{θ2, 50 \[Degree], "θ2"}, -150 \[Degree], 150 \[Degree]},      {{d3, 5, "d3"}, 0, 10},      {{θ4, 20 \[Degree], "θ4"}, -180 \[Degree], 180 \[Degree]},      ControlPlacement -> Bottom,       FrameLabel -> Style[" The Kinematics of SCARA Robot " , FontFamily -> Times, 15,Purple]      ]      **_It generrate the picture as below:_** ![SCARA Model](http://i.stack.imgur.com/6YIQS.jpg) **_However,I want add a`module` that can show `the position of the endeffector of SCARA robot.` or help the user to read the coordinate of the endeffector._** **I have a method that construct a coordinate system that owns detailed calibration.Unfortunately,`I don't know how to write the code`**


title: Can I use a custom (Frame)Ticks specification to define the PlotRange?

text: The documentation for `Ticks` and `FrameTicks` shows how one can define a function for custom ticks or frame ticks, for example:               niceTicks[min_, max_, n_: 7] := FindDivisions[{min, max}, n]      After creating some example data               fakedata1 = FoldList[0.99 #1 + #2 &, 1.,         RandomVariate[NormalDistribution[0, 1], {100}]];      We can see that `FrameTicks` specifications will allow for functions, and will automatically pass the minimum and maximum of the data set as arguments.               ListLinePlot[fakedata1, Frame -> True, PlotRange -> All, PlotRangePadding -> 0,       FrameTicks -> {{niceTicks, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/jvylT.png) Similarly one could use:               ListLinePlot[fakedata1, Frame -> True, PlotRange -> All, PlotRangePadding -> 0,       FrameTicks -> {{niceTicks[##, 10] &, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/EajtH.png) As an aside, when using data points specified in terms of ${x,y}$ coordinates, as in `DateListPlot` and related functions, the `FrameTicks` specification will correctly pass the minimum and maximum _of the x or y coordinates as appropriate_ , which is pretty cool. My question is how one can link the `PlotRange` of the plot to the ticks determined by such a custom function. In this particular instance, the `FindDivisions` function called by `niceTicks` ranges from -2 to 10, but the plot only takes up as much space as the data require, plus any `PlotRangePadding`.               niceTicks[Min@fakedata1, Max@fakedata1]     (* {-2, 0, 2, 4, 6, 8, 10}  *)      If I want the plot to have ticks effectively at the very top and bottom of the frame like this, using all the ticks output by my `niceTicks` function, I need to specify the PlotRange explicitly using the same `niceTicks` function:               ListLinePlot[fakedata1, Frame -> True,       PlotRange -> niceTicks[Min@fakedata1, Max@fakedata1][[{1, -1}]],       PlotRangePadding -> 0,  FrameTicks -> {{niceTicks, None}, {Automatic, None}}]      ![enter image description here](http://i.stack.imgur.com/prKyB.png) I'm sure that calling an auxiliary function twice like this doesn't add a lot of overhead, but it does require getting explicit minima and maxima from the data, which is a bit clunky when you consider multiple series, dated data for `DateListPlots` etc. **Is there a way to pass the maximum and minimum tick values determined in the`Ticks` or `FrameTicks` option expression to the `PlotRange` option automatically?** It would be more elegant code with fewer special cases to code for. I'm building this into a suite of custom plotting functions, where a tick specification like the last picture shown is a requirement. It would also be nice to pass the same tickmarks to `GridLines` somehow, so that `Automatic` gridlines automatically matched up with the specified ticks.


title: Mathematica quine

text: A quine is a computer program which takes no input and produces a copy of its own source code as its only output. There are many trivial quines in Mathematica:               In[1]:= "Hello world"     Out[1]= "Hello world"          In[2]:= 3.14     Out[2]= 3.14          In[3]:= f[x]     Out[3]= f[x]      where `f` and `x` are undefined symbols; and some more               In[4]:= Hold[N[\[Pi]]]     Out[4]= Hold[N[\[Pi]]]      These are all trivial. I was thinking that perhaps a more interesting challenge for Mathematica was a multiquine. This is a program A that outputs another program B, _distinct_ from A, such that when B is exectued, the output is A. Multiple levels of depth are also allowed: Thus one might have a program that when executed outputs a distinct program that when executed outputs another program distinct from the first two ... that when executed outputs the original program. There are also multiquines that output a distinct program _in a different language_ , such that when this program is executed, the output is the original program. **QUESTION** (Though more of a challenge): Can you come up with a multiquine for Mathematica?


title: Using Thread or MapThread over multi-level, ragged lists

text: This may be a rather strange question. I will try to create a sort of minimal working example. Suppose that I have two lists, `list1` and `list2`. Both `list1` and `list2` are ragged, and they both have multiple levels. However, `list1` and `list2` have the same number of elements, and their level distributions/arrangements are the same. For example:               list1 = {{{a, b, c}, {d, e, f, g, h}, {i, j}}, {{AA, BB}, {CC, DD, EE}}};     list2 = {{{1, 2, 3}, {4, 5, 6, 7, 8}, {9, 10}}, {{11, 12}, {13, 14, 15}}};      I would like to "thread" or "transpose" `list1` and `list2` to obtain `list3`, which has the same basic structure but with corresponding elements paired:               list3 =      {{{{a, 1}, {b, 2}, {c, 3}}, {{d, 4}, {e, 5}, {f, 6}, {g, 7}, {h, 8}}, {{i, 9}, {j, 10}}},         {{{AA, 11}, {BB, 12}}, {{CC, 13}, {DD, 14}, {EE, 15}}}}      Is there a relatively simple way to obtain `list3` from `list1` and `list2`, apart from using a complicated nesting of `Table` commands? `Transpose`, `Thread`, and `MapThread` all seem potentially useful, but not entirely straightforward for such "deep," ragged lists. Do you have any suggestions? Thanks for your time.


title: Elementwise join

text: I have two tensors of arbitrary but equal rank n (and equal dimensions): `A` and `B`, and I want to get a third tensor of rank n + 1, `C`. I want to do a element by element `Join`, so the element in `A` and the corresponding element in `B` are contracted into a list in `C`. For example, with n = 2:               A = {{a[0,0],a[1,0]},{a[0,1],a[1,1]}};     B = {{b[0,0],b[1,0]},{b[0,1],b[1,1]}};      then:               C = {{ {a[0,0],b[0,0]} , {a[1,0],b[1,0]} },{ {a[0,1],b[0,1]} , {a[1,1],b[1,1]} }}      I think it might be doable with some combination of `Inner` and `List`, but I'm not sure.


title: How to show legend in a combined plot of many lists,

text: I am having trouble with adding a legend to a plot. The example I discuss here is simpler than my real problem, but describes it well. I have a vector, called X with dimensions (100 x 6). I use the command `ListPlot` to plot one row of X at a time:               plotX={};     Do[     p1=ListPlot[X[[i]]];     AppendTo[plotX,p1],     {i,1,Length[X]}];      Therefore, the list `plotX` contains six list plots with 100 points each. To show all the plots, I use the command `Show`               Show[plotX]      Now I want to create a legend for this graph, for example `{"x1","x2","x3","x4","x5","x6"}`. How can I do this? Thanks


title: Auto line breaks in workbench

text: I have been using Mathematica for a while and thought of using Worbench to structure my project better. However, moving my code from .nb-files to .m-files in a Workbench project does not really work, since unlike the Mathematica frontend Workbench does no line breaks. Is there a way to enable auto line breaks in Wolfram Workbench? If not, how is one supposed to work with long expressions in Workbench?


title: Probability of xy point on bivariate normal distribution

text: I have a bivariate normal distribution and I am trying to calculate the probability of finding a point at a certain distance from the mean, so far with limited success. My approach has been to build the two normal distributions, and then form a product distribution:               px = NormalDistribution[-3.89764, 0.08369444426];     py = NormalDistribution[1.29137, 0.0175124];     pxy = ProductDistribution[px, py];      I can plot this and things look fine, but I can't seem to get the syntax correct for the probability calculation. I want to calculate the probability of finding x between -3.98529 and -3.80999, and y between 1.27792 and 1.30482. I can do this in 1D if I take just one of the normal distributions and do:               prob = Probability[x > -3.98529  && x < -3.80999, x \[Distributed] NormalDistribution[-3.89764, 0.08369444426]];      although so far I haven't been able to extend the syntax to the 2D case. I'm still reasonably new to Mathematica and any help will be much appreciated!


title: Formatting Fortran complex number output for use in Mathematica

text: Here is a list that was orignially output from Fortran.               {{"(0.277336296055697, 0.120000000000000E+000)"},       {"(-1.489297392708939E-002, 0.340000000000000E+000)"}}      which is to be interpreted as a list of two complex numbers. Of course, _Mathematica_ does not understand this, so, I would like to convert it into something like               {{0.277336296055697 + 0.12I}, {-0.01489297392708939 + 0.34I}}      Can I do this programmatically in _Mathematica_?


title: How to organize and run functions?

text: I am very new to Mathematica. I thought I would try it out for my first assignment in my computer science class. Until now I have only used C-base languages including C#, Java, Objective-C, and Python. This assignment is to implement RSA encryption and I thought Mathematica would be perfect for this. My code works when it is run outside of functions, but for some reason I can not figure out how to make functions and run them properly. Can someone please explain what is wrong with how I have my document set up right now? Thank you. My Document (after attempting to run)![enter image description here](http://i.stack.imgur.com/nlRe1.png) It seems like Mathematica is trying to run the document even though I have not called any of the functions.


title: Finding real roots of negative numbers (for example, $\sqrt[3]{-8}$)

text: Say I want to quickly calculate $\sqrt[3]{-8}$, to which the most obvious solution is $-2$. When I input $\sqrt[3]{-8}$ or `Power[-8, 3^-1]`, Mathematica gives the result "$2 (-1)^{1/3}$". Not what I want. When I input `Power[-8, 3^-1] // N` or `Power[-8., 3^-1]`, Mathematica gives the result "$1. + 1.73205i$". While technically correct, this is messy and not always useful. **How can I get the _real_ cube root of a negative number?** Or more generally, how can I get a list of _all_ valid roots?


title: obtaining real roots of negative numbers in a long expression

text: I have a complicated symbolic expression which contains many terms like $(a/(a-2))^{1/m}$, where $a/(a-2)$ could be positive or negative after replacement. I only need the real root after replacement, but `Power[]` function in _Mathematica_ most of the time gives me a complex number instead. I found something that almost suits my need here (the `realPower` function by Peter Breitfeld), but I have a hard time get it working in the way I want. For example:               ((a/(-2 + a))^(1/3) /. {x_^y_ :> realPower[x, y]}) /. {a -> 0.5}      still gives me a complex number. (it seems that `realPower` only work with numerical values) What should I do to get only the real root after replacement?


title: Plot cubic root which includes the negative graph

text: > **Possible Duplicate:**   >  Finding real roots of negative numbers (for example, $\sqrt\[3\]{-8}$) Yes, I know there are other Threads which have similar questions and yes I read them but I am just not able to solve the problem. Please help me I am totally at the limit with this :( How do I plot a cubic root in Mathematica, where also the negative graph is shown? ![cubic root in plot without negative graph](http://i.stack.imgur.com/6Yne2.png) NOTE: Threads I have found and not understood How to plot imaginary part of a function Finding real roots of negative numbers (for example, $\sqrt[3]{-8}$) Plotting Complex Quantity Functions


title: How to tell Mathematica to use Real Only Mode

text: How do I tell Mathematica to use real only mode. For example if I want to graph $(x-1)^{1/3}$ for $-3<x<3$, I need to use Real Only mode to get the right graph.


title: Reduce an equation by putting a new variable

text: I have the following equation given: $$ (26-x)\cdot\sqrt{5x-1} -(13x+14)\cdot\sqrt{5-2x} + 12\sqrt{(5x-1)\cdot(5-2x) }= 18x+32. $$ In order to solve it, I want to substitute $t = \sqrt{5x - 1}-\sqrt{5-2x}$. This cannot be done directly but with this step the equation could be transformed in the form $(t-2)^3 = 0$, which can be solved easily. Is it possible to make this substitution with Mathematica? The only thing I have achieved is to solve it directly with               Solve[(26 - x)*Sqrt[5*x - 1] - (13*x + 14)*Sqrt[5 - 2*x] +            12*Sqrt[(5*x - 1)*(5 - 2*x)] == 18*x + 32]


title: Mean squared error of two matrices

text: I want to compare two matrices. For this I use the mean squared error between them with the following code               mse[mat1_, mat2_] :=(mat1 - mat2)^2 // Flatten // Mean       Is this code correct? Are there other methods to compare two matrices? **update** Thank you all for your answers! Actually, I want to determine an unknown parmeter by comparing model and data. The matrix 1 contains empirical data, whereas matrix 2 is calculated from a model which has an unknown parmeter. My idea was to calculate a set of theoretical matrices with different values of the parameter $\Theta$ and compute the mean squared difference between empirical and theoretical matrices for each $\Theta$. The best $\Theta$ is the one for each the mean squared difference is minimum. Does this make sense? Are there better ways to do that?


title: Functional-Style Fixed-Length Queue Object?

text: Following up on question Side-effecting an array in an association? and @Mr.Wizard's answer in there, I'm modernizing and tweaking Daniel Lichtblau's efficient queues and ran into a little roadblock. First, I came up with the following API, stripped-down for brevity. The queue I want is fixed-length and lossy. Make a new queue with `newQ[capacity]`. Push values to the back with `pushQ[aQueue, aValue]`; pop values from the front with `popQ[aQueue]`, just like a queue of humans. If the queue is full, just pop the value at the front, losing it (on purpose) I want `pushQ` to return the queue it receives, so that I can fold it and chain it as follows:               Fold[pushQ, newQ[4], Range[10]]      Here's what I came up with, with the functional mojo highlighted:               ClearAll[newQ, emptyQQ, fullQQ, pushQ, popQ, peekQ, bumpQ];      newQ[cap_Integer] /; cap > 0 :=       <|"storage" -> ConstantArray[Null, cap],        "len"    -> 0, "cap"   -> cap,        "iFront" -> 1, "iBack" -> 1|>;     emptyQQ[Q_] := Q[["len"]] === 0;     fullQQ[Q_]  := Q[["len"]] === Q[["cap"]];     peekQ[Q_]   := Q[["storage", Q[["iFront"]]]];     SetAttributes[bumpQ, HoldFirst];     bumpQ[Q_, index_] := Q[[index]] = Mod[Q[[index]] + 1, Q[["cap"]], 1];     SetAttributes[pushQ, HoldFirst];     pushQ[Q_, item_] :=       (Q[["storage", Q[["iBack"]]]] = item;        bumpQ[Q, "iBack"];        If[fullQQ[Q],         (*then*)bumpQ[Q, "iFront"],         (*else*)Q[["len"]]++];        Q); (* <<<<<<< HERE IS THE FUNCTIONAL MOJO <<<<<<<< *)     SetAttributes[popQ, HoldFirst];     popQ[Q_] /; emptyQQ[Q] := Null;     popQ[Q_] :=      (Q[["len"]]--;       With[ {result = Q[["storage", Q[["iFront"]]]]},        Q[["storage", Q[["iFront"]]]] = Null;        bumpQ[Q, "iFront"];        result ])      This passes a bunch of unit tests:               $q = newQ[4];     pushQ[$q, 1]; $q["storage"]      > >     {1, Null, Null, Null} >                 pushQ[$q, 2]; $q["storage"]      > >     {1, 2, Null, Null} >                 pushQ[$q, 3]; $q["storage"]      > >     {1, 2, 3, Null} >                 popQ[$q]      > >     1 >                 $q["storage"]      > >     {Null, 2, 3, Null} >                 popQ[$q]; $q["storage"]      > >     {Null, Null, 3, Null} >                 pushQ[$q, 4]; $q["storage"]      > >     {Null, Null, 3, 4} >                 pushQ[$q, 5]; $q["storage"]      > >     {5, Null, 3, 4} >                 popQ[$q]      > >     3 >                 $q["storage"]      > >     {5, Null, Null, 4} >                 pushQ[$q, 6]; pushQ[$q, 7]; pushQ[$q, 8]; pushQ[$q, 9]; pushQ[$q, 10];         $q["storage"]      > >     {9, 10, 7, 8} >                 popQ[$q]      > >     7 >   and so on. Now, when I try the obvious generalization to folding, I'm back where I started with the `... in the part assignment is not a symbol.`               Fold[pushQ, newQ[4], Range[1]]      > >     During evaluation of In[49]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >     During evaluation of In[49]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >     During evaluation of In[49]:= General::stop: Further output of > Set::setps will be suppressed during this calculation. >> >     <|"storage" -> {Null, Null, Null, Null}, "len" -> 0, "cap" -> 4, > "iFront" -> 1, "iBack" -> 1|> >   Ok, I need some kind of symbol for `Set` to work. A couple more attempts as follows produce the same results, and I did a bunch of tracing and printing, and couldn't see a good way through this:               Module[{$q = newQ[4]}, Fold[pushQ, $q, Range[1]]]      > >     During evaluation of In[48]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >                 Module[{$q = newQ[4]}, Fold[($q = pushQ[#1, #2]) &, $q, Range[1]]]      > >     During evaluation of In[44]:= Set::setps: > <|storage->{Null,Null,Null,Null},len->0,cap->4,iFront->1,iBack->1|> in the > part assignment is not a symbol. >> >   **EDIT** : This question is really about elegance because I _can_ get meaningful, useful side effects with `Map` and `Scan`, as follows:               Module[{q = newQ[4]}, pushQ[q, #] & /@ Range[10]]      > >     {<|"storage" -> {1, Null, Null, Null}, "len" -> 1, "cap" -> 4, "iFront" > -> 1, "iBack" -> 2|>, >        <|"storage" -> {1, 2, Null, Null}, "len" -> 2, "cap" -> 4, "iFront" > -> 1, "iBack" -> 3|>, >        <|"storage" -> {1, 2, 3, Null}, "len" -> 3, "cap" -> 4, "iFront" -> > 1, "iBack" -> 4|>, >        <|"storage" -> {1, 2, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 1, > "iBack" -> 1|>, >        <|"storage" -> {5, 2, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 2, > "iBack" -> 2|>, >        <|"storage" -> {5, 6, 3, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 3, > "iBack" -> 3|>, >        <|"storage" -> {5, 6, 7, 4}, "len" -> 4, "cap" -> 4, "iFront" -> 4, > "iBack" -> 4|>, >        <|"storage" -> {5, 6, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 1, > "iBack" -> 1|>, >        <|"storage" -> {9, 6, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 2, > "iBack" -> 2|>, >        <|"storage" -> {9, 10, 7, 8}, "len" -> 4, "cap" -> 4, "iFront" -> 3, > "iBack" -> 3|>} >


title: Is it necessary to introduce ImplicitRegion and ParametricRegion in version 10?

text: In version 10.0, _Mathematica_ introduced a new function about region plotting: ImplicitRegion. But I'm wondered that haven't this function been already existed in the older version? That is, RegionPlot. I truly can't see the difference. Another question is, in version 10, _Mathematica_ also introduced a function called `ParametricRegion`, my question is the same again: isn't it equivalent to the third usage of `ParametricPlot`? PS: I found a little bit difference is that `ParametricRegion`(new function in ver. 10) have the ability to constrain the parameters in more specific way(not just required to be `{u,u_min,u_max}, {v,v_min,v_max}`, but also `{1 <= u <= 5, 3 <= v <= 10, u+v < 7.5}`), but it can seemingly be done by option `RegionFunction` in the older version!


title: How do I insert a piece of code in Mathematica?

text: In Fortran, I can use `include "file"` to insert a piece of code. Is there a similar method in Mathematica?


title: Non-geometric transformation of Graphics3D primitives

text: I want to apply non-geometric transformations to polygons etc, the goal is to have a `Manipulate` objects that behaves like that famous möbius transform video. Since I was unable to apply non-geometric transformation to a polygon I went ahead and created a bunch of points in the plane and did appropriate transforms to them               (* plane region *)     region = {-1, 1};     d = 0.07;     (* Some points in plane *)     pts = Flatten[Table[{xi, yi, 0},         {xi, First@region, Last@region, d},         {yi, First@region, Last@region, d}]        , 1];     col = ColorData["Rainbow"] /@ Rescale[pts[[All, 1]], region];     (** Projections from plane to sphere on line going through north pole \     of sphere centered at {0, 0, 1} **)          (* Plane to sphere *)     f[vec_] := With[{t = 4/(4 + vec[[1]]^2 + vec[[2]]^2)}, vec*t + (1 - t) {0, 0, 2}]     (* Sphere to plane *)     g[vec_] := With[{t = -(2/(-2 + Last@vec))}, vec*t + (1 - t) {0, 0, 2}]          rt = RotationTransform[2.1, {0, 1, 0}, {0, 0, 1}];     Graphics3D[{       {Black, Opacity[0.3], Sphere[{0, 0, 1}]},       Point[(rt@f@# &) /@ pts, VertexColors -> col],       Point[((g@rt@f@# &) /@ pts), VertexColors -> col]       },      PlotRange -> {{-10, 10}, {-10, 10}, {0, 2}}]      ![output](http://i.stack.imgur.com/DVADU.png) I wish that I could instead do something like:               Graphics3D[{      {Black, Opacity[0.3], Sphere[{0, 0, 1}]},      SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], rt@f@#&],      SomeTransformation[Polygon[{ {-1, -1, 0}, {-1, 1, 0}, {1, 1, 0}, {1, -1, 0}}], g@rt@f@#&]      ]      And end up with a smooth output, not just a few points here and there. Is there already a function like this that I have missed? If not are there other ways to arrive at the same result? How about for more advanced transformations?


title: Remove image background of headshot in Mathematica?

text: For example, using `ExampleData[{"TestImage", "Girl2"}]`: ![Mathematica graphics](http://i.stack.imgur.com/wstxf.png) what's a general way to make the background transparent? I've tried various combinations of `EdgeDetect` and `Threshold` and ImageAdd but can't figure it out. Thank you.


What function can I use to evaluate $(x+y)^2$ to $x^2 + 2xy + y^2$? I want to evaluate It and I've tried to use the most obvious way: simply typing and evaluating $(x+y)^2$, But it gives me only $(x+y)^2$ as output. I've been searching for it in the last minutes but I still got no clue, can you help me?


title: Performance tuning - Explicitly set Mathematica use Nvidia GPU for rendering

text: I feel hesitated to ask this question, but I cannot figure out a way to increase the performance. ![enter image description here](http://i.stack.imgur.com/rOAt9.gif) The problem is about running this featured example on a computer with both Intel HD GPU and Nvidia GPU. If the computer only has a Nvidia GPU, everything is smooth and fine. However, if both GPUs are installed on the computer, the performance will be very poor due to the transparent rendering and the fact that Mathematica always use the Intel GPU for rendering. Even if I set Nvidia GPU as the default one to use for all programs and explicitly run Mathematica with Nvidia GPU, this example is still run with the Intel GPU... I wonder if there is a way to fix this? Furthermore, can we explicitly tell Mathematica which GPU it should try to use by using a `Style`-like statement similar to this answer? I am running on a windows 7 laptop with following configurations, ![enter image description here](http://i.stack.imgur.com/Y3L37.png) ![enter image description here](http://i.stack.imgur.com/HYTij.png) * * * **Edit** I have reported this problem to Wolfram.


title: Fast method to select matrix elements based on a vector of positions

text: There is an operation for which I have long wanted to find a better solution. Let:   * `a` be a matrix of dimensions $m\times n$   * `v` be an integer vector of length $n$ with elements drawn from $[1, m]$ For every element $x$ at position $p$ in `v` I wish to select the element at row $x$, column $p$ in `a`. Example:               SeedRandom[0]          a = Array[Range[7] 10^# &, 3, 0]          v = RandomInteger[{1,3}, 7]      > $\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 10 & 20 & 30 & > 40 & 50 & 60 & 70 \\ 100 & 200 & 300 & 400 & 500 & 600 & 700 \\ \end{array} > \right)$ >   >   >     {3, 3, 2, 1, 1, 3, 1} >   Desired output:               {100, 200, 30, 4, 5, 600, 7}      * * * ### Details:   * Although a compiled function is likely to be the fastest approach for packed arrays I want something more general, allowing arrays of mixed types, and ideally optimized for arrays in which each row is a packed array (list) of a different type, e.g. $\left( \begin{array}{ccccccc} 1 & 2 & 3 & 4 & 5 & 6 & 7 \\ 0.1 & 0.2 & 0.3 & 0.4 & 0.5 & 0.6 & 0.7 \\ \text{a} & \text{b} & \text{c} & \text{d} & \text{e} & \text{f} & \text{g} \\ \end{array} \right)$   * I am still interested in seeing the fastest possible compiled function as it may serve as the basis for a general solution as well.   * I seek a solution that works well for any shape of array `a`, from $n\gg m$ to square to $m\gg n$, though if compromise is necessary I would optimize for $n > m$.


title: Trying to generate a function from InterpolatingFunction with FunctionInterpolation

text: Here is the code (I'm sorry to give you such a complex code sample but I failed to reproduce the error with a simpler InterpolatingFunction):               (*constants*)     R0 = 8.314; M = 28.8 10^(-3); R = R0/M;     te0 = 298; pa0 = 101325; \[Rho]g0 = Pi 25 10^-4 pa0/(R te0);     \[Rho]s0 = 0.17; t0 = 0.005; x1 = 0.01; x2 = -10^-3;     Q = 3000000; A = 10^15; ea = 9 10^4; cg = (5/2) R; cs = 1.46 10^3;     kg = 2.61 10^-2; ks = 0.36; ac = 4/0.01; hc = 1500;               c1 = NDSolve[{((ArcTan[-10^5 x]/Pi) + 1/2) (\[Rho]s0 cs D[te[t, x], t] -              (0.005^2 Pi) ks D[te[t, x], x, x] - \[Rho]s0 Q A Exp[-ea/(R0 te[t, x])])           + ((ArcTan[1000000 x]/Pi) + 1/2) (\[Rho]g0) cg D[te[t, x], t]              (+\[Rho]g0) (A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2 -               A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2/x1 x) (1 - Exp[-10^4 t])                cg D[te[t, x], x] (+\[Rho]g0) R te[t, x] (1 - Exp[-10^4 t])              (-A \[Rho]s0/\[Rho]g0 Exp[-ea/(R0 te0)] x2/x1) -              ((0.005^2 Pi) kg D[te[t, x], x, x]) + (0.005^2 Pi) ac hc (te[t, x] - te0) == 0,             te[0, x] == te0, te[t, x2] == te0, te[t, x1] == te0},           {te[t, x]}, {t, 0, t0}, {x, x2, x1}, PrecisionGoal -> 3];          f[t_, x_] = te[t, x] /. c1; teb1[t_] = f[t, 0];     Plot[teb1[t], {t, 0, t0}]     Subscript[teb, i] =       FunctionInterpolation[       If[(D[(te[t, x] /. c1), x] /. x -> 0) < 100, ((te[t, x] /. c1) /. x -> 0) + 0.01,                                                     ((te[t, x] /. c1) /. x -> 0)],       {t, 0, t0}]      After I ran the code, the warning message generated…"The function did not evaluate to a real number", why? Who can tell me what is wrong?


title: How can I create Arguments Maps with Mathematica's graph functions?

text: I am relatively new to _Mathematica_ , and I would like to know how I could use it to represent an Argument Map, such as those that you generate on online tools such as http://debategraph.org. The goal is to test an algorithm on a Argument-Map-like data structure. I think this should not be too difficult as they are nothing else but simple graphs with vertex/edge labeling.


title: Can $\it{every}$ usage of While be changed into NestWhile?

text: Ok, I think this problem is more close to philosophy. :P I've some idea now. But I'm not sure whether it's correct. For the purpose of convenience, I will use some C-like code instead of MMA's. A `While` loop is something like:               i=0; // some initialize of variable i     While(test of variable i)   // such like i<10 or i^3<90, etc.     {        // involving doing something which has nothing to do with i (e.g. Print["*"])        // or involving taking i as an argument of another function, such like Sin[i]        // or involving re-assign some value to i, such like i=i+7     }     Print[i] // after doing such evaluations, we want to get the final value of i      The first and second line surrounded in while is not really a problem for `NestWhile`. It is just because `NestWhile` is `NestWhile[f,expr,test]`, one can write `(Print["*"];Sin[#]+1&)` in the place of `f`, doing the same thing you want when you're dealing with `While`. However, when you want to re-assign `expr` in `NestWhile`, No, you cannot. `i=0;NestWhile[#=#+1&,i,#<70&]` is not what you want. (The `i` is immediately change into 0 before you would want to do `i=i+1`) And just because of this simple difference between `While` and `NestWhile`, I doubt that EVERY `While`-code can change into `NestWhile`-code.


title: DownValue "associative array" to list?

text: I have a "sparse array" like this               arr[1.5]=0.4, arr[3.5]=0.7, arr[7]=0.3      which is not really a sparse array since the keys are not all integers. This is like a hash table or associative array. How can I convert `arr` into a list? I tried `Normal[arr]`, but it won't work. I would like to be able to compute `Total@arr`, but first it needs to be converted to a normal list.


title: Implementing Kane's Subset Sum Algorithm

text: In the following paper, D. Kane describes an algorithm for subset sum that runs in logspace: http://arxiv.org/pdf/1012.1336v2.pdf. I am trying to implement it               subsetsum[sum0_, set0_] := Module[{sum = sum0, set = set0},     c = 0;     csum = Abs[sum] + Total[set] + 1;     p = NextPrime[csum];     n = Length[set];     check = False;     While[c <= n,     Print["c=" <> ToString[c] <> "p=" <> ToString[p]];     If[IntegerQ[Sum[x^(-sum)*Product[(1 + x^(set[[i]])), {i, 1, n}], {x, 1, p - 1}]/p],     check = True; Break[];];     c = c + Floor[Log[2, p]]; p = NextPrime[p];     ];     check     ];      This initial value $C$ which seems to be the $C$th prime or the next prime after $C$ is given as: $ C = \lvert B \rvert + \sum_{i=1}^n \lvert m_i \rvert +1 $ $B$ is the sum to which a subset of some set $\{m_1,m_2,m_3,\ldots,m_n\}$ sum to. Furthermore, on a simple instance such as:                   set = {2, 3, 5, 7, 8, 9};         sum = 9;         subsetsum[sum, set]       the program seems to stop after 2 loops returning False... which is wrong. It should be returning true... Anyone has any ideas on this?


title: Autocomplete of non-global functions

text: In Mathematica 9 and 10 they added autocompletion. Out of the box this works great, but when I set the CellContext to "Notebook" instead of the default "Global" (following this) it no longer autocompletes the functions I define in my notebook. If I specify that the function is global, then the autocomplete mechanism works as you can see in the example below: ![enter image description here](http://i.stack.imgur.com/PoRBh.png) Is there a way of making Mathematica's autocompletion work with functions just defined within the notebook, and not just with global functions?


title: FindRoot - Speed and errors

text: I am using `FindRoot[]` to solve a complicated equation. It seems I get the correct answer even though I get errors about an `NIntegrate[]` inside the `FindRoot[]` and the number of evaluatons is just one. Moreover is there any possibility of speeding up the process? In the following example I calculate the function `ABar` from the functions `bf` and `cf` and then recover `bf` from `ABar` and `cf`. This is done in the function `bn`. `bnVerbose` and `bn` are identical except for the `EvaluationMonitor`.                   n = 5;         a0 = 1;         bmax = 0;         For[i = 1, i <= n,           Subscript[b, i, 1] = 1/i^2;           Subscript[b, i, 2] = 1/i^2;           a0 = a0 + Subscript[b, i, 1] + Subscript[b, i, 2];            bmax = a0 + Subscript[b, i, 1] + Subscript[b, i, 2]; i++;];         For[i = 1, i <= n,           Subscript[c, i, 1] = 1/i^2;           Subscript[c, i, 2] = 1/i^2;           a0 = a0 + Subscript[c, i, 1] + Subscript[c, i, 2]; i++;];              bf[x_] :=            Sum[Subscript[b, i, 1]*Sin[2 \[Pi] i x] +              Subscript[b, i, 2]*Cos[2 \[Pi] i x], {i, 1, n}];         cf[x_] :=            Sum[Subscript[c, i, 1]*Sin[2 \[Pi] i x] +              Subscript[c, i, 2]*Cos[2 \[Pi] i x], {i, 1, n}];         ABar[x_] := 1/NIntegrate[1/(a0 + bf[x] + cf[y]), {y, 0, 1}];         ABarB[b_?NumericQ] := 1/NIntegrate[1/(a0 + b + cf[y]), {y, 0, 1}];         ABarBJ[b_?             NumericQ] := {{NIntegrate[               1/(a0 + b + cf[y])^2, {y, 0,                 1}]/(NIntegrate[1/(a0 + b + cf[y]), {y, 0, 1}])^2}};              bn[x_] :=            b /. FindRoot[ABarB[b] - ABar[x], {b, 0, -bmax, bmax},              Jacobian -> ABarBJ[b]];              bnVerbose[x_] :=            Module[{e, b}, e = 0;             sol = FindRoot[ABarB[b] - ABar[x], {b, 0, -bmax, bmax},               Jacobian -> ABarBJ[b], EvaluationMonitor -> e++];            Print["Number of evaluuations:", e, "\n"];            b /. sol            ];         bnVerbose[0.5]         Plot[{bn[x], bf[x]}, {x, 0, 1}, PlotStyle -> {Green, Red}]      In each evaluation `bn` I get several errors of the form:                   NIntegrate::inumr: The integrand 1/(6169/900+b$2526673+Cos[2 \[Pi] y]+<<6>>+1/9 Sin[6 \[Pi] y]+1/16 Sin[8 \[Pi] y]+1/25 Sin[10 \[Pi] y])^2 has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>      Edit: Error Screenshot: ![error](http://vollmer.ms/error.png)


title: Are Mathematica 9 units really slow?

text: This generates 75 unitized pairs for a plot that displays physical units:               x = UnitConvert@Quantity["PlanckConstant" "SpeedOfLight" / "BoltzmannConstant"]     x1 = UnitConvert@Quantity[2,"PlanckConstant" ("SpeedOfLight")^2]     B[L_,T_]:= (L^-5) /(Exp[x/(L T)]-1)     p = Table[{Quantity[ll, "Micrometers"], UnitConvert[      x1 B[Quantity[ll, "Micrometers"], Quantity[1000, "Kelvins"]],       "Watts"/("Meters")^3]}, {ll, 0.1, 15, 0.2}]; //Timing      Then plot it               ListLinePlot[p, AxesLabel -> Automatic]      to get nice unitized labels. However, this naive coding to generate "p" takes 27 seconds on my core-duo 2.4 GHz laptop under windows 7 32-bit, ridiculously slow for 75 pairs! Can anyone accelerate this, say tenfold? Not too tricky please because I need transparency for Mathematica beginners.


title: Reduction of repetitive calculations in Table

text: If I generate two tables inside a function which are               function[n_, x_, y_]:=(      table1 = Table[i* x/n^x, {i,1,n}];      table2 = Table[i* y/n^y, {i,1,n}];     )      where `y - x = z`. So I can notice that I am making very similar evaluations and generate two almost identical tables. Can I do it faster, I mean: after generating of `table1` can I generate table2 based on values from table1? Of course I am looking for some solution which is faster than generating `table1` and `table2` as above. I was trying to use ParallelTable but it was wrong direction I think. I will be grateful if someone can suggest something.


title: How to reduce the InterpolatingFunction building overhead?

text: I want a linear interpolation from the following example list:               list={{0.0005023, 22.24}, {0.01457, 21.47}, {0.04922, 19.79},            {0.07484, 18.7}, {0.104, 17.55}, {0.1331, 16.52}, {0.1632, 15.49},           {0.1888, 14.52}, {0.2215, 13.31}, {0.2506, 12.16}, {0.3024, 10.01},            {0.3435, 8.304}, {0.3943, 6.036}, {0.4098, 5.329}, {0.4726, 2.384}};      The easiest way is to use:               Interpolation[list, InterpolationOrder -> 1]      but my `list` will be changing a lot, and the `InterpolatingFunction` takes a lot of time to build:               Timing[        Table[Interpolation[list, InterpolationOrder -> 1][q], {q,           0.0006, 0.4, 0.00001}];]      is 10x slower than:               test=Interpolation[list, InterpolationOrder -> 1];     Timing[Table[test[q], {q,0.0006, 0.4, 0.00001}];]      How can I remove the overhead? **EDIT** (following JxB comment) This compiled version is 5 times faster than the original version, but I don't think Partition is compiling (it appears between all the `List`s when I use `FullForm`); and there's also a `CopyTensor` that _doesn't look good_ :               Compile[{{list, _Real, 2}, {value, _Real, 0}},      Module[{temp},       temp = Select[          Partition[list, 2, 1], #[[1, 1]] <= value && #[[2, 1]] > value &][[1]        ];       temp[[1, 2]] +        (value - temp[[1, 1]])/(temp[[2, 1]] - temp[[1, 1]])*(temp[[2, 2]] - temp[[1, 2]])       ]      ]      Any suggestions? (I don't want to compile to C)


title: Is there an $n^{\text{th}}$ root function in Mathematica?

text: Is there a way to find $\sqrt[n]{x}$ with _Mathematica_ beside of `x^(1/n)` as this is something different, because this is not always the same $$(-1)^{\frac{2}{4}}=i \neq 1= \sqrt[4]{(-1)^2}$$ In the help I only found `Sqrt[x]` which is the squareroot and `CubeRoot[x]` for the cubic root.   Is there a reason that there aren't $n$-th roots implemented? (Assuming they really don't exist and I am not to stupid to find them). I am using _Mathematica_ 9.0.1 Student Edition.


title: Select positive value from a vector

text: I am wondering how to pick out the positive `Omega` value from `soln`, and make these positive values into a row vector. I know how to do it if elements in `soln` are numerical. But here all the elements are in the symbolic form.               Remove["Global`*"]          Nmax = 4;          T = 1/2 Sum[m[i] x[i]'[t]^2, {i, 1, Nmax}];     U = 1/2 Sum[k[i] (x[i][t] - x[i - 1][t])^2, {i, 1, Nmax + 1}];     L = T - U;          EL[q_] := D[L, q] - D[D[L, D[q, t]], t]          eigen = Table[EL[x[i][t]], {i, 1, Nmax}];          x[i_][t_] = a[i] E^(I \[Omega] t);          sim = eigen /. t -> 0;     x[0][t] = 0;     x[Nmax + 1][t] = 0;          For[i = 1, i < Nmax + 1, i++, m[i] = m]     For[i = 1, i < Nmax + 2, i++, k[i] = k]          matrix = D[sim, {Array[a, Nmax]}];          Print["The reduced eigenmatrix looks like ", matrix // MatrixForm]          soln = \[Omega] /. Solve[Det[matrix] == 0, \[Omega]]      ![enter image description here](http://i.stack.imgur.com/iFonl.png)


title: Using PatternSequence on its own in ReplaceAll?

text: Say I have this list:               list = {0, 1, 2, 0, 1, 3, 0, 1, 4}      and say I want to remove consecutive sequences of 0 and 1. I'd normally go for this:               list //. {before___, 0, 1, after___} :> {before, after}      > >     {2,3,4} >   But a more concise way would be the following:               list /. PatternSequence[0, 1] -> Sequence[]      Alas, this doesn't do anything. The examples in the `PatternSequence` documentation are all of the form               list //. {before___, PatternSequence[0, 1], after___} :> {before, after}      which kind of defeat the purpose. (It's pretty useful if you want to _name_ the `PatternSequence` on the LHS of the rule, but that's not my aim). So the question is, is there a way to use constructs like `PatternSequence[0, 1] -> Sequence[]` in `ReplaceAll`?


title: How to tweak the following purely numerical code

text: I am using the following numerical function in my program and I would like to speed it up.               calculate[mm_, nn_, pp_, ff_, quiet_] :=        Module[{n, y, m, z, f, k, p, l, \[Tau]},        h[0, 0, 0] = 1;        h[n_, 0, y_] := If[Mod[n, 2] == 0,          n!*y^(n/2)/((n/2)!),          0];             If[quiet != 1,          If[Simplify[h[4, 0, -1] - HermiteH[4, 0]] === 0, ,           Print["Bogus definition of h[n_,0,y_]"]]];        If[quiet != 1,          If[Simplify[h[3, 0, -1] - HermiteH[3, 0]] === 0, ,           Print["Bogus definition of h[n_,0,y_]"]]];             hh[m_, n_, 0, y_, 0, z_, \[Tau]_] :=          Sum[m!*n!/((m - k)!*(n - k)!*k!)*(\[Tau])^k*h[m - k, 0, y]*           h[n - k, 0, z], {k, 0, Min[m, n]}];             r[m_, n_, k_, f_] := (1/f)^k*          Sum[Binomial[k, l]* m!*n!/((m - l)!*(n - k + l)!)*            hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0, k}];             integral[m_, n_, p_, f_] :=          Sqrt[N[Pi]/f]*          Sum[Binomial[p, k]*h[p - k, 0, 1/(4*f)]*r[m, n, k, f], {k, 0, p}];             Return[integral[mm, nn, pp, ff]];        ];      Performance isn't too bad at the moment,               Timing[Table[calculate[n, n, 0, f, 0], {n, 0, 100}]]     {0.096000, {....}}      but the function is called millions of times. All the input to the function will be solemnly numeric. I don't need any symbolic evaluation and machine precision would be just fine. So I figured that there would be plenty of room for improvement, but I am fairly new to Mathematica and especially to its numerical capabilities. I would greatly appreciate any suggestions on speeding up that code. Thanks so much. **Note:** after taking into account the comments, this is my current code:               h[0., 0., 0.] = 1;     h[n_, 0., y_] := If[Mod[n, 2] == 0, n!*y^(n/2)/((n/2)!), 0];          hh[m_, n_, 0, y_, 0, z_, \[Tau]_] :=        Sum[m!*n!/((m - k)!*(n - k)!*k!)*(\[Tau])^k*h[m - k, 0., y]*         h[n - k, 0., z], {k, 0., Min[m, n]}];          r[m_, n_, k_, f_] := (1/f)^k*        Sum[Binomial[k, l]*m!*n!/((m - l)!*(n - k + l)!)*          hh[m - l, n - k + l, 0, -1 + 1/f, 0, -1 + 1/f, 2/f], {l, 0.,           k}];          calculate[m_, n_, p_, f_] :=        Sqrt[N[Pi]/f]*        Sum[Binomial[p, k]*h[p - k, 0., 1/(4*f)]*r[m, n, k, f], {k, 0.,           p}];      and the performance is               f = 1.;     Timing[Table[integrateGaussAndTwoHermite[n, n, 0, f], {n, 0, 100}]]     {0.080000, {...}}      **Note:** After taking into account even more comments, my code is               h[0., 0., 0.] = 1;     h[n_, 0., y_] :=        If[Mod[n, 2] == 0, Gamma[n + 1.]*y^(n/2.)/((n/2.)!), 0];          hh[m_, n_, 0., y_, 0., z_, \[Tau]_] :=        Sum[Binomial[m, k]*Gamma[n + 1.]/(Gamma[n - k + 1.])*(\[Tau])^k*         h[m - k, 0., y]*h[n - k, 0., z], {k, 0., Min[m, n]}];          r[m_, n_, k_, f_] := (1./f)^k*        Sum[Binomial[k, l]*Gamma[m + 1.]*          Gamma[n + 1.]/(Gamma[m - l + 1.]*Gamma[n - k + l + 1.])*          hh[m - l, n - k + l, 0., -1. + 1./f, 0., -1. + 1./f, 2./f], {l,           0., k}];          integrateGaussAndTwoHermite[m_, n_, p_, f_] :=        Sqrt[N[Pi]/f]*        Sum[Binomial[p, k]*h[p - k, 0., 1./(4.*f)]*r[m, n, k, f], {k, 0.,           p}];      and the execution time is               {0.0720000, {...}}


title: A derivative encountered in matrix factorization using gradient descent

text: I want to factorize a matrix $a_{ij}$ as $$ a_{ij} = \sum_k u_{ik} v_{jk} $$ using variational method for some reason. That is, I want to minimize the cost function $$ F = \sum_{ij} b_{ij}^2 $$ with respect to $u_{ik}$ and $v_{jk}$ where $$ b_{ij} = \sum_k u_{ik} v_{jk} - a_{ij} $$ I use gradient descent to find the minimum, therefore I need to calculate the derivative of $F$ with respect to $u_{ik}$ and $v_{jk}$. These can be calculated very easily with hand for example $$ \frac{\partial F}{\partial u_{ik}} = 2 \sum_j b_{ij} v_{jk} $$ However, I want to see how Mathematica solves this quite typical problem so that I don't need to use hand to calculate a much more complex version of the problem. The code I wrote is               KD[x_, y_] := KroneckerDelta[x, y]     u /: D[u[a_, b_], u[c_, d_], NonConstants -> {u}] := KD[a, c] KD[b, d]     v /: D[v[a_, b_], v[c_, d_], NonConstants -> {v}] := KD[a, c] KD[b, d]     b[i_, j_] := Sum[u[i, k] v[j, k], {k, Infinity}] - a[i, j]     F = Sum[b[i, j]^2, {i, Infinity}, {j, Infinity}];     $Assumptions = {i, j, k, i1, k1} \[Element] Integers && i > 0 && j > 0 && k > 0 && i1 > 0 && k1 > 0;     D[F, u[i1, k1], NonConstants -> {u}]      after a few minutes I got the result $$ \sum _i^{\infty } \sum _j^{\infty } 2 \left( \begin{array}{ll} \{ & \begin{array}{ll} v[j,\text{k1}] & i==\text{i1} \\ 0 & \text{True} \\ \end{array} \\ \end{array} \right) \left(-a[i,j]+\sum _k^{\infty } u[i,k] v[j,k]\right) $$ Is there an elegant way to evaluate the simple derivative $\frac{\partial F}{\partial u_{ik}}$ with Mathematica?


title: What is wrong with triangle PlotMarkers in v.10.0.0?

text: In _Mathematica_ 10.0.0 we have built-in graphical triangle `PlotMarkers`. Let us look closer on them:               ListLinePlot[{{Missing[]}, {{0, 0}}}, PlotTheme -> "Monochrome",       ImageSize -> 20, Ticks -> False, AxesOrigin -> {0, 0},       BaseStyle -> {Magnification -> 10, Thickness -> Tiny}]          ListLinePlot[{{Missing[]}, {{0, 0}}},       PlotTheme -> {"OpenMarkersThick", "LargeLabels"}, ImageSize -> 20,       Ticks -> False, AxesOrigin -> {0, 0},       BaseStyle -> {Magnification -> 10, Thickness -> Tiny}]      > ![plot1](http://i.stack.imgur.com/pZDW8.png) > > ![plot2](http://i.stack.imgur.com/f9mXH.png) It is clear that there is something wrong with the triangles. Is this functionality implemented correctly?


title: How can I style a TabView?

text: I have been trying to style a `TabView` like in the examples on the Wolfram CDF site, where they have custom sizes and backgrounds with images or gradients, but I am struggling to find documentation on how to style `TabViews` Is there a way in _Mathematica_ I can list all the properties of a control like `TabView` or just those controls which can be modified by the user? Edit: Link to an example of styling done by Wolfram


title: Clipboard with transparency

text: After reading this question I have determined that               Rasterize[Graphics[Circle[]], "Image", Background -> None]      allows you to do `Save As` on the Image and the keep the transparency. But if you use the the menus `Edit->Copy As->Bitmap` or `Edit->Copy As->Metafile` I have noticed that graphics fail to keep their transparency when pasting into other applications. Now I can `Export` an image and copy and paste it back into Mathematica(or another application) and everything works just fine, therefore the clipboard can hold references to transparent images. Doing some further investigation, here is an image of ClipSpy showing how `CF_HDROP` and `FileNameW`(FileName doesn't seem to contain the entire piece of text) contain the location of the png file, allowing you to paste it into other applications. ![enter image description here](http://i.stack.imgur.com/4UyTZ.png) When working with lots of images, exporting every image becomes quite tedious. It seems like their should be some way to automatically have Mathematica export the file and store a reference of it in the clipboard to retain the image transparency. **So how do I patch or extend Mathematica's clipboard functionality to work with transparent images?** Possible useful links for myself and others 1 2 3 4 **EDIT:** It appears a handful of applications like Inkscape and Powerpoint don't allow you to paste with only a `CF_DROP` reference. Instead it seems to be better to store the actual image as a `PNG` on the clipboard.


title: Solving a Volterra integral equation numerically

text: I would like to solve for $P(t)$, in Mathematica, a Volterra integral equation of the 2nd kind. It is: $$P(t) = R_0(t) + \int_0^t P(t') R_0(t-t')dt'$$ I know the function $R_0$ and would like to find a general way to solve for $P(t)$ given any $R_0$. I am aware that it is a convolution and can be solved in Laplace domain but I do not want to do it that way since inverting the transform brings about a whole other set of problems for me.


title: Converting Mathematica to $\LaTeX$

text: Is there a _Mathematica_ -to-$\LaTeX$ converter, so that I can place _Mathematica_ code, including things like `A // MatrixForm`, just as they are in the console straight into a $\LaTeX$ document?


title: How to solve this system of equations?

text: I want to solve the following system of equations: $$\begin{cases} 1+\sqrt{2 x+y+1}=4 (2 x+y)^2+\sqrt{6 x+3 y},\\ (x+1) \sqrt{2 x^2-x+4}+8 x^2+4 x y=4. \end{cases}$$ I tried               Reduce[{    1 + Sqrt[2 x + y + 1] == 4 (2 x + y)^2 + Sqrt[6 x + 3 y],             (x + 1) Sqrt[2 x^2 - x + 4] + 8 x^2 + 4 x  y == 4 },                 {x, y}, Reals]      I also tried with `Solve` and `NSolve`, but the evaluation exhausted my patience. I know the given system has $\left(\frac{1}{2};-\frac{1}{2}\right)$ as the only real solution. How do I tell _Mathematica_ to get that solution ?


title: Problem with Raster and custom ColorTable

text: **Context** Let me define two colour tables: (which come from brewer and xmedcom respectively)                  GoldColor = Blend[{{0, Black},         {1/9, RGBColor[32/97, 1/62, 0]},         {2/5, RGBColor[44/59, 23/78, 1/32]},         {3/5, RGBColor[84/85, 1/2, 4/51]},         {2/3, RGBColor[84/85, 53/87, 1/10]},         {4/5, RGBColor[84/85, 4/5, 11/32]},         {9/10, RGBColor[84/85, 68/75, 46/75]},         {1, White}}, #1] &       and               GalColor = Blend[{          {0, RGBColor[7/11, 0, 1/7]},           {1/17, RGBColor[10/13, 1/9, 1/7]},           {31/255, RGBColor[7/8, 1/4, 1/6]},           {47/255, RGBColor[13/14, 5/13, 1/4]},           {21/85,RGBColor[31/32, 5/9, 4/13]},           {79/255,RGBColor[46/47, 7/10, 2/5]},           {19/51, RGBColor[46/47, 5/6, 9/17]},           {37/85, RGBColor[1, 10/11, 5/8]},           {127/255, RGBColor[1, 1, 3/4]},          {143/255, RGBColor[10/11, 22/23, 7/8]},           {53/85, RGBColor[5/6, 11/12, 17/18]},           {35/51, RGBColor[7/10, 6/7, 10/11]},           {191/255, RGBColor[4/7, 10/13, 6/7]},           {69/85, RGBColor[3/7, 21/32, 4/5]},           {223/255, RGBColor[1/3, 8/15, 11/15]},           {239/255,RGBColor[1/4, 5/13, 2/3]},           {1, RGBColor[1/5, 3/13, 3/5]}}, #1] &       which looks like this:               GraphicsRow[{ContourPlot[x y , {x, -1, 1}, {y, -1, 1},         ColorFunction -> GalColor],       ContourPlot[x y , {x, -1, 1}, {y, -1, 1},         ColorFunction -> GoldColor]}]      ![Mathematica graphics](http://i.stack.imgur.com/bu9cg.png) But if I use it on large data sets, the first one works fine                dat = RandomReal[{0, 1}, {512, 512}];      Graphics[Raster[dat, ColorFunction -> GoldColor]]      ![Mathematica graphics](http://i.stack.imgur.com/Cuhej.png) whereas the second one fails with `Raster`                Graphics[Raster[dat, ColorFunction -> GalColor]]           (* void plot *)      while it works fine with `MatrixPlot` ![Mathematica graphics](http://i.stack.imgur.com/H91IL.png) Note that the problem depends on the size of `dat`; e.g. it works fine with `256^2`. **Question** How come `Raster` fails on this color table?


title: Half-delayed evaluation

text: In a certain wider context, I need to make some delayed definitions, such as `x := a + b + c`, but within these definitions I want `a` and `b` to be evaluated to their current values, not their later values. Here's a bit of code that does the trick:               a = 1; b = 2; c = 5;     With[{a = a, b = b}, x := a + b + c; y := b + c];     a = 10; b = 20; c = 50;      If `x` is printed at the end, it comes out to be `53` and if its definition is inspected with `?x`, it comes out to be `x := 1 + 2 + c`. Likewise at the end `y` is `y := 2 + c`. This is precisely the behaviour I want, but within my wider context, I care about elegance and this is inelegant. So I'd like to be able to define a command (really, a "macro") `WithCurrent`, so that `WithCurrent[{a, b}, delayeddefs]` would be equivalent to `With[{a = a, b = b}, delayeddefs]`. Any ideas?


title: Add options to upvalues

text: I have some objects that I want to present in TeXForm. Thus, it is easily to do as follows:               YoungTableau/:TeXForm[YoungTableau[diagram_]]      However, what if I want to extend the functionality of TeXForm, but only when working with this particular object? Say that I wish to be able to specify if I want line breaks or not in the output. I can do it like this,               YoungTableau/:TeXForm[YoungTableau[diagram_],OptionsPattern[]]      but then `OptionValue[LineBreaks]` will not work, since I have not added this as a possible option. It IS possible to do it as follows:               Unprotect[TeXForm];     Options[TeXForm] = {LineBreaks->True};     Protect[TeXForm];      but this feels too intrusive. Should I just give up, and invent my own version of TeXForm which can take options? What alternatives are there that does something similar to what I want?


title: Using a given colour table with Image?

text: **Context** I would like to represent large images with a given colour table. Now, if I use `Image`               dat = RandomReal[{0, 1}, {1024, 1024}];     dat // Image; // Timing          (* ==> {0.000027, Null} *)      its fast, but in grayscales; on the other hand if I use, say `MatrixPlot`               dat // MatrixPlot[#, ColorFunction -> "Temperature"] &     dat // MatrixPlot[#, ColorFunction -> "Temperature"] &; // Timing          (* ==> {1.5748, Null} *)      ![Mathematica graphics](http://i.stack.imgur.com/BS1jb.png) its in colour, but its slow. **Question** Is there a method to get the best of both worlds? (i.e. Speed and chosen colour table). Thank you for your help.


title: Fast principal component analysis

text: I'd like to speed up a principal value value analysis. The data contains a large set of vectors with a large dimension. Both are in the range of 1000. I want to obtain the loadings matrix for further calculations. The "Eigenvectors" part takes most of the computation time.               lMat = Table[RandomReal[], {i, 1000}, {j, 2000}];      mwVec = Mean[lMat];      lVerMat = (# - mwVec) & /@ lMat (* translation to the mean *);      covarMat = Covariance[lVerMat];      loadMat = Eigenvectors[covarMat] (* loadings matrix *); //AbsoluteTiming      lHKMat = lVerMat.Transpose[loadMat];      Thanks in advance.


title: Can I tell Simplify to prefer nested polynomials?

text: I need to export expressions for numerical evaluations in a C codebase. Simplify often does a good job for this, and polynomial factorisation goes a long way. However, occasionally I would come across things like               8 + 13 r^2 + 11 r^4 + 5 r^6 + r^8      as a subexpression. Obviously for floating point evaluation it is preferable to write this as               8 + r^2 (13 + r^2 (11 + r^2 (5 + r^2)))      Given a polynomial it is easy enough to write a function to do this conversion. The question is: how do I tell Mathematica that, after Simplify is done with its default rules, it should find all (sufficiently complicated by some metric) polynomial subexpression and turn each of them into the above "nested form"? EDIT: I wrote this question up in a hurry and perhaps didn't quite make the point clear. I'll admit I wasn't aware of `HornerForm`, but that sort of really isn't the issue. As mentioned before I've quickly cooked up a bit of code to perform the same basic function already so I perhaps neglected to check if there's a built-in one. The real issue here is that `HornerForm` would undo any factorisation, that is, `Simplify` may well have produced a factor of               (1 + 3 r^3 + r^7)^2      which `HornerForm` would expand into               1 + r^3 (6 + r^3 (9 + r (2 + r^3 (6 + r^4))))      whereas I would rather prefer               (1 + 3 r^3 + r^7)^2 -> (HornerForm[1 + 3 r^3 + r^7, r])^2      which gives `(1 + r^3 (3 + r^4))^2`. Similarly,               HornerForm[Sqrt[1 + 3 r^3 + r^7], r]      would just fail completely, where my desired output is `Sqrt[1 + r^3 (3 + r^4)]`. I suppose what I'm really looking for is to put each _unfactorisable_ polynomial in the expression, on which `Simplify` was previously applied, through `HornerForm`. Apologies for any confusion.


title: Filling between two 3D surfaces

text: I know it is possible to create a filling in between two curves on a 2D plot, but is it possible to do the same in 3D? My attempt like this:               Z1 := E^(-x^2) Cos[x^2 + y^2]     Z2 := 2 - x^2 - y^2          Plot3D[{Z1, Z2}, {x, -1, 1}, {y, -1, 1}, AspectRatio -> 1,      ViewPoint -> {4, 1, 1}, Filling -> Top, FillingStyle -> Opacity[0.9]]      yields the graph below: ![enter image description here](http://i.stack.imgur.com/FcHgF.png) Is there a way I can fill the graph between the two aforementioned 3D surfaces? Thank you for your time.


title: Plot Piecewise-Smooth Vector Field.

text: I want to plot a piecewise-smooth vector field. For instance: $F_1(x,y) = (x^2 + y^2, y^2)$, $F_2 (x,y) = (2xy,2xy-x^2)$ and $H(x,y) = x-y$ $F(x,y) = \begin{cases} F_1(x,y) \text{ if } H(x,y) >0 \\ F_2(x,y) \text{ if } H(x,y)<0 \end{cases}$ How can I plot $F(x,y)$ in Mathematica?


title: How do I write a ValueQ function that only returns True if there exists an OwnValue?

text: Reading the comments in this answer has motivated me to request a full solution to part of this problem. What I'd like is an efficient solution that returns `True` if there exist an `OwnValue` and `False` in _all_ other cases. This narrow behavior mirrors what folks coming from other programming languages expect of asking if something has a value or not. A solution needs to be able to handle symbols with any number of `OwnValue`, `UpValues`, `DownValues`, `SubValues`, `NValues`, and `FormatValues`. The only evalution that should occur is that required to get the value of the symbol's `OwnValue`. ## Motivation My motivation for this request is twofold.   1. There have been many queries on this topic, but none that appear to be specific enough to narrow down to one correct interpretation. I hope this question solves that.   2. The behavior requested mirrors the behavior of most programming languages that folks are familiar with. That is, when we think of a symbol/"variable" having a value, we really mean to ask if the symbol has some `OwnValues` or not. Yes there are other interpretations of what it means to have a `ValueQ` that does not do extra evaluations, but this question does not cover them.


title: How can I connect database(MSSQL Server) with Mathematica?

text: Newly I started working with database(MSSQL Server 2012). by google help, I created `Table` name as `EmployeesList` and also `Inserted`values into the table. know I want to connect database with `Mathematica`.for that I seen documentation and founded `OpenSQLConnection`function.but still not connected.                databaseInstalizationLink="C:\\Program Files\\Microsoft SQL Server";        Needs["DatabaseLink`"];      OpenSQLConnection[databaseInstalizationLink]      I seen `JDBC`function also but I didn't get it. I tried `OpenSqlConnection[]`wizard also.like if you evaluate the below one line code we get the wizard that screenshots I posted below                  OpenSQLConnection[]      Step 1: ![enter image description here](http://i.stack.imgur.com/4Nu8c.jpg) I click on `New` Button Step 2: ![enter image description here](http://i.stack.imgur.com/ongm0.jpg) I click on `Next` button. Step 3: ![enter image description here](http://i.stack.imgur.com/Mmd5C.jpg) Step 4: ![enter image description here](http://i.stack.imgur.com/ig8F7.jpg) here,I changed to `SystemLevel`. Step 5: ![enter image description here](http://i.stack.imgur.com/HRTn2.jpg) but,I installed 2012 version . Step 6: ![enter image description here](http://i.stack.imgur.com/nIObA.jpg) Step 7: ![enter image description here](http://i.stack.imgur.com/5Ys9v.jpg) here,I didn't add any properties because,I didn't understood. Step 8: ![enter image description here](http://i.stack.imgur.com/iDRSh.jpg) Finally,I click on `Connect` button but,it shows `$Failed`. I hope,everyone understood what my problem. can anyone help me? Fell free,If you want to edit my question.


title: Splitting a list using SplitBy, by comparing adjacent elements

text: Suppose that I have the following list called `mylist`:               mylist = {80.2, 80.3, 80.4, 327.6, 327.7, 327.8};      I would like to split `mylist` so that "runs of consecutive elements" are placed in the same sublist. Here, I will define two "consecutive elements" as real numbers that differ by 0.1. The second element can be either 0.1 greater than or 0.1 less than the first element, although in reality it makes more sense if the second element can only be 0.1 greater than the first element. (In my actual application, `mylist` is a list of times [i.e., elapsed time], in seconds, for example. My system is sampled every 0.1 seconds. Time never moves backwards, at least in my world!) So the result I would like is:               {{80.2, 80.3, 80.4}, {327.6, 327.7, 327.8}}      I am thinking that `SplitBy` would be appropriate for this application: > `SplitBy[list, f]` splits _list_ into sublists consisting of runs of > successive elements that give the same value when _f_ is applied. However, in looking in the documentation, it is not clear to me how "adjacent elements" are defined. In Mathematica 7, "More Information" says: > `SplitBy` performs comparisons only on adjacent pairs elements. Thus, what `f` do I use? I have tried:               SplitBy[mylist, #[[2]] - #[[1]] == 0.1 &]      and               SplitBy[mylist, #2 - #1 == 0.1 &]      but neither work. Does `SplitBy` define separate "slots" for the first and second element of a pair? Thanks for your time.


title: Is there any way to force Mathematica to collect a symbol in a polynomial?

text: Let's say that I have a polynomial like this:               a + b + c      Is there any way that I can get _Mathematica_ to transform it to:               a*(1 + b/a + c/a)      I found such a manipulation on polynomials very common when deducing equations by hand; however, I have been trying all day and still can not figure out how to make _Mathematica_ do this automatically.


title: Plotting the open ball for the post office metric space

text: The post office metric space, $P$ has the distance function defined as follows: $$ d_P (\mathbf{x},\mathbf{y}) := \begin{cases} 0 & \mathbf{x} = \mathbf{y}\\ \Vert \mathbf{x}\Vert_2+\Vert \mathbf{y}\Vert_2 & \mathbf{x}\neq \mathbf{y} \end{cases} $$ where $\Vert \mathbf{x}\Vert_2 = \sqrt{x_1^2+x_2^2}$ is the Euclidean distance from $\mathbf{x}=(x1,x2) \in \mathbb{R}^2$ to the origin. I am interested in drawing the balls of this metric centered at point $\mathbf{p}$, having a radius $r$: $$B_r(\mathbf{p}) \triangleq \{\mathbf{x} \in P\vert\ d(\mathbf{x},\mathbf{p})<r \}$$ Does anyone have any tips on how to do this?


title: How to prevent errors in Manipulate with ListPlot when a result is an empty list?

text: I am trying to plot two lists, where one is the reference list, and the other is only used to select and highlight the first list. Basically, I want to use the selection list `slist` to highlight different points in the reference list `reflist` after using `Manipulate`:               reflist = Flatten[Table[{x, y, z, a}, {x, 0, 4}, {y, -4, -1}, {z, 0, 5}, {a,0, 3}], 3];     slist = Flatten[Table[{x, y, z, a}, {x, 0, 1}, {y, -2, -2}, {z, 0, 1}, {a, 0, 1}],3];          Manipulate[      Show[ListPlot[        Select[reflist, #[[1]] == x && #[[2]] == y &][[All, 3 ;; 4]],         PlotStyle -> Black, AxesLabel -> {"z", "a"}, PlotLabel -> {x, y},         PlotRange -> All, Joined -> False],        ListLinePlot[        Select[slist, #[[1]] == x && #[[2]] == y &][[All, 3 ;; 4]],         PlotStyle -> Red, AxesLabel -> {"z", "a"}, PlotRange -> All,         Joined -> False]], {x, 0, 4, 1}, {y, -4, -1, 1}]      Returns the following graph when x=1 and y=-2: ![enter image description here](http://i.stack.imgur.com/H2IIH.png) The problem occurs when `slist` has no point in common with `reflist`: ![enter image description here](http://i.stack.imgur.com/Hb4pn.png) So my questions are: 1. Is there any way for me to avoid getting the error and just have **no point highlighted** when the two lists have no points in common, and **just show all points in black**? 2. I am also looking to highlight the whole regions where the points are (this would make a square in the first figure, with vertices in each red point). Is there any way to do it in `ListPlot`? Thanks so much for all the help!


title: I see error messages when I use LogLinear Plot but not when I use Plot

text: I have written an application with `Manipulate` that plots the results of several calculations. What I find strange is that when I have my application use `Plot` it runs fine for any values of my parameters. However, when I make the sole change of `Plot` to `LogLinearPlot` it will return an a error on the matrix calculations (`Inverse`,or `Eigenvectors`) done by my program for some parameters and say it is suppressing them for the rest of the calculation. However, the created plots by `LinearLogPlot` look fine from a visual inspection. I find it strange that `Plot` works fine while `LogLinearPlot` seems to be giving issues. The code below resembles the functionality of my code when `LogLinearPlot` is used. When I copy and paste it I get an `unable to find all eigenvalues` error. When `LogLinearPlot -> Plot` it runs fine. Usually the value of \row is what determines the error. I have initialized \row to a value that gives an error for the `LogLinearPlot`               (*First I define a few parameters*)          i=1;     j=2;     a[t12_] = Cos[t12];     b[t13_] = Cos[t13];     c[t23_] = Cos[t23];     s[t12_] = Sin[t12];     r[t13_] = Sin[t13];     t[t23_] = Sin[t23];     m1 = 1;     m2[m21_] = m1 + m21;     m3[m21_, m32_] = m1 + m21 + m32;                    (*Below are the definition for several matrices that resemble the matrices       in my code. First is V which is the product of three matrices, the middle matrix containing \row which is the parameter that seems to trigger the errors.*)                    V[t12_, t13_, t23_, \[Delta]_, \[Rho]_] = Transpose[( {      {a[t12] b[t13], s[t12] b[t13], r[t13] E^(I \[Delta])},      {-s[t12] c[t23] - a[t12] t[t23] r[t13] E^(-I \[Delta]),        a[t12] c[t23] - s[t12] t[t23] r[t13] E^(-I \[Delta]),        t[t23] b[t13]},      {s[t12] t[t23] -         a[t12] c[t23] r[t13] E^(-I \[Delta]), -a[t12] t[t23] -         s[t12] c[t23] r[t13] E^(-I \[Delta]), c[t23] b[t13]}     } )].     ( {      {7.56 .5 10^-14 \[Rho], 0, 0},      {0, 0, 0},      {0, 0, 0}     } ).     ( {      {a[t12] b[t13], s[t12] b[t13], r[t13] E^(-I \[Delta])},      {-s[t12] c[t23] - a[t12] t[t23] r[t13] E^(I \[Delta]),        a[t12] c[t23] - s[t12] t[t23] r[t13] E^(I \[Delta]),        t[t23] b[t13]},      {s[t12] t[t23] -         a[t12] c[t23] r[t13] E^(I \[Delta]), -a[t12] t[t23] -         s[t12] c[t23] r[t13] E^(I \[Delta]), c[t23] b[t13]}     } );          (*Next is the matrix M*)          M[t12_, t13_, t23_, \[Delta]_, \[Rho]_, m21_, m32_, e_] = ( {          {m1/(2 e), 0, 0},      {0, m2[m21]/(2 e), 0},      {0, 0, m3[m21, m32]/(2 e)}     } ) + V[t12, t13, t23, \[Delta], \[Rho]];          (*Then g which uses a SetDelayed because I only want it to deal with numbers*)          g[t12_, t13_, t23_, \[Delta]_, \[Rho]_, m21_, m32_, e_] :=      (Transpose[     Eigenvectors[M[t12, t13, t23, \[Delta], \[Rho], m21, m32, e]]]).( {      {0, 0, 1},      {0, 1, 0},      {1, 0, 0}     } );          (*Then h*)          h[t12_, t13_, t23_, \[Delta]_, \[Rho]_, m21_, m32_, e_] :=        Eigenvalues[M[t12, t13, t23, \[Delta], \[Rho], m21, m32, e]];          U[t12_, t13_, t23_, \[Delta]_, \[Rho]_, m21_, m32_, e_] := ( {       {a[t12] b[t13], s[t12] b[t13], r[t13] E^(-I \[Delta])},      {-s[t12] c[t23] - a[t12] t[t23] r[t13] E^(I \[Delta]),        a[t12] c[t23] - s[t12] t[t23] r[t13] E^(I \[Delta]),        t[t23] b[t13]},      {s[t12] t[t23] -         a[t12] c[t23] r[t13] E^(I \[Delta]), -a[t12] t[t23] -         s[t12] c[t23] r[t13] E^(I \[Delta]), c[t23] b[t13]}     } ).g[t12, t13, t23, \[Delta], \[Rho], m21, m32, e];                    (*Then the Manipulate starts here using the LogLinearPlot *)          Manipulate[               (*The Plot*)          LogLinearPlot[     (\!\(\*UnderoverscriptBox[\(\[Sum]\), \(l = 1\), \(3\)]\(\(U[t12, t13, t23, \[Delta], \[Rho], m21, m32,         e]\)[\([\)\(i, l\)\(]\)]      \*SuperscriptBox[\(E\),      FractionBox[\(\(\ \)\(\(-I\)\ \(h[t12, t13, t23, \[Delta], \[Rho],            m21, m32, e]\)[\([4 - l]\)]*\          L\)\), \(\(\ \)\(1.97327*10^\(\(-\)\(10\)\(\ \)\)\)\)]]      \*SuperscriptBox[\(E\),       FractionBox[\(\(\ \)\(I\ \(h[t12, t13, t23, \[Delta], \[Rho], m21,            m32, e]\)[\([4 - l]\)]*\          L\)\), \(\(\ \)\(1.97327*10^\(\(-\)\(10\)\(\ \)\)\)\)]] \(U[        t12, t13, t23, \[Delta], \[Rho], m21, m32, e]\)[\([\)\(l,        j\)\(]\)]\)\)),{e,10^7,10^8},        AxesLabel -> {"Energy (GeV)", "Probability"},        PlotRange -> All],                (*The declaring of Manipulate variables*)                 {{\[Rho], 10.,"\[Rho]"}, 0.,        12.}, {{m21, 8.1*10^-5}, 0.0000377,      0.0001508}, {{m32, .002119}, 0.001227, 0.0049108}, {{t23, 0.785398, "t23"}, 0.,           2. \[Pi]}, {{t13, 0.1127, "t13"}, 0.,          2. \[Pi]}, {{t12, 0.547381, "t12"}, 0., 2. \[Pi]}, Delimiter,          Style["CP Symmetry factors", 12, Bold], {{\[Delta], 0, "CP factor"},        0., 2. \[Pi]}, ControlPlacement -> Left,       SynchronousUpdating -> False]


title: Alternate method of conjugation using replaceall

text: Mathematica really struggles to simplify complex conjugates of complicated expressions - even given assumptions for every symbol in the expression being real. Often times I've found that I can actually accomplish what I want better by doing my own conjugation using replaceall and manually switching all the i's to -i. For example, I'll have `psi = Exp[I k x]` (well, a more complicated mixture of things like that), so to get `psi*` I just do               psi /. I -> -I      This works quite well - but apparently `I`, `2I`, `3I` and so on are all different, so I have to look at the expression, pick out all the `I`'s, then do something like this:               psi /.{I->myi,2I-> 2 myi, 3I-> 3 myi}     psiconj = % /.{myi->-I}      This seems to work, usually. Is there any way I can do this without individually specifying each form of `I` that appears? Like `psi /. x_I :> -x I` ? (That doesn't work). Or maybe /. x?ImaginaryQ:>-x or something? I'm also open to other suggestions. The problem here is that mathematica is being very careful - and that keeps it from doing things incorrectly in certain situations... but in most cases, I know what I want, and I just want a simple straightforward conjugation that switches all visible `I`'s to -`I`'s. EDIT: I edited to clear up confusion about i vs I in code snippets. As for why I wouldn't want to use Conjugate - if it's not clear enough above, than see other issues such as these: Remove annoying Conjugate http://stackoverflow.com/questions/13337630/mathematica-simplify-conjugate- expresion Conjugates often cause expressions to not simplify - best case scenario it will work as long as I explicitly tell mathematic to assume that every symbol in the expression is real and positive, but with lots of symbols this is cumbersome - and when I know the expression well enough to know that a simple switching of just the visible I's to -I's will work, I don't really want to spend time doing something more complicated. ComplexExpand and Refine sometimes can help - but sometimes not. What does work for me in my situations is what I described above - but they're not very general. I've toyed around with what I said above, and this seems to work, though it's not very elegant (still much better that using Conjugate, Simplify and having to explicitly tell mathematica to assume a bunch of symbols are real and positive):               psi = Exp[3 I k x + 5 x + Sqrt[2 I m]]     psi /. {x_?(NumberQ[#] && Element[#, Complexes] &) :>  Conjugate[x]}      EDIT 2: Szabolcs suggestion is simpler/better than what I that above:               psi = Exp[3 I k x + 5 x + Sqrt[2 I m]]     psi /. x_Complex :>  Conjugate[x]


title: Increasing the thickness of line in plot legend

text: I've been using the shiny new legends in V9 for my plots. However, I usually increase the `Frame`/`Axis` `Thickness` and the plot `Thickness` and I would like the thickness of the legend line to match. There is a related question (Legend of a plot: how to increase the size of the line/marker?) asked about using the previous `PlotLegends` package. See this simple example, modified from the documentation:               Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]},        PlotLegends -> Automatic,        PlotStyle -> Thickness[0.005],        AxesStyle -> Thickness[0.005]]      ![Mathematica graphics](http://i.stack.imgur.com/QzXvr.png) I've tried the obvious modification of the `LineLegend` `LabelStyle`, however, this just appears to modify the text and has no effect here:               Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]},        PlotLegends -> LineLegend[Automatic, LabelStyle -> Thickness[0.5]],        PlotStyle -> Thickness[0.005],        AxesStyle -> Thickness[0.005]]      ![Mathematica graphics](http://i.stack.imgur.com/yi89K.png) I found that I could set `Joined -> False` and use a thicker `line` as a `LegendMarker` but it is never as long as the normal legend line no matter how long you make the line... (also note that to get a comparable thickness it has to be set two orders of magnitude higher)               Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]},       PlotLegends ->        LineLegend[Automatic, Joined -> False,         LabelStyle -> Directive[FontFamily -> "Helvetica", Medium],         LegendMarkers ->          Graphics[{Thickness[0.5], Line[{{-2, 0}, {2, 0}}]}]],       PlotStyle -> Thickness[0.005], AxesStyle -> Thickness[0.005]]      ![Mathematica graphics](http://i.stack.imgur.com/tvUcx.png) now make the line really long (no change):               Plot[{Sin[x], Cos[x]}, {x, 0, 2 \[Pi]},       PlotLegends ->        LineLegend[Automatic, Joined -> False,         LabelStyle -> Directive[FontFamily -> "Helvetica", Medium],         LegendMarkers ->          Graphics[{Thickness[0.5], Line[{{-100, 0}, {100, 0}}]}]],       PlotStyle -> Thickness[0.005], AxesStyle -> Thickness[0.005]]      ![Mathematica graphics](http://i.stack.imgur.com/0TBXn.png) I've tried to look at the `InputForm` for the plots and for just a `LineLegend` but I can't figure out what exactly I need to replace to fix this.


title: Number ending with zero, add precision

text: Is it possible to simply add ending zeros to a decimal number? For example: 2.1 should be 2.10 (precision till 1/100), 2 should be 2.00, etc. I've tried looking into               digits = RealDigits[3.1,10,3][[1]]      which gives `{3, 1, 0}`, and using this, the impressively complicated form               Row@{digits[[1]], ".", Sequence @@ Rest@digits}      gives the desired result. But this is enormously complicated, and I was wondering whether there exist another (easier) method? Thanks for all help, as always!


title: Fitting a theoretical density function with log-return sample

text: I am working on a exercise to fit a theoretical density function,presented below, with log-return series of a stock. $\frac{1}{2}a e^{a(x-\mu)} \quad \text{if x } < \mu $ or $ \frac{1}{2}be^{-b(x-\mu)} \quad \text{if x } \geq \mu \\$ I am now stuck on estimating the parameters for the function. I have tried different approaches, such as creating a probability distribution and use FindDist.Param. and also tried to fit it with a ExponentialDistr(or Laplace), multiplying neg. returns with -1 for case $(x < \mu)$, however without any success. Given I have the moments of the sample and at least think I have worked out the correct moments (mean, var, skew, kurt) I would also like to try a method of moments, but not sure how to do proceed with the above function? As I am relatively new to _Mathematica_ and keep getting lost but enjoying the endless possibilities, any suggestions or recommendations on procedure is greatly appreciated. For importing my log-returns I have used `ImportString["...", "List"]`. Many thanks for the feedback guys! Alas, my original post was written 4 am in the morning. Anyway, I'll be more thorough in coming posts. The following is the procedure I have tried,   1. `logretun = ImportString["r1, r2, .., rT", "List"]` Where $r_i$ are daily log-returns of a stock, copied from an .csv spreadsheet.    2. Define the above density as a function,               f[x_] = 1/2*a*Exp[a*(x - m)]*Boole[x < m] +        1/2*b*Exp[-b*(x - m)]*Boole[x >= m]      (is the use of Boole correct?)   3. Define a function from (2) as distribution               fdist = ProbabilityDistribution[f, {x, -Infinity, Infinity}]        4. Run               FindDistributionParameter[logreturn, fdist]       With no luck. (Just runs and runs with no answer - even if I take a smaller sample, so I do not think its me just being impatient..). I have gotten some values for $a$ and $b$ (87.76922562 and -82.00007391, respectively) through the following method; however I am not sure it is justifiable. Step (3) piecewise, for a `ExponentialDistribution[λ]`:   1. Sort the return series, select the ones that are $x < \mu$ and multiply by -1 and import as "minuslogreturns"    2. Run step 3 as               FindDistributionParameter[minuslogreturns, ExponentialDistribution[a]]        3. Run again for the positive part, with $b$ as the parameter for `ExponentialDistribution`. I am not confident that this is a feasible approach. I have tested my $a$ and $b$ by moments ($\mu$ = sample median), getting relative close mean, variance and skewness, however I cannot seem to get the kurtosis close. (sample kurtosis 9.494758128 vs estimated 15.33348985). On a side note, it might be very well that the expressions for expected return, variance, skewness and kurtosis also be off, as they are quite long expressions. I can post these if deemed necessary? Hope this make my questions a bit more clearer.


title: Why I am not getting the same frequency when sampling a waveform?

text: I am trying to simulate the sampling of a waveform to then apply FFT Analysis to it. Here is the sample code I have now using a square wave:               frequency =50;     sampleFrec = 1000;     period =1/frequency;          f=\[Piecewise]  -1  (period/2)<=Mod[x,period]<period                      1  True                          testData=Table[N@f,{x,0,2*period,1/sampleFrec}];          Plot[f,{x,0,2*period}, PlotLabel->"Fundamental",ExclusionsStyle->Dashed, PlotStyle->{Thickness[0.006], Red}]          ListLinePlot[testData,PlotRange->Full, PlotLabel->"Fundamental"]      And this are the plots I'm getting, the first one is the 50Hz square wave I want but when I use `Table[]` and `ListLinePlot[]` I am not getting the same frequency, why? I am relatively new to Wolfram Mathematica so maybe this is something very stupid. Thank you for your help! ![enter image description here](http://i.stack.imgur.com/lwviH.jpg) ![enter image description here](http://i.stack.imgur.com/EOmWI.jpg)


title: Solving minimum length confidence interval problem

text: I'm trying to find the minimum length of a confidence interval for the variance from a sample iid with normal distribution. I tried               Solve[      CDF[ChiSquareDistribution[n - 1], (n - 1)/k1] -         CDF[ChiSquareDistribution[n - 1], (n - 1)/k2] == 0.95 &&         (n - 1)/(2*k1) - (n - 1)/(2*k2) == (n/2 - 3)*Log[k1/k2], {k1, k2}]      When running the command I get: > Solve::inex: Solve was unable to solve the system with inexact coefficients > or the system obtained by direct rationalization of inexact numbers present > in the system. Since many of the methods used by Solve require exact input, > providing Solve with an exact version of the system may help. Is there a way to make this work? For more info about this statistics problem check this minimum length confidence interval problem Any help would be appreciated


title: Calculate geo location based on distance from other locations

text: Given a list of entities (or `GeoPosition`s) and their distances from a particular location, how do I find that location's `GeoPosition`?               dist = Map[{#, GeoDistance[$GeoLocation, #]}&, GeoNearest["University", $GeoLocation, 5]]      ![enter image description here](http://i.stack.imgur.com/Bh5oA.png) How do I find this point?               GeoGraphics[{Thick, GeoMarker[], GeoCircle @@@ dist}, ImageSize -> 500]      ![enter image description here](http://i.stack.imgur.com/BlQ8k.png) If you want to try with this data:               {{Entity["University", "VanderCookCollegeOfMusic149639"],   Quantity[1.407900938586476, "Miles"]},      {Entity["University", "IllinoisInstituteOfTechnology145725"], Quantity[1.5607147441441935, "Miles"]},      {Entity["University", "UniversityOfIllinoisAtChicago145600"],   Quantity[1.6865509085430637, "Miles"]},      {Entity["University", "ShimerCollege148849"], Quantity[1.7240912464169733, "Miles"]},      {Entity["University", "IllinoisCollegeOfOptometry145628"],   Quantity[1.7283592978609772, "Miles"]}}