title: How to obtain dual values? in Simplex(LinearProg.) and... the final tableau?

text: I can resolve the function value and the primal values in Linear Programming like in (* Examen de avións Sept 2003 *)               M = {        {0, 0, 1, 1, 1, 1, 1},        {0, 1, 0, 0, 1, 1, 1},        {1, 0, 1, 0, 0, 1, 1},        {1, 1, 0, 1, 1, 0, 1},        {1, 1, 1, 0, 1, 0, 0},        {1, 1, 1, 1, 0, 1, 0}        };     MAsterisco = M + 2;     b = {       {1, -1}, {1, -1},       {1, -1}, {1, -1},       {1, -1}, {1, -1}       }     coef = {       -1, -1, -1, -1, -1, -1, -1}     x = LinearProgramming[coef, MAsterisco,        b] (*Obtenemos en x el punto donde se alcanza el óptimo*)     coef.x (* multiplicamos los coeficientes  por  el punto de minimo \     OJO: Hemos de recordar que hemos cambiado el signo a los coeficientes \     para adaptarnos al Mathematica*)      But the QUESTION 1 is: ¿How can you obtain the dual values? and the QUESTION 2 is: ¿How may I obtain the final tableau of the simplex algorithm? to analyze other possible solutions.


title: How can I extract the outline of bubbles in my image?

