title: random split a dataset

text: I've got a very simple problem, but not so trivial. I need to split a dataset (input and output data) in three part randomly: training set 70%, validation set 20% and is test set 10%. First of all this splitting have to be random, but reproducible, so I set SeedRandom. So I produce this simple code to split in two part (70% and 30%), but I've some problem to split in three part (70%, 20% and 10%). input is a matrix and oputput a list of numbers, for example:               input= {{0.688217, 0.362944, 0.468409, 0.133651}, {0.746246, 0.365313,      0.661147, 0.124928}, {0.688217, 0.362944, 0.892652,      0.133651}, {0.736027, 0.327411, 0.429482, 0.138367}, {0.765381,      0.390355, 0.81139, 0.148402}, {0.869656, 0.485533, 0.851523,      0.200265}, {0.757873, 0.412183, 0.573253, 0.174008}, {0.64025,      0.323266, 0.477443, 0.1111}, {0.648592, 0.327327, 0.614614,      0.115339}, {0.993743, 0.701184, 0.71341, 0.290435}, {0.763712,      0.542893, 0.685418, 0.22885}};          output={0.707695, 0.641002, 0.576708, 0.514697, 0.454514, 0.395702,      0.338031, 0.280931, 0.224174,0.1211,0.23234};          SeedRandom[1234];     index = RandomSample[Range[Length[input]], IntegerPart[Length[input]*0.3]];     indexp = Partition[index, 1];     inputv = {};     outputv = {};     (*Validation TEST*)     inputv = Table[Append[inputv, input[[i]]], {i, index}];     outputv = Table[Append[outputv, output[[i]]], {i, index}];     (*Test TEST*)     inputt = Delete[input, indexp];     outputt = Delete[output, indexp];          inputv = Flatten[inputv, 1];     outputv = Flatten[outputv];      Could you help me? Thanks...


title: Build recursion in parallel?

text: _Problem_ Let's define a simple recursion.               f[1] = 1;     f[n_] := f[n] = f[n - 1]*n;      If I evaluate f in parallel               ParallelTable[f[i], {i, 10}];      and then query f               ?f     Global`f     f[1]=1     f[n_]:=f[n]=f[n-1] n      _Question_ How can I tell the sub kernels to build up the recursion, so that               ?f          Global`f          f[1]=1     ....     f[10]=3628800          f[n_]:=f[n]=f[n-1] n      Thanks ! PS: of course the actual function is not that trivial.


title: Mathematica8 can compile this function but Mathematica 9 can't if I set CompilationTarget -> "C"

text: Following code worked on Mathematica 8, but in Mathematica 9 it can't be compiled, it return this message > CompiledFunction::cflist: Nontensor object generated; proceeding with > uncompiled evaluation. >> How can I fix this?               Clear[cf1];     cf1 = Compile[{},        Module[{s = 0.0},         Do[           If[s > 15, Print@i; Break[]];           s = s + 1.0/i;           , {i, 10^7}];         ], CompilationTarget -> "C"];          cf1[]


title: Point-like function but with diamond instead of circle

text: I would like to use something like `Point[x,y]` to plot diamonds instead of small circles ("points"). I'm creating charts from scratch inside a `Graphics` expression using my own graphics functions. I've looked through the documentation and questions here and haven't found anything about how to do it.


title: splitting a list into files

text: Given is a list with x, y, z coordinates: > {{100, 94, -1.112}, {100.05, 94, -1.112}, {100.1, 94, -0.982}, ..., {100, > 94.25, -1.112}, {100.05, 94.25, -0.855}, {100.1, 94.25, -0.728}, ..., > {139.95, 114.75, 1.184},{140, 114.75, 1.184}} I want to split this list into files with y = constant, y should moreover form the name of the new file (see the code below) and only the (x, z) values should be written into the file. Getting the name for the first file I use this code:               liste = ReadList[inffile, {Number, Number, Number}];     y = liste[[All, 2]];     fil = IntegerString[IntegerPart[First[y]*100], 10, 5];     newfile = ToString[fil] <> ".dat";     wfile = OpenWrite[newfile, FormatType -> TraditionalForm];      Which is the best way to extract now all (x,y,z) with the same y (y = 94) from this list, to write all of them into the new file, and to continue with the next new file with the next y-value (y = 94.25)? Thanks a lot


title: Custom contour labels in ContourPlot