text: I have an image: ![enter image description here](http://i.stack.imgur.com/UNXEV.jpg) I tried to extract the outline of the bubbles, but I met with some problems. Firstly I tried the method used in _Mathematica_ documentation for `Analyze Segmented Cells In An Image`, but it didn't work well, I got an irregular figure: ![enter image description here](http://i.stack.imgur.com/CkzBU.jpg) Then I tried the function `EdgeDetect`. Things got a little bit better, but it's still not what I want. Could you please help me with my problem?


title: From a list to a list of rules

text: Starting from these two lists,               var = {a, b, c}      values = {{1, 2, 3}, {4, 5, 6}, {7, 8 , 9}}      how can I generate a list of rules?               rules = {{a -> 1, b -> 2, c -> 3}, {a -> 4, b -> 5, c -> 6}, {a -> 7, b -> 8, c -> 9}}      This is how far I have got               In: {{a, b, c}, {1, 2, 3}} // Transpose     In: Rule @@@ %     Out: {{a, 1}, {b, 2}, {c, 3}}     Out: {a -> 1, b -> 2, c -> 3}


title: How to make a discretized NMinimize more precise

text: I am using _Mathematica_ for physics research and I want to minimize a Hamiltonian equation with respect to two variables (I have also discretized the problem). I have a single constraint. When I plot the result from `NMinimize` for two variables, the end behavior for one of them is not very stable. Is there a way of making `NMinimize` more precise, so I can get a stable solution?


title: Overlay of pdf using PairedHistogram in Mathematica

text: With a standard 1D histogram, I can generate a pdf overlay using `Show` and `Plot`. I'd like to do something similar with `PairedHistogram`. I can't find any examples. I have tried using `Epilog`, but I can't figure out how to pass the graphics primitive correctly such that they are matched to the correct histogram. I'd like to add overlays to the below, with an overlay specified for each histogram in the pair.               PairedHistogram[data[[18]],data[[22]],Automatic,"PDF",        ChartStyle->{{LightOrange,LightBlue},None,None},        ChartLegends->Placed[{names[[18]],names[[22]]},Top]]


title: How to determine edgeweights from width of skeleton using MorphologicalGraph (or workaround)?

text: **Background** I'm trying to create a workaround for what seems to be a bug in MMA's graph functions related to edge weights: SO: _How to Label Graph Edges with their weights_ According to MMA's documentation for MorphologicalGraph: _For EdgeWeight->Automatic the weight of each edge is set to the number of pixels in the corresponding skeleton connection. If more than one connection exists, the shortest one is chosen to represent the weight of the edge._ However, looking at the AdjacencyGraph, it seems to always fill in 0's and 1's, so I assume this not to be working. What I am looking for can be illustrated with the following code:               img = Import["http://i.stack.imgur.com/Z6RtX.png"]      ![img](http://i.stack.imgur.com/Z6RtX.png)               g = MorphologicalGraph[img, EdgeWeight -> Automatic]      ![g](http://i.stack.imgur.com/m3Osn.png)               (ColorNegate@        ImageAdjust@         SkeletonTransform@img)~MinFilter~2.~Colorize~(ColorFunction ->         "SunsetColors")      ![image manipulated with edge colour corresponding to width](http://i.stack.imgur.com/Kkvw3.png) This last image shows that it is possible to compute the edge weights using SkeletonTransform, and I assume these to be the ones that MorphologicalGraph is supposed to return. **Question** How can I get the corresponding edge weights in the graph (or, for example as an AdjacencyMatrix), that corresponds to the pixelwidth of each edge in the image? **Additional question** How can I visualize these graph weights as thickened coloured edges so that a GraphPlot corresponds to the coloured image above?


title: How to exit a package gracefully in the middle?

text: How to exit a package in the middle, for example,               BeginPackage["myPackage"]     Begin["`Private"]          DoSomething          If[$FrontEnd===Null, Abort[]]          DoSomethingIfFrontEndDefined          End[]     EndPackage[]      Here Abort[] doesn't really quit the whole package. Is there any command which can do this? I could use Goto but that sounds not good. Also I don't want to Quit[] because I want to use the definitions in the DoSomething part.


title: Animating a rotating disk

text: I have a system with 3 degrees of freedom that I want to know if it is possible to visualise with `Mathematica` in the two-dimensional $X-Y$ plane. I have a plane circular object rotating at its set speed say $10$ deg/s. This object is not rotating at the $(0, 0)$ origin point but is displaced from the origin $(0, 0)$ coordinates and its motion path is described by $x=x_0 + a \times \cos(\omega \: t)$ and $y=a \times \sin(\omega \: t)$ Some values: $x_0 = 1$ mm; $a=0.25$ mm, $\omega=10$ deg/s (same as the rotating speed of the circular object). The radius of the circular object can be taken to be a couple of cm say $2$ cm. The time parameter $t$ in the parametric equations can be discretised in $20$ steps as follows: $\mathrm{step}= \frac{360 \; \mathrm{deg}}{\omega \times 20} = \frac{360}{10 \times 20}=1.8$ s so that $\mathrm{step}$ will take values $0$, $1.8$, $3.6$, $\ldots$, $34.2$ s. Thus the product $\omega \: t$ as the cosine and sine arguments of the parametric path can be written as $\omega \: t = \omega \times \frac{\mathrm{step \times \pi}}{180}$ which in units gives $\frac{\mathrm{deg}}{\mathrm{seconds}} \times \frac{\mathrm{seconds} \times \mathrm{radians}}{\mathrm{deg}} = \mathrm{radians}$. Any help will be appreciated to this `Mathematica` newbie on how to go about to simulate this kind of motion. Desired animation fatures:   1. Perhaps the circular object can have **hatched shading** so that its rotating motion can be seen on top of its following the parametric circular path;   2. The $x-$ and $y-$axes should be visible;   3. The parametric path given by the parametric equations in $x$ and $y$ should be visible as a circle.


title: Difference between action of a Slider and a HorizontalGauge

text: First time posting. I am working on creating some interactive materials for the engineering classes that I teach and have run into an issue that I cannot puzzle out. I am using a slider to allow for a user to interactively change parameters but I also want to allow for the user to change the range of the slider. When I implement this using the standard `Slider` everything works fine, however, if I replace the `Slider` with a `HorizontalGauge`, I get a situation where the pointer does not update smoothly. So this works fine...               DynamicModule[{y = 1, LowerLimit = 1, UpperLimit = 10},     Column[{        Row[{          PopupMenu[Dynamic[LowerLimit], {1, 2, 3, 4}],          PopupMenu[Dynamic[UpperLimit], {5, 6, 7, 8, 9, 10}]          }],        Dynamic[Slider[Dynamic[y], {LowerLimit, UpperLimit}]],        Framed[         Row[{           "Slider Value", Spacer[10], Dynamic[y], Spacer[20],            "Lower Limit", Spacer[10], Dynamic[LowerLimit], Spacer[20],            "Upper Limit", Spacer[10], Dynamic[UpperLimit]           }]         ]        }]      ]      ![Mathematica graphics](http://i.stack.imgur.com/D1VAK.png) But with `Slider` replaced with `HorizontalGauge`, I run into problems...               DynamicModule[{y = 1, LowerLimit = 1, UpperLimit = 10},      Column[{        Row[{          PopupMenu[Dynamic[LowerLimit], {1, 2, 3, 4}],          PopupMenu[Dynamic[UpperLimit], {5, 6, 7, 8, 9, 10}]          }],        Dynamic[HorizontalGauge[Dynamic[y], {LowerLimit, UpperLimit}]],        Framed[         Row[{           "Slider Value", Spacer[10], Dynamic[y], Spacer[20],            "Lower Limit", Spacer[10], Dynamic[LowerLimit], Spacer[20],            "Upper Limit", Spacer[10], Dynamic[UpperLimit]           }]         ]        }]          ]      ![Mathematica graphics](http://i.stack.imgur.com/08Eci.png) Any suggestions and/or explanations would be greatly appreciated!!!


title: How to simplify symbolic matrix multiplication results?

text: I've defined three symbolic abstract matrices X, M and S as shown below.               In[1]:= $Assumptions = {      Element[X, Matrices[{k, 1}]],     Element[M, Matrices[{k, 1}]],     Element[S, Matrices[{k, k}, Reals, Symmetric[{1, 2}]]]     };          In[7]:= prodA = TensorTranspose[X].S.M;             prodB = TensorTranspose[M].S.X;          In[12]:= TensorReduce[prodA + prodB]     Out[12]= TensorTranspose[M, {2, 1}].S.X + TensorTranspose[X, {2, 1}].S.M      Since the S is a square and symmetric matrix, the production results prodA and prodB should be equal. How can I let the output reflect that? I need the output show something like 2TensorTranspose[X].S.M.


title: Splicing a list of arguments into a function with Sequence

text: Not sure if this has been asked, but I have a fairly simple operation that I don't know the syntax for. Say I have an array with some values, and a function f that accepts an arbitrary number of arguments. The following:               array = {e,f};     f[a, b, c, d, array];      ...is functionally equivalent to:               f[a, b, c, d, {e, f}];      OK, will Sequence help? Nope, this does the same thing:               f[a, b, c, d, Sequence@array];      Essentially, I want to include e and f into the list of arguments, i.e. I want to know the syntax for telling Mathematica I want it to evaluate this:               f[a, b, c, d, e, f];      How do I go about doing this?


title: Make MyLogicalExpand

text: The function by _Mathematica_ to expand a formulation with ANDS, ORS, NOT, XOR, and others, is `LogicalExpand`, let see an example:               LogicalExpand[ p && (q || x)]     (p && q) || (p && x)      I want to make the same thing but with strings, and these strings can be regular expression (it's contains parenthesis in some cases). I mean the form of the strings. Let set a test case.               expr = "(?i)god && (evil || salvation(.) )"     MyLogicalExpand[ expr ]      And the result should be: > >     "(?i)god && evil || (?i)god && salvation(.)" >   Notice that result don't group the atomic expression with parenthesis and the regular expression are the same. I don't know which way I should take. It's a parser problem, and the regular expression make it more complex, some space after o before inside atomic expressions could be appear. How do you program `MyLogicalExpand` method ?


title: Converting expressions into functions

text: I have defined an expression, such as               a = x      I would like to convert this into a function, such as               f[x_]:=x      However, in my case, the expression on the right-hand-side of `a` is rather complicated, so I do not want to manually write the expression on the right- hand-side of the function definition. I would like to write something like               f[x_]:=a      I know that this will not work. Is there a way to evaluate `a` in the function definition to ensure that I have actually defined a function in the end?


title: How to get axes labels with PlotTheme->"Scientific"?

text: I'm liking the new plot themes in Mathematica 10, but finding that I can't override the options it sets. For example,               Plot[x^2, {x, 0, 10}, AxesLabel -> {x}, PlotTheme -> "Scientific"]      returns the right plot but without the axis label. How do I fix this?


title: Definite integral takes a very long time

text: I'm trying to integrate the following function: $$ r_e=\int_0^z\frac{dz}{\sqrt{\Omega_m(1+z)^3+\Omega_\Lambda}} $$ where $\Omega_\Lambda=1-\Omega_M$ and both $\Omega_\Lambda$ and $\Omega_M$ are real and positive. Doing the definite integral using `Integrate` doesn't produce a result even after a few hours of running. I found that just doing the indefinite integral and then putting in the limits later produces a result. Why is this? Additionally, the result is unexpected and discontinuous for different values of $z$ depending on the value of $\Omega_M$. Any suggestions on the best strategy for integrating this?               FunH[omM_,omL_,z_]:=1/((omM(1+z)^3+omL)^(1./2.))     F[omM_,z_]:=Evaluate[Block[{omL=1-omM},Integrate[FunH[omM,omL,z],z]]]     Table[(1+z)^(-1)*(F[omM,z]-F[omM,0]),{omM,0.000001,1,0.1},{z,0.000001,3,0.001}]      I had to copy the code from another machine so I might have missed a bracket somewhere. EDIT: If anyone is interested, there is a publicly available paper dealing with a transformation of this integral to make the solution easier: http://mnras.oxfordjournals.org/content/412/4/2685.full Essentially one can transform the above integral using a few simple substitutions into something which is proportionate to the difference between two separate integrals of the form: $$ \int\frac{du}{\sqrt{u^4+u}} $$ This can be easily integrated by Mathematica.


title: Control objects Sizing and placement in Graphicsgrid Vs Grid:

text: I have created a grid, and also made a list of control objects(e.g., input fields, buttons, etc.). Then, I lay the list in my grid. There is no problem. However, the final layout takes a lot of time. I timed each operation and realized that the final grid layout is the one that takes up a huge chunk of time. Is there a better way of controlling the execution time of the graphics grid.               mygrid = ConstantArray["", {100, 100}];     mybutton1 = Button["Example", ImageSize -> {40, 50}];      myinput2 = InputField[x];      updatedlist = {};      updatedlist = ReplacePart[mygrid, {1, 2} -> mybutton1];      updatedlist = ReplacePart[updatedlist, {2, 3} -> myinput2];      Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]      ![Screen Layout](http://i.stack.imgur.com/cB2aH.png) The above code takes a lot of time to execute. I used the `Timing` function of _Mathematica_ to figure out which part took the long time to execute and it was the               Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]      part that was the longest. Because of this, my entire application has slowed down. Based on the comments in _Mathematica_ , I tried to use a `Grid` for the `updatedlist` above, but the problem is, how can I set the `ImageSize` of the Grid which is an option for the `GraphicsGrid` and not `Grid`? One could use scaled `ItemSize` and wrap the `Grid` in a `Pane` that has a fixed imagesize eg. `Pane[Grid[{{1, 2}, {3, 4}}, ItemSize -> Scaled[0.5]], ImageSize -> 200]`. But the problem with `Grid` is that `Scaled` option for `ItemSize` does not work for all times. And another problem is the size of the `Grid` is not a constant value because of the individual `ItemSize`. However my application demands that the `Grid` be a constant. Also, I tried to do something like this:               li=ConstantArray["",{5,20}];     b1=Button["Click",Null,ImageSize->{250,60}];     b2=Button["Click",Null,ImageSize->{400,80}];     b3=Button["Click",Null,ImageSize->{250,90}];     b4=Button["Click",Null,ImageSize->{100,90}];     li=ReplacePart[li,{1,2}->b1];     li=ReplacePart[li,{4,2}->b2];     li=ReplacePart[li,{5,2}->b3];     li=ReplacePart[li,{5,3}->b4];     li[[1,3;;6]]=SpanFromLeft;     li=ReplacePart[li,{4,3}->SpanFromLeft];     li=ReplacePart[li,{4,4}->SpanFromLeft];     li=ReplacePart[li,{4,5}->SpanFromLeft];     li=ReplacePart[li,{4,6}->SpanFromLeft];     Grid[li,Frame->All, ItemSize->Full]      The output was something like this: ![Second](http://i.stack.imgur.com/FX1F5.png) I want to be able to accurately place the control objects without messing the sizes and have perfect predictable appearance on the front end. Anyone knows how to make my code better and the interactive application look better?


title: Rotational Averaging of Image Periodograms (FFTS)

text: I'm writing a code to do rotational averages of image FFT's. I have a working version but it is pretty slow. Wondering if anyone has any thoughts on a way to do this more efficiently. Data looks like this generally: ![rawData FFT](http://i.stack.imgur.com/sGVvR.jpg)                   img1 = Import["http://i.imgur.com/0QZs0AN.png"];         img = ImageAdjust[ImagePeriodogram[img1], 1];              imgpts[r_, \[CapitalDelta]_, imagedimension_] :=            If[r != 0 , Table[{r Cos[2 \[Pi] t] + imagedimension/2,          r Sin[2 \[Pi] t]          + imagedimension/2} // N, {t, 0, 1,          1/(\[CapitalDelta] r)}], {{imagedimension/2, imagedimension/2},         {imagedimension/2, imagedimension/2}} // N];              RotationalAverage[FFT_, imgdim_, rmax_, \[CapitalDelta]_, inter_] :=            Table[{r, Mean[ImageValue[FFT, #, Resampling -> inter] & /@            imgpts[r, \[CapitalDelta], imgdim]]}, {r, 0, rmax}];              imagevals = RotationalAverage[img, 1024, 140, 16, "Bicubic"];      I decided to make each circle average over bins of the same arc-length. Im not sure if this is the "right" way to do this, but it seemed like a good idea. This gets me the data I want and I usually make a plot at this point just to check.                   ListPlot[imagevals]      ![plot for checking](http://i.stack.imgur.com/ku4fD.jpg) Then i stitch the images together to get a picture.                   ImgData = Reverse@Table[If[N[Sqrt[x^2 + y^2]] < 140,                  Interpolation[imagevals][Sqrt[x^2 + y^2] // N], 0], {x, 0, 128},          {y, 0, 128}] // Quiet;              ImageAdjust[ImageAssemble[{{Image[Reverse@Transpose@ImgData],          Image[ImgData]}, {Image[Transpose@ImgData],Image[Reverse@ImgData]}}], 1]      To get something like this ![final product](http://i.stack.imgur.com/ncEHq.jpg) What I'm ultimately after i guess is some optimization of accurate and fast, which is pretty vague but i guess i don't know how else to say it.


title: Understanding Transpose

text: It is very likely that it is my lack of math skills that is showing up here. However, I think `Transpose` is such an important function that I need to master it. So I am going to ask because I do not understand the information given in the documentation. > Transpose[list,{Subscript[n, 1], Subscript[n, 2], …}] transposes list so > that the k-th level in list is the Subscript[n, k]-th level in the result. Would anyone be able to provide a simple example and point out in a matrix what is going on? I am in particular struggling with the nth and k-th level. How does that work? I want to master `Transpose[list, {…}]`. Please explain the case where the k-th and n-th level are to be transposed, since this is where I am struggling. If this is considered mathematical question, and therefore not in the right place, I would appreciate a comment so that I could delete the post.


title: Plotting John Conway's Hecatohedron

text: John Conway has given an explanation how a regular Hecatohedron (polyhedron with 100 faces) looks like: http://www.ics.uci.edu/~eppstein/junkyard/hecatohedron.html Conway explains: _Here's a hecatohedron with full tetrahedral symmetry: Form the "16-reticulated cube", by dividing each face of a cube into 18 smaller "square" faces in the obvious way, giving a 96-hedron. Then tetrahedrally truncate this. I suppose I'd call it the **"semi-trivalently-truncated 16-reticulated cube"** !_ Unfortunatly I was not able to find a way how implement this into Mathematica. Can somebody give me some more hints or explanations? Thanks!


title: I can't understand FindShortest Tour

text: I can't understand the function `FindShortestTour` because of the result:               FindShortestTour[{ {0, 1}, {5, 1}, {2, 1}, {10, 1}}]      > >     {20, {1, 2, 4, 3}} >   and I think that the result should be: > >      {10, {1, 3, 2, 4}} >   or > >      {10, {4, 2, 3, 1}}   >


title: Spacer and Text in Graphics going Awry (in Mathematica 7)

text: Use of a vertical `Spacer` in justified text inside a graphic isn't working as required. The result in the green box looks right, but when this is placed in a graphic the spacing is messed up. Is there some way to fix it?               g1 = StringTake[ExampleData[{"Text", "BeowulfModern"}], {4740, 5200}];     g2 = StringTake[g1, 319] <> "\n";     g3 = StringDrop[g1, 319];     g4 = Row[{g2, Spacer[{0, 30}], g3}];          TextCell[g4, LineSpacing -> {0, 16}, TextJustification -> 1,       Background -> LightGreen]          Graphics[{       LightBlue, Rectangle[{0, 0}, {500, 140}], Black,       Inset[TextCell[g4, LineSpacing -> {0, 16}, TextJustification -> 1],        {0, 0}, {Left, Bottom}, {500, Automatic}]},      PlotRange -> {{0, 500}, {0, 140}}, ImageSize -> 500,      BaseStyle -> {FontFamily -> "Courier New", FontSize -> 12}]      ![enter image description here](http://i.stack.imgur.com/4zwET.png)


title: How to save Manipulate bookmarks permanently?

text: I would like to save current `Manipulate` parameter values to load them again later. Bookmarks (previously discussed here and here) work fine until the cell is reinitialized. Is it there a way to save a bookmark permanently and restore it at the next _Mathematica_ session? If not, how could I export a bookmark to a file and import it back? Since the code is huge (more than 80 controls of different types) and constantly evolving, I would like to have it automatized, preferably by a button within the same `Manipulate`. Many thanks in advance for any useful hints! Here is a small toy model to play with:               Manipulate[          Plot[Fun[2 Pi freq x], {x, 0, 2},              Axes -> showAxes,               PlotLabel -> If[showPlotLabel, plotLabel, ""]           ],         {Fun, {Sin, Cos}},         {freq, 1, 3},         Row[{            Control[{showAxes, {True, False}}],            Control[{showPlotLabel, {True, False}}]            }, "\t"],          {plotLabel, "Plot Label", Enabled -> showPlotLabel}          ]


title: How to study asymptotic behavior, built-in functions

text: My question is as follows. Suppose we have a function $f(r)$ and we want to study its asymptotic behavior at infinity ($r\rightarrow \infty$). For example, the function may reduce to $-\frac{a}{r}$ or $b e^{-cr}$ at infinity. How do I identify the constants $a,b$ and $c$ using _Mathematica_? Or, more generally, how do I identify the asymptote of a function? Can anybody point out useful built-in functions? I am interested in the function: $$ f(r)=-\frac{\sqrt[3]{3} e^{-2 r/3}}{\pi ^{2/3}}-\frac{\sqrt[3]{2 \pi } e^{2 r/3}}{5 \left(\frac{3 \sqrt[3]{\pi } e^{2 r/3} \sinh ^{-1}\left(2 \sqrt[3]{2 \pi } e^{2 r/3}\right)}{5\ 2^{2/3}}+1\right)} $$ or               f[r_]:=-((3^(1/3) E^(-2 r/3))/\[Pi]^(2/3)) - (E^(2 r/3) (2 \[Pi])^(1/3))/(      5 (1 + (3 E^(2 r/3) \[Pi]^(1/3)           ArcSinh[2 E^(2 r/3) (2 \[Pi])^(1/3)])/(5 2^(2/3))))      I expect this function to have -$\frac{1}{r}$-behavior. How do I check it? I am not interested in a numerical value of the limit (which is 0), but rather in a function the original function reduces to at infinity. P.S. Using _Mathematica_ for a week


title: List manipulation to build a functional expression

text: Since Mathematica deals with `Head[a, b]` as an expression in this way   * The first Part of `Head[a, b]` is `a`   * The second Part of `Head[a ,b]` is `b`   * The zeroth Part of `Head[a, b]` is `Head` it is natural to look at the expression in a `List[]` way as `List[Head, a, b]`, which contains all the information the _Mathematica_ Kernel requires. Based on such thinking, I want to construct, from any _Mathematica_ expression, a list of this form so said expression is a list that can be manipulated easier providing we have sufficient knowledge of list manipulation. For example, if I have a list               list = {{x, 1, 10}, Plot, Sin[x]}      I thought I could construct a plot-command `Plot[Sin[x], {x, 1, 10}]` by evaluationg               list[[2]][list[[3]], list[[1]]]      or               Extract[#, {2}][Extract[#, {3}], Extract[#, {1}]] &[list]       But these are invalid for reasons that I have no knowledge about. Could anyone explain the reason why my ideas failed in _Mathematica_. By the way, the expression               f[Extract[#, {3}], Extract[#, {1}]] &[list] /. f -> Extract[#, {2}] &[list]      works. Why do the former two examples before this one not work?


title: Mathematica - set end-of-line characters when importing

text: I have a plain text file of tab-separated values that was created on a Windows machine. I want to import it into Mathematica on a Mac.               rawdata = Import["filename.csv", "tsv"]      The output list has a blank list every other element. I think this is due to the old `\r\n`-vs-`\n` compatibility issue. How can I tell `Import` which convention the input file is using? Edit: I should mention that I want to do this in a cross-platform way, because I'll probably be moving notebooks between Mac and Windows machines. So simply skipping every other element of the output list (`[[1;2;-1]]`) won't work. Edit 2: This is what the file looks like when I open it in Emacs:               ...     4.510000000000000E+008  -1.052316667849458E+002 -1.412043034275902E+002 ^M     4.515000000000000E+008  -1.159523802353636E+002 1.631532615796773E+002 ^M     ...      The spaces between the fields are tabs. A moment's Googling tells me that `^M` is a carriage return (`\r`). This fits my hypothesis that the Windows-based device is terminating lines with `\r\n`, and Mathematica is reading that as two new-lines. My question remains: How do I tell `Import` what EOL characters are in use in my file?


title: Incompatibility of Row and TeXForm

text: In _Mathematica_ 7 `Row` and `TeXForm` work harmoniously:               {x^a, Sqrt@b, ArcSin[c]} // Row // TeXForm      > >     x^a\sqrt{b}\sin ^{-1}(c) >   As LaTeX: > $x^a\sqrt{b}\sin ^{-1}(c)$ Unfortunately this is broken in more recent versions. _Mathematica_ 10 returns: > TeXForm::unspt: TeXForm of TemplateSlotSequence[1,] is not supported. >> This error was reported in version 9 as well. An attempt at a workaround is to substitute `Grid` for `Row` but the LaTeX code generated is different:               {{x^a, Sqrt@b, ArcSin[c]}} // Grid // TeXForm      ![enter image description here](http://i.stack.imgur.com/XXm7I.png) And it formats differently: > $\begin{array}{ccc} x^a & \sqrt{b} & \sin ^{-1}(c) The documentation for `TeXForm` indicates that it is extensible with rules for `Format` but I could not fine a rule that worked. While I can manually convert a single Row as follows:               StringJoin[ToString /@ TeXForm /@ {x^a, Sqrt@b, ArcSin[c]}]      > >     x^a\sqrt{b}\sin ^{-1}(c) >   (Though note that one must copy as **Plain Text**.) However attempting to make this a `Format` rule results in double-conversion and I get this: ![enter image description here](http://i.stack.imgur.com/8mkuh.png) * * * ### Is this indeed a bug as I believe? ### What is the best work-around for the problem, preferably automatic?


title: Can I combine a manipulate plot and a plot of data from a file?

text: I am fitting a theoretical equation for a complicated curve to some experimentally measured data. As you might be aware, algorithmically quantifying 'goodness of fit' for a complicated curve is something of a dark art... I want to load the experimental data and display it in a graph, and then over the top have a manipulable plot of the generated curve superimposed, so that I can tweak the parameters by eye until the fit looks good. I can plot the measured data, and I can plot the manipulable curve from theory, but I need them to be plotted on top of each other! I'm having trouble getting it to show the two graphs at once though... is it possible? Many thanks, Ben


title: Should DSolve always return solution with constant of integration?

text: Version 10.0               Clear[y,x];     DSolve[D[y[x], x] - y[x]^2 + y[x]*Sin[x] - Cos[x] == 0, y[x], x,          GeneratedParameters -> C]      or               DSolve[D[y[x], x] - y[x]^2 + y[x]*Sin[x] - Cos[x] == 0, y[x], x]      both return a solution that does not include `C[1]`, the constant of integration.               {{y[x] -> Sin[x]}}      The question is: Should `DSolve` always return an arbitrary constant? Even though the answer is correct, it is missing `C[1]` hence this is a particular solution. If `DSolve` does not _have to_ generate a constant of integration in the solution of a differential equation, then what caused it not to generate it in this specific case? **Update:** Let me add a solution found by Maple for this, which _does_ include a constant of integration:               Clear[C,y,x];     eq = Derivative[1][y][x] - y[x]^2 + y[x]*Sin[x] - Cos[x] == 0;     eq /. y -> (- Exp[-Cos[#]]/(C[1] + Integrate[ Exp[-Cos[#]], x]) + Sin[#] &);     Simplify[%]     (* True *)      So, the above is a general solution with a constant of integration that solves the same differential equation.


title: Deleting parts of groups that do not have equal dates

text: Find the intersection of dates within the pair and remove the other dates & corresponding prices. Also keep the list in same format as it currently is in. Let me explain: Each stock has closing dates and prices. There are many groups of 2 stocks in the list.(all unique pairs) Within each stock pair(group) I want to delete the dates and corresponding prices if the dates does not match both stocks(finding the intersection of dates within the pairs.)               Input: Subsets[Partition[tt, 2, 3], {2}]     Output: {{{{"AAD AT Equity",      "Date", $Failed, {2013, 8, 1, 0, 0, 0.}, {2013, 8, 2, 0, 0,           0.}, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.}}, {"",          "PX_LAST", 0.82, 1.77, 1.75, 1.72, 1.71}}, {{"ABC AT Equity",          "Date", $Failed, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.},          "", ""}, {"", "PX_LAST", 0.6808, 3.33, 3.35, "",          ""}}}, {{{"AAD AT Equity",          "Date", $Failed, {2013, 8, 1, 0, 0, 0.}, {2013, 8, 2, 0, 0,           0.}, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.}}, {"",          "PX_LAST", 0.82, 1.77, 1.75, 1.72, 1.71}}, {{"ABP AT Equity",          "Date", $Failed, {2013, 8, 2, 0, 0, 0.}, {2013, 8, 5, 0, 0,           0.}, {2013, 8, 6, 0, 0, 0.}, ""}, {"", "PX_LAST", 5.3942, 2.22,          2.2, 2.2, ""}}}, {{{"AAD AT Equity",          "Date", $Failed, {2013, 8, 1, 0, 0, 0.}, {2013, 8, 2, 0, 0,           0.}, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.}}, {"",          "PX_LAST", 0.82, 1.77, 1.75, 1.72, 1.71}}, {{"ACR AT Equity",          "Date", $Failed, {2013, 8, 6, 0, 0, 0.}, "", "", ""}, {"",          "PX_LAST", 1., 3.32, "", "", ""}}}, {{{"ABC AT Equity",          "Date", $Failed, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.},          "", ""}, {"", "PX_LAST", 0.6808, 3.33, 3.35, "",          ""}}, {{"ABP AT Equity",          "Date", $Failed, {2013, 8, 2, 0, 0, 0.}, {2013, 8, 5, 0, 0,           0.}, {2013, 8, 6, 0, 0, 0.}, ""}, {"", "PX_LAST", 5.3942, 2.22,          2.2, 2.2, ""}}}, {{{"ABC AT Equity",          "Date", $Failed, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.},          "", ""}, {"", "PX_LAST", 0.6808, 3.33, 3.35, "",          ""}}, {{"ACR AT Equity", "Date", $Failed, {2013, 8, 6, 0, 0, 0.},          "", "", ""}, {"", "PX_LAST", 1., 3.32, "", "",          ""}}}, {{{"ABP AT Equity",          "Date", $Failed, {2013, 8, 2, 0, 0, 0.}, {2013, 8, 5, 0, 0,           0.}, {2013, 8, 6, 0, 0, 0.}, ""}, {"", "PX_LAST", 5.3942, 2.22,          2.2, 2.2, ""}}, {{"ACR AT Equity",          "Date", $Failed, {2013, 8, 6, 0, 0, 0.}, "", "", ""}, {"",      "PX_LAST", 1., 3.32, "", "", ""}}}}      For the first pair of stocks I want to end up with this correct result:               {{{"AAD AT Equity",      "Date", $Failed,, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.}}, {"",          "PX_LAST", 0.82, 1.72, 1.71}}, {{"ABC AT Equity",          "Date", $Failed, {2013, 8, 5, 0, 0, 0.}, {2013, 8, 6, 0, 0, 0.},      "", ""}, {"", "PX_LAST", 0.6808, 3.33, 3.35, "",      ""}}}      As you can see, what has happened is that AAD equity have lost it two first trading dates in the list and its corresponding close price, and we end up with a pair of stocks with equal number of corresponding dates, and each stock have same amount of closing prices. Note: I want this to be done for each pair.


title: Script with command line argument

text: As a test I want a simple script to take a command line argument and print it to a file: `Export["c://cygwin/home/jorgen/yu.dat",$ScriptCommandLine[[2]],"Data"] // MatrixForm;` However when I run this with `./MathKernel -script Swargtest.m 45` the resulting file yu.dat looks like this: `{}[[2]]` I've tried what I could think of: making another variable with `out=$ScriptCommandLine[[2]]` and exporting that, removing the `$`, running the script with `'45'` and `"45"` on the command line, etc. I'm using cygwin on a windows 7 machine.


title: Implementing a first person view of 3D objects in a scene

text: I've created the following scene with a Chinese-style building surrounded by trees, and a horse and a rabbit grazing on the grass in Mathematica (don't ask me why there's a bust of Beethoven in there...). The Chinese-style roof was created using J. M.'s equations in this answer. The code to create this is at the very end of this post. ![enter image description here](http://i.stack.imgur.com/XHf3Y.png) How can I use the various `View*` options to implement a first-person view of the objects in the scene? In other words, be able to walk around freely and see objects as if I were in the scene. * * * ### Code to create the scene               Begin["NonProprietaryCode`"];     Module[{roof, columns, base, ground,         fauxLame = {#2 Abs@Cos@#1 Cos@#1, #2 Abs@Sin@#1 Sin@#1,            9 #2 ((9 #2/10 - 2/3) Cos[2 #1]^2 - 4/3)/20} &,        roofExt = 3/2, roofTex = ExampleData[{"ColorTexture", "Roof"}],        colRad = 0.15, colOff = 1, colHt = 2.5,        baseHt = 0.25,         baseTex = ExampleData[{"ColorTexture", "GrayMarble"}],        vtc = {{0, 0}, {1, 0}, {1, 1}, {0, 1}},        cubeCoords = {{{0, 0, 0}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}}, {{0, 0,             0}, {1, 0, 0}, {1, 0, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1,             0}, {1, 1, 1}, {1, 0, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 1,             1}, {1, 1, 1}}, {{0, 1, 0}, {0, 0, 0}, {0, 0, 1}, {0, 1,             1}}, {{0, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}}},        groundTex = Import["http://i.stack.imgur.com/hMQwd.jpg"]        },            roof = ParametricPlot3D[{fauxLame[u, v]}, {u, -Pi, Pi}, {v, 0,           roofExt},         Mesh -> None, Lighting -> "Neutral",         PlotStyle -> Texture[roofTex]];       columns =         ParametricPlot3D[         With[{x = colOff + colRad Cos@t, y = colRad Sin@t,            u = Rescale[             t, {-Pi, Pi}, {-#, #} &@              ArcTan[colOff, colRad]]},          {Sequence[#],              Min[v, Last@fauxLame[u, y/Sin@u/Abs@Sin@u]]} & /@ {{x,              y}, {-x, y}, {-y, x}, {y, -x}}], {t, -Pi,           Pi}, {v, -colHt, -0.585}, Mesh -> None, PlotStyle -> Red];       base = Graphics3D[{Texture[baseTex], Lighting -> "Neutral",           EdgeForm[None],           Rotate[Polygon[            cubeCoords /. {x_, y_,                z_} :> {2 roofExt x, 2 roofExt y, -baseHt z} - {roofExt,                 roofExt, colHt},             VertexTextureCoordinates -> Table[vtc, {6}]],            Pi/4, {0, 0, -(colHt + baseHt/2)}]}];       ground =         Graphics3D[{Texture[groundTex], Lighting -> "Neutral",           EdgeForm[None],           Polygon[cubeCoords /. {x_, y_,               z_} :> {8 x, 8 y, -0.1 z} - {4, 4, colHt + baseHt},            VertexTextureCoordinates -> Table[vtc, {6}]]}];            building = Show[roof, columns, base, ground, PlotRange -> All];       ];          Module[{treePoly =          ExampleData[{"Geometry3D", "Tree"}, "PolygonObjects"],        trunkTex = ExampleData[{"ColorTexture", "Ash"}],         vtc = {{0, 1}, {1, 0}, {1, 1}}        },       trunk =         Graphics3D[{Texture[trunkTex], Lighting -> "Neutral",           EdgeForm[None],           treePoly[[;; 19000]] /.            Polygon[x__] :> Polygon[x, VertexTextureCoordinates -> vtc]}];       leaves =         Graphics3D[{FaceForm[Darker@Green], Lighting -> "Neutral",           EdgeForm[None],           treePoly[[19001 ;;]] /.            Polygon[x__] :> Polygon[x, VertexTextureCoordinates -> vtc]}];            tree = Show[trunk, leaves, PlotRange -> All];       ];          Module[{        bunnyVtx =          ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"]        },       bunny =         ListSurfacePlot3D[bunnyVtx, MaxPlotPoints -> 35, Mesh -> None,          TextureCoordinateFunction -> (Normalize[{#1, #2, #3}] &),          PlotStyle -> Directive[Lighting -> "Neutral"]]       ];          Module[{        horseVtx = ExampleData[{"Geometry3D", "Horse"}, "VertexData"],        horseTex = ExampleData[{"ColorTexture", "BurlOak"}]        },       horse =         ListSurfacePlot3D[horseVtx, MaxPlotPoints -> 35, Mesh -> None,          TextureCoordinateFunction -> (Normalize[{#1, #2, #3}] &),          PlotStyle -> Directive[Texture[horseTex], Lighting -> "Neutral"]]       ];          Module[{bustPoly =          ExampleData[{"Geometry3D", "Beethoven"}, "PolygonObjects"]},       bust = Graphics3D[{FaceForm[Gray], Lighting -> "Neutral",            EdgeForm[None], bustPoly}];       ];          Draw := With[{c = -Mean /@             AbsoluteOptions[tree, PlotRange][[1, 2]] - {0, 0, 0.75},         treeLocs = {{-2, 2, 0}, {2, 2, 0}, {-2, -2, 0}}},       Show[building,        Graphics3D[{          {FaceForm[Gray], EdgeForm[None], Lighting -> "Neutral",            Cylinder[{{0, 0, -3}, {0, 0, -2}}, 0.1]},          Translate[Scale[bust[[1]], 0.05], {0, 0, -1.5}],          Translate[Scale[horse[[1]], 5], {-3, 0, -2.25}],          Translate[Scale[bunny[[1]], 1.5], {2, -2, -2.75}],          Translate[Scale[tree[[1]], 0.013],            Outer[Plus, treeLocs, {c}, 1]]          }], PlotRange -> All, Boxed -> False, Axes -> None]       ]          End[];      Create a scene with `scene = NonProprietaryCode`Draw`. Feel free to modify the code as desired to implement the FPV.


title: Generating an autoregressive time series

text: Find $X_t = c_1 X_{t-1} + \dots + c_n X_{t-n} + n_t$ for given $c_i$, initial conditions $(X_1, \dots, X_n)$, and distribution for i.i.d. $n_t$. I would like to know if there is a more efficient or elegant way to code this than using a for loop.


title: Checkbox behaving weird when variables are local

text: I have a `DynamicModule` in which I need a checkbox with a `Max` in the dynamic part:               Checkbox[Dynamic[... Max ...]]      After removing everything else from the `DynamicModule`, it still behaves badly: (whether `q[[1, 1]]` is false or true, the checkbox shows a big square, although `q[[1,1]]` doesnt have a bad value):               DynamicModule[{s = 1, q = {{False}}},       {Checkbox[Dynamic[q[[1, 2 - Max[s, 0]]]]], Dynamic[q[[1, 2 - Max[s, 0]]]]}]      If variables aren't local, it behaves well:               s = 1; q = {{False}};     Checkbox[Dynamic[q[[1, 2 - Max[s, 0]]]]]     Dynamic[q[[1, 2 - Max[s, 0]]]]


title: Pasting "rectangles" of text side-by-side

text: In Emacs/Xemacs, there is a rectangle feature, such that you can delete, copy, etc., "rectangles" of text. Now suppose I have two text files, each containing one column of numbers. Is it possible to use Mathematica to "paste" the columns of text, side by side (perhaps separated by at least one space)? For example, suppose I have two text files:               (* file 1 *)     1     20     300          (* file 2 *)     4     50     600      I would like to be able to obtain a single text file like this:               (* file 3 *)     1   4     20  50     300 600      Do you have any ideas of how I can do this efficiently? The ideas I have (like stripping and joining row-by-row, and adding the appropriate number of spaces) are really complicated, and I feel like there must be an easier way. Thanks!


title: Split string into sub-strings of length n

text: > **Possible Duplicate:**   >  Partition string into chunks How can I split a string into sub strings of length n? For example I have a string               "ABCDEabcde1234"      I would like to split it into               {"AB", "CD", "Ea", "bc", "de", "12", "34"}      How can I achieve this? I have looked at the `StringSplit[]` documentation but that seems like it only works for splitting a string by character, not length.


title: Generalizing Characters to n-character substrings

text: I'm doing some frequency analysis on an encrypted plaintext. Tally[] and Characters[] make the basic task quite easy. To count the number of times each character appears (sorted alphabetically; Plaintext has been pre-sanitized), I can carry out               Sort[Tally[Characters[Plaintext], #1[[2]] > #2[[2]] &]        For a more nuanced cryptanalytic approach, I will also want to count the frequency of each digraph (pair of adjacent characters), trigraph (triple of same), ..., n-graph. Tally[] will still work fine here, but the original splitting task (previously performed by Characters[]) is slightly more complicated. I want a function`nGraphList[PTstring_String, Chunklength_Integer]` that outputs a list (including repeats) of the Chunklength-graphs found in PTstring. When Chunklength = 1, the function should give identical output to Characters[]. Okay, so the problem isn't really that hard. A quick approach is               nGraphList[PTstring_String, Chunklength_Integer]:=      Table[        StringTake[PTstring, {k, k + Chunklength - 1}],      {k, 1, StringLength[PTstring] - Chunklength + 1}]      The thing drives me crazy, though. It seems like a terribly easy string operation of the sort Mathematica would be able to do in a snap. My solution is clunky, and I can't find any better ideas in the documentation or here. Can you show any different ways to do this? Any smarter or prettier ways? Related: Clif's question hints at possible usage of stream methods, but 1) I know little on the subject and 2) it looks equally if not more clunky.


title: Parallelize a few commands

text: I'm trying to parallelize a few commands that are time consuming, but independent of each other, in _Mathematica_ , but I can't seem to get it to work and I can't seem to find any beginner's tutorial on the subject either. I have four commands on the following form:               data2x = Table[{x0, y0, fx[x0, y0]}, {x0, -range, range, step}, {y0, -range, range, step}]      with different function fx, so I thought that I could cut time by using all four processors at once. I've tried `Parallelize`, `ParallelEvaluate`, and `ParallelSubmit`. For example as follows:               LaunchKernels[4];     Parallelize[       data2a = ...,       data2b = ...,        data2c = ...,       data2d = ...,       Method -> "EvaluationsPerKernel" -> 1     ];      But when I run the program, it's run sequentially (25 % CPU usage, same time to finish as sequential method) even though several processes running MathKernel.exe are launched. I run _Mathematica_ 10.0 on Windows 7, with i5-2400


title: Part::pspec error returned when using a ListLinePlot ColorFunction variable as list index

text: In ListLinePlot, I'm attempting to construct my own ColorFunction for coloring points differently based on a third dimension of data not plotted to a specific axis. However, ColorFunction only uses variables corresponding to the specific data inserted, so that third dimension of data is not available internally. Therefore, if I want to use it in my plot, I have to reference it externally. Here's an example setup:               data := Table[{Range[0, 2] + x}, {x, 0, 20}][[All, 1]]      Produces the following list:               {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}, {6,        7, 8}, {7, 8, 9}, {8, 9, 10}, {9, 10, 11}, {10, 11, 12}, {11, 12,        13}, {12, 13, 14}, {13, 14, 15}, {14, 15, 16}, {15, 16, 17}, {16,        17, 18}, {17, 18, 19}, {18, 19, 20}, {19, 20, 21}, {20, 21, 22}}      Now, I want to plot this list as a 2D graph with the first and second entries corresponding to x and y, and the third entry corresponding to a color. Here's what I tried:               ListLinePlot[data[[All, {1, 2}]],      ColorFunction -> Function[{x, y}, Hue[data[[x + 1, 3]]/22]]      ]      This produces errors like this:               Part::pspec: Part specification 1.05` is neither a machine-sized integer nor a list of machine-sized integers.      Part::pspec: Part specification 1.05` is neither a machine-sized integer nor a list of machine-sized integers.      Part::pspec: Part specification 1.1` is neither a machine-sized integer nor a list of machine-sized integers.      General::stop: Further output of Part::pspec will be suppressed during this calculation.       The final output is a graph with variable but unexpected coloring. Substituting a regular number in for x in the ColorFunction's Function performs correctly (e.g., `Function[{x, y}, Hue[data[[0 + 1, 3]]/22]]`). I can't see why I can't use given variables in a ColorFunction for referencing external objects. What have I done wrong? Why are these messages being generated, and what do they mean? **Update:** here's the graph outputted by the version attempting to use x as an index: ![](http://i.stack.imgur.com/QPEDs.png)