text: Suppose I wanted to draw the zero contour for the function $$d^2-g.$$ I could use the following code:               ContourPlot[d^2-g,{g,0,1},{d,0,1},Contours->{0},                     ContourStyle->Black,ContourShading->None,FrameLabel->{"g","d"}]      Which produces this: ![contour plot](http://i.stack.imgur.com/ZvUY1.png) Taking this one step further, I might want to plot the zero contour for $$td^2-g.$$ at various values of $t$, which I could achieve functionally with               Show[Table[ContourPlot[t*d^2-g,{g,0,1},{d,0,1},Contours->{0},                ContourStyle->Black,ContourShading->None,FrameLabel->{"g","d"}],{t,0.1,1,0.1}]]      producing this: ![multi-contour plot](http://i.stack.imgur.com/zu9W4.png) Now, to make this easier to understand, I want to label each contour with its corresponding value of $t$, but this is where I run into trouble. I had thought that this could be achieved with the option               ContourLabels->t      but that yields this: ![enter image description here](http://i.stack.imgur.com/CGFlA.png) (it seems to have moved the labels rather than changing them). Does anyone know how to get Mathematica to draw a label equal to the relevant value of t on each of these contours? Secondly, assuming I can get that working, how can I reposition the labels towards the top of the contours so that they appear where the contours are furthest apart.


title: How to link a button to a manipulate play

text: I am wondering how I can link a button to the play button shown if you expand "Show Animation Control", So something like,               Manipulate[x, {x, 0, 1}, Row[{Button["Play", ImageSize -> 80]}]]      But where pushing the button "plays" x


title: solve non-linear system of equations

text: I have a system of equations and I want to solve it to get x, y $$\begin{cases} u= C_{1}+(x-C_{1})(1+k_{1}((x-C_{1})(x-C_{1})+(y-C_{2})(y-C_{2}))) \\\ \\\ v= C_{2}+(y-C_{2})(1+k_{2}((x-C_{1})(x-C_{1})+(y-C_{2})(y-C_{2}))) \end{cases}$$ If it possible I want to know how can it can be done in C++ too. Update: `Solve[]` gives me very large output, so the problem is that I want to place solution in my C++ aplication and $C_1$, $C_2$, $k_1$, $k_2$ are variables. `CForm[]` doesn't help, I need more simple and suitable form for C++ to use.


title: How to add a short wav music clip into a Mathematica animation

text: I have the following Mathematica animation:               Animate[Plot[k*x^2, {x, -2, 2},        PlotRange -> {{-2, 2}, {-10, 10}}], {k, -2, 2, 0.1}]      I also have a sound file in the same Mathematica file, which is A VERY SHORT music clip, in "wav" format. The clip is about 32 seconds long. Now I want to integrate this sound file into the above animation: The following command will do the job, but it will make the animation WAY TOO sluggish, and almost useless:               Animate[Plot[k*x^2, {x, -2, 2}, PlotRange -> {{-2, 2}, {-10, 10}},        Epilog -> {EmitSound[snd]}], {k, -2, 2, 0.1}]      Could you please suugest a better way of doing it? Thank you very much!


title: Dealing with dynamic tables

text: Making dynamic vector variables is difficult in Mathematica. For example:               X=Table[ToExpression["x" <> ToString@i], {i, 0,4}];     X[[2]]      Yields x1. However, if we make X a dynamic variable, then               n=4;     Row[{SetterBar[Dynamic@n, Range[1, 10, 1]], "     Length of X."}]         X=Table[ToExpression["x" <> ToString@i], {i, 0,n}];     X[[2]]      Yields "Part 2 of {x0,x1,x2,x3,x4} does not exist". How do I make dynamically updating vector objects of variable length?


title: Combining images and plots in LevelScheme figures

text: I've found that the `LevelSchemes` package is extremely useful when combining several plots with precise control over where to place legends, making plots withing plots other neat stuff like that, however I ran into problems when I tried to combine a graphics object (like a .png file) and a plot. Here is what I am trying to do: I have a plot depicting the squeezing parameter value in depending on the external electric field strength. ![Plot without the picture](http://i.stack.imgur.com/SGcQP.png) I wanted to obtain something that looks like this: ![This is what I want made by hand in a graphics editor \(Inkscape\)](http://i.stack.imgur.com/WfGGd.png) To achieve said result I tried something like this:               Figure[      {       (*Main panel*)       FigurePanel[        {{0, 1}, {0, 1}}, PlotRange -> {{0, 1}, {-0.6, 20}},         FrameTicks -> {Automatic, Automatic}, FontSize -> 15,         LabB -> textit["x"], BufferB -> 2.5, TickFontSize -> 12        ],       DataPlot[        dati, Tag -> set[1]        ],       ScaledLabel[{0.5, 0.2},         "some value=" <>          ToString[Some expression that returns a number],         FontSize -> 13],           (*Smaller Pannel*)       ScaledFigurePanel[        {{0, 0.55}, {0.55, 0.95}},        PlotRange -> {Automatic, Automatic}        ],        (*AMPSPlot is essentially SphericalPlot3D that takes a nxn matrix as an argument.        It is found in the ADM package*)       RawGraphics[        Rasterize[         Axes3D[AMPSPlot[           WignerRotate[            gdm[Flatten[sols[[30, 2]]]], {optlen[              gdm[Flatten[sols[[30, 2]]]]], 0, 0}], PlotRange -> All,            Boxed -> False, Axes -> False]]]]            },      PlotRange -> {{-0.2, 1.1}, {-0.2, 1.1}}, ImageSize -> 100*{6, 4}           ]      but I get something like this: !["This doesn't work at all"](http://i.stack.imgur.com/5tgSG.png) Is there any way to incoorporate pictures in graphics by `LevelScheme`? The main goal I am trying to do this is to see how the graphs look every time I tweak which set of parameters I've used, without going through the fiddly process of merging them in Inkscape.


title: How can the opacity of a dense data set be automatically chosen?

text: ### The problem In a dense data set plotted with opaque points, data points can pile on top of each other. This can cause serious problems with the interpretation of the plots. I'll use as an example a scatterplot of normally distributed points.               theData = RandomReal[NormalDistribution[], {100000, 2}];      Unless one is careful, these plots end up showing a solid disk around the origin, which obscures the distribution since point densities above a certain level appear clipped. This also gives inappropriate emphasis to outliers, by plotting them with the same intensity as what might be a pile of a million points close together at the origin. Here is the same plot shown at different sizes.               Row[ListPlot[      theData,      AspectRatio -> Automatic, ImageSize -> #, PlotStyle -> Directive[Black]     ] & /@ {90, 180, 360}]      ![enter image description here](http://i.stack.imgur.com/WSEwg.png) An artificial black disk appears at the origin and its apparent size depends on the plot size, even though the data are identical. Here is the same plot with different settings for PointSize.               Row[ListPlot[      theData,      AspectRatio -> Automatic, ImageSize -> Medium, PlotStyle -> Directive[Black, PointSize[#]]     ] & /@ {0.01, 0.005, 0.0025}]      ![enter image description here](http://i.stack.imgur.com/bX6oY.png) The disk appears a different size depending on point size, even though the data are identical. Here are plots of successively smaller subsets of the data.               Row[ListPlot[      theData[[;; #]],      AspectRatio -> Automatic, ImageSize -> Medium, PlotStyle -> Directive[Black]     ] & /@ {100000, 50000, 25000}]      ![enter image description here](http://i.stack.imgur.com/bw5uG.png) The distributions are obviously all the same, but they look different in the plot because of the pileup of points. ### Solving pileup by changing opacity For a given point size, one solution is to choose the minimum opacity where the darkest pixel in the plot is black. Here is an ugly, slow, procedural, brute-force way of choosing the correct opacity:               Block[      {darkestPixel},      darkestPixel=1;      idealOpacity=0;      While[       darkestPixel>0,       idealOpacity=idealOpacity+0.001;       darkestPixel=Min@Flatten@ImageData@ColorConvert[        Rasterize@ListPlot[         theData,         AspectRatio->Automatic,ImageSize->Medium,         PlotStyle->Directive[Black,PointSize[0.01],Opacity[idealOpacity]],Axes->False        ],       "Grayscale"       ]      ]     ]      Here are the resulting plots for different subsets of the data:               Row[ListPlot[      theData[[;; #[[1]]]],      AspectRatio -> Automatic, ImageSize -> Medium,       PlotStyle -> Directive[Black, PointSize[0.01], Opacity[#[[2]]]]     ] & /@ {{100000, 0.018}, {50000, 0.042}, {25000, 0.1}}]      ![enter image description here](http://i.stack.imgur.com/3MBGh.png) ### Solving pileup by changing point size Another way is to choose a fixed opacity and increase the size of the points until the darkest pixel is black.               Block[      {darkestPixel},      darkestPixel = 1;      idealPointSize = 0;      While[       darkestPixel > 0,       idealPointSize = idealPointSize + 0.001;       darkestPixel = Min@Flatten@ImageData@ColorConvert[        Rasterize@         ListPlot[theData,          AspectRatio->Automatic, ImageSize->Medium,           PlotStyle->Directive[Black,PointSize[idealPointSize],Opacity[0.05]],Axes->False         ],        "Grayscale"       ]      ]     ]      The results for different subsets of the data:               Row[      ListPlot[       theData[[;;#[[1]]]],       AspectRatio->Automatic,ImageSize->Medium,       PlotStyle->Directive[Black,PointSize[#[[2]]],Opacity[0.05]]      ]&/@{{100000,0.003},{50000,0.01},{25000,0.015}}     ]      ![enter image description here](http://i.stack.imgur.com/MYlLR.png) ### The question What's the best way to quickly and automatically choose the correct opacity, point size or combination of the two so that there is no "clipping" in a dense plot? Is it possible to do this inside of `PlotStyle` instead of as a pre- processing step? For bonus points, explain the best way to do this for multiple data sets on the same plot.


title: How can I provide dividers and control item alignment in a Grid?

text: I make a `Grid` with multiple Rows and Columns. I want to apply different types of Dividers and Alignment to that `Grid`. ![enter image description here](http://i.stack.imgur.com/7nVsA.png) If you can observe above picture, 1.First row `Alignment` is `Left`,and remaining all the rows `Alignment` is `center`. 2.in the second row only `Dividers` are appeared I want like this,for this purpose I wrote a simple code but it was nor working                Grid[{{Style["Life Alerts", Bold, 20], SpanFromLeft, SpanFromLeft},             {Style["Alert", Bold, 15], Style["<>", Bold, 15],              Style["%Life", Bold, 15],              Style["OnDay", Bold, 15]            },            {Style["L1", Bold, 15],              Style["<", Bold, 15], Style["90", Bold, 15],              Style["0.35", Bold, 15]            },            {Style["L2", Bold, 15],              Style[">", Bold, 15], Style["90", Bold, 15],              Style["0.35", Bold, 15]            },            {Style["L3", Bold, 15],              Style[">", Bold, 15],              Style["90", Bold, 15],              Style["0.35", Bold, 15]            }           },          Alignment -> {{Left}, Center}, Background -> {None, {Yellow}}, Frame -> True,         FrameStyle -> Directive[Thickness[4], Black], Spacings -> {1, 1},         Dividers -> {{}, {True, True, True}}]      Already I seen documentation still I didn't get it can anybody help me?


title: Unexpected behavior of Compile, Return and ;

text: Could somebody explain why               test = Compile[{{x}},           Return[x];         ];     test[0.]      returns               Compile::cret: "The type of return values in Return[x]; are different. Evaluation will use the uncompiled function. "      while               test = Compile[{{x}},           Return[x]         ];     test[0.]      works as expected? Notice that the only difference is the semicolon at the end of `Return`.


title: Simplifying expressions involving Divisible

text: FullSimplify[ Divisible[p^2 - 1, 24] , Element[p, Primes] && p > 3]      Should evaluate to `True`, but I get > >     Divisible[-1 + p^2, 24] >   Compare with               FullSimplify[Divisible[(6 k - 1)^2 - 1, 24], k \[Element] Integers]       Which does evaluate to > >     True >


title: My code is not converging using NIntegrate. Why? Help please

text: I have been trying to see why this integration is not converging but to no avail. The output gives only the y-values but fail to give any real value for x-values. Rather I always have something like this:               0.1, -1, Re[ NIntegrate[ Abs[x + y - 1]^k*Sign[x + y - 1]*f[x, y, θ, ρ],                               {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100]],     2 - 2*Re[CDF[StudentTDistribution[1.1], ComplexInfinity]] 0.1, -0.7,      Re[ NIntegrate[ Abs[x + y - 1]^k*Sign[x + y - 1]*f[x, y, θ, ρ],                      {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100]],     0.22388681701262803 0.1, -0.39999999999999997,      Re[ NIntegrate[ Abs[x + y - 1]^k*Sign[x + y - 1]*f[x, y, θ, ρ],                      {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100]],      0.33847856188105085 0.1, -0.09999999999999998,      Re[ NIntegrate[ Abs[x + y - 1]^k*Sign[x + y - 1]*f[x, y, θ, ρ],                      {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100]],      0.43918067389892146      0.1, 0.2, Re[ NIntegrate[ Abs[x + y - 1]^k*Sign[x + y - 1]*f[x, y, θ, ρ],                               {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100]],     0.5383910479350043 "      The code is this:               ClearAll[A, f, θ, ρ, data, θmin, θmax, ρmin, ρmax, θinc, ρinc, c1, c2];     θmin = 0.1; θmax = 5; ρmin = -1; ρmax = 1; θinc = 0.01; ρinc = 0.3; k = 3;     data = {};     A[w_, θ_, ρ_] :=  w (CDF[StudentTDistribution[θ + 1], Sqrt[(1 + θ)/(1 -   ρ^2)] ( (w/(1 - w))^(1/θ) - ρ)]) + (1 - w) (CDF[ StudentTDistribution[θ + 1], Sqrt[(1 + θ)/(1 - ρ^2)] (((1 - w)/ w)^(1/θ) - ρ)]);     c1[x_, y_, θ_, ρ_] := Exp[Log[x y] A[Log[y]/Log[x y], θ, ρ]];     c2[x_, y_, θ_, ρ_] :=  x + y - 1 + c1[1 - x, 1 - y, θ, ρ];     f[x_, y_, θ_, ρ_] := D[c1[x, y, θ, ρ], x, y];     stream = OpenWrite["./data2011", BinaryFormat -> True];       For[θ = θmin, θ <= θmax, θ += θinc, ρmin = -1; ρmax = 1;      For[ρ = ρmin, ρ < ρmax, ρ += ρinc,        Print["θ=", θ, ", ρ=", ρ];     list = Re[{{θ, ρ, NIntegrate[ Abs[x + y - 1]^k Sign[x + y - 1] f[x, y, θ, ρ], {x, 0, 1}, {y, 0, 1}, WorkingPrecision -> 100], 2 - 2 A[1/2, θ, ρ]}}];     Export[stream, Table@list, "CSV"];          WriteString[stream, "\n"];]]


title: Rescuing a vertically clipped histogram

text: I recently ran a rather time intensive calculation and plotted the results in a histogram by simply called Histogram[data]. However, because of a rather serious error on my part, I recently lost my original data and all I have is the histogram plot. I need to change the vertical cut-off on the histogram (it will cut off any bars with an event count >= N). I can hover over the bars and read the values, so I know the information is there, but how can I change the value of N for the vertical cutoff?


title: Function behavior based on Head

text: I'm figuring how to implement a function behavior based on the Head of its argument. I mean               Unprotect@Head;     Head[p_[x]]:= Kind;     Protect@Head;     function[h_]:= 0;     function[p_Kind]:= 1;          Head[f[x]]     function[f[x]]     function[f]      the first instance of `function` should evaluate to `1` whereas the second instance should evaluate to `0`. However, both evaluate to `0`. Notice that `Head[f[x]]` evaluate to `Kind` as expected. Where am I doing mistake(s)? Thank you very much


title: NSolve or Reduce for obtaining the results and connecting roots

text: Here I have one problem how to solve numerically equation for different values of one parameter x. I used just two digits because of length, but for x=0.57 I should have one real root and for others 0.6, 0.7 ... complex roots. These seven points I want to plot in complex (Re,Im) plane with line. The first problem is that NSolve doesn't work, with Reduce I can obtain some results with problems. Another problem is to understand what's happen when x-> Infinity                     x = {0.57, 0.6, 0.7, 0.8, 0.9, 1, 1.1};                NSolve[1/Sqrt[y]           0.02 (1.`5. I (64.`5. + 2.10 Sqrt[y]) Sqrt[-64.`5. +            4.21 Sqrt[y]] + (64.`5. - 2.10 Sqrt[y]) Sqrt[           64.`5. + 4.21 Sqrt[y]]) Sqrt[-64.`5. + 4.21 Sqrt[y]] Sqrt[           64.`5. + 4.21 Sqrt[y]] + 0.03 Sqrt[y] - # == 0, y] & /@ x


title: Sort matrix rows iteratively according to sum of some columns

text: I have a matrix say               matinitial =       {{41, 42, 43, 44, 45, 46, 47, 48, 49, 410},        {11, 12, 13, 14, 15, 16, 17, 18, 19, 10},        {21, 22, 23, 24, 25, 26, 27, 28, 29, 210},        {31, 32, 33, 34, 35, 36, 37, 38, 39, 310}};      I want to form matrices `matfinal[i],` where i runs from 1 to 6 in this example.My `matfinal[i]` should be equal to matinitial after sorting rows based on sum of columns from `i` to `i + 4`. I tried the following codes :               Do[matfinal[i] = SortBy[matinitial,Total[matinitial[[All, i ;; i + 4]], {2}]], {i, 1, 6}];      But I do not get the results I desire. For example, my matfinal[1] should be equal to matinitial sorted based on Total of first four columns:               {41 + 42 + 43 + 44, 11 + 12 + 13 + 14, 21 + 22 + 23 + 24, 31 + 32 + 33 + 34} = {170, 50, 90, 130}.      Therefore,               matfinal[1]={{11, 12, 13, 14, 15, 16, 17, 18, 19, 10},                 {21, 22, 23, 24, 25, 26, 27, 28, 29, 210},                 {31, 32, 33, 34, 35, 36, 37, 38, 39, 310},                 {41, 42, 43, 44, 45, 46, 47, 48, 49, 410}};      Please note, in my real world problem my matinitial matrix is 100 by 20000 in size.Any help is greatly appreciated.And also, thank you for your help in advance!! :))


title: How can I decide whether a closed surface is intersected by a triangle?

text: A closed surface consisted of `Polygons` or `GraphicsComplex` and a triangle made by 3 points are in a 3D space. How can I decide whether intersected or not. I have tried by using `RegionMember` but It does not work. (this code is typed in _version 10_ )               g1 = RevolutionPlot3D[{2 + Cos[t], Sin[t]}, {t, 0, 2 Pi},        PlotPoints -> 2];     surface =        GraphicsComplex[g1[[1, 1]], {Opacity[0.7], g1[[1, 2, 1, 1, 5, 1]]}];          triangles = {        Polygon[{{0, 0, 0}, {0, 2, 2}, {0, -1, 2}}],        Polygon[{{2, 0, 0}, {2, 2, 2}, {2, -1, 2}}],        Polygon[{{-3, 0, -3}, {3, 2, 2}, {-3, -1, 2}}]};      examples               Grid[{{"Not Intersected", "Inside 1-Point,        Intersected", "Outside 3-Point,        Intersected"},       Table[Graphics3D[{surface, Opacity[0.7], Green, t},         Boxed -> False], {t, triangles}]}, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/DSKTg.png) I want to make a function that is decide whether intesected or not like this: ![enter image description here](http://i.stack.imgur.com/f0let.png) I expect like this results. ![enter image description here](http://i.stack.imgur.com/kIqme.png) **Is there any idea or algorithm paper?** * * * **My Wrong Try**               makeSurfaceEq[v_List, {x_, y_, z_}] :=      Module[{a, b, c, d, eq},        eq = a x + b y + c z + d == 0;        eq = eq /. NSolve[(a #1 + b #2 + c #3 + d == 0 &) @@@ v];        eq = If[eq[[0]] === List, eq[[1]]];        eq /. {a | b | c | d -> 1}        ] /; Length[v] >= 3     polygonToSurfaceInEq[v_, f_, {x_, y_, z_}] := Module[{cOfG, eqs, ineq},       cOfG = Mean@v;       eqs = makeSurfaceEq[v[[#]], {x, y, z}] & /@ f;       Table[         ineq = eqs[[i]] /. Equal -> Greater;         If[ineq /. Thread[{x, y, z} -> cOfG], ineq, ! ineq],         {i, Length[eqs]}] /.        {Greater -> GreaterEqual, Less -> LessEqual}       ]      here is something wrong result. and though a point is in closed surface, **the command** > polygonToSurfaceInEq **is not applied for a like torus.**               intersectedQ[polygons_, triangle_] := Module[{},       f = Function @@ {{x, y, z},          And @@ polygonToSurfaceInEq[            polygons[[1]],            Cases[polygons, Polygon[a_] -> a, \[Infinity]][[1]],            {x, y, z}]          };       Or @@ f @@@ triangle[[1]]       ]      my try is this.               intersectedQ[surface, triangles[[1]]]      > True 3 points are all outside of the surface.               intersectedQ[surface, triangles[[2]]]      > False * * * **Wrong Try2** Pickett's answer is good approach but is not a answer of my question. The closed surface is made by polygons and **bounded by polygons surfaces**. The following example show that I mean.               intersectQ[polygon_] := With[{distFunc = RegionDistance@Polygon[polygon]},         Length@Select[           findPossibleIntersections[polygon, surface[[1]], 0.01],            distFunc@# < 0.05 &] > 0];     intersectQ@{{1.8, 1.2, 0.9}, {1.5, 1, 2}, {1.5, 2, 2}}      > False This is inside of surface, but this code answer FALSE.               Graphics3D[{surface,       Opacity[.7], Green,        Polygon[{{1.8, 1.2, 0.9}, {1.5, 1, 2}, {1.5, 2, 2}}],       Opacity[1], Red, Point[{1.8, 1.2, 0.9}]},      Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/4ipUw.png)


title: Slider with non-linear behavior

text: I am trying to develop a small tool and I am stuck on a very simple problem. This how I want it to look: ![enter image description here](http://i.stack.imgur.com/LPh6y.png) I have               minValue = steps = 100.000     valueRange = 500.000.000 - 100.000     newPercent = where the circle is right now (0-100%)     newValue = minValue + (valueRange * newPercent / 100.0);      The range is very big, and it is very hard to set the right value at the beginning, but when the value is above 200 million, I don't care about 100000. So I wont to make it exponential; e.g., $x=y^2$ That what I was thinking. http://www.wolframalpha.com/share/clip?f=d41d8cd98f00b204e9800998ecf8427e9onr7i6926 I want to make the first steps with 100.000 and them more and more. Maybe like this? http://www.wolframalpha.com/share/clip?f=d41d8cd98f00b204e9800998ecf8427ev8h6m2vulq Maybe I am totally wrong. Any suggestions?


title: Asymmetric X and Y error bars on ListLogPlot

text: The wonderful error bar log plots package `ErrorBarLogPlots` from `V6` no longer positions labels correctly (since `v9` or maybe `v8`) so I used the same function with `Prolog` to place a list of labels. Then in `v10 beta` `PlotRangePadding` no longer works either and I can't find a work around for that, so I tried to go back to basics and use the very elegant solution by Belisarius' et.al in: Plotting Error Bars on a Log Scale I was able to modify this to make asymmetric $Y$ error bars, then I tried to add $X$-errors and got tied up in knots with the `Joined` and `Filling` commands. **The aim** is to plot a set of $5$ lists of `xy` values, `{xy, xyP, xyM, xPy, xMy}` where `P` and `M` refer to the plus and minus error of the $x$ or $y$ value preceding it, with a `Filling` / `Joined` statement that joins the first point to the other 4 points. Ideally the plot symbols should also switch between vertical and horizontal bars for the $x$ and $y$ error points and something else for the $x, y$ point. (I asked Support about including an `errorlistlogplot` command in _Mathematica_ but I expect it won't make it into `v10`). The lines below generate and plot the `5` sets of points. Is there a straightforward combination of `Filling` / `Joined` statements to achieve this?               SeedRandom[1234]     dataX = Sort@RandomReal[{0.5, 1}, 10];     dataY = RandomReal[{0.5, 1}, 10];     {errorYP, errorYM, errorXP, errorXM} = RandomReal[.5, {4, 10}];     dataYP = dataY + errorYP;     dataYM = dataY - errorYM;     dataXP = dataX + errorXP;     dataXM = dataX - errorXM;     xy = Transpose[{dataX, dataY}];     xyP = Transpose[{dataX, dataYP}];     xyM = Transpose[{dataX, dataYM}];     xPy = Transpose[{dataXP, dataY}];     xMy = Transpose[{dataXM, dataY}];          ePlot[plotFun_, data_] := plotFun[data, Filling -> Automatic, PlotRange -> All,                                             Joined -> {False, False, False, False, False}];          ePlot[ListLogPlot, {xy, xyP, xyM, xPy, xMy}]      ![enter image description here](http://i.stack.imgur.com/xVSE7.png)


title: How do I create a list of 25 random quadratic equations in the form ax^2+bx+c?

text: My teacher suggests using the RandomInteger command along with the Factor command, but I cannot figure out the syntax. A, b, and c need to be non zero integers between -10 and 10.


title: Change font of formula number in DisplayFormulaNumbered

text: I am trying to change the font of the formula number in a cell which has style DisplayFormulaNumbered. I can easily change the font of the formula I enter by selecting it and using the format menu. But the number to the right of the formula wont change. Any help with this would be greatly appreciated. I am using mathematica 9.


title: Solving a system of DAE on mathematica

text: I am having trouble solving a system of Differential Algebraic equations of mathematica, the solution I get is just zeros although it should give me an answer, here is my code:               eqns = {AL1''[z] -           AR1''[z] - (1/z)*(AL1'[z] - AR1'[z]) + (MW^2)*(AL1[z] -              AR1[z]) - (\[Alpha]*(z)^(2 + 2*\[Beta]))*(AL1[z] - AR1[z]) ==          0, AL2''[z] -           AR2''[z] - (1/z)*(AL2'[z] - AR2'[z]) + (MW^2)*(AL2[z] -              AR2[z]) - (\[Alpha]*(z)^(2 + 2*\[Beta]))*(AL2[z] - AR2[z]) ==          0, AL3''[z] -           AR3''[z] - (1/z)*(AL3'[z] - AR3'[z]) + (MZ^2)*(AL3[z] -              AR3[z]) - (\[Alpha]*(z)^(2 + 2*\[Beta]))*(AL3[z] - AR3[z]) ==          0, AL1''[z] +           AR1''[z] - (1/z)*(AL1'[z] + AR1'[z]) + (MW^2)*(AL1[z] +              AR1[z]) == 0,         AL2''[z] +           AR2''[z] - (1/z)*(AL2'[z] + AR2'[z]) + (MW^2)*(AL2[z] +              AR2[z]) == 0,         AL3''[z] +           AR3''[z] - (1/z)*(AL3'[z] + AR3'[z]) + (MZ^2)*(AL1[z] +              AR1[z]) == 0, B''[z] - B'[z]/z + (MZ^2)*B[z] == 0};          bcs = {AL1'[10^-8] == 0, AL2'[10^-8] == 0, AL3'[10^-8] == 0,         AR1[10^-8] - Sqrt[-1]*AR2[10^-8] == 0,         AR1[10^-8] + Sqrt[-1]*AR2[10^-8] == 0,         B'[10^-8] + (1/2.49144)*AR3'[10^-8] == 0,        AR3[10^-8] - B[10^-8] == 0, AL1[1/372.5] == 0, AL2[1/372.5] == 0,         AL3[1/372.5] == 0, AR1'[1/372.5] - Sqrt[-1]*AR2'[1/372.5] == 0,         AR1'[1/372.5] + Sqrt[-1]*AR2'[1/372.5] == 0,         B[1/372.5] + (1/2.49144)*AR3[1/372.5] == 0,         AR3'[1/372.5] - B'[1/372.5] == 0};          params = {MW -> 912, MZ -> 918, \[Beta] -> 2, g -> 0.6356, V -> 300,         RUV -> 10^-8, \[Alpha] -> (1 + \[Beta])*           Log[RTeV/             RUV]*(((g V)/(RTeV^(1 + \[Beta])))^2)/(2*(1 - (RUV/RTeV)^(2 +                    2*\[Beta]))) /. {g -> 0.6356, V -> 300, RUV -> 10^-8,           RTeV -> 1/372.5, \[Beta] -> 2}};           sol = First[       NDSolve[{eqns, bcs} /. params, {AL1, AL2, AL3, AR1, AR2, AR3,          B}, {z, 10^-8, 1/372.5}, Method -> {"Shooting"}]]


title: Graph generation given number of edges and nodes

text: I was wondering if it is possible to have Mathematica generate all graphs with a given number of edges and nodes (and possibly restricting the adjacencies) and draw them I know that there are some commands in Mathematica but I don't quite seem to find this particular one if it exists. For the physicists among you: I'm basically looking for a way to generate all possible Feynman diagrams at 4 loops given only cubic interaction for 1 or 2 external particles excluding internal bubble graphs :)


title: Changing the background images of a slideshow presentation

text: _Mathematica 9_ lets you create presentations with background images. There are 6 default stylesheets for this: Earth, Garnet, Sapphire, Opal, Sunrise, Steel and Water. ![enter image description here](http://i.stack.imgur.com/V2Jpm.png) For your existing presentations I have found that you can apply the new appearance by selecting one of those stylesheets and copying the very first cell in a blank presentation created with the desired stylesheet. My question is: What is the recommended procedure to change the background image to something else? I have already found that the background images are controlled by the following cells in the stylesheet:               Cell[       StyleData["Notebook", "SlideShow"],       BackgroundAppearance -> FrontEnd`FileName[{"SlideShow"}, "EarthBackground.png"]]          Cell[       StyleData["FirstSlide"],       PrivateCellOptions ->          {"PagewiseNotebookBaseStyle" ->            {System`BackgroundAppearance ->              FrontEnd`FileName[{"SlideShow"}, "EarthTitleBackground.png"]}}]      And I can indeed put an adiditional background image file inside the `$InstallationDirectory/SystemFiles/FrontEnd/SystemResources/SlideShow` directory, but If I do that it will not be portable. So it is possible to use a background image that is contained inside the presentation notebook?


title: What devices are supported by the connected devices framework?

text: One of the new features in v10 is support for connected devices. How can I find out if a particular device is supported by Mathematica? Is there a complete list? Is support being added continually? The documentation says: > Many classes of devices listed in the Wolfram Connected Devices Project are > immediately supported within the Wolfram Language. Out of curiosity, I connected a Garmin nüvi50 and ran `FindDevices` to see if it would recognize it and be able to import tracks. I got the result:               {DeviceObject[{"Camera", 1}], DeviceObject[{"FunctionDemo", 1}],       DeviceObject[{"RandomSignalDemo", 1}], DeviceObject[{"WriteDemo", 1}]}       The only device it recognized here was the built-in camera. Is `FindDevices` generally sufficient to find out of a device is supported, or is manual configuration necessary for some devices?


title: Discontinuous Forcing for a Cancer Model -- Issues with v9 NDSolve

text: I'm new here, so please be gentle with me and hopefully the post is appropriate and not too basic. I am a math teacher and use modeling in my courses. I had working code (in v8 of Mathematica) for a cancer model with discontinuous forcing and now that previously working code doesn't work with v9. The model can be found displayed at ![Antiangiogenic Model](http://www.biomathdynamics.com/antiangiogenics/antiangiogenicModel.jpg) The following code worked in Mathematica version 8 but now doesn't work under version 9 (I haven't tried it in v10 yet):               lambda1 = 0.192; lambda2 = 0.000; b = 5.85; d = 0.00873; dose = 30;      efficacy = 0.66; clearance = 1.7; numberofdoses = 30; doseinterval = 2;      t0 = 0; tfinal = 84; v0 = 185; k0 = 625; is = 840;          h[t_] = Integrate[Sum[DiracDelta[tau - doseinterval*i], {i, 1, numberofdoses}]*Exp[-clearance*(t - tau)], {tau, 0, t}];          f := -lambda1*v[t]*Log[v[t]/k[t]];          g := -lamda2*k[t] + b*v[t] - d*k[t]*(v[t])^(2/3) - efficacy*dose*h[t]*k[t];          eqns := {v'[t] == f, k'[t] == g, v[0] == vinit, k[0] == kinit};          sol := NDSolve[eqns /. {vinit -> v0, kinit -> k0}, {v[t], k[t]}, {t, t0, tfinal}, MaxSteps -> 10000, MaxStepSize -> 1];          g1 := Plot[h[t], {t, t0, tfinal}, PlotStyle -> {Thick, Black}, AxesLabel -> {time, " "}, PlotLabel -> Treatment, ImageSize -> is];          g2 := Plot[Evaluate[{v[t], k[t]} /. sol], {t, t0, tfinal}, PlotStyle -> {{Thick, Blue}, {Thick, Red}}, AxesLabel -> {time, volume}, ImageSize -> is, PlotRange -> All, PlotLabel -> Response];          g3 := ParametricPlot[Evaluate[{v[t], k[t]} /. sol], {t, t0, tfinal}, ImageSize -> is, PlotStyle -> {Thick, Black}, AxesLabel -> {Vasculature, Tumor}];          g4 := Show[GraphicsGrid[{{g1}, {g2}, {g3}}]];          g4      Partial output, found at the link below, should be obtained ![Output for TNP470 Parameters](http://www.biomathdynamics.com/antiangiogenics/tnp470.jpg) What gives? I get the following beginning error message:               NDSolve::deqn: Equation or list of equations expected instead of ConditionalExpression[(k^\[Prime])[t]==-lamda2 k[t]-1.04875*10^45 E^(-1.7 t) (1. HeavisideTheta[Plus[<<2>>]]+0.0333733 HeavisideTheta[Plus[<<2>>]]+<<27>>+1.50857*10^-43 HeavisideTheta[Plus[<<2>>]]) (-0.5+1. HeavisideTheta[t]) k[t]-0.00873 k[t] v[t]^(2/3)+5.85 v[t],t\[Element]Reals] in the first argument {(v^\[Prime])[t]==-0.192 Log[v[t]/k[t]] v[t],ConditionalExpression[(k^\[Prime])[t]==-lamda2 k[t]-1.04875*10^45 E^(-1.7 t) (1. HeavisideTheta[<<1>>]+0.0333733 HeavisideTheta[<<1>>]+<<27>>+1.50857*10^-43 HeavisideTheta[<<1>>]) (-0.5+1. HeavisideTheta[<<1>>]) k[t]-<<1>>+5.85 v[t],t\[Element]<<5>>],<<1>>,k[0]==625}. >>      And there are other error messages seemingly related to this issue. Can you please help me out so I can get the model up and running for my students again? Thanks in advance for any help. I get the sense it's in how NDSolve handles discontinuous forcing functions. Is there a workaround? Mike


title: Are there tools for getting Mathematica 9 Notebooks working in Mathematica 10?

text: As often happens with Mathematica updates, nearly all of my notebooks no longer work as they did with the previous version. The upgrade from 9 to 10 has changed the appearance or introduced errors into almost every figure or graphic I create. I'm also encountering many errors in code that has worked without error since version 7. Many of these errors are quite surprising (e.g. calculations that suddenly give division by zero errors on the same data that I've always used, out of range errors when indexing lists that have not changed since running in version 9, graphics suddenly scaling to different sizes than before, etc.), and very difficult to locate (they are generally in large notebooks that I've been using for years). _Is there a tool for analyzing version 9 code for potential issues in version 10?_ I've enabled the notebook compatibility scanning feature; but that does not detect anything in any of my affected notebooks: ![](http://i.stack.imgur.com/tIZit.png) * * * As I spend hours going through my code to track down the sources of my many 10-induced bugs, I've come across the following, so far:   * `DateDifference` now returns a `Quantity` so that comparisons need to be wrapped in `QuantityMagnitude` (documented).   This leads to all kinds of errors, as many tests, filters and comparisons now fail (`x≠x days` for example), resulting in lots of empty lists.   * `DateListPlot` seems to behave as if `Joined` is `True` by default (apparently not documented).    * Default line weights and point sizes have changed in many (all?) plots, with now clear way to restore them to exactly what they were before.   This is vexing if you've got any kind of document production or style guidelines you've been following: all your code will now need to be adjusted to produce the results you've had.   * I `DateListPlot`, if two points have the same time coordinate, only one is plotted; the others are ignored. In addition, I'm getting at least a strong subjective impression that many operations are _much_ slower, especially file imports (e.g. importing several GPX files taking hours — so far — rather than minutes, in 9). There also appears to be some pollution of the global namespace taking place: I can get errors and very long delays in execution depending on the order in which I run different notebooks. I've had no luck tracking down the source of this behavior; but it's quite consistent.


title: Compile issues, scoping and order of evaluation

text: I have a few questions about compiling functions, which I think are all related to scoping and order of evaluation. I will illustrate them by a minimal example of the problem I have. I'm sorry for the lengthy question. The setup code is this,               mat = {{0, 1}, {1, 0}};          expr = {a^2 - ma + 3 x^3, a mb^2 + 2 b x, mc a - mb ma x^6};     Do[exprIndexed[i] = expr[[i]], {i, 1, 3}]     x = {5, -2};     atest = {1, 2}; btest = {2, 1}; ctest = {0, 0};      I have a list of expressions expr, each of which represents a vector. The first depends only on `a`, `ma` stands for the matrix `mat` times the vector `a`, and `x` is a constant known vector. The second depends on `a` and `b` and the last on `a, b, c`. I want to write for each of these expressions a compiled code that evaluates them. In particular I want to be able to define these compiled functions inside a do loop, I want them to really fully compile, and I want it to evaluate as much as it can without knowing the variables (`a`, `{a, b}` and `{a, b, c}` respectively). One attempt is this: (NOTE: i'm omitting everywhere the last argument `CompilationOptions -> {"InlineExternalDefinitions" -> True}, CompilationTarget -> "C"` for brevity)               Compile[Evaluate[({#, _Real, 1} &) /@ Take[{a, b, c}, i]],       ma = mat.a;        If[i > 1, mb = mat.b];        If[i > 2, dc = mat.c];       exprIndexed[i],       {{exprIndexed[i], _Real, 1}, {ma, _Real, 1}, {mb, _Real,1}, {mat, _Real, 2}}]      (A not so important question I have here is: when it is and when it's not necessary to include these type specifications at the end) Plugging in by hand `i = 1`, and copying for `i = 2`, etc., this code works. Wrapping it in a `Do`, e.g.               Do[comp[i]= (expr above)]      does not work. _Mathematica_ gives > CompiledFunction::cfse: Compiled expression {373. +a^2,-25.+a^2} should be a > machine-size integer. >> However, writing               loopCode[i_] := (code above)     Do[comp[i] = loopCode[i]]      does work. I wonder why this is so? Although the code works, it does not compile completely (I checked this by doing `Export["test.c", comp[1]]`). The reason is that the assignments set the global value of e.g. da, so must talk to _Mathematica_. This can be fixed by changing the body of the compile to               Module[{ma = mat.a},     exprIndexed[i]]      Now it works and compiles, but it cannot be defined in a loop. Explicitly, I tried,               loopComp[i_] :=        Compile[Evaluate[({#, _Real, 1} &) /@ Take[{a, b, c}, i]],         Module[{da = mat.a}, exprIndexed[i]],           {{exprIndexed[i], _Real, 1}, {da, _Real, 1}, {db, _Real, 1}, {mat, _Real, 2}}]          Do[comp[i] = loopComp[i], {i, 1, 3}]      I haven't found a way to automate the assignment of `ma`, `mb` and `mc`, i.e. to get `Module[{ma=mat.a},...]` for `i=1`, `Module[{ma=mat.a, mb=mat.b},...}]` for `i=2` etc., so `comp[2]` and `comp[3]` shouldn't work, but at least `comp[1]` should, but it does not.               comp[1][atest]       gives the error > CompiledFunction::cfte: Compiled expression da should be a rank 1 tensor of > machine-size real numbers. >> and the output > >     {376 - da, -20 - da} >   I think the issue is in the scoping of `Do`, `Module` and `Compile`, but I don't know how to fix it. The final issue is this. Even in the working versions of this code (just by explicitly copy-pasting and inserting the `i = 1, 2, 3` ) each time it runs everything is computed, i.e. the `x^6` is not computed by compile once and for all, but every time the code is run. Note that if `x` is defined before expr is defined, then this does not happen, but then there is another problem in that i.e. `x + a` will become `{5 + a, -2 + a}` and when `a` is plugged in we get a matrix instead of a vector. So I want to evaluate as much as possible, while still getting a vector as output.


title: Histogram: Bars not stacked, not overlapped, but side by side?

text: I would like to make a histogram with multiple datasets. Then Mathematica allows to either overlap or stack the data from the different data sets. However, I would like to have the bars side by side, but could not find a way how to do this. To illustrate what I mean: ![Mathematica graphics](http://i.stack.imgur.com/VXqw3.png) I want the thing on the right, but Mathematica does the thing on the left. Thanks! Obviously I should have supplied the data. Thanks for the answers so far - I couldn't figure out how to apply these to my data. Here they are:               {{1.25268, 0.944003, 0.508123, 0.835465, 1.08849, 0.730729, 0.539924,        0.458693, 0.62392, 1.14587, 0.69167, 0.969927, 0.627031, 0.371587,        0.477359, 0.844106, 0.414103, 1.03941, 0.95057, 0.448324, 0.419288,        0.362599, 0.482544, 0.129278, 0.39682, 0.838922, 0.870031, 0.566886,        0.522641, 0.472174, 0.447978, 0.558935, 1.19184, 0.807466,        0.621846, 0.765641, 0.701002, 0.998617, 0.536467, 0.602834, 1.04632,        0.563083, 0.629105, 0.493605, 0.421362, 0.716212, 0.520913,        0.653301, 0.688559, 0.612859, 0.21673, 0.683028, 0.381265, 0.638092,        0.671275, 0.710335, 0.301763, 0.860698, 0.621846, 0.460767,        0.716212, 0.719323, 0.642931, 0.665745, 0.628759, 0.383339, 1.0999,        0.713446, 0.564466, 0.65261, 0.494988}, {0.698237, 0.699274,        0.649499, 0.673349, 0.626339, 0.576218, 0.692707, 0.626339, 0.65261,        0.63982, 0.544418, 0.535085, 0.67888, 0.660906, 0.675769, 0.676115,        0.665399, 0.573453, 0.450743, 0.650881, 0.643623, 0.647425,        0.64777, 0.645005, 0.643968, 0.69962, 0.62945, 0.55375, 0.670584,        0.671621, 0.659523, 0.642586, 0.330107, 0.362254, 0.63982, 0.699274,        0.680954, 0.668856, 0.638438, 0.703768, 0.690633, 0.610785,        0.681991, 0.557898, 0.666091, 0.674732, 0.646388, 0.633253, 0.58486,        0.690978, 0.605254, 0.716212, 0.659523, 0.619772, 0.672312,        0.688213, 0.640857, 0.679226, 0.587625, 0.591773, 0.596613,        0.640857, 0.624611, 0.658832, 0.640166, 0.670584, 0.64466, 0.66056,        0.646388, 0.528517}, {0.237815, 0.238161, 0.251988, 0.211891,        0.222606, 0.197373, 0.220878, 0.193571, 0.248185, 0.226409,        0.206015, 0.225026, 0.234013, 0.26132, 0.222952, 0.252333, 0.187003,        0.243692, 0.211545, 0.273764, 0.193225, 0.236433, 0.238161,        0.230211, 0.258209, 0.246803, 0.203941, 0.254062, 0.272382,        0.244037, 0.231594, 0.155894, 0.23505, 0.24542, 0.208434, 0.1673,        0.230557, 0.248877, 0.176979, 0.218804, 0.213619, 0.272382,        0.253025, 0.203249, 0.227791, 0.259246, 0.212582, 0.237124,        0.197373, 0.221915, 0.258209, 0.277221, 0.286899, 0.17214, 0.216384,        0.207397, 0.241618, 0.252333, 0.208434, 0.206706, 0.238852,        0.256827, 0.200138, 0.237124, 0.244037, 0.239889, 0.215347,        0.215002, 0.119945, 0.196336, 0.196336, 0.208434, 0.247148}}      Which with Histogram gives: ![enter image description here](http://i.stack.imgur.com/FW2vD.png)


title: Find elements in a decay chain using IsotopeData

text: I am trying to write a program using the _Mathematica_ function `IsotopeData`, but am finding the code troublesome. Due to my (relative) familiarity with Python, I am puzzled as to how _Mathematica_ works, as they are very different. $\require{mhchem}$ What I am trying to do, is to find the elements in a decay chain which end with either $\ce{^{191}_{77}Ir}$ or $\ce{^{193}_{77}Ir}$. In Python syntax, what I'm trying to do would look a bit like this:               #A would be the Atomic Mass and Z the Atomic Number     #DaughterNuclide(Z,A) would return the Daughter Nuclides of the isotope          def IsoCheck(z,a):         try:             x = DaughterNuclide(z,a)             if x in Isotopes:                  return [z,a]             else:                  return [0,0]         except:             return [0,0]          L=[]     Isotopes = [[76,191],[78,191]]     for a in xrange(1,295):         for z in xrange(1,119):             if IsoCheck(z,a) != [0,0]:                 L.append(IsoCheck(z,a))          repeat = 1     #Then, repeat until all chains are over     while repeat == 1:          repeat = 0          for x in L:              if IsoCheck(x) != [0,0] #Lets just pretend it isn't a list                  L.append(x)                  repeat = 1      Now, my question is this: what would the equivalent code to perform this task in _Mathematica_ look like?


title: FindFit returns worse result when putting constraints on parameters

text: I want to fit some data to a model of exponential decay using the `FindFit` function:               data = {{0, 78}, {24, 64.5}, {48, 70.5}, {96, 54}, {144, 64.5}, {216, 3}, {336, 0}, {696, 0}};     model = data[[1, 2]]*Exp[-k1*t];          fit1 = FindFit[data, model, k1, t]     fit2 = FindFit[data, {model, k1 > 0}, k1, t]          modelf1 = Function[{t}, Evaluate[model /. fit1]];     modelf2 = Function[{t}, Evaluate[model /. fit2]];          Plot[#[t], {t, 0, 696}, Epilog -> Map[Point, data], PlotRange -> All] & /@ {modelf1, modelf2}      Interestingly, the model with no specified constraint on _k1_ finds a much better solution than the constrained model, but the solution of the unconstrained problem falls within the range of the constrained one. Here is the output: * * *               {k1 -> 0.00512571}     {k1 -> 1.01979}      ![Result of the Plot](http://i.stack.imgur.com/bB51j.png) Why isn't the solution to the constrained problem at least as good as the solution of the unconstrained one?


title: Assigning weights to edges of a hypercube based on the Gray code labels for vertices being connected

text: Say I want to construct an $n$-dimensional hypercube graph $G$ using the command: `G = HypercubeGraph[n]`. I'd like to assign edge weights to the $2^{(n-1)}n$ edges in $G$, $(e_1,e_2,...)$, with something like a function `assignWeights[G,weightList]` where `weightList` is of the form:               weightList = {{grayCodeA, grayCodeB, w1},{grayCode..., grayCode..., w2}, ...};      Here, each entry in `weightList` specifies a weight $w_i$ for an edge between vertices in the hypercube correspond to specific Gray codes (e.g. between "0010" and "0110" codes for the $n = 4$ dimensional hypercube in this picture: http://en.wikipedia.org/wiki/File:Hamming_distance_4_bit_binary.svg). Nothing's better than an example, so let's construct one for the $n = 3$ dimensional hypercube, where our edgeweights are just random real numbers over the interval $[0,1]$:               n = 3;          tupleSet = Tuples[{0, 1}, n];     weightList = Array[{} &, 2^(n - 1)*n];          counter = 0;     For[a = 1, a <= Length[tupleSet], a++,       For[b = a + 1, b <= Length[tupleSet], b++,         If[HammingDistance[tupleSet[[a]], tupleSet[[b]]] == 1,           counter += 1;           weightList[[counter]] = {tupleSet[[a]], tupleSet[[b]], RandomReal[{0, 1}]};           ];         ];       ];          weightList      (Please let me know if you there's a nice built-in way to generate these tuple pairs without nested loops...) How would we write something like `assignWeights[G,weightList]`? Once we assign the weights, can we color code the edges to visually represent the weight assignments?


title: Differentiating an unknown solution to a PDE

text: Sorry if this question is too basic -- I'm not very familiar with Mathematica. I am interested in a way to systematically address the following sort of problem: Suppose that $u=u(x,y)$ is a function of two variables on $\mathbb{R}^2$ that satisfies a Liouville type equation: $$\Delta u= e^{-2u}$$. I can check by hand that the function $$v=\partial^2_{xy} u+\partial_x u \cdot \partial_y u$$ is harmonic, i.e. $$\Delta v=0.$$ My question is how can I make Mathematica verify this? I'm interested in more complicated examples I don't want to check by hand, but the principle is the same.


How to avoid plotting lines not defined in a Which function?               fa1[x_] := Which[x >= 15, 1, x >= 10, 0.55, x >= 5, 0.1]     Plot[fa1[x], {x, -1, 20}, BaseStyle -> AbsoluteThickness[4],       PlotLegends ->        LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]]      ![enter image description here](http://i.stack.imgur.com/beNmg.png)


title: Mathematica Solve Hangs Indefinitely

text: The following code hangs               Clear[S, Ext, k, α, β, γ, δ, f, a, b, c];     S[k_] := α β^(f - k) γ^(f - k)^2 δ^(f - k)^3;     Ext[k_] := a + b k + c k^2;     Solve[{S'[km] == Ext'[km], S''[km] == Ext''[km], Ext[km] == S[km]}, {a, b, c}, Reals];      This sort of algebra was going to get really ugly and I was really hoping Mathematica could handle it... any ideas on how what might be causing Mathematica to get stuck in the "Running..." state? My goal is is a solution for {a,b,c} in terms of {α, β, γ, δ, f, km}.


title: How does Mathematica determine that an evaluation should be terminated?

text: How **exactly** does _Mathematica_ determine that evaluation of particular expression should be finished and the result should be returned? Here are some examples of unclear behavior which have arisen, when I tried to understand deeper Todd Gayley's `Block` trick:               x := Block[{tried = True}, x + 1] /; ! TrueQ[tried]         x + y         (* 1 + x + y *)          x + 1      > During evaluation of In[3]:= $IterationLimit::itlim: Iteration limit of 4096 > exceeded. >>               (* Hold[4096 + x] *)      Why did the evaluation stop at `1 + x + y` in the first case and the second go into an infinite loop? The other interesting side of the trick is that when we evaluate just `x`, the infinite loop does not begin. The reason is that evaluation in this case does not go outside of the `Block` scope:               Clear[x];     x := Block[{tried = True}, x + 1] /; ! TrueQ[tried]     x /; ! TrueQ[tried] := x + 1     x     x /; TrueQ[tried] := x + 1     x          (* 1 + x *)      > During evaluation of In[1]:= $RecursionLimit::reclim: Recursion depth of 256 > exceeded. >>               (* 254 + Hold[RuleCondition[$ConditionHold[$ConditionHold[          Block[{tried = True}, x + 1]]], ! TrueQ[tried]]] *)      But if we try to use `Set` instead of `SetDelayed` we get a couple of infinite loops:               x = Block[{tried = True}, x + 1] /; ! TrueQ[tried];      ![](http://i.stack.imgur.com/j6XYg.png) What happens in this case?


title: Is it possible to obtain explicit symbolic solutions to such linear ordinary differential equations?

text: The ordinary differential equations to solve have symbolic parameters $k_1,k_2,k_3,k_4,k_5,k_6 \in \mathbb{R}$. $$ \left\\{ \begin{array}{l} {y_1}'(t)=-{k_1} {y_1}(t)-{k_2} {y_1}(t),\\\ {y_2}'(t)={k_2} {y_1}(t)-{k_3} {y_2}(t),\\\ {y_3}'(t)={k_1} {y_1}(t)+{k_3} {y_2}(t)-{k_4} {y_3}(t),\\\ {y_4}'(t)={k_4} {y_3}(t)-{k_5} {y_2}(t) {y_4}(t)+{k_6} {y_5}(t),\\\ {y_5}'(t)={k_5} {y_2}(t) {y_4}(t)-{k_6} {y_5}(t)\\\ \end{array} \right.$$ The ODE system itself seems simple when all $k_i$ are numerical numbers. How to solve it symbolically ? Is it possible to obtain explicit solutions? Update: Expressions in MMA:(DSolve does not work for such nonlinear ODE system)                 DSolve[{D[y1[t], t] == -k1*y1[t] - k2*y1[t],       D[y2[t], t] == k2*y1[t] - k3*y2[t],       D[y3[t], t] == k1*y1[t] + k3*y2[t] - k4*y3[t],       D[y4[t], t] == k4*y3[t] - k5*y2[t]*y4[t] + k6*y5[t],       D[y5[t], t] == k5*y2[t]*y4[t] - k6*y5[t]}, {y1[t], y2[t], y3[t],        y4[t], y5[t]}, t]


title: On using DiracDelta[t] in OutputResposne in version 10. Different result from version 9

text: I am baffled by this. I was trying to run same example I had working in version 9.01 and found now I get empty plots. The example is here . Here is a simplified version of the above. The same exact example produces a plot in version 9.01. But in Version 10, it is empty. ![enter image description here](http://i.stack.imgur.com/t6ajQ.png)               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], {t, 0, 20}];     Plot[Evaluate[%], {t, 0, 20}]      I tried to find what is going on, so I asked for analytical solution, in version 10 it says:               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], t] // ComplexExpand // Simplify // Chop      ![Mathematica graphics](http://i.stack.imgur.com/E8C68.png) In version 9.01:               w = 1; z = 0.07;     sys = TransferFunctionModel[w^2/(s^2 + 2 z*w*s + w^2), s];     fun = First@OutputResponse[sys, DiracDelta[t], t] // ComplexExpand // Simplify // Chop      ![Mathematica graphics](http://i.stack.imgur.com/jF5Vi.png) So in version 10 the solution seems to be reversed. going back in time !                Plot[Evaluate[fun], {t, -20, 0}]      ![Mathematica graphics](http://i.stack.imgur.com/xD0uO.png) Any idea what is going on? What changes could have caused this?


title: Rectangles of the Same Size Aren't Shown the Same!

text: I've written a mathematia code which arranges $n$ unit squares in columns of length $m$ (of course, when $n$ is not divisible to $m$, then the last column is not full). This is the code:               n = 60;     m = 1;     l = {};     For[i = 0, i <= n - 1,       l = Append[l,         Rectangle[{Quotient[i, m], Mod[i, m]}, {Quotient[i, m] + .9,           Mod[i, m] + .9}]]; i++]     Graphics[{Red, l}]      **Here's my problem:** For a fixed value for $n$ (say, $60$), if you change $m$ then you get squares of smaller or larger sizes, as shown below. I want all the squares for different $m$'s be of the same size. What should I do? Thanks in advance. for $n = 60$ and $m = 1$: ![enter image description here](http://i.stack.imgur.com/H9P67.gif) for $n = 60$ and $m = 13$: ![enter image description here](http://i.stack.imgur.com/55UOW.gif)


title: Changing line thickness without changing line length

text: Is there any way to change the thickness of line without changing the width? For instance, the following example shows that as thickness increases, the white gap decreases. Is there any way to maintain the gap?               Show[         ListPlot[{{0, 2}, {13.4, 2}}, PlotRange -> All, Joined -> True,                  Mesh -> None, PlotStyle -> {Gray, Thickness[0.01]}],         ListPlot[{{14.7, 2}, {24, 2}}, Joined -> True, Mesh -> None,                  PlotStyle -> {Gray, Thickness[0.01]}]     ]      ![thin lines with gap](http://i.stack.imgur.com/UTdOv.png)               Show[         ListPlot[{{0, 2}, {13.4, 2}}, PlotRange -> All, Joined -> True,                  Mesh -> None, PlotStyle -> {Gray, Thickness[0.05]}],         ListPlot[{{14.7, 2}, {24, 2}}, Joined -> True, Mesh -> None,                  PlotStyle -> {Gray, Thickness[0.05]}]     ]      ![thick lines without gap](http://i.stack.imgur.com/TVtxR.png)


title: Factor inside argument

text: How do you use Factor so that it will factor expressions inside the arguments of some bigger expression. For example                Factor[ Cos[t w - t z]]      gives                Cos[t w - t z]      but i would like it to give:                Cos[t(w - z)]


title: Mathematica command for type checking?

text: I have a program where users can enter mathematica commands that can evaluate to any of the standard numeric types (complex, real, int, etc.), or to boolean values. Moreover the users can enter functions that depend on variables. (For the sake of this post let's assume the variables are all of type complex.) I want to know if there's a mathematica command that can type-check an _arbitrary_ string. Specifically, I'd want something like               ReturnsComplex[string, assumptions]      that would return true for "1/x + 7x^2 + Sin[x]" but false for "E^x == 5", say. Does anyone know of such a command, or a way to implement one without a huge quantity of work? (Assume that I can identify all the variables in the string and substitute in if necessary.)


title: Why Solve and Simplify give different results?

text: I want to solve the following equation               y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y))      I tried               Simplify[y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y)), y]      which gave me > Solve[0.166667] Then I tried               Solve[y == (1/(1/4 + y) - 1/(3/4 - y))/((1/4 + y) + 1/(3/4 - y)), y]      which gave me > {{y -> 1.70683179538858`}, {y -> -0.82623525169495` \+ 0.902601424800742`I},   >  {y -> -0.82623525169495` \- 0.902601424800742`I}, {y -> > 0.195638708001323`}} I guess `Simplify` deletes potential roots, but `Solve` and `Simplify` didn't even have an overlap in the roots. Any idea?


title: Strange behaviour of OutputResponse

text: I am having some trouble when using OutputResponse. For instance consider the following command               Simplify[Chop[OutputResponse[       TransferFunctionModel[           {             {{12265.875860667435 + 15863.964729950849*s + 5000.*s^2}},              12265.875860667435 + 15986.623488557521*s + 5132.222766045224*s^2 +             81.0807167110999*s^3 + 16.908502769264427*s^4 + 1.*s^5           },           s,           SystemsModelLabels -> {{None}, {None}}           ],       UnitStep[t],       t]]]      The output is zero on version 9.0.1-mac. It can't be zero. The above transfer function is a result of the feedback connection of a series connection between two transfer functions. What am I missing? Many thanks Ed


title: How can I return a Sequence?

text: Recently I had the need to redefine a certain symbol in my init.m so it would be automatically omitted from any lists it appears in. I decided to redefine it to an empty sequence, e.g. `Locked = Sequence[]`, but that got me thinking. What if I wanted to return a sequence (not necessarily an empty one) in a `:=` definition? `Return` doesn't have the `SequenceHold` attribute, and adding it in a package might cause problems, so what would I do? **EDIT:** I think I've figured out what exactly causes me to have the problem. I've defined it to display a `Message` first to let me know whenever a package I'm importing attempts to attack my computer. (It _is_ trying to cause my computer to behave in a manner not consistent with my wishes, after all.) So I defined it as `Locked := (Message[Locked::nope]; Sequence[])`, but strangely it just returns Null. (It doesn't show a return value, but if I do `{Locked}`, it returns `{Null}`, and if I try to set it as an attribute it says that Null is not a valid attribute and doesn't set any of them.)


title: float output left in CDF

text: I'm experimenting with embedding a CDF on a Wordpress site and while it mostly works, the plots are running out of room along the right edge. It seems like if the images were floated left they would fit and look like the output does in MMA. This might have a simple answer, yet how to force the plot output to float left? See http://nomtbf.com/2013/04/weibull-vs-exponential-pdfs/ for an example of the issue.


title: How can one find undocumented options or option values in Mathematica?

text: _Mathematica_ has a lot of undocumented or poorly documented options.   1. How does one go about working out if there is an undocumented option that might solve a particular problem?   2. How does one work out what the universe of possible values the option might take are? (This also applies to options whose existence is documented, but where the range of valid values isn't.) * * * As background, here is a collection of ones I and others have found so far: **Graphics** The `Method` option is an option for `Graphics` and related commands like `BarChart`. It is mentioned in the notes in the documentation and turns up in `Options[Graphics]` but is not listed as an option in the documentation with any examples. There are many sub-options, none of which are explicitly documented.   * `Method -> {"ShrinkWrap" -> True}` removes whitespace that _Mathematica_ adds as a tiny rim to each plot. (pointed out by Sjoerd)   * `Method -> {"GridLinesInFront" -> True}` does what it says (see Brett Champion's answer to this question and this MathGroup thread). `Dynamic` `GridLines` using this option are present in much of the graphical Wolfram|Alpha output (See, e.g. the edited number line code).   * `Method -> {"AxesInFront" -> True}` also does what it says. (see TomD's comment on Brett's answer)   * `Method -> {Refinement -> {ControlValue -> angle}}` sets the angle that decides when two points in a plot are not further subdivided - default is `5\[Degree]`. (see Yaro's answer here and the relevant page in Stan Wagon's book. Also, a `Plot` version comparison by Alexey)   * The option `"MessagesHead"` is used to track the origin of calls to `Plot`, etc., made by dependent plot functions such as `LogPlot`, `LogLinearPlot`, and `DateListLogPlot`. This allows the correct options and messages to be passed to and from the general function. An example of its use can be seen in this question.   * `ImageSizeRaw` option for various plotting and graphics functions is not documented, but turns out to be important for embedding CDFs into web pages.   * `PrivateFontOptions -> {"OperatorSubstitution" -> False}`, as documented here, stops minus signs, parentheses and the like from being in _Mathematica_ 's special fonts rather than the selected text font.   * s0rce discovered that the `ScalingFunctions` option works for line plots (`ListPlot`, `Plot`, etc). Possible values include `"Reverse"`, `"Log"` `"Log10"` – the last of these being itself undocumented.   * Not strictly a graphics function, but often used to create nice-looking ticks, `FindDivisions` has an undocumented `Method` option: for example, `FindDivisions[{-1.8,8.9}, 6, Method -> "ExtendRange"]` gives the encompassing divisions `{-2, 0, 2, 4, 6, 8, 10}`, as does `Method -> Automatic`; any other setting for `Method` gives the _inner_ divisions: `{0, 2, 4, 6, 8}`.    * You can control the amount a `PieChart` segment pops out of the chart when you click it using `SetOptions[Charting'iSectorChart, {PopoutSpacing -> n}]`, where `n` is numeric. The default is 0.2; for fun, try a negative number. You can suppress this behaviour altogether using `SetOptions[Charting'SectorChart, {Popout -> False}]` (in both these examples, change the quote mark to a backquote). **Panels** As noted in an earlier question, these options pop up in some graphics/panels, but are unrecognised when one uses them explicitly in `Panel`, `Graphics` or related structures:   * `LineColor`   * `FrontFaceColor`   * `BackFaceColor`   * `GraphicsColor` **Legends** There seem to be a lot of undocumented options here:   * `AssembleLegendContainer`   * `BubbleScaleLegend`   * `ColorGradientLegend`   * `ContourLegend`   * `CurveLegend`   * `GridLegend`   * `Legend`   * `LegendContainer`: `SetOptions[Legending`GridLegend, Legending`LegendContainer -> Identity]` removes the border from legends (thanks to Mr.Wizard)   * `LegendHeading`   * `LegendImage`   * `LegendItemLayout`   * `LegendLayout`   * `LegendPane`   * `LegendPosition`   * `LegendReap`   * `Legends`   * `LegendSize`   * `LegendSow` **Equation-solving and minimisation/optimisation**   * `Evaluated -> False` option of `FindRoot` (TomD in comments)  **System options for evaluation** Per acl's answer below, `SystemOptions[]` reveals many hidden options using the following syntax. These can be set using `SetSystemOptions[]`.   * `"PackedArrayOptions" /. SystemOptions[]`   * `"CompileOptions" /. SystemOptions[]` Although this book by Nancy Blachman has been written for Version 2, it is still not a bad starting point: http://www.amazon.com/Mathematica-Quick- Reference-Version-Spiral/dp/0201628805


title: Geomarker Scaling

text: Struggling to get a 3d cylinder to scale properly on a street map. I want to use the stacked cylinder as a custom pin.               mypin = Graphics3D[     Table[Cylinder[{{0, 0, h}, {0, 0, h + 0.95}}, 0.25], {h, 1, 19}],      ImageSize -> Automatic];          GeoGraphics[{GeoPosition[{51.5144, -0.08028}],      GeoMarker[GeoPosition[{51.5144, -0.08028}], mypin,      "Scale" -> Automatic, "Alignment" -> Bottom]},      GeoRange -> Quantity[0.05, "Miles"]]      I know automatic doesn't work on its own but I've been replacing it with various values and all that happens is the marker vanishes. I should add that the reason for doing this is that the cylinder represents a building of x floors, and once I get the cylinder scaled properly the intention is to use each cylinder to display various feature of the building. E.g. Red cylinder if a floor is over capacity, cylinder radius proportional to the number of desks it contains.


title: How to create a group action table with Mathematica?

text: Background: I want to explain the Sylow Theorems as detailed as possible, therefore I am rewriting the proof using concrete examples. Since the answers to my questions ( about Mathematica ) have often, if not always, exceeded my expectations, and I lack the tools to adequately show a table, I start with a compact description of my question. I can elaborate if required, of course. Question: **Is it possible to create a group action table with Mathematica?** For example: Let $G = \left\\{ 1,a,a^2, b, ba, ba^2 \right \\}$, where $a^3=b^2=1, ab=ba^2 (D3) $ . Let $S$ be the set of subsets of size $3$ of $G$: $\left\\{ \left\\{ 1,a,a^2 \right \\}, \left\\{1,a,b \right \\}, ..., \left\\{b,ba,ba^2 \right \\} \right \\} $ . Define the map $f: G \times S \rightarrow S \ $ by $(g,s) \mapsto gs$. **The group action table, illustrating the map $f$ would be of size 20 X 6 with each cell containing an element of $S$.** I have ( experience with ) the Mathematica AbstractAlgebra package. I'll accept answers in GAP also.


title: Flatten at a certain level

text: In an earlier question the brainteasing fourth syntax variant of `Flatten` was discussed. I see that with               Flatten[{{{1, 2, 3}, {4, 5}}, {{6, 7}, {8, 9, 10}}}, {{1}, {2, 3}}]      I can `Flatten` the lists at level 2 (i.e., Merge `{1, 2, 3}` with `{4, 5}`, and `{6, 7}` with `{8, 9, 10}`) to `{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}}`, something that I expected `Flatten` to be able to do with the usual level specification. But that convention doesn't work here. `Flatten[{{{1, 2, 3}, {4, 5}}, {{6, 7}, {8, 9, 10}}}, {2}]` returns `{{{1, 2, 3}, {6, 7}}, {{4, 5}, {8, 9, 10}}}` With that introduction, now to my question: How would I use `Flatten` to flatten the slightly differing               {{{1, 2, 3}, {4, 5}, 11}, {{6, 7}, {8, 9, 10}, 12}}      to               {{1, 2, 3, 4, 5, 11}, {6, 7, 8, 9, 10, 12}}?      If that's not possible I'd have to resort to using an additionally `Map`, but I really would like to avoid that, as I just feel that `Flatten` or another single function ought to be able to do this on its own. In this case, a simple               Flatten /@ {{{1, 2, 3}, {4, 5}, 11}, {{6, 7}, {8, 9, 10}, 12}}      would do, and since `Map` does follow the level specification conventions I can use it to `Flatten` other depths in more complex constructions.


title: Celebration: How to golf a marriage with a prefix free code

text: We all know a conspicuous member of our community got hitched recently. As most of us are not in Malta, and weren't able to fly there, I thought of a celebration question. Sort of. The challenge is golfing a function (Mma only) that finds a prefix free encoding for the letters of two sentences. The trick is that both sentences (given as parameters) must share **the same encoding** , with one of them written backwards. The number of available symbols for the encoding is also a parameter for the function (always less than 10), and the function should attempt to find the shortest encoding for that number of symbols. There is no a-priori guarantee that a solution exists for every parameter set. As an example, related to our celebration:               we wish you the best      and               sz is the handsomest groom      Inspiration was taken from this question (which does not require a prefix free code), but is a good explanation of what is required. Happy wedding and golfing! Shortest code wins! **PS:** A bounty of 100, a wedding garter and the party leftovers to the winner **EDIT** Clarifications. To be updated as comments and answers arise   1. No caps. Only lowercase.   2. No need to encode whitespaces, special chars or punctuation (skip them and consider only lowercase letters)    3. Your solution _should_ be able to show up results before they are back from the honeymoon.


title: What are some useful, undocumented Mathematica functions?

text: There have already been some questions about some undocumented functionality in Mathematica. Such as ( _please add to these lists!_ )   * How can one find undocumented options or option values in Mathematica?   * What do these undocumented Style options in Mathematica do?   * Undocumented command-line options Also, other questions and answers that contained undocumented functions   * `Internal`InheritedBlock` (also in Exposing Symbols to $ContextPath)   * `Internal`Bag` (in Implementing a Quadtree in Mathematica) (also here)   * `RuleCondition` (in Replace inside Held expression) Along with the "Undocumented (or scarcely documented) Features" segment of the What is in your Mathematica tool bag? question. Szabolcs also maintains a list of Mathematica tricks which contains a list of "undocumented stuff". * * * **So, what undocumented functions do you know and how do you use them?** (Added useful information is maybe how you discovered the functions and any version dependence.)


title: CUDALink Error: A CUDALink kernel timed out?

text: I'm following the CUDALink tutorial [ http://reference.wolfram.com/language/CUDALink/tutorial/Introduction.html ] and everything is going fine until I get to the part that calls CUDADot on the matrices. At this part I get a time out error but the Out line returns almost immediately. I've included the commands and some other CUDA and system information bits. I'm running Windows 8.1 with Mathematica 10 Home. There is an on-board intel graphics chip and the Nvidia GPU. I can see that the Nvidia GPU registers that Mathematica is using it when I execute the CUDAQ[] command (Nvida taskbar icon shows GPU is active and that Mathematica is using it). What is odd is that I can execute a few of the CUDA examples in the help. I've tried a few of the image ones (the tiger and the moon, for example) but I can't seem to get the CUDADot to work. Everything seems to be installed fine.               Needs["CUDALink`"]          CUDAQ[]     True          CUDAInformation[]     {1 -> {"Name" -> "GeForce GTX 860M", "Clock Rate" -> 1019500,      "Compute Capabilities" -> 5., "GPU Overlap" -> 1,      "Maximum Block Dimensions" -> {1024, 1024, 64},      "Maximum Grid Dimensions" -> {2147483647, 65535, 65535},      "Maximum Threads Per Block" -> 1024,      "Maximum Shared Memory Per Block" -> 49152,      "Total Constant Memory" -> 65536, "Warp Size" -> 32,      "Maximum Pitch" -> 2147483647,      "Maximum Registers Per Block" -> 65536, "Texture Alignment" -> 512,     "Multiprocessor Count" -> 5, "Core Count" -> 160,      "Execution Timeout" -> 1, "Integrated" -> False,      "Can Map Host Memory" -> True, "Compute Mode" -> "Default",      "Texture1D Width" -> 65536, "Texture2D Width" -> 65536,      "Texture2D Height" -> 65536, "Texture3D Width" -> 4096,      "Texture3D Height" -> 4096, "Texture3D Depth" -> 4096,      "Texture2D Array Width" -> 16384,      "Texture2D Array Height" -> 16384,      "Texture2D Array Slices" -> 2048, "Surface Alignment" -> 512,      "Concurrent Kernels" -> True, "ECC Enabled" -> False,      "TCC Enabled" -> False, "Total Memory" -> 4294967296}}          randM = RandomReal[1, {4000, 4000}];          AbsoluteTiming[randM.randM;]     {1.276902, Null}          randMG = CUDAMemoryLoad[randM]     CUDAMemory["<22093>", "Double"]          AbsoluteTiming[res = CUDADot[randMG, randMG]]     CUDADot::lnchtout: A CUDALink kernel timed out. >>     {0.071061, CUDADot[CUDAMemory["<22093>", "Double"], CUDAMemory["<22093>", "Double"]]}          CUDADriverVersion[]     "340.52"          CUDAResourcesInformation[]     {{"Name" -> "CUDAResources", "Version" -> "10.0.0.1",      "BuildNumber" -> "", "Qualifier" -> "Win64",      "WolframVersion" -> "10+", "SystemID" -> {"Windows-x86-64"},      "Description" -> "{ToolkitVersion -> 6.0, MinimumDriver -> 270.0}",      "Category" -> "", "Creator" -> "", "Publisher" -> "",      "Support" -> "", "Internal" -> False,      "Location" ->      "C:\\Users\\Edmund\\AppData\\Roaming\\Mathematica\\Paclets\\\     Repository\\CUDAResources-Win64-10.0.0.1", "Context" -> {},      "Enabled" -> True, "Loading" -> Manual,      "Hash" -> "8cd86e25825c095afcb781fa82d3cf73"}}          CUDAResourcesInstall[]     {     PacletManager`Paclet[     "Name" -> "CUDAResources", "Version" -> "10.0.0.1",      "MathematicaVersion" -> "10.*",      "Description" -> "{ToolkitVersion -> 6.0, MinimumDriver -> 270.0}",      "SystemID" -> {"Windows-x86-64"}, "Qualifier" -> "Win64",      "Extensions" -> {{     "Resource",      "Resources" -> {     "CUDAToolkit", "ExampleData", "LibraryResources", "CUDALink",      "OpenCLLink"}}},      "Location" -> "C:\\Users\\Edmund\\AppData\\Roaming\\Mathematica\\\     Paclets\\Repository\\CUDAResources-Win64-10.0.0.1"]}      Any ideas? Thanks, Edmund


title: Ploting legends in contourplot

text: In Mathematica 8. Given this:               f[x_, y_, z_] := z - x^2 - y^2 (*relation among the variable f[x,y,z]==0*)     parameter = Range[0.1, 1, 0.1];(*choice of parameter values*)      I'm trying to plot the level curves               ContourPlot[Evaluate@Table[f[x, y, z] == 0, {z, parameter}], {x, -1, 1}, {y, -1,1}, PlotLegends -> parameter]      I have the next error message: > ContourPlot::optx: "Unknown option PlotLegends in ContourPlot[{0.1 > -x^2-y^2==0,0.2 -x^2-y^2==0,0.3 -x^2-y^2==0,0.4 -x^2-y^2==0,0.5 > -x^2-y^2==0,0.6 -x^2-y^2==0,0.7 -x^2-y^2==0,0.8 -x^2-y^2==0,0.9 > -x^2-y^2==0,1. -x^2-y^2==0},{x,-1,1},{y,-1,1},PlotLegends->parameter]" I tried using:               Needs["PlotLegends`"]          ShowLegend[        ContourPlot[Evaluate@Table[f[x, y, z] == 0,         {z, parameter}], {x, -1, 1}, {y, -1,1}, PlotLegends -> parameter] ]      what I should do?


title: Edit Automatic PlotRange

text: if I have a plot let us say               Plot[x^2 - 5 x - 10, {x, 0, 8}]      I want o check if there is a way to know the automatic plot range and to add or subtract from that range as I need. I will assume something fictitious like this:               Plot[x^2 - 5 x - 10, {x, 0, 8}, PlotRange -> (Automatic + {0, 10})]      is there a way to do something like this?


title: Problem with infinite sum

text: I am facing a problem in evaluating infinite sums of the following form. As a first thing define the following function               Z[n_] := Product[1/(1 - t^i), {i, 1, n}]          P[list_] := (num = Union[list]; Product[Z[Count[list, num[[i]]]], {i, 1, Length[num]}])      Then consider a sum of the following kind               Sum[P[{i, j}]*t^(-i - j), {i, 0, \[Infinity]}, {j, 0, \[Infinity]}]      Now, Mathematica behaves in a strange way: it considers the P[{i,j}] factor as if i is always different than j. This does not make sense, since for example I am summing over the couples (2,2) and (3,3). I believe the problem relies in the way the infinity is considered, since everything works fine with arbitrary high finite sums. What could I do?


title: How to typeset a system of equations

text: Is it possible to typeset systems of equations in _Mathematica_ , and if so, how can I do it using a big left bracket as one could in LaTeX with `\left\{ ... \.`? I know this is possible using the `Piecewise`, but is there a special command for this?


title: The following code doesn't seem to work finding Chomatic Number of Undirected Graph in Mathematica(MathKernel)

text: In[37]:= g = Graph[{4->3, 5->3, 5->4, 6->1, 6->2, 6->4, 6->5}]          Out[37]= Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]      I created a graph as show above and while trying to import combinatorica package, I get the following error               In[38]:= << Combinatorica`;          General::compat:         Combinatorica Graph and Permutations functionality has been superseded by         preloaded functionaliy. The package now being loaded may conflict with         this. Please see the Compatibility Guide for details.      I don't know what's going on here, but while trying to find the chromatic number using the following command, it gives the subsequent following error.               In[43]:= CN = ChromaticNumber[g]          First::normal: Nonatomic expression expected at position 1 in First[All].          First::normal: Nonatomic expression expected at position 1 in First[All].          Part::partw: Part 2 of First[All] does not exist.          First::normal: Nonatomic expression expected at position 1 in First[All].          General::stop: Further output of First::normal          will be suppressed during this calculation.          Part::partw: Part 2 of First[All] does not exist.          Part::partw: Part 2 of First[All] does not exist.          General::stop: Further output of Part::partw          will be suppressed during this calculation.          Range::range: Range specification in          Range[V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]]          does not have appropriate bounds.          Table::iterb: Iterator {Combinatorica`Private`i$318,           V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]} does          not have appropriate bounds.          Join::heads: Heads Combinatorica`Private`Double and Table at positions 1 and 2          are expected to be the same.          Join::heads: Heads Combinatorica`Private`Double and Table at positions 1 and 2          are expected to be the same.          Join::heads: Heads Combinatorica`Private`Double and List at positions 1 and 2          are expected to be the same.          General::stop: Further output of Join::heads          will be suppressed during this calculation.          Table::iterb: Iterator {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,              6 -> 4, 6 -> 5}]]} does not have appropriate bounds.          Transpose::nmtx:         The first two levels of the one-dimensional list {} cannot be transposed.          Transpose::nmtx:         The first two levels of the one-dimensional list {} cannot be transposed.          Part::pspec: Part specification          {4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}          is neither an integer nor a list of integers.          Part::pspec: Part specification          Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}][[2]]          is neither an integer nor a list of integers.          Table::iterb: Iterator {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,              6 -> 4, 6 -> 5}]]} does not have appropriate bounds.          General::stop: Further output of Table::iterb          will be suppressed during this calculation.          Part::pspec: Part specification Combinatorica`Private`Double[]          is neither an integer nor a list of integers.          General::stop: Further output of Part::pspec          will be suppressed during this calculation.          Range::range: Range specification in          Range[1 + Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2,                  6 -> 4, 6 -> 5}]]}][[Combinatorica`Private`Double[],0]]] does not          have appropriate bounds.          Complement::heads:         Heads Part and Range at positions 2 and 1 are expected to be the same.          Out[43]= Table[Complement[Range[1 +           >       Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4,           >             6 -> 5}]]}][[Combinatorica`Private`Double[],0]]],           >     Table[0, {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4,           >           6 -> 5}]]}][[Combinatorica`Private`Double[],0]]],           >    {V[Graph[{4 -> 3, 5 -> 3, 5 -> 4, 6 -> 1, 6 -> 2, 6 -> 4, 6 -> 5}]]}]      Did I go wrong somewhere ? please help.


title: Is it possible to find a CellularAutomaton behind a sequence of 2D Tables

text: Maybe this is a hard question, maybe not. Whoever knows the answer can help me a lot starting working on CA theory. Let's suppose I have a sequence               a[n_] := Table[f[i, j], {i, -n, n}, {j, -n, n}]      for some known function $f$. And let's make it simple: $f$ takes only the values $0$ and $1$. Is there a way to find a cellular automaton that will create the same table-- that is, to generalize the approach demonstrated by Michael E2 in his answer to the question about how to generate a certain type of nested array? For reference, the code he presented was the following:               Grid[CellularAutomaton[{     670410854876259114171370389518449844628889143930760386943729872789478228151265\     8462491554691453382697921609151728673186802143641955019044568101339107753983,     2, {1, 1}}, {{{0}}, 1}, {{{9}}}] /. 1 -> "*"]


title: How to use many global assumptions

text: I would like to use many global assumptions. Say I have two global assumptions.               $Assumptions = 0 < a < 1          $Assumptions = 0 < b < 1      Then I would like to print `Yes` if `a b > 1` holds and print `No` otherwise. For this I have               Refine[If[a*b > 1, Print[Yes], Print[No]], $Assumptions]      My result is just a repetition of `If` term as follows:               If[a q > 1, Print[Yes], Print[No]]      Can anyone help?


title: Image Restoration

text: I want to degrade the image, and then execute the restoration, such as a lena.jpg. I tried this:               lena = ExampleData[{"TestImage", "Lena"}];     lena1 = GaussianFilter[lena, 5]       With these get stained image lena1.jpg is stained image from lena this image use for recognition in folow step                ImageDeconvolve[lena1, GaussianMatrix[5.10]]      only parameter 5.10 gives beter picture then lena1.jpg Then this I have three pictures "lena.jpg"-original image, "lena1.jpg"-degraded image and Image after deconvolve - Restoration image. Problem: 1) I do not know which settings (filters) to apply during restoration pictures and 2) Which function to use when degradation and restoration during which, as you know? Whether we can write a concrete example of an image degradation and restoration so obtained images? Sorry for my English... :)


title: Calling Mathematica from Lazarus/Freepascal

text: I will appreciate if anyone can give me an hint about freepascal and mathematica mathlink communication. I'd like to build a Form using Lazarus/freepascal that call mathkernel. I'm trying to move away from ExcelLink-component to a home made Form.


title: Function that displays set of integers fulfilling constrictions

text: I would like to make a function of three parameters $i$, $j$ and $k$ that displays a list of integers fulfilling some criteria. Specifically the set of integers is: $\zeta_{ijk} = \Big\\{p\in\\{2j+2,2j+3,\ldots,2k+2\\}\ |\ $ $p=2i+1,\ \text{or}\ p\leq i+j,\ \text{or}\ p\geq i+k+3 \Big\\}$ for $k\in\\{0,1,\ldots\\}$, $\ j \in \\{0,1,\ldots,k\\}$ and $i\in\\{j,j+1,\ldots,k+1\\}$. where $|$ denotes that constrictions on $p$ follows. To clarify, some examples are: $\zeta_{000}=\zeta_{100}=\emptyset$ $\zeta_{001}=\\{4\\}$, $\ \zeta_{101}=\\{3\\}$, $\ \zeta_{201}=\\{2\\}$ $\zeta_{111}=\zeta_{211}=\emptyset$ $\zeta_{002}=\\{5,6\\}$, $\ \zeta_{102}=\\{3,6\\}$, $\ \zeta_{202}=\\{2,5\\}$, $\ \zeta_{302}=\\{2,3\\}$ And so on. I have problems implementing the logical constrictions in e.g. the Table-function, inside my user-defined function. Any ideas?


title: TimeSeriesForecast Forecasts

text: I am trying to make sure I understand how `TimeSeriesForecast` works. I apologize in advance for the basic nature of this question. I am using Mathematica 10. I create a `TimeSeries` in a stock like GE, containing O/H/L/C prices and from there estimate a vector autoregression (ARMA) model using some in-sample data. I now want to produce 1-step ahead forecasts, period by period, for the out of sample data. The code I have listed below does this and produces the results as shown. I want to make 100% sure that the forecast produced for period n are the forecast OHLC prices for period n, and not the forecast prices produced at period n for period n+1. So below, is the first set of forecast prices the forecast for period 8325, or the forecasts produced in period 8325 for period 8326? Whats confusing me is the with ISend = 8325, I get:               GE["Path"][[ISend + 1]]         (* {8325, {20.4819, 20.5104, 20.1867, 20.32}} *)      i.e it seems that the TimeSeries variable GE somehow "lags" by 1 period. _Forecasting code_               ISend         (* 8325 *)          n = 1;          forecasts =        Flatten[Table[         TimeSeriesForecast[eproc,            TimeSeriesWindow[GE, {ISend - 3 + i, ISend - 2 + i}], {n},            Method -> "Covariance"]["Path"], {i, 1, 386}], 1];          Take[forecasts, 5]          (* {{8325, {19.8498, 19.8257, 19.3094,         19.6899}}, {8326, {20.711, 20.7849, 20.3424,         21.2416}}, {8327, {20.142, 20.4853, 20.1133,         20.2042}}, {8328, {20.1565, 20.2824, 20.009,         20.0737}}, {8329, {20.0761, 20.1621, 19.96, 20.0177}}} *)


title: Associate the elements of a table

text: I have a table form as:               table = {{a, 6}, {b, ff}, {c, 2}}      I want to associate the first element of each pair from the table to the second element of the pair as in:               a=6, b=ff, c=2.      I want the parameters a,b,c to be recognized throughout the program with assigned values. Doing as below, everything is perfect:               a := 6;     a^2 + 5     Clear[a]     Out[2] 41      But in the example below, I failed:               Clear[table, a, b, c]     table = {{a, 6}, {b, ff}, {c, 2}}     z = table[[1, 1]]     z := table[[1, 2]]     a^2 + 5          Out[4]  {{a, 6}, {b, ff}, {c, 2}}     Out[5]  a     Out[6]  5 + a^2      Why this fail?


title: Differential equation with random variable

text: How can I derive analytically or compute numerically the solution to following differential equation $$ dy/dt = y\cdot X\cdot (y\cdot X - g(y,X))\cdot X $$ where X is a random variable (e.g. from a normal distribution) and g is a known function of y and X, e.g. $g=E[(y\cdot X)^2]$ ?


title: Web Browsing Automation with Mathematica

text: I want to build a bot to automate web browsing, this mean something like:   * filling forms   * press "submit" buttons   * find certain text inside pages   * and so on... How can I do this with Mathematica? The `Import` function just make you download a single web page but it doesn't support cookies and similar things to build a complete automated bot, does Mathematica have some useful packet to do so?


title: Question about modifying a Slider2D control

text: Background: I want to develop a custom control, based on a 2D slider. I currently have this ( working ) example.                 Manipulate[        If[(iOld != i || jOld != j),         lata[[1]] = i; lata[[2]] = j];         i = lata[[1]];         j = lata[[2]];         iOld = i;         jOld = j;         lata,         Row[{            Column[{            Control[{{i, i, "i"}, -5, 5, 0.25}],            Control[{{j, j, "j"}, -5, 5, 0.25}]}]            ,            Control[{{lata, lata, "lata"}, {-5, -5}, {5, 5}, {0.25, 0.25}}]         }],         Initialization -> {           lata = {1, 0},           i = lata[[1]],           j = lata[[2]],           jOld = j,           iOld = i         }]      This control is a 2D Slider and two normal sliders in sync. Clearly the two sliders are not necessary but I like the built-in functionality of the slider's drop down precision- entry ( and auto play ). **Question: Is there an easy way to build a 2D Slider with the drop down precision provided for a normal slider, thus in x and y direction? Or do I have to build it from scratch?** ( Update: Basically remove the two sliders =itself= but remain all other functionality in the example. )


title: About number truncation of ticks display in ListPlot

text: In my problem, I need to plot a figure in a relatively small region of the $x$ axis, e.g.,                ListPlot[{RandomReal[#] + 10^4,         RandomReal[#]} & /@ (Range[100] 10^-10), Frame -> True, Axes -> False]      and the figure is displayed properly, but all the tick marks have the same label: ![Mathematica graphics](http://i.stack.imgur.com/ujeYw.png) Is there any clever way to get rid of this problem?


title: Where can I take a pool of words from?

text: Dear Community members, I am thinking about an interactive machine to teach a school child to write difficult words correctly. As a first step I need a collection of words. I will select a pool of words from this collection. Then I will use the pool to make the machine. My question is: is there a way to get the words with _Mathematica_? A constraint is that I need German words.


title: Doing a chi-square independence test in Mathematica

text: I have a matrix consisting of the following data:               Needs["HypothesisTesting`"]     data = {{11, 206}, {32, 1374}}      How would I make a chi-square independence test with a level of 5% of significance out of this? When I try the following:               In[9]:= ChiSquarePValue[data, 0.05]      I get this a very little value out of it.               Out[9]= OneSidedPValue -> 1.89247*10^-303      However, the correct answer would be something around `0.017` or `1.7%`.


title: Convert Locator (x,y) values to Lat/Lon as per GetCoordinates on Map

text: I want to convert the (x,y) coordinates you get from using a locator on a map to Lat/Lon coordinates - exactly like the GetCoordinates tool does when you right click on a map.               Manipulate[GeoGraphics[GeoPosition[{51.5164090, -0.0943590}],     GeoRange -> Quantity[0.20, "Miles"]], {u, Locator}, {u}]      ie if I create a simple map and use use right click -> GetCoordinates it will give me 3 pairs of values   1. Lat Lon   2. Lat Lon in degrees   3. (x,y) <\-- this is the one Locator returns. Simple demo map               GeoGraphics[GeoPosition[{51.5164090, -0.0943590}],      GeoRange -> Quantity[10, "Miles"]]      Im presuming its related to GeoPositionENU somehow but the starting point seems to change for each instance of the map.


title: Neural Network and New Mathematica version

text: do you think that Wolfram would integrate the Neural Networks package in the new version of Mathematica? Also because the Neural Networks package is not compatible with ListPlot in Mathematica 9.0. Thanks!


title: Why do I get an error message when for this type of recursion?

text: When I type the following code:               mus[] = 0;      mus[x__] := First[List[x]] + mus[Rest[List[x]]]      What one would think would happen is that if, `mus[1,2,3,4]` is input, the number 10 would be output. However, I get the error message, > $RecursionLimit::reclim: Recursion depth of 1024 exceeded However if I use the following code:               lsum[{}] := 0;      lsum[L_] := First[L] + lsum[Rest[L]];      sum[x__] := lsum[List[x]]      It works as I thought it should, namely if input lsum[x1,x2,x3,...,xn], the output is the sum of the xi's.


title: Limit of a complex function

text: Can someone show me how to find the limit of a complex function? Example:               z1 = 3 + 4*I          some_function[z] = z * z1      Set-up:               Limit[some_function[z],z->z1]      The result should be > >     (4*I + 3)*z >   but I get > >     Limit[some_function[z], z -> 3 + 4 I] >   What am I doing wrong? I tried to search in google and in the help files in the section about complex analysis. Thank you for your attention.


title: Generating social network graph from a CSV file

text: I am new to Mathematica and wanted to generate undirected graph for data sets that show the relationships of organizations with each other. The data is in a square matrix. The cells of the matrix provide information about the relationships between each pair of organization (0 if no relationship exists; 1 if there is some relationship; 2 if the organizations work as partners; 3 if any of the board members serve in the paired organization). There are 81 organizations in the study, so the matrix is 81x81. The data data structure in CSV looks like the following. ![example of data structure](http://i.stack.imgur.com/6IlMw.jpg) I would very much appreciate if anyone would provide me the steps for generating the social network graph for the stated scenario using Mathematica 9. Thanks! -Brian


title: Solving for any one variable in a formula given values for all the others

text: Consider the formula for the area of a rectangle. I can write the formula as `area[length_, width_] := length*width` and plug in numbers for the dimensions and get the area. Also, I could write a formula for finding each specific dimension in terms of the remaining two. My question is this: Is there a way to write a single expression which will do the whole job, that is I can plug in any two of the components of the area formula and have _Mathematica_ return the third?


title: Searching linked lists that contain lists?

text: Following the advice I've read here and other sites, I've been trying to use the Mathematica equivalent of a linked lists...               testList = {{a, b}, {{c, d}, {{e, f}, {}}}}      Now, I want to see if `{c,d}` is a member of `testList`. How do I do that? MemeberQ doesn't transverse the list recursively and Flatten also nukes the sub lists. The following seems to work but I would expect there to be a cleaner simpler way...               memberInLinkedList[{}, _] = False;     memberInLinkedList[l_List, v_] := True /; First[l] == v;     memberInLinkedList[l_List, v_] := memberInLinkedList[Last[l], v];      Is there a more eloquent or built-in way to do this? Perhaps a general idiom or package that handles this transparently?


title: Generating a random tree of given cardinality, depth, and labeling

text: For demo, exploration and teaching purposes, I would like to be able (and asking you for help) to generate these special instances of trees: For given:   * **N** \- number of nodes in the tree   * **D** \- depth of the tree (largest distance root-leaf) I need to generate a random tree with all nodes labeled so that:   * Root is labeled _"Lorem"_   * First or other prominent child of the root is labeled _"ipsum"_.   * All other children are labeled randomly from words from following paragraph: _"dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."_ * * * Example from related question: (but this solution doesn't care about depth limitations)               vtx[] := Table[i <-> RandomInteger[{0, i - 1}], {i, 1, 50}];     Graph@vtx[]      ![](http://i.stack.imgur.com/TkBHq.png) * * * Tree should look like this: (just imagine words instead of numbers) ![enter image description here](http://i.stack.imgur.com/bNcCn.jpg)