title: How to define range for Manipulate using exponents

text: I have a function:               f[x_,y_] = x*y // ScientificForm;     Manipulate[f[x,y], {x, 10^-1, 10^-10}, {y, 0.01, 1, 0.01}]      When I try to execute it - it does work. However I want my x to increment in following manner: for `x`, 10^-1, 10^-2, 10^-3, ..., 10^-10 and for `y`, 0.01, 0.02, ..., 0.1, ..., 0.11, ..., till eventually 1; I can't get my head around this. Could somebody please share any links on how to actually build interface in _Mathematica_. That would be very much appreciated


title: Excel column label from integer

text: I would like to create a function in _Mathematica_ , which returns the equivalent Excel column label (e.g., A, Z, AA, AZ, and so on) given a column number. I think it can be done with `IntegerString[10,26]`, but this representation set of this chars is 0 to 9 and then a to z. However, Excel uses only A to Z. How can this be done?


title: Show graphics content in front of frame

text: Consider some graphics which spill over the plot range, like these:               Graphics[{Red, Disk[{0, 0}, 1]},       PlotRange -> {{-1.1, .9}, {-1.1, 1.1}}, Frame -> True,       PlotRangeClipping -> False, ImagePadding -> 20, FrameStyle -> Thick]      ![Mathematica graphics](http://i.stack.imgur.com/M9DxJ.png) Can I make the graphics be drawn in front of the frame without drawing the frame manually? Is there a possibly undocumented option for this (maybe a `Graphics` `Method` option)?


title: Problem with indentation with a section having a RegularExpression

text: I have this line of code (a one-liner to import the Abaqus dispalcements!)               displacements =       DeleteCases[        ImportString[         StringCases[fileStr,            RegularExpression[             "------------------------------\n([.\\s\\S]*)Minimum"] -> \     {"$1"}][[1, 1]], "Table"], {}][[       All, {1, 3, 4}]];(* drop the 2nd column = U.Magnitude *)      This line gives a trouble in the auto-intendation when sometimes the * ) in the RegularExpression matches with an opening (* somewhere earlier. One solution to correct the wrong formatting (I know) is to delete the *) and retype it. Anyone else faces such trouble in the front-end? Any way to avoid it? I am on M8


title: Projecting on an arbitrary plane

text: I have the following code, giving me a representation of a photon hitting a cylinder:               scale1 = 1.2;     scale2 = 2.25;     scale3 = 1.4;     scale4 = 2;     inp = {scale2, scale2, scale2};     intp = {4, 4, 3};     rainp = {4, 0, 0};     raoutp = {4, 8/scale3, 6/scale3};     outp = {4, 4.65, 3.25};     ninra = (intp - inp)\[Cross](raoutp - rainp);     inttan = (raoutp - rainp) - inp;     tandir = (raoutp - rainp)\[Cross] ninra;     tanvect[t_] := inp + t*tandir;     tanvect1 = tanvect[0.15];     v = tandir;     u = raoutp - rainp;     w = rainp - inp;     s = (v[[2]]*w[[1]] - v[[1]]*w[[2]])/(v[[1]]*u[[2]] - v[[2]]*u[[1]]);     t = (u[[1]]*w[[2]] - u[[2]]*w[[1]])/(u[[1]]*v[[2]] - u[[2]]*v[[1]]);     d = EuclideanDistance[inp, tanvect1]*t;     p = tanvect[2*t];          nareaR = ({1, 0, 0}\[Cross]((rainp - raoutp)/Norm[{raoutp - rainp}]));     nareaR = nareaR/Norm[nareaR];          cylinder =        ContourPlot3D[y^2 + z^2 == 25, {x, 0, 10}, {y, -5, 5}, {z, -5, 5},        Mesh -> None, ContourStyle -> Directive[Brown, Opacity[0.25]],        AxesLabel -> {"x", "y", "z"}];     areaX =        ContourPlot3D[x == 4, {x, 2, 7}, {y, 2, 7}, {z, 0, 5},        Mesh -> None, ContourStyle -> Directive[White, Dashed, Opacity[0]],       AxesLabel -> {"x", "y", "z"}];     areaR =        Plot3D[         (nareaR[[1]]*intp[[1]] + nareaR[[2]]*intp[[2]] + nareaR[[3]]*intp[[3]] -          nareaR[[1]]*x - nareaR[[2]]*y)/(nareaR[[3]]),          {x, 2, 7}, {y, 2, 7},          Mesh -> None,         PlotStyle -> Directive[White, Dashed, Opacity[0]],          AxesLabel -> {"x", "y", "z"}];     axial =        Graphics3D[{Arrowheads[0.02], Black, Dashed, Arrow[{{0, 0, 0}, {10, 0, 0}}],          AxesLabel -> {"x", "y", "z"}}];     radius =        Graphics3D[{Arrowheads[0.02], Black, Dashed, Arrow[{rainp, raoutp}],          AxesLabel -> {"x", "y", "z"}}];     inv =        Graphics3D[{Thick, Arrowheads[0.02], Red, Arrow[{inp, intp}],          AxesLabel -> {"x", "y", "z"}}];     outv =        Graphics3D[{Thick, Arrowheads[0.02], Blue, Arrow[{intp, scale1*outp}],          AxesLabel -> {"x", "y", "z"}}];     reflv =        Graphics3D[{Thick, Arrowheads[0.02], Green, Arrow[{{4, 4, 3}, p}],          AxesLabel -> {"x", "y", "z"}}];     directCos1 =        Graphics3D[{Arrowheads[0.02], Purple, Dashed, Thick,          Line[{{4, 4, 3}, {4, scale1*4.65, 3}, {4, scale1*4.65, 3},                {4, scale1*4.65, scale1*3.25}, {4, scale1*4.65, scale1*3.25},                {scale1*4, scale1*4.65, scale1*3.25}}],          AxesLabel -> {"x", "y", "z"}}];     directCos2 =        Graphics3D[{Arrowheads[0.02], Orange, Dashed, Thick,          Line[{{scale2*1, scale2*1, scale2*1}, {scale2*1, scale2*1, 3},                {scale2*1, scale2*1, 3}, {scale2*1, 4, 3}, {scale2*1, 4, 3},                {4, 4, 3}}],          AxesLabel -> {"x", "y", "z"}}];     directCosReflv =        Graphics3D[{         Arrowheads[0.02], Cyan, Dashed, Thick,          Line[{{4, 4, 3}, {4, p[[2]], 3}, {4, p[[2]], 3},                {p[[1]], p[[2]], 3}, {p[[1]], p[[2]], 3}, {p[[1]], p[[2]], p[[3]]}}],          AxesLabel -> {"x", "y", "z"}}];     Show[       directCos1, directCos2, directCosReflv, radius, outv, axial,         inv, reflv, areaR, areaX, cylinder,        Axes -> False,        AxesLabel -> {"x", "y", "z"},        Boxed -> False]      By setting the viewpoint option in `Show` to be:               ViewPoint -> {∞, 0, 0}      I get a nice representation in the y,z plane. My question is how do I easily project the cylinder and its vectors onto the r,x plane?


title: Show contour area as tooltip?

text: I have contour plots, such as               plot = ContourPlot[Sqrt[(x - 2)^2 + (y - 2)^2 - 5], {x, -15, 15}, {y, -15, 15}, Contours -> {4}] /. _Polygon -> Sequence[]      I have successfully found the numerical area enclosed using Stokes' theorem, essentially the "x dy" case shown here.               points = Transpose[Cases[Normal@plot, Line[pts_] :> pts, Infinity][[1,         All]]];       area = N[Abs[Rest[First[points]].Last[ListCorrelate[{1, -1}, #1] & /@ points]]]       What I would like to accomplish now is to apply the found area as a `Tooltip[]` on the contour plot. However, this isn't working properly:               Tooltip[ContourPlot[Sqrt[(x - 2)^2 + (y - 2)^2 - 5], {x, -15, 15}, {y, -15, 15}, Contours -> {4}] /. _Polygon -> Sequence[],"example"]      ![enter image description here](http://i.stack.imgur.com/im34Rm.png) `"example"` comes up as a tooltip anywhere on the whole plot area, not just when the cursor is on the contour line. Also, sometimes it doesn't show "example"; it only shows like "ex" and then is cut off by white space. How can I implement this properly?


title: How to create a column for ordering values

text: I have a dataset, where some data has to be ranked in regard to the number of ranking of the total dataset. I've made a simple example below:               names = {"Set A", "Set B", "Set C"};     values = {67, 80, 50};     {names, values} // Transpose      I would like to add a 3rd column, which described the rank of the total column. I've tried with `RankedMax` but without any luck. To be more exactly, the matrix below shows my problem, where the third column is ranking the highest to lowest value. $$\left( \begin{array}{ccc} \text{Set 1} & 67 & 2 \\ \text{Set 2} & 80 & 1 \\ \text{Set 3} & 50 & 3 \\ \end{array} \right)$$ How can create such a column?


title: Why do I get a different answer from the use of TrigExpand?

text: This is an old post but I get two different answers from _Mathematica_ 9.0.1.0               f[x_] =  Sin[x]^3 + Cos[x]^2 /.          AlgebraicRules[{Sin[x]^2 + Cos[x]^2 == 1, Sin[3*x] == 1/2}]          (* 1 - Sin[x]^2 + Sin[x]^3 *)          g[x_] = Sin[x]^3 + Cos[x]^2 /.          AlgebraicRules[{Sin[x]^2 + Cos[x]^2 == 1, TrigExpand[Sin[3*x]] == 1/2}]          (*  7/8 + (3 Sin[x])/4 - Sin[x]^2 *)          Plot[{f[x], g[x]}, {x, 0, 2 π }]      ![](http://i.stack.imgur.com/x5XKR.png) The plot shows that `f[x]` and `g[x]` are clearly different. It appears that the use of `TrigExpand[Sin[3*x]]` in `g[x]` messes up the answer.


title: Keep MathKernel Running In Background - Speed Up Execution Time

text: **Background:** I'm running Debian on a remote server with Mathematica installed. I have several dozen small mathematica files that are run in cron jobs at unpredictable intervals and updated based on a web interface. I'm trying to get faster response times when I run the smaller files. **Question:** For Example I have `file.m` which contains(This is just an example)               Export["/home/rob/Desktop/eq.png",Sum[1/2,{x,i}]]      If I setup a cron job to run the following               time MathKernel -noprompt -script /home/rob/Desktop/file.m      I get a real response time of **`6.31`**. But now if I ssh into the server and run `MathKernel` and the following               AbsoluteTiming[Export["/home/rob/Desktop/eq.png",HoldForm[Sum[1/2,{x,i}]]]       the script returns **`1.13`**. The start up time definitely appears to be the issue `6.31` vs `1.13`. So what is the best way to keep MathKernel running it the background so it can periodically run `file.m`? **EDIT:** I would like to avoid using `CreateScheduledTask` because of the extensive rewrite that would be needed.


title: How to change the start path of SystemDialogInput

text: It seems that every time the start directory of `SystemDialogInput` is always the same, is it possible to set the start directory to the last used directory? For example:               SystemDialogInput["FileOpen"]      ![enter image description here](http://i.stack.imgur.com/vh4SE.png) will start from the "Documents" directory, if I change to other directory and select some file, and run the second input dialog               SystemDialogInput["FileOpen"]      it forgets the directory I chose in the first `SystemDialogInput` and starts from "Documents" directory again. Is it possible to set `SystemDialogInput` to always remember the last used directory?


title: Help me to find a way to do this repetitive stuff

text: I'm trying to do this:               p = 10;     a = ToString[N[Sqrt[3], p^2 - 1]];          a = Characters[a ];     b = Table[ToString[n], {n, 0, 9}];     n = 0; i = 0;     a = StringReplace[a, "." -> "g"];          a /. ToString[0] -> Graphics[{CMYKColor[1, 0, 0, 0], Rectangle[]}]      The idea is to replace the numbers, with a rectangle of each color - small numbers are brighter, bigger numbers are dark, the point is to be transformed in a green square. But for doing this, I must repeat the code a lot:                   a /.      ToString[0] -> Graphics[{CMYKColor[0, 0, 0, 0], Rectangle[]}]  /.      ToString[1] -> Graphics[{CMYKColor[1, 0, 0, 0], Rectangle[]}]  /.      ToString[2] -> Graphics[{CMYKColor[2, 0, 0, 0], Rectangle[]}]  /.      ToString[3] -> Graphics[{CMYKColor[3, 0, 0, 0], Rectangle[]}] ...      I tried to use Table, but it didn't work. I was trying the following:               Table[a /. ToString[o] -> Graphics[{CMYKColor[o, 0, 0, 0], Rectangle[]}], {0, 0, 9}]      But it didn't work. What would be a nice way to do this?


title: Memory usage of timeseries - lists of {Integer32, Real32}

text: A list of `{Integer32, Real32}` items in _Mathematica_ seems to use 12-times as much memory than the `C` equivalent array of structs. And it looks like it can't be stored in a packed array, due to the integer/real mix. Besides splitting the time-series into two lists, one of timestamps and the other of values, so that each one can be packed individually, is there any other strategy? Also, _Mathematica_ 9 has a new function – `TemporalData`. Is that more efficient than a simple list?


title: How can we create a histogram distribution from binning data?

text: `HistogramDistribution` takes a list of data points, creates a histogram from them, and returns this histogram in a form that can be used as a distribution. I already have the binned data, and I do not have the original data points. How can I create a distribution object equivalent to a histogram distribution using this binning data? Let's assume we have the binned data in the same format that `HistogramList` returns. Example data: `bins = N@HistogramList@RandomVariate[NormalDistribution[], 1000]`.


title: Using NetLink to Import Excel File

text: I can import an Excel file into Mathematica easily: ![enter image description here](http://i.stack.imgur.com/ZZqmE.png) But when I try from .Net it fails: ![enter image description here](http://i.stack.imgur.com/FCJhQ.png) * * * These are the commands and errors I am getting:               xlData = Import[\"C://Users//138013//Desktop//RefinedDataset.xlsx\", {\"Sheets\", \"MySheet\"}]      > "Import::chtype: \r\n First argument > C://Users//138013//Desktop//RefinedDataset.xlsx\r\n is not a valid file, > directory, or URL specification."               xlData = Import[\"//Desktop//RefinedDataset.xlsx\", {\"Sheets\", \"MySheet\"}]      > "Import::nffil: File not found during Import." * * * I've done research and seen these articles but nothing shed light on why its an invalid file:   Importing from Excel   Open Excel file with Mathematica   http://reference.wolfram.com/mathematica/ref/format/XLS.html * * * Does someone know why `Import` is giving me a **is not a valid file** when the same command works in Mathematica and the file does exist and is valid?


title: How can I use FindRoot on an expression from NDSolve?

text: I have a second order ODE that I can only solve numerically using NDSolve, but I then need to use the solution in FindRoot and am running into errors. A simplified but analogous problem is the following: Find the solution to $\phi^{\prime\prime}(u) = -\omega^2 \phi(u)$ on the interval $0<u<1$ with the boundary conditions $\phi(0)=\phi(1)=0$, which will only be true for certain values of $\omega$ ($\omega=n\pi$ in this case). The code I am using is               eqnp = p''[ u] + ω^2 p[u];          psol[ω_?NumericQ] = NDSolve[{eqnp == 0, p[0] == 0, p[1] == 0}, p, u];          FindRoot[psol[ω], {ω, 3}]      but I am receiving errors. How can I feed a solution from NDSolve into FindRoot? I know that in the specific case above everything can be done analytically, but my actual ODE must be solved numerically, so I need to figure out how to solve this simplified problem completely numerically. EDIT: I have updated the post with the full problem. The ODE is both homogeneous and linear               λ = 0.00001; k = 1.0;     f[u_] := 1/(2λ u) (1-Sqrt[1-4λ+4λ u^2]);     A = Sqrt[1/2(1+Sqrt[1-4λ])];     K2[u_] := u^(-3/2)f[u](1 + 2λ u^2f'[u]);     K1[u_] := K2[u](4ω^2)/(A^2f[u]^2) - 4k^2u^(-1/2)(1 - λ(6u^2f'[u] + 4 u^3f''[u]));     eomu = 4u^3K2[u]ϕ''[u] + (6u^2K2[u] + 4u^3K2'[u])ϕ'[u] + K1[u]ϕ[u];      I define the boundary conditions at $u=1$ by finding the first few coefficients in the series solution (using normal Froebenius method). I then want to find the solution and use Dirichlet boundary conditions at $u=0$ to determine the eigenfrequencies. The first coefficient is $a1$ and the indicial exponent is $-\frac{I\omega}{2A}$ (the other solution to the indicial equation is unphysical and is discarded)               a1 = (k^2(1 + Sqrt[1 - 4λ])(1 + 8λ) + 2(-1 + 2λ)ω^2 + (I Sqrt[1 + Sqrt[1 - 4λ]] (12λ ω))/Sqrt[2])/(2Sqrt[2] Sqrt[1 + Sqrt[1 - 4λ]] (Sqrt[1 + Sqrt[1 - 4λ]]/Sqrt[2] - I ω))      (I have separate code to find an arbitrary number of coefficients, but to enter them here would be too much) Then define the solution to use as boundary conditions               ϕhnum[u_] := (1 - u)^(-I ω/(2A))(1 + a1(1 - u))     numh = 0.999999;     numb = 0.000001;      Then I use the code suggested by Jens               ϕsol[ω_?NumericQ] := ϕ /. First@NDSolve[{eomu == 0, ϕ[numh] == ϕhnum[numh], ϕ'[         numh] == ϕhnum'[numh]}, ϕ, {u, numb, numh}];          FindRoot[ϕsol[ω][numb], {ω, 1.0 - 1.0 I}]      When I do this I get the following error               FindRoot::lstol: The line search decreased the step size to within tolerance specified          by AccuracyGoal and PrecisionGoal but was unable to find a sufficient decrease in the      merit function. You may need more than MachinePrecision digits of working precision to      meet these tolerances. >>      I know that for the first solution I expect something like $\omega = 1.95- 1.27 I$. Hopefully this clarifies the problem, and thanks again for any help.


title: Convert spectral distribution to RGB color

text: Presume I have a spectrum as a function of wavelength (an example being the blackbody spectrum): ![enter image description here](http://i.stack.imgur.com/wG9zg.jpg) I want to convert that to a single RGB color to display on-screen, i.e. the "color" of that object as it would appear to the eye. From Googling I can see that there are ways to do this with a matrix transformation for a single wavelength, but I was hoping someone already had a solution coded up in Mathematica for an arbitrary input spectrum.


title: Interpolation function rejected by ParametricPlot3D

text: I was playing around with the bouncing ball example, and decided to make a 3d version. I decided to use `ParametricPlot3D` for a simple independent 3D presentation. However, I found that having an interpolating function as the the first element in the list of three functions passed to `ParametricPlot3D` doesn't work.               ballz = NDSolve[{z''[t] == -9.81, z[0] == 5, z'[0] == 0,     WhenEvent[z[t] == 0.2, z'[t] -> -0.9 z'[t]]}, z, {t, 0, 10}];          bally = NDSolve[{y''[t] == 0, y[0] == -2, y'[0] == 4,      WhenEvent[y[t] == 4.8, y'[t] -> -0.9 y'[t]],      WhenEvent[y[t] == -4.8, y'[t] -> -0.9 y'[t]]}, y, {t, 0, 10}];          Manipulate[       ParametricPlot3D[{t - 2, y[t] /. bally, z[t] /. ballz}, {t, 0, a},          PlotStyle -> {Gray, Dashed, Thick},          PlotRange -> {{-5, 5}, {-5, 5}, {0, 10}}],        {a, 0.025, 10, 0.025}]      The above code works fine, but when I substitute by an interpolation function for the `t - 2` term, the function doesn't work. Can this be fixed?


title: How to generate a unique file name similar as that created by CreateTemporary

text: CreateTemporary can generate a unique file name like > >     file = CreateTemporary[] >     (* "C:\Documents and Settings\kkouptsov\Local > \Settings\Temp\m-263a0380-3a03-49ac-95cb-d21390b2d3fd" *) >   How do we generate a unique file name such as above example? The reason I don't use CreateTemporary because I don't need to actually create the file, but only need the file path. I plan to generate many of these names in parallel, and they should be unique to each other.


title: How to simplify power series in terms of functions

text: For example, after some computations mathematica outputs $$ \sum_{k=0}^{\infty} \frac{k g_k z^{k+4}}{(1-z)^3} $$ and we assume that $$G(z)= \sum_{k=0}^{\infty} g_k z^k $$ so the question is: how to force mathematica to simplify the first sum into the form $$ \frac{z^5}{(1-z)^3} G'(z) $$ **Edit** : In fact, the sequence `g[k]` and its generating function `G[z]` are unknown and I would keep them in a symbolic way. So the _Mathematica_ code could look like this:               G[z_] := Sum[g[k]*z^k, {k, 0, \[Infinity]}]     Some_function[Sum[k*g[k]*z^{k + 4}/(1 - z)^3, {k, 0, \[Infinity]}]]      > >     z^5/(1-z)^3 G'[z] >   I mean, after defining function `G[z]` (maybe it should be defined in some other way), one can use `Some_function` to transform some series into the formula that operates on the function `G[z]`. So the question is how to write such `Some_function`? I hope that clarify the problem.


title: Do any mainstream text editors support Wolfram Language syntax for highlighting?

text: Syntax Highlighting for Mathematica on a Blog There is the above, but I'm not terribly excited to install rogue packages. For example on github, I share lots of _Mathematica_ code. I see no way to highlight syntax. This may keep _Wolfram_ down in the way of becoming a more often used and more robust programming language. If the answer is, as I suspect, _"no"_ , perhaps a better question is _"why not?"_


title: Increase Size of InputForm in Manipulate

text: I would like to set a variable equal to a copy n' pasted list, all within the Manipulate[] environment:                Manipulate[list,{list,0}]      I would like to view and edit the elements of the list within the input field. The problem is the "white space" is not long enough to view the entire pasted list. How can I make the input field larger, as if I were entering in a paragraph of text?


title: FindRoot for numerical function and how to search more than one root

text: I have to find the first few zeros of function for which I have not the analitycal expression. The function is named `f` in the following code and it is the result of a combination of solution of differential equation. (I have attach its plot ). I tried with `FindRoots` and I tried to follow this post but I've not solved my problem...               ti = 0;     u = 8;     yi = 0;     zi = -.75;     zf = -.5;          sol = FullSimplify[DSolve[{y'[t] == 1/(2 zf) y[t] - u z[t],       z'[t] == -1 + 1/zf z[t] + u y[t], y[ti] == yi,       z[ti] == zi}, {y[t], z[t]}, t]];          {{ysol[t_], zsol[t_]}} = Simplify[{y[t], z[t]} /. sol,       Assumptions -> Element[u, Reals] && Element[zi, Reals] && t > 0];          {{Gy[t_], Gz[t_]}} = {-z[t], y[t]} /. sol;          soladj = DSolve[{vy'[t] == 1/(2 zf) vy[t] - u vz[t],       vz'[t] == -1 + 1/zf vz[t] + u vy[t], vy[T] == Gy[T],       vz[T] == Gz[T]}, {vy[t], vz[t]}, t];          {{VY[t_], VZ[t_]}} = {vy[t], vz[t]} /. soladj;          f[T0_?NumericQ] := ArcTan @@ First@RotationMatrix[{{VY[0], VZ[0]},      {Gy[0],Gz[0]}} /. T -> T0]          plotf = Plot[f[T0], {T0, 0, 4}, PlotRange -> Full, MaxRecursion ->15,      LabelStyle -> {FontSize -> 15}]      ![plotf](http://i.stack.imgur.com/dUcSI.jpg)


title: Why are some function names red?

text: I need to evaluate               Needs["GraphUtilities`"]      before I can use functions such as `GraphPath[]`. When I do so, some functions get colored red, but still work. Why does this happen and can I change this?


title: Is it possible to create iOS apps with Mathematica?

text: I am fairly new to Mathematica and don't have much experience with other programming languages, but I can already see that Mathematica and the Wolfram language are far easier to use than most others. With this in mind, I was wondering about the possibility of building apps for iPhone and iPod through Mathematica. Basically is it at all possible to use Mathematica to build apps? Even if it isn't possible to use Mathematica for iOS app development, what about using it to build programs for other platforms, like Windows, Macs, or browser programs? I've heard a bit about MathLink and Workbench but I don't really understand what they do or how to use them. Also i understand that the Wolfram Cloud will be launched soon but don't know what it will enable us to do. I would appreciate it if someone could give me a brief answer, or point me in the right direction.


title: How to find all possible correlations between n vectors

text: Given the Matrix               M = {{31.3, 31.2, 29.7, 29.7, 29.8, 29.2, 28.7, 28.3, 28.2, 28.2},        {31.7, 30.7, 30.7, 30.1, 30.2, 29.8, 29.2, 28.7, 28.5, 27.7},        {24.0, 24.2, 23.7, 23.7, 23.2, 23.1, 22.6, 22.2, 22.1, 21.7},        {23.2, 22.2, 22.2, 22.0, 22.2, 21.8, 19.5, 19.1, 19.1, 18.9}};      I want to get a list of all possible correlations between its vectors. With               x1 = Take[#, 2] & /@ Permutations[Range@Length@M];      And               x2 = Union@Cases[x1, {a_, b_} /; a < b];      I get the necessary permutation:               {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}      Finally, with               Correlation @@@ Partition[M[[Flatten@x2]], 2]      I get the desired result:               {0.923, 0.933, 0.893, 0.952, 0.946, 0.934}      I am, of course, not happy with this code and would wellcome any suggestion how one could write this succinctly.


title: Specify column width while exporting

text: I am trying to export a set of data into a file but I can not force mathematica to keep a certain width for each column. For example, when I export a table:               table={{10,2},{3,40}};     Export["file.dat",table, "Table", "FieldSeparators"->" ", Alignment->Right]      The result is:               10  2      2 40      Mathematica automatically determines column width such that the number with largest number of digits fits in. How can I export data with arbitrary space in each column to get:                10    2       2   40      such that `"FieldSeparators"->" "` is still the same but first column has space for three digits and the second one has space for 4 digits?


title: Programmatically copy code so that all output is commented out

text: **UPDATE: The final palette has a new homehere! Please test and provide feedback (usability, suggestions, bugs)** **A note to the readers and voters:** This is intended for community use, so please test the palettes in practice! I encourage all answerers to "steal" from each others, and come up with a solution that is the most pleasant / practical to use. * * * Sjoerd suggested that when we want to post input lines that alternate with output lines, instead of including the In/Out labels, we could simply comment out the output. Read his suggestion here:   * How should I include code samples in posts? I have seen several people use this style in the past few days. The only problem with it that it requires a lot of manual editing (too much work for my taste). How can we automate this process? **The challenge is:** Create a palette button that will copy the selection in the format suggested by Sjoerd. Two-dimensional expressions (i.e. things like $\int x^2 \; dx$) should be converted to plain text or input form. The notebook contents must not be modified/destroyed. An example (directly copied from Sjoerd's post):               In[108]:= D[Cos[x] Exp[x], x]     Out[108]= E^x Cos[x] - E^x Sin[x]      should be copied as               D[Cos[x] Exp[x], x]          (*       ===> E^x Cos[x] - E^x Sin[x]     *)      Let us ignore cells that are neither input nor output for now (text, headings, etc.) Can we create a tool that is good enough to be of practical use to the community?


title: Arnold's problem #8

text: The famous Arnold's problems (see http://www.math.upenn.edu/Arnold/Arnold- Trivium-1991.pdf ) are aimed at the strong graduate and postgraduate students of the top universities. I find it remarkable that a big part of the Arnold's problems can be solved with CASes. However, I have not seen any satisfactory solution of his problem #8: "How many maxima, minima, and saddle points does the function $ x^4+y^4+z^4+u^4+t^4 $ have on the surface $$ \{x+y+z+u+t=0,x^2+y^2+z^2+u^2+t^2=1,x^3+y^3+z^3+u^3+t^3=c\} ,$$ where $c$ is a real parameter?" Can it be solved with Mathematica?


title: How to use NDSolve to track equilibrium?

text: I am looking for an extension of `NDSolve` where integration runs until certain variables are settled at an equilibrium. Now I have a working solution in my sleeves but I would rather not show it yet, as I want answers to be unbiased and original, since I'm not convinced that my solution is optimal at all. Consider the following putative example (note that `EquilibriumNDSolve` is an undefined hypothetical function):               eqns = {        Derivative[1][a][t] == -a[t] - 0.2` a[t]^2 + 2.1` b[t],        Derivative[1][b][t] == a[t] + 0.1` a[t]^2 - 1.1` b[t],        a[0] == 0.5`,        b[0] == 0.5`        };          steps = {};          sol = EquilibriumNDSolve[eqns, {a, b}, {t, 0, 1000}, a + b,         EquilibriumThreshold -> 10^-5,         EquilibriumStepMonitor :> AppendTo[steps, t]        ];      This reads as: "numerically solve _eqns_ for _a_ and _b_ variables while _t_ goes from 0, until ( _a_ + _b_ ) is settled at an equilibrium. If no equilibrium is reached until _t_ = 1000", terminate. The solution should be a set of `{y.i -> InterpolatingFunction[...]}` (just like in case of `NDSolve`), and the result should be something like this:               Plot[Evaluate[{a[t], b[t]} /. sol], {t, 0, Last[steps]},       PlotStyle -> AbsoluteThickness[2], ImageSize -> 400,       GridLines -> {steps, {}}, GridLinesStyle -> {Dashed, GrayLevel[.7]}]      ![Mathematica graphics](http://i.stack.imgur.com/uyAsE.png) Vertical gridlines indicate positions where an equilibrium test was performed. The syntax and usage should vaguely work like this: > `EquilibriumNDSolve[eqns, {y1, y2, ...}, {t, t0, tmax}, z}]` numerically > solves the differential equation system _eqns_ for all variables $y_i$, with > independent variable _t_ running from $t_0$ to a maximum of $t_{max}$. > Iteration stops when variable _z_ settles at an equilibrium or no > equilibrium was found in the given range of _t_. Variable _z_ can be a > single variable, a list of variables, or any sensible combination of them, > e.g. $a+b$. `EquilibriumThreshold` should define a threshold value above which no equilibrium is registered. `EquilibriumStepMonitor` should work like `StepMonitor`: each time an equilibrium-test is performed, the _rhs_ of `EquilibriumStepMonitor :> func` is evaluated as well.


title: Template completion

text: In version 8, if one evaluates               test::usage="test[x,y]";      then types `test`, then `shift`-`cmd`-`k` (or `shift`-`ctrl`-`k`), a template appears with placeholders for `x` and `y`. In version 9, this does not work: if I evaluate the same thing, when I type `te`, I am offered the choice to select `test` from the dropdown menu, just like for the built-in functions. If I select `test` and then press `shift`-`cmd`, however, I do not get the template (whereas I do get a template for built-in functions if I do this). How do I get the frontend to show a template? # Note: This has been fixed as of 9.0.1


title: Color Change of Area under a curve

text: I am trying to set a graph to show the value of the equity of an investment based on whether the portfolio is invested or in cash. I tried using the `ColorFunction`, but was not successful. Here is the sample data.               colorCash = RGBColor[90/255, 180/255, 172/255];     colorInvested = RGBColor[216/255, 179/255, 101/255];     invested = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1,                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,                 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,                 0, 1, 0, 0, 0, 0};          period = {        {2005, 7, 1}, {2005, 8, 1}, {2005, 9, 1}, {2005, 10, 3}, {2005, 11, 1}, {2005, 12, 1},        {2006, 1, 3}, {2006, 2, 1}, {2006, 3, 1}, {2006, 4, 3}, {2006, 5, 1}, {2006, 6, 1},        {2006, 7, 3}, {2006, 8, 1}, {2006, 9, 1}, {2006, 10, 2}, {2006, 11, 1}, {2006, 12, 1},        {2007, 1, 3}, {2007, 2, 1}, {2007, 3, 1}, {2007, 4, 2}, {2007, 5, 1}, {2007, 6, 1},        {2007, 7, 2}, {2007, 8, 1}, {2007, 9, 4}, {2007, 10, 1}, {2007, 11, 1}, {2007, 12, 3},        {2008, 1, 2}, {2008, 2, 1}, {2008, 3, 3}, {2008, 4, 1}, {2008, 5, 1}, {2008, 6, 2},        {2008, 7, 1}, {2008, 8, 1}, {2008, 9, 2}, {2008, 10, 1}, {2008, 11, 3}, {2008, 12, 1},        {2009, 1, 2}, {2009, 2, 2}, {2009, 3, 2}, {2009, 4, 1}, {2009, 5, 1}, {2009, 6, 1},        {2009, 7, 1}, {2009, 8, 3}, {2009, 9, 1}, {2009, 10, 1}, {2009, 11, 2}, {2009, 12, 1},        {2010, 1, 4}, {2010, 2, 1}, {2010, 3, 1}, {2010, 4, 1}, {2010, 5, 3}, {2010, 6, 1},        {2010, 7, 1}, {2010, 8, 2}, {2010, 9, 1}, {2010, 10, 1}, {2010, 11, 1}, {2010, 12, 1},        {2011, 1, 3}, {2011, 2, 1}, {2011, 3, 1}, {2011, 4, 1}, {2011, 5, 2}, {2011, 6, 1},        {2011, 7, 1}, {2011, 8, 1}, {2011, 9, 1}, {2011, 10, 3}, {2011, 11, 1}, {2011, 12, 1},        {2012, 1, 3}, {2012, 2, 1}, {2012, 3, 1}, {2012, 4, 2}, {2012, 5, 1}, {2012, 6, 1}};          equity = {100, 100, 100, 107.60368663594471, 106.91244239631337, 113.13364055299542,               118.84792626728114, 130.6451612903226, 129.19354838709677, 133.8709677419355,               149.97695852534562, 147.99539170506912, 141.08294930875573, 145.52995391705065,        143.52534562211977, 137.02764976958522, 137.02764976958522, 137.02764976958522,        134.51650476681908, 137.964008923159, 141.4753557490608, 139.9005698998685,        142.77349003015175, 139.47495210278947, 136.77227909133777, 136.77227909133777,        138.2898921592307, 152.82155701480832, 163.44484849005894, 160.74224987600297,        171.42790901157795, 190.01347178823949, 199.95071899992203, 187.95533899753534,        180.13859223688132, 181.8017298455311, 190.01347178823949, 187.2692947339673,        187.2692947339673, 187.2692947339673, 187.2692947339673, 187.2692947339673,        187.2692947339673, 197.63707006655756, 200.49416055487052, 195.407673700677,        188.89264160232702, 208.22129164826242, 197.3556899427086, 202.0525735484958,        202.16079667305314, 213.9571172497998, 221.92233921721777, 250.29844247614417,        232.26846992489646, 229.34644556184912, 236.85713040612634, 235.8181884103762,        249.69239297862313, 257.3113009474577, 263.37179592266705, 249.97377310247217,        264.2375809191255, 276.85639724250774, 287.0510155758062, 293.1115105510154,        300.2542367717978, 281.0987437251542, 297.95990653118287, 302.7217240117045,        329.79914977594314, 323.8901671751141, 316.011523707342, 342.6127677235285,        384.66827392649884, 342.11494135056495, 362.2011532684015, 368.24000361869935,        328.9766540293077, 328.9766540293077, 319.22257687363395, 319.22257687363395,        319.22257687363395, 319.22257687363395};      The following charts show the value of the portfolio and whether I am an investor or not:               Column[{             DateListPlot[Transpose[{period, equity}], Filling -> Axis,                Joined -> True, ImageSize -> Large],              DateListPlot[Transpose[{period, invested}], Filling -> Axis,                ImageSize -> Large]     }]      This is what I tried to change the color, but it is not the correct thing to do as the period painted does not coincide with the investment period:               myColor = If[# == 1, colorInvested, colorCash] & /@ invested;          DateListPlot[Transpose[{period, equity}], Filling -> Axis,       Joined -> True, ColorFunction -> myColor, ImageSize -> Large]


title: Installing CRAN Packages

text: When I install `RLink`:               Needs["RLink`"]     InstallR[]      then evaluate the command               REvaluate["R.version.string"]      I see that it is running               {"R version 2.14.0 (2011-10-31)"}      a version which I did not intentionally install on my system. I believe that _Mathematica_ downloaded this itself. Now I wish to install packages. For example:               REvaluate["install.packages('LaplacesDemon')"]      yields               REvaluate::err:      General error in function RLink`Private`withRTemporaryVariables >>      Is it possible to install packages with _Mathematica_ 's version of R? Even a command line solution would be great. EDIT: It seems that the error above was an aberration. It stopped showing up after I restarted Mathematica. Following Sasha's advice, I tried to add a repository:               REvaluate["install.packages('LaplacesDemon', repos='http://cran.wustl.edu/')"]      and the error is equally as bad:               REvaluate::rerr: Failed to retrieve the value for variable or piece of code     install.packages('LaplacesDemon', repos='http://cran.wustl.edu/'.      The following R error was encountered: Error in typeof(myRandomVar123456759046) :     object 'myRandomVar123456759046' not found >>      Similar errors for ggplot2, Zelig, etc. There appears to be a whole R tree in               $HomeDirectory/Library/Mathematica/Paclets/Repository/RLinkRuntime-MacOSX-x86-64-9.0.0.0/SystemFiles/MacOSX-x86-64/R/library      but the R version there doesn't seem to be usable.


title: Using a different R version with RLink

text: I wish to use a different version of R than what is provided by _Mathematica_ 9. For example, I want to use the Macports version of R, where `R_HOME` is `/opt/local/lib/R`. When I type:               Needs["RLink`"]     InstallR["RHomeLocation" -> "/opt/local/lib/R"]      I get the error:               InstallR::fail: Failed to install R.      The following error was encountered: Unable to load dynamic libraries >>      (I tried to doctor up my `~/.MacOSX/environment.plist` with `DYLD_LIBRARY_PATH`, but no luck.)


title: How to choose variables from a list for a function and then use the solution in a subsequent function?

text: I am trying to calculate heating degree days and cooling degree days and output that information to a table. I am using mathematica's curated data to do this. In text this is what I would like to do. Use a city name to collect weather data (the mean temp for every day of a certain year), then calculate the HDD and CDD and to create a cumulative value of hdd and cdd for the entire year. I want to use the city name to collect a value for country name, country gdp, and city population. I have used a demonstration project to try and figure this out but I am stuck at this point. I have the following already worked out.               Module[      {dateRange, mean, cdd, hdd, station, country, location, population,        GDPPerCapita,       reference = (65 - 32)/1.8, cumList},      station = "Chicago";      country = CityData[station, "Country"];      population = CityData[station, "Population"];      location = CityData[station, "Coordinates"];      GDPPerCapita = CountryData[country, "GDPPerCapita"];      dateRange = {{2011, 1, 1}, {2011, 12, 31}, "Day"};      mean = WeatherData[station, "MeanTemperature", dateRange];      cdd = Join[Transpose[{mean[[All, 1]]}],         Transpose[{Max[# - reference, 0] & /@ mean[[All, 2]]}], 2];      hdd = Join[Transpose[{mean[[All, 1]]}],         Transpose[{Max[reference - #, 0] & /@ mean[[All, 2]]}], 2];      cumList = Transpose[{Join[          Transpose[{cdd[[All, 1]]}],          Transpose[{Drop[FoldList[Plus, 0, cdd[[All, 2]] + hdd[[All, 2]]],              1]}],          2]}];      Grid[station, country, location, population, GDPPerCapita,        Last[cumList]]]      In this particular example I used a set city name ie station = "Chicago". When I do this it returns the correct result for that specific city, in a grid in this case..               Grid["Chicago", "UnitedStates", {41.8376, -87.6818}, 2695598,        45230.2, {{{2011, 12, 31}, 3935.4}}]      I want the variables to be chosen from a list of cities....               cityLIST = CityData[#, "Name"] & /@ CityData[];      So basically I want to run this or something like it for every string in a list, and output the results to a table. I am new to mathematica, this is the first thing I have ever tried. If anyone has a minute to help me out with this I would really appreciate it. Thanks


title: Symbol not added to context

text: I have run into a problem that is currently stumping me. I'm running a WebMathematica server, and am trying to create a package to use on one of the pages. However, when I load the package, it appears to only load some of the public functions, and loads the rest of the public functions as belonging to the Private page, and the functions in the Private functions that are not revealed don't seem to be loaded at all. I'm including the entirety of the code here, because I honestly can't tell where my mistake could be... (I should note that this is running on Mathematica 5.2)               BeginPackage["UtilitiesTest`"]          revToIrrev::usage = "Takes a reaction string,          and if it is a reversible reaction returns a list         in the form {forward, backward}         Otherwise, it returns the reaction.";          getSpecies::usage = "Takes a reaction and         returns a list containing every species within that reaction.";          isValidRxnStr::usage = "Takes a reaction and         returns true if the reaction is correctly formatted.";          replaceWithVars::usage ="test";          getRxnSide::usage = "Test2";          generateVars::usage = "Generates a list of {species, variable}          pairs.";          Begin["`Private`"]               generateVars[specs_] := Module[{specList = specs},         specList = specList /. spec_ -> {spec, "Elem"};         Return[Table[{specList[[1]], Append[specList[[2]], i]}, {i, specList//Length}]];         ];          replaceWithVars[exprStr_, vars_] := Module[{repExpr = exprStr, varList = vars, repRules},         repRules = Table[{varList[[i,1]]->varList[[i,2]]}, {i, varList//Length}];         Return[StringReplace[repExpr, repRules]];          ];          replaceVars[expr_, vars_] := Module[{repExprStr = expr, varList = vars, repRules},         repRules = Table[{varList[[i,2]]->varList[[i,1]]}, {1, varList//Length}];         Return[StringReplace[repExprStr, repRules]];         ];          revToIrrev[rxn_] := Module[{rxnParser},         rxnParser[react__ ~~ "" ~~ prod__] := Module[{},                     Return[{react  ">"  prod, prod  ">"  react}];];         rxnParser[react__] := Module[{}, Return[react]];         Return[{rxnParser[rxn]}];         ];          getIrrevRxnList[rxns_, seperator_:"|"] := Module[{splitRxns},         splitRxns = StringSplit[rxns, seperator];         Return[Flatten[Map[revToIrrev, splitRxns]]];         ];          getSpecies[rxn_] := Return[Union[getReactants[rxn], getProducts[rxn]]];           getRxnSide[front__ ~~ "" ~~ back__, "front"] := Return[front];     getRxnSide[front__ ~~ "" ~~ back__, "back"] := Return[back];     getRxnSide[Except[__ ~~ "" ~~ __, front__ ~~ ">" ~~ back__], "front"] := Return[front];     getRxnSide[Except[__ ~~ "" ~~ __, front__ ~~ ">" ~~ back__], "back"] := Return[back];          getSumSpeciesWithCoeffs[sum_] := Return[StringSplit[sum, "+"]];          getSpeciesWithCoeffs[rxn_, type_] := Module[{rxnString = rxn, specString, specs},         specString = getRxnSide[rxnString, type];         specs = getSumSpeciesWithCoeffs[specString];              Return[specs];         ];          splitCoeff[coeff:(NumberString||"") ~~ spec:(LetterCharacter ~~ WordCharacter...)] :=         If[coeff === "", Return[{1, spec}], Return[{ToExpression[coeff], spec}]];          getReactantsWithCoeffs[rxn_] := Return[Map[splitCoeff, getSpeciesWithCoeffs[rxn, "front"]]];          getProductsWithCoeffs[rxn_] := Return[Map[splitCoeff, getSpeciesWithCoeffs[rxn, "back"]]];          getReactants[rxn_] := Return[Map[getSpec, getSpeciesWithCoeffs[rxn, "front"]]];           getProducts[rxn_] := Return[Map[getSpec, getSpeciesWithCoeffs[rxn, "back"]]];          getSpecPattern[] := Return[NumberString|"" ~~ LetterCharacter ~~  WordCharacter...];     getSpecPattern[spec_] := Return[NumberString ~~ spec];     getSpec[specStr_] := Module[{spec},         specStr /. ((NumberString|"") ~~ spec: (LetterCharacter ~~ WordCharacter...)) -> spec;              Return[spec];         ];           getSidePattern[spec_:getSpecPattern[]] := Module[{speciesPat, sidePat},         speciesPat = getSpecPattern[];         sidePat = (speciesPat ~~ "+")...~~ getSpecPattern[spec] ~~("+" ~~ speciesPat)...;                 Return[sidePat[]];         ];          isValidRxnStr[rxn_] := Module[{sidePat, posPat},         sidePat = getSidePattern[];         posPat = sidePat ~~ (""|">") ~~ sidePat;               Return[StringMatchQ[rxn, posPat]];         ];            removeInvalidRxns[rxns_] := Module[{rxnList = rxns, goodPos},         goodPos = Position[rxnList, {_?isValidRxnStr,_NumberString,(_NumberString)|NULL}];         rxnList = Extract[rxnList, goodPos];               Return[rxnList];         ];          isReactant[rxn_, spec_] := Module[{fullPat},         fullPat = getSidePattern[spec] ~~ (""|">") ~~ getSidePattern[];              Return[StringMatchQ[rxn, fullPat]];         ];          isProduct[rxn_, spec_] := Module[{fullPat},         fullPat = getSidePattern[] ~~ (""|">") ~~ getSidePattern[spec];              Return[StringMatchQ[rxn, fullPat]];         ];                decomposeRxnInfo[rxns_] := Module[{rxnList = rxns, parseRxn},          rxnList = removeInvalidRxns[rxnList];         rxnList = Flatten[Map[revToIrrev, rxnList]];              Return[NULL];            ];      End[]     EndPackage[]                In the webMathematica page I have the following (The msp:evaluate tags seem to get hidden, but each line is enclosed by them:                    Needs["UtilitiesTest`"]                    ?UtilitiesTest`*           The output from loading this page is               General KernelData0::      getSpecies     isValidRxnStr     revToIrrev      If I change ?UtilitiesTest to ?UtilitiesTest`Private The output is               General KernelData0::      UtilitiesTest`Private`generateVars


title: Changing BarLegend border style

text: I want all the lines in my plot to be a consistent style, let's say thick and black for the purpose of this question.               ContourPlot[y - x^2, {x, 0, 1}, {y, 0, 1},      ContourStyle -> Directive[Thick, Black, Opacity[1]],       FrameStyle -> Directive[Thick, Black],      PlotLegends -> BarLegend[Automatic]]      ![enter image description here](http://i.stack.imgur.com/h0YqV.png) However, the border of the legend bar is thin and grey. How do I change its style to match? I couldn't find any relevant options in the `BarLegend` documentation.


title: EstimatedProcess hangs with documentation example

text: Not sure if this is a bug or a typo but for the first example of the `ARMAProcess` in _Mathematica_ 9 we have:               data = Select[WeatherData["Champaign", "Temperature", {2012, 8}],                    FreeQ[#, Missing] &][[All, 2]];     temp = TemporalData[data]     eproc = EstimatedProcess[temp, ARMAProcess[3, 3]]      `EstimatedProcess` hangs, whereas if I just send the data (with `RLink`!) to R's `arima` solver (with `order=c(3,0,3)` so it is an ARMA model), it solves instantly, and all further analysis looks the same as the example, so it isn't given a bad solution or anything. Is there something wrong with the documentation (reminds me of the issues of trying to do optimization without using `?NumericQ` variables). Any thoughts? Really want to use this feature...


title: Why DateDifference returns machine number?

text: Is there any specific reason why `DateDifference` cannot give an exact number in this case?               DateDifference["Jan 2, 2013", "Jan 8, 2013", "Week"]      > 0.857143 Also, I'd like to know how the various `DayCountConvention` settings interact with the calculation, in particular for "Week", "Month", etc.


title: Drawing an implicit function using ListPlot with a constraint on the solution

text: I need to plot a complex implicit function, `ContourPlot` in this case is not very convenient for me. Therefore, I want to plot my function using discrete points. I think this simple approach is convenient, both for me to understand and for those who I want to help. So let's plot the unit circle using `ListPlot`. I can do it in this way (I'm sure there is much simpler way):               y[x_] := y /. FindRoot[x^2 + y^2 == 1, {y, 0.01}]     data = Table[{x, y[x]}, {x, -1, 1, 0.1}]     y2[x_] := y2 /. FindRoot[x^2 + y2^2 == 1, {y2, -0.01}]     data2 = Table[{x, y2[x]}, {x, -1, 1, 0.1}]     ListPlot[{data, data2}, PlotStyle -> {Black, Black}, AspectRatio -> 1]      Now I want to set constraint on the solution of y, say `y < 0.5`. How could I do this by using `Select`?


title: Display Log with desired notation in output

text: I wish to display logarithms with different bases in the single-term rather than numerator/denominator form during output:               Log[17]/Log[2]   ->  Log2[17]     Log[13]/Log[10]  ->  Log10[13]     Log[99]/Log[11]  ->  Log[11, 99]      What is the best way to apply formatting rules like this?


title: Check every list element for appearance

text: I'm used to _MATLAB_ so this might be a stupid question but _Mathematica_ is freaking me out. I have a big matrix with the following format:               M = {{A,B,C},{1,{1,3,6,7},0},{1,{3,7,9},1}}      As you can see, each element in the second column is a separate list again. These separate lists contain integers, so it's no problem to get back to them. For example if I use `MemberQ[M[[2,2]],1]` it returns `True`, as it's supposed to do. What I want to do now: my Matrix is a little longer, contains approx. 5'000 rows. I want to check every seperate list mentioned above for the appearance of a specific integer, as I did above with the `MemberQ`. As a result it should give me something like the following (taking `M` as example): `{True,False}`. I thought that's supposed to be easy with a for-loop as it is in _MATLAB_ , but _Mathematica_ always stops when condition is not met... Looking forward to your answers. Please state if I need to clarify my question!


title: Differences between 'Solve' and 'LinearSolve'

text: Using the function 'Solve' I can do the following: Solve[a x + y == 7 && b x - y == 1, {x, y}] I get the following output: ![enter image description here](http://i.stack.imgur.com/n5myu.jpg) I want to get the same output using 'LinearSolve' instead. How is this possible and also what's the difference between the two?


title: Cannot find the maximum value of a function

text: Consider the following function: $a Sin(x)+b Cos(x)$ I tried to obtain the maximum value of this function using `MaxValue[]`:               MaxValue[a Sin[x] + b Cos[x], x, Reals]      I expect _Mathematica_ to return the following answer: $\sqrt{a^2+b^2}$ But _Mathematica_ cannot find the answer. Why does this happen?


title: Strange behavior of DateList when converting string

text: DateList experiences some strange behavior which i cannot explain. This code works fine:               DateList[{"2012September1211:45:26", {"Year", "MonthName", "Day",         "Hour", ":", "Minute", ":", "Second"}}]      Returning               {2012, 9, 12, 11, 45, 26.}      But this code doesn't work:               DateList[{"2012October1211:45:26", {"Year", "MonthName", "Day",         "Hour", ":", "Minute", ":", "Second"}}]      Returning this error message: > DateString::str: String 2012October1211:45:26 cannot be interpreted as a > date in format {Year,MonthName,Day,Hour,:,Minute,:,Second}. >> The only thing i changed is the month from september to october. Really frustrating, i'm already staring at it for 2 hours... **Question: What am i doing wrong?**


title: Smooth Peter de Jong attractor

text: Today I was playing with Peter de Jong attractor. At the bottom of the page I've linked there are beautiful examples like: ![enter image description here](http://i.stack.imgur.com/R4Eg6.jpg) My attempts are not so great: ![enter image description here](http://i.stack.imgur.com/sX0Fa.png) **It is around 10^5 points. For more than 5*10^5 my 4GB RAM gives up. How can I achieve such smooth result on standard/oldish pc?** * * * Here is the piece of code to play with: Points generator:               fr2 = Compile[{{p, _Real, 1}, {n, _Integer}, {a, _Real, 1}, {b, _Real, 1},                    {c, _Real, 1}},        NestList[         { Sin[a[[1]] #[[2]]] - Cos[a[[2]] #[[1]]],           Sin[b[[1]] #[[1]]] - Cos[b[[2]] #[[2]]],           Sin[c[[1]] #[[1]]] - Cos[c[[2]] #[[1]]]           } &, p, n]];      Interactive toy: For printed color image I've used approach introduced by Szabolcs in antialiasing3D.               DynamicModule[{a, b, c, n, type, fig, controls, print},      Deploy@Dynamic[Refresh[         Panel@Grid[{{fig, controls}}, Spacings -> 2],         None]],           Initialization :> (        type = 1;        n = 100000;        {a, b, c} = {{1.4, -2.3}, {2.4, -2.1}, {2.41, 1.64}};             controls = Column[{           Slider2D[Dynamic@a, {-Pi, Pi, .01}], Dynamic@a,           Slider2D[Dynamic@b, {-Pi, Pi, .01}], Dynamic@b,           Slider2D[Dynamic@c, {-Pi, Pi, .01}], Dynamic@c,           Button["Print", print[], Method -> "Queued"] }];             fig = Graphics[{White, AbsolutePointSize@1,            Dynamic[            Point@fr2[{.0, .0, .0}, ControlActive[2 10^4, 10^5], a, b, c][[All , ;; 2]]]           }, ImageSize -> {1, 1} 500, Background -> Black, AspectRatio -> Automatic];             print[] := With[{t = 3, pointsize = 1, pts = 10^5, res = 72},          Composition[            CreateDocument,            ImageResize[Rasterize[#, "Image", ImageResolution -> t res], Scaled[1/t]] &,            Graphics[{AbsolutePointSize@pointsize,                Riffle[Hue@Rescale[#, {-2, 2}, {0, 1}] & /@ #[[;; , 3]],                   Point /@ #[[;; , ;; 2]]] &@#               }, ImageSize -> 800, Background -> Black] &            ][fr2[{.0, .0, .0}, pts, a, b, c]]];        )]      ![enter image description here](http://i.stack.imgur.com/RG401.png)