Recursion doesn't happen any more or doesn't happen correctly if I store the recursive relationship in a variable first

I know the following code will form a recursion:               Clear["Global`*"]     u[i_, n_] := u[i - 1, n] + u[i, n - 1]     u[0, n_] := n     u[i_, 0] := i          u[2, 2]      (* => 8 *)      But if I store the recursive relationship in a variable first, the recursion will fail:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i_, n_] := exp     u[0, n_] = n     u[i_, 0] = i          u[2, 2]      (* ERROR *)      Why? I guess maybe `exp` "shields" `i` and `n`, so, I tried something like:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i1_, n1_] := (i = i1; n = n1; exp)     u[0, n_] := n     u[i_, 0] := i     u[2, 2]     Table[Table[{i, u[i, n]}, {i, 0, 2}], {n, 0, 2}];     u[2, 2]     (* =>5        =>5 *)      …As you see, it doesn't give the right answer. A even "amazing" case is this:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i1_, n1_] := (i = i1; n = n1; u[i, n] = exp)     u[0, n_] := n     u[i_, 0] := i     u[2, 2]     Table[Table[{i, u[i, n]}, {i, 0, 2}], {n, 0, 2}];     u[2, 2]     (* =>5         =>14 *)      Ah…the process of recursion is so complex, how to explain all these? And, how to solve the original problem?


Downloading files without using Import

A quick question, but which I don't believe has been asked here or at SO. Does _Mathematica_ have a simple way to just download a file from the web? i.e. if I have a list of PDF links (~ 2,000), can I use Mathematica to quickly take them and save them to my system. The obvious way that I've used in the past is to `Import[]` the data, but since we're talking large-ish PDFs I wonder if there's a way to skip that step. I have used wget for this sort of thing in the past, but just seeing if there's an easy way to do it within _Mathematica_. The 'Web Operations' section of the documentation does not seem to have any obvious reference to this. If not, I will obviously just use the 'proper' tool.


The "right" way to define a custom Encoding format?

I have implemented an `Import|Export` format for xz that behaves like gzip and other encoding formats:               Import["some.ext.gz"]     Import["some.ext.xz"]      But I think I did it in a really roundabout way, is there a more straightforward way than adding `DownValues` for all these things:               ImportExport`EncodingsDump`rundecoder["XZ", infile_String, outfile_String, opts___]     ImportExport`EncodingsDump`runencoder["XZ", infile_String, outfile_String, opts___]     FileFormatDump`$FILEFORMATMATRIX["XZ"] (* $ /mma.SE bug *)     ImportExport`EncodingsDump`InstallCoderQ["XZ"]     ImportExport`EncodingsDump`CreateShortName[infile_ /; StringMatchQ[infile, "*.xz"]]     AppendTo[FileFormatDump`$FILEFORMATS, "XZ"]      Together with:               ImportExport`RegisterImport["XZ", ImportXZ,        "BinaryFormat"->True,        "Extensions"->{"*.xz"},        "Encoding"->True,        "AvailableElements"->{_String},        "FunctionChannels"->{"FileNames"}]      (* Similar for Export *)      What's the best way to do this?


How to transform an equation so that the coefficient of a certain term becomes 1

Say I have an equation like               A + 5 B + 10 C == 0      and I want to have _Mathematica_ write this as               (A/5) + B + 2 C == 0      i.e., I want to pick a term (B in this case) and choose its coefficient (1 in this case) and have _Mathematica_ divide or multiply the equation appropriately. I can't figure out a way other than using Solve to solve the equation for B, but that's not ideal (especially since it moves B to the other side of the equation). ### Edit A good solution should also be something one can apply after a Collect, a Simplify, etc., without undoing those commands, since the equations I'm dealing with are much more complicated than this simple example!


Stopping a head from evaluating more than once

While attempting to answer my own question, Is there a way to "hold" prefix / infix / postfix notation?, I came across the need to evaluate a recursive function only one level deep. For example, consider a factorial function:               factorial[n_Integer /; n >= 0] := If[n >= 2, n*factorial[n - 1], 1]      Normally, expressions using `factorial` would be fully evaluated:               2 + 3*(factorial[5] + factorial[7])     (* 15482 *)      However, is there a way to evaluate `factorial` just once, and prevent evaluating any further occurrences? That is, a function, `EvaluateHeadOnce`:               EvaluateHeadOnce[factorial, 2 + 3*(factorial[5] + factorial[7])]     (* 2 + 3 (5 factorial[4] + factorial[7]) *)      I found a method (self-answered below) but it felt rather... inelegant. I'm curious to see how others would implement such a method, as well as hear criticisms / flaws in my approach.


Splitting dates into groups in half year steps

list = DayRange[{1999, 1, 1}, {2014, 2, 6}]      I want to split this list into sublists one and a half year long, moving a half year forward every time. That would mean that the first dataset would go from 1999 to 2000 June. Next group would go from June 1999 to 2001 and so on. Last dataset group would not be complete due to the fact that the dates only goes to the 6th of February 2014. There are two things that I want to point out.The assumption you made was correct about dividing the dates from Jan to the end of June so one. However, I have lists of dates with different length so I would like to be able to map a function over the different lists of dates where this dividing is occurring. So that no matter how long the list is it would divide it as I asked above. Please note, that the lists vary all from 4 to 20 years. Also some lists are just Business days, so it would mean that in some cases the end of the month is not the last date of that month.


Can mathematica resolve this equation?

Obviously，the equation $x^2-3 y^2=2 z^2$ doesn't have positive integer solutions. I tried               Exists[{x, y, z}, x > 0 && y > 0 && z > 0 && x^2 - 3 y^2 == 2 z^2]     Resolve[%, Integers]      and               Exists[{x, y, z}, Element[{x, y, z}, Integers],       x > 0 && y > 0 && z > 0 && x^2 - 3 y^2 == 2 z^2]     Resolve[%]      but I don't get any useful result. Am I using these functions incorrectly?


Tools for Importing/working with SEED seismographic data in Mathematica?

Do you know if exist a library or a package in order to import and work with SEED Seismographic data in Mathematica?


Constructing a function with Flat and OneIdentity attribute with the property that otimes[a]:>a

I want to have a function (called `otimes`) with the following two properties:   1. it has the attribute `OneIdentity` and `Flat`   2. if evaluated with a single argument it returns that argument The built-in function `Times` has these properties; e.g., evaluating `Times[a]` yields `a`. I am struggling implementing my own function having the same behavior. What I tried is the obvious implementation               SetAttributes[otimes,{OneIdentity,Flat}]     otimes[a_]:=a      However this does not work and leads to an infinite recursion when I evaluate otimes[a,b]. I do not now how to implement the desired behavior consistently. Maybe somebody can help?


How do you find the longest sublist within a nested list

Say, I have a list               stuff={{eat,tea,now},{how,did,you,say},{the,cat,ate,was,can},{win,din,sin}}      I have a nested list and I want to find the list that has the most words in it and then I want to find the length of those words. How would I do that? I thought it was               Max[StringLength[stuff]]       and               Length[Max[StringLength[stuff]]]      but `StringLength` doesn't do me any good here since the length of each letter is the same.


Two questions on strategies for quantifier elimination

With the help of people here I was able to solve several cases similar to IC3 but this case - unlike the other cases - does not return an answer. I will try to run it for a day with 8 processors but will be grateful for:   1. Any suggestions on how to solve IC3 (besides more memory or more time)   2. In the end I only care about some other constraints so would help resolve if I add additional constraints on the other variables (a, c and d) when trying to eliminate x and z?              IC3 := (4 d^3 + 24 a d^2 x + 3 (2 a + c) d (-c x^2 + 2 a (x^2 + 4 x z - 2 z^2)) - (2 a + c)^2 (c x^3 + 4 a (x^3 - 3 x^2 z + z^3)))/(6 (2 a + c)^2)              && 0 < -((2 d)/(2 a + c)) < 1     Resolve[{x,z}, (-(2 d)/(2 a + c)) <= x <= 1, (-d/(2 a + c))<=z<=(-(2 d)/(2 a + c)), IC3]


RandomVariate does not evaluate a Hyperbolic Distribution

Any Idea why I can't get a result from this expression:               In[170]:= RandomVariate[HyperbolicDistribution[59.428`, 18.441`, 3.428`*^-9, -0.00065`]]          Out[170]= RandomVariate[HyperbolicDistribution[59.428, 18.441, 3.428*10^-9, -0.00065]]      I have found this Distribution modelling daily balance of a bank in order to calculate Liquidity Risk.


Counting elements skipped using Reap & Sow

I am using the following code to filter data based on the percentage change between points.               Reap[z = data[[1]]; Sow[z];               Scan[If[Abs[# - z]/z > delta,               z = #; Sow[z]] &, data]][[2, 1]]      That is, only considering point that were separated but a certain percentage change. While it gives me the correct answer, I would like to count the values that are dropped in between each selected point. How could I do that ?


Extrude 2D cross-section to 3D shape with shrinkfactor

I would like to create a 3D shape from extrusion and scaling of a 2D contour. The 2D contour that I have looks like this: ![enter image description here](http://i.stack.imgur.com/82RTu.png) and it consists of a bunch of points (here plotted with `ListPlot` with `Joined->True`). I have looked at a bunch of questions and answers here on Mathematica.SE, notably this one and this one, but I don't see how to apply those to my problem in any straightforward manner. For the sake of a MWE I will switch to a circle from this point on:               xdata = Table[x, {x, -1, 1, 0.05}];     ydata = Table[Sqrt[1 - x^2], {x, -1, 1, 0.05}];     circData = {Transpose[{xdata, ydata}], Transpose[{xdata, -ydata}]};     ListPlot[circData, Joined -> True, AspectRatio -> Automatic]      The extruded shape that I would like to make then looks like this: ![enter image description here](http://i.stack.imgur.com/NywlJ.png) It is a shape consisting of slices of the contour with constant radius $r_0$ over some range let's say $-1 < z < 1$ and decrease in radius with $z$ at the tips according to $r(z)=r_0\sqrt{1-(z-1)^2}$ and $r(z)=r_0\sqrt{1-(z+1)^2}$ (depending on which tip). **My question is: how can I do this extrusion for the set of listdata that I have?** Just to be clear, to create the 3D shape for the circle I cheated and used the formula for a circle and a sphere like this:               p = Plot3D[{1 + Sqrt[1 - y^2 - x^2 ], -1 -           Sqrt[1 - y^2 - x^2 ]}, {x, -2, 2}, {y, -2, 2},         PlotStyle -> {Orange}, Lighting -> Automatic, Mesh -> Automatic,         BoxRatios -> Automatic, Boxed -> False, Axes -> None];     q = RegionPlot3D[        Sqrt[x^2 + y^2] < 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1},         PlotStyle -> {Orange}, Lighting -> Automatic, Mesh -> Automatic,         BoxRatios -> Automatic, Boxed -> False, Axes -> None];     Show[p, q]      **Is there a way to achieve the same with the data from a list?** * * * **[Adaptation to thicknessFunc by @Halirutan and accompanying re-scaling]** To make the thicknessFunc more generic I adapted it to:               thicknessFunc[z_, body_,        b_] := (HeavisideTheta[z] - HeavisideTheta[z - b])*        Sqrt[b^2 - (z - b)^2] +        b (HeavisideTheta[z - b] -           HeavisideTheta[z - body - b]) + (HeavisideTheta[z - body - b] -           HeavisideTheta[z - body - 2 b])*Sqrt[b^2 - (z - body - b)^2]      such that you can set the radius of the circular parts by setting $b$. A consequence of this is that you have to rescale the thicknessFunc in append with $1/b$ like               Append[1/b thicknessFunc[u,2]*fdata[t], u]      I don't fully understand why, but I guess it has to do with the fact that `fdata` is multiplied by `thicknessFunc` and therefore needs the straight ends of `thicknessFunc` to be at 1


How to combine objects from different .obj files?

I got a screw .obj model with the head diameter of `2cm`, and a board .obj model of `10cmx10cmx4cm` in dimension. I would like the screw duplicated in 25 copies painted with different color and "screw" on the board in an array of `5x5` with random heights. How can I attain this in Mathematica? ![enter image description here](http://i.stack.imgur.com/7Gi69.gif)               (* assuming the .obj files are located in the c: root *)     scw = Import["c:\\screw.obj"];     brd = Import["c:\\board.obj"];     Show[brd, Graphics3D[{        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {1, 0.8, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], { 3, 1, -1}],        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {5, 1.1, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {7, 0.7, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {9, 1.0, -1}]          }]      ]      With the code shown above, I got something like this: ![enter image description here](http://i.stack.imgur.com/Ruq74.jpg) I need a better(faster) way to do this, and need to knew how to "paint" the nails and the board.


export table with number written in scientific notation

I am trying to write on a file the table generated in this way:               error = ConstantArray[0, 3];     error[[1]] = ScientificForm[Sqrt[CovMat[[1, 1]] /. out[[2]]]];     error[[2]] = ScientificForm[Sqrt[CovMat[[2, 2]] /. out[[2]]]];     error[[3]] = ScientificForm[Sqrt[CovMat[[3, 3]] /. out[[2]]]];     Ris = out[[2]] /. Rule -> (#2 &);     par = out[[2]] /. Rule -> (#1 &);     Finale = MapThread[{#1, ScientificForm[#2], #3} &, {par, Ris,          error}] // TableForm      CovMat anf out are generated in a previoous part of the code (a `NMinimize`). Typing Finale on the notebook I find:               M   4.35203*10^(10) 4.2566*10^(9)     \[Delta]    4.10847*10^(5)  2.12356*10^(4)     L   1.01689*10^(9)  1.30717*10^(16)      The problem is that in the file I find:               "M  ScientificForm[1.7467449664329874*^11]  \     ScientificForm[4.784135569792907*^9]          [\Delta]    ScientificForm[606745.0359163599]   \     ScientificForm[10326.21966853348]          L   ScientificForm[2.788541796939519*^10]   \     ScientificForm[1.5410843643505646*^18]"      I used `Export` and               file = OpenAppend["out.txt"]          string = ExportString[Finale,"Table"];          WriteString[file, string]     WriteString[file, "\n"];          Close[file]      (I thought that `ExportString` read the values as they are) but I cannot get rid of that `ScientificForm`. I suspect that I should use something like:               Export["file.dat", {elem1->expr1, elem2->expr2, ...}, "Rules"]      but I cannot find a way to express the rule.


How can I use the Rules returned by FindFit?

When I evlauate               data = RandomReal[10, {5, 10, 2}];     fit[i_] := FindFit[data[[i]], a Sin[x] + b, {a, b}, x]     fit[1]      I get something like: > >     {a -> 0.177375, b -> 3.91185} >   Then, I try to plot the points and the fitted function together in one figure.               Show[ListPlot @ data[[1]], Plot[a Sin[x] + b /. %, {x, 0, 10}]]      With % I can get the figure I want, but               Show[ListPlot @ data[[1]], Plot[a Sin[x] + b /. fit[1], {x, 0, 10}]]      returns errors. Why does this occur? Why can't I insert fit[1] in `ReplaceAll`, and how can I correct my mistake?


Camera Simulator

I am developping a perspective camera simulator. For the moment, I am considering only the projection of a quadrics form that gives us a conic. For testing my simulator, I use povray an image rendering software to generate a 2D image for a quadric. My problem is how to plot my resulat in a different standard dimensions (like 800*600, 1080*1920,320*240,…..). Here is a portion of my code.               Conic={{7.08617*10^-6,4.20705*10^-14,-0.00283447},   {4.20705*10^-14,8.77616*10^-7,-0.000219319},{-0.00283447,-0.000219319,1.18635}}     ell=Plot[Evaluate[     y /. Solve[{x, 600 - y, 1}.Conic.{x, 600 - y, 1} == 0, y]], {x, 0,      800}, PlotRange -> {0, 600}, AspectRatio -> 6/8,      Filling -> {1 -> {{2}, RGBColor[{1, 1, 1}]}}, Axes -> False,      Background -> Black, PlotStyle -> {Directive[RGBColor[{1, 0, 1}]]}]     (*Here I plot my conic (ellipse) in (800,600) and for {600-y}, I do this because the   coordinate system between image and graphics are inversed… Then to convert my graphic to image, I use Rasterize() and I tested succefully my result *)      Rasterize[ell,ImageSize -> {400, 300}, Background -> RGBColor[{0, 1, 0}]]      (I need to simulate my camera with image dimensions 320 x 240 ) I changed my code like this               ell=Plot[Evaluate[     y /. Solve[{x, 240 - y, 1}.Conic.{x, 240 - y, 1} == 0, y]], {x, 0,      320}, PlotRange -> {0, 240}, AspectRatio -> 3/4,      Filling -> {1 -> {{2}, RGBColor[{1, 1, 1}]}}, Axes -> False,      Background -> Black, PlotStyle -> {Directive[RGBColor[{1, 0, 1}]]}]      Here I have not get the ellipse. It seems that there is not a point that satify `{x, 240 - y, 1}.Conic.{x, 240 - y, 1}`. But it is not logic because when I use the camera on povray, I can render this image. Any clarification please


Why does MemoryConstrained not abort when memory limit is exceeded?

I thought I had an idea that might lead to an answer to @yohbs' question, but as I was trying to check out the usage of `MemoryConstrained[expr,b,failexpr]`, I discovered behavior I did not expect.   The following aborts immediately; neither `k` nor `t` are set. (Please don't worry about the `Rule` -- I added `"Abort"->` merely to distinguish an aborted computation):               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10j], {j, 1000}],       2199, "Aborted" -> Table[t[j], {j,k}]]      > Out[2]= Aborted->Table[t[j],{j,k}] I guess that it takes more than 2199 bytes to build the `Table` expression and it does not even evaluate one iteration. If the limit is raised one byte to 2200, then the command does not abort at all.               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10j], {j,1000}],       2200, "Aborted" -> Table[t[j], {j, k}]] // Short      > Out[4]= //Short= {{1,2,3,4,5,6,7,8,9,10},<<998>>,{1,2,<<9997>>,10000}} As you can see below, 41M were used to store the result, not to mention the other 41M stored in `t[_]`.               ByteCount[%]      > Out[5]= 41277832 The last list, `Range[10000]`, is stored in `t[1000]` and exceeds the limit of 2200 bytes:               ByteCount[t[1000]]          > Out[6]= 80144 Any `Range[n]` with `n` equal to 256 or more causes an abort:               MemoryConstrained[Range[256], 2200]      > Out[7]= $Aborted               ByteCount[Range[256]]      > Out[8]= 2160               ByteCount[Range[257]]      > Out[9]= 2416 (It is believable that there are more than 40 bytes of overhead in computing `Range` and that the chunking of memory causes the 256 byte jump, although these are just a random stabs at an explanation.) Does someone know how to make `MemoryConstrained` abort when the limit is 2200? Or can someone explain when memory request counts toward the `MemoryContrained` limit? **Addendum** Thanks for the help so far. I'm on Mac OS 10.8.2, Mma 9.0.0, slightly old MacBook Pro (~2008), 6GB RAM. I restarted Mathematica and tried again. Same result. However, changing the limit on the iterator `j` from 1000 to 100 got it work. Strange.               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10 j], {j, 100}],       2200, "Aborted" -> Table[t[j], {j, k}]] // Short      > Aborted->{{1,2,3,4,5,6,7,8,9,10},{1,<<18>>,20},t[3]}


Manipulation of InterpolatingFunction

Suppose that $q[t]$ is obtained by `NDSolve` as an `InterpolatingFunction`, and I want to define $Q[t]$ to be some function of $q[t]$, say $\sqrt{q[t]}$. How can I define it in such a way that I become able to plot its time derivative for example?


Plot a cone in spherical co-ordinates

As we all know in spherical coordinates a function `phi = π/3` gives us a cone. The cone makes an angle of `π/3` with the imagined `z`-axis. How do I type this formula into _Mathematica_?


Create simple table with function of column values

I just want to create a simple table: Three input columns, one output column Call the inputs `{x,y,z}`, each can take values `{-1,0,1}` The output column should be some function `f(x,y,z)` Sample table:               x  | y  | z  | f(x,y,z)          -1 | -1 | -1 | f(-1,-1,-1)          1  | -1 | -1 | f(1,-1,-1)      etc... (all possible combinations) Thanks!


How to keep $FrontEnd options from resetting?

I'm trying to get _Mathematica_ to look in a different, version-tracked folder for the 'TextResources' files that it uses to build the Front End. I've prepended my version-tracked folder path to the `$FrontEnd` option `PrivatePaths`, both from the Options Inspector and using SetOptions. Both of these methods make _Mathematica_ use my version-tracked files the next time I restart the Front End, but it quickly reverts to the versions at `$InstallationDirectory\SystemFiles\FrontEnd\TextResources\Windows` within one or two Front End restarts. I'm not certain what triggers this switch back to the default directory, but I'd really like to stop it from happening so that I can reliably and persistently use my customized, version-tracked instances of the 'TextResources' files. How might I accomplish this?


Solving a pair of recurrence relations

Why does this               RSolve[{y[t] == a*y[t - 1]}, {y[t]}, t]      work, while this               RSolve[{y[t] == a[t - 1]*y[t - 1], a[t] == a[t - 1]}, {y[t], a[t]}, t]      does not given any interesting result? * * * My goal is to solve something of the kind:               RSolve[{y[t] == function[y[t - 1],a[t-1]], a[t] == b*a[t - 1]}, {y[t], a[t]}, t]


Automating the "Get Indices" right click function

Is there a way to do this? What I am trying to do is allow a user to take a lineout averaged over the rows of a user defined ROI (Region of Interest) of an image. I have the bit of code that allows for the lineout but at present the only way I can get the indices of the ROI is to use the right click Get Indices function and then copy and pasting them into the function. I would like to eliminate the need for the copy and paste. I would like the user to click on the image in two locations with locators (or some sort of marker) appearing on the click, then have the lineout be plotted as an output. I need to have the image be full size (1000 x 2000) so that the user can see detail. I will also need to write the indices and the lineout to user defined variables so that multiple lineouts can be plotted together as the user needs them and the image reproduced with the markers overlay-ed on top. I have the code to do the lineouts and the plotting but I am hung up on a way to pass the indices cleanly out of a Module/DynamicModule structure. Would it be cleaner to do this all in 1 Manipulate structure? There will be 50 or so images each with there own lineout that my be compared to one another or all at once. Thanks


How do I plot a 3D vector field using a data file with three x y z columns?

I have a data file that is the solution of the laplace equation on a rectangular area, which has three columns: x, y and z with their numerical values. How do I plot this data into a vector field with vectors in z direction with magnitude from the third column? When I import that data as "Table", is gives me a list of lists, i.e. {{x1,y1,z1},{},...,{}}, which makes it unsuitable to use with `ListVectorPlot3D[]`... Cheers //edit I would like to use the imported data to interpret it as a vector field and calculate its rotation.


When to use indexed variables

Still learning the fundamentals of the language I would like to ask you what advantages there might be in writing something like:               a[1] = 2;     a[2] = 4;     a[3] = "x";      It seems to me that it is always better to write               a = {2, 4, "x"};      Do you know about any practical constructs where indexed variables would offer an advantage?


is there an option for FitResiduals in FindFit?

I know this option exists in NonlinearModelFit and probably in other fit models as well but for some reason the best result i get is with FindFit. Regards Doron


Entering block matrices for an arbitrary matrix size

Background: How to enter matrices in block matrix format? and the following: I want to create $$ f(A,t) = \left [ \begin{matrix} A & t \\ 0 & 1 \end{matrix} \right ] $$ where $A$ is a $n$ by $n$ square matrix size , and $t$ is a column vector of length $n$. The solution in the question above works for case 2, the following code works for cases 2 and 3:                 Transpose[Append[Transpose[Append[IdentityMatrix[2], {0, 0}]], {a1, a2, 1}]] // MatrixForm       Transpose[Append[Transpose[Append[IdentityMatrix[3], {0, 0, 0}]], {a1, a2, a3,1}]] // MatrixForm      **Question: What is the best code for case $n$?**


tol and None in output of CompilePrint

**A bit of background:** I'm trying to fit a very complicated symbolic function. By compiling the function I got about 100x speedup, but I would need another 10. Therefore I'm trying to understand if the function is correctly compiled (I allready checked that there are no calls to MainEvaluate). **The problem:** While scanning through the output of `CompilePrint` I see the following snippet repeating a lot               12  B0 = R39 None R38 (tol R42)     13  if[ !B0] goto 46      **The question:** What does line **12** do? Is this R39 * **None** * R38? What is ( **tol** R42)? Here is some more context:                   33 arguments         1 Boolean register         1 Integer register         123 Real registers         Underflow checking off         Overflow checking off         Integer overflow checking off         RuntimeAttributes -> {}              R0 = A1         R1 = A2                 ...         Result = R64          1   R38 = Reciprocal[ R2]     2   R39 = R37 * R38     3   R38 = R36 + R39     4   R39 = Reciprocal[ R38]     5   R38 = - R39     6   R39 = - R2     7   R41 = R40 + R39     8   R39 = Reciprocal[ R2]     9   R41 = R41 * R39     10  R39 = R36 + R38 + R41     11  R38 = I0     12  B0 = R39 None R38 (tol R42)     13  if[ !B0] goto 46     ....     19k something lines:)


What is $ sign in Mathematica?

Is it a special sign or it can be used as anything else? For creating variables for example.               $x=4


Variable naming changes everything

I am having a rather unusual problem I do not understand with Mathematica where renaming one of the variables of my function causes the function to stop "working". Here is the example of the code doing what it should:               F[t_, a_, b_, l_] = x[t] /. First@     DSolve[{x'[t] == a*x[t]*(1 - (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t];      Changing one variable name causes the code to throw out error messages. The non-working code is               F[t_, r_, b_, l_] = x[t] /. First@ DSolve[{x'[t] == r*x[t]*(1 -     (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t];


Strange domain dependency with Maximize

I'm using Mathematica 8 and strangely enough this code:                   Maximize[{x*(1-0.01 x),x>0},x,Integers]      produces the result `{8.19,{x->9}}`, which seems at odds with the actual answer of `x->25`. Does anyone know if it is an intended behavior or my mistake?


Construct DifferentialMatrices and Kernel for LevinRule for this integral and ODE set

I've made a lot of progress on my problem the last few days thanks to all the help I've received on here. I think I'm upto the final step of greatly improving the performance of NIntegrate[..] on my setup. I have an integral that looks like $$\int^{x_f}_{x_i} \mathrm{d}x\, \exp{(ix)} \exp{(i\omega t(x))} \phi^*(x)$$ (* refers to complex conjugation).The $\exp{(ix)}$ is slowly oscillatory compared with everything else. The $x_i,x_f$ are negative; typical values might be $-115,-75$, the closer you get to $-4/3$ the more problematic things get, $x>x_h=-4/3$. Similarly the bigger $\omega$ gets the more oscillatory things are. The function $t(x)$ is $$t(x)=3x_h (x/x_h)^{1/3}+x-3x_h\text{arctanh}{\left((x_h/x)^{1/3}\right)}$$ and satisfies $$\frac{dt}{dx}=\frac{1}{1-\left(\frac{x_h}{x}\right)^{2/3}}$$ and $$\phi''(r)+\frac{2(r-1)}{r(r-2)} \phi'(r)+\left(\frac{\omega^2 r^2}{(r-2)^2}-\frac{2}{r(r-2)}\right)\phi(r)=0$$ where $r=2(x/x_h)^{2/3}$. So this can be transformed into an ODE in x. Is it possible using this information to construct the "DifferentialMatrices" and "Kernel" of the LevinRule? If this turns out not to be possible, is it possible to tell Mathematica to use LevinRule only in some finite range of integration where one of the above factors becomes non-oscillatory and I can lump it in the amplitude.


How can I get the unchanged Box form of an arbitrary expression?

One may observe that `MakeBoxes` does not give the actual Box form of various expressions:               MakeBoxes[{1*^4, 000123, a*b c}]      > >     RowBox[{"{", RowBox[{"10000", ",", "123", ",", RowBox[{"a", " ", "b", " > ", "c"}]}], "}"}] >   The `1*^4` was expanded, the leading zeros of `000123` were stripped, and the distinction between `*` and (space) was lost. Also, `MakeBoxes` doesn't like syntactically invalid or incomplete strings:               MakeBoxes[0001+`1,*^6*a b]      > Syntax::sntxi: Incomplete expression; more input is needed. How can one get the actual Box form visible with Show Expression (`Ctrl`+`Shift`+`E`) without copy & paste?


Problem with using the chain rule

I have the functions               w[x_] := x*Cosh[x]       and                x[a_] := n/k*a.       I take the derivative `D[w[x[a]], a]` and get > >     a*n^2/k^2*Sinh[a*n/k] + n/k*Cosh[a*n/k]. >   This is odd because I expected the result > >     n/k*(x*Sinh[x] + Cosh[x]). >   I know I can use replacement rules to achieve this but is there a direct way?


BoxWhiskerChart too slow on big datasets, how to speed it up?

I have very big dataset, with over 14 000 000 records. And maybe more! Each record consists of Data ( Real ) and Time ( integer ). I group records by time interval, resulting in 300 groups. In each group there are 70 000 records. I need to draw a `BoxWhiskerChart`. BUT, The system has frozen for 15 minutes. And then work is very slow. I think the reason this froze, is that I give it groups that are very large. But what can I do?


Visualizing the difference between two sequences (strings)

I'm trying to develop a way of comparing two sequences (probably originally text, such as text writing or source code, possibly converted to lists). As a familiar example, consider the revisions display for any typical SE question or the diff output from a command-line `diff`. I found a cool _Mathematica_ function called `SequenceAlignment` which looks promising:               text1 = ExampleData[{"Text", "ToBeOrNotToBe"}];     text2 = StringReplace[text1, {"s" -> "th"}]          (*      To be, or not to be,--that ith the quethtion:-- Whether 'tith nobler     in the mind to thuffer The thlingth and arrowth of outrageouth      fortune Or to take armth againtht a thea of troubleth, And by      oppothing end them? ...     *)      (lisp programming... :) Now:               sa = SequenceAlignment[text1, text2]      gives:               {"To be, or not to be,--that i", {"s", "th"}, " the que", {"s", "th"},      "tion:-- Whether 'ti", {"s", "th"}, " nobler in the mind to ", {"s", "th"},     "uffer " ...      which I want to convert to some kind of colored display. The best I've managed so far is this:                Reap[       If[Length[#] == 2,            Sow[Column[{Style[#[[1]], Red], Style[#[[2]], Green]}]],            Sow[Style[#, Black]]]          & /@       sa]      but it's not a pretty display: ![my attempt](http://i.stack.imgur.com/2R7Eb.png) How can I make this display look like a single piece of text with colored markup, like the SE revisions display? And would it be possible to process _Mathematica_ code as well - without evaluating said code first, obviously?


Globally loading packages while using a CellGroup as the default context

I have a notebook I wish to set up where the sections are conceptually related to each other. But, I wish to isolate them from each other programmatically, so that they do not interfere with one another. A built-in method of doing this is to set the default context to `CellGroup` so that each group of cells has its own context. However, each section relies on the same set packages, and because one of them is quite large, I do not wish to reload the packages for each section. An option is to put each section in its own context manually using `Begin` and `End`, but I would rather avoid that if possible. Ideally, though, I would like to be able to load the packages in their own separate section and elevate them to the `Global`` (or equivalent) context. Any thoughts on how this can be accomplished?


GridLines at TickPositions

How can I force the GridLines to be at the positions of the Tick marks? A simple code, `FrameTicks -> Automatic` and `GridLines -> Automatic` will do it, but not this code. The error must be in the function `myTickList`, but I didn't find it. Moreover, `AspectRatio -> 1` seems not to work... Result: ![enter image description here](http://i.stack.imgur.com/ilre0.jpg) Input-File data.dat:               3542228.204 5433969.188     3542221.426 5433999.371     3 1 2 0     40      The code of the notebook:               inffile = OpenRead["data.dat"];     x1 = Read[inffile, Number]; y1 = Read[inffile, Number];     x2 = Read[inffile, Number]; y2 = Read[inffile, Number];     n1 = Read[inffile, Number]; n2 = Read[inffile, Number];      m1 = Read[inffile, Number]; m2 = Read[inffile, Number];      diff = Read[inffile, Number];     grad = Pi/2-ArcTan[y2 - y1, x2 - x1];     winkel=grad*180./Pi;     If[winkel < 0.0, winkel = winkel + 360.0];     s1 = ToString["Drehung erfolgt um "]; s2 = ToString[winkel];      s3 = ToString[" Grad "]; str = StringJoin[s1, s2, s3];     Style[str, FontSize -> 35, Italic, FontFamily -> "Helvetica"]     iend = n1 + n2 + 1;     Do[xkoor[i] = x1 - n2*diff + (i - 1)*diff, {i, 1, iend}]     jend = m1 + m2 + 1;     Do[ ykoor[j] = y1 + m1*diff - (j - 1)*diff, {j, 1, jend+1, 1}]     xvals = Table[xkoor[i], {i, iend}];     yvals = Table[ykoor[j], {j, jend}];     ungedreht = Outer[List, xvals, yvals] // Flatten[#, 1] & ;          myTickList[min_, max_, seg_, shift_?NumericQ, phi_?NumericQ,        len_: 0.01] :=       Table[{i,         Rotate[Pane[Style[AccountingForm[i], LineSpacing -> {0, 12}],           FrameMargins -> {{shift, 0}, {0, 0}}], phi], {len, 0}}, {i,         If[Head[seg] === List, Union[{min, max}, seg],          Range[min, max, seg]]}]          r = RotationTransform[grad, {x1, y1}]; gedreht =       r[ungedreht];          sortiert = SortBy[gedreht, Last];          labelingfunc[v : {x_, y_, w_}, i_, ___] :=        Placed[Grid[{{"Pflock ", i}, {"Koordinaten",            AccountingForm[{x, y}]}}, Frame -> All, Alignment -> Left],         Tooltip];     g = BubbleChart[(Append[#, 1] & /@ sortiert), ChartElements -> \!\(\*     Graphics3DBox[SphereBox[{0, 0, 0}],     Boxed->False,     ImageSize->30,     Lighting->"Neutral",     ViewPoint->{0,      DirectedInfinity[-1], 0}]\),        ColorFunction -> Function[{x, y, r}, Lighter[Yellow, x]],        ChartLabels ->         Placed[Style[#, "Subsection"] & /@ Range[Length@sortiert], Center],        BubbleSizes -> {0.07, 0.07}, LabelingFunction -> labelingfunc,        AspectRatio -> 1, Frame -> True, GridLines -> Automatic,        FrameStyle -> {Thick, Thick, Thick, Thick},        GridLinesStyle -> Directive[Blue, Dashed, Thick],        FrameLabel -> {" Easting [m\!\(\*     StyleBox[\"]\", \"Subsubsection\"]\) ", " Northing [m] ", " ", " ",},        PlotLabel -> "Grid-coordinates",        BaseStyle -> {FontWeight -> "Bold", FontSize -> 24},        FrameTicks -> {{myTickList[Min[gedreht[[All, 2]]] - 40.0,            Max[gedreht[[All, 2]]] + 40., 20, 5, 0],           None}, {myTickList[Min[gedreht[[All, 1]]] - 40.0,            Max[gedreht[[All, 1]]] + 40., 20, 5, Pi/6], None}},        BaseStyle -> {FontWeight -> "Bold", FontSize -> 18},        ImageSize -> {800, 800}       ]


ESRI shape files

ESRI shape files (shp): importing the polygon data can yield a very large list. It is computationally intensive rendering the polygon. I have been trying to convert to `GraphicsComplex` by extracting all the vertices, indexing them and then specifying the polygon by the vertex index. However, the computational effort of removing duplicates (shared borders) seems to be computationally worse than the original issue (for the large input size of the list of vertices). Can someone advise me if there is a better way to work with these files? I am able to use them but not efficiently.


How could I get the value of y[t] at each specific interpolation point?

sol = NDSolve[{Derivative[2][y][t] + Sin[y[t]] == 0, Derivative[1][y][0] == 0, y[0] == 1},     y, {t, 0, 2}]      the above-mentioned differential equations can be solved by Numerical interpolated integrations at a series of discontinuous points, and the number of the points depends on the Integration methods selected by the NDSolve. My problem is that how I can obtain all these points selected because I want to get the specific value of `y[t]` at each interpolation point?


Multiplicative partition function

I am trying to create a multiplicative partition function that would generate something like               f[12]     (*{{2, 2, 3}, {4, 3}, {6, 2}}*)     f[24]     (*{{2, 2, 2, 3}, {2, 2, 6}, {4, 2, 3}, {8, 3}, {12, 2}, {4, 6}}*)     f[48]     (*{{2, 2, 2, 2, 3}, {2, 2, 2, 6}, {4, 2, 2, 3}, {2, 2, 12}, {2, 3, 8}, {2, 4, 6},      {4, 4, 3}, {6, 8}, {4, 12}, {3, 16}, {2, 24}}*)      I have got as far as               n = 30;     i = FactorInteger[n];     r = Range[Length[i]];     Join[{f = Flatten[Map[Table[i[[#]][[1]], {x, 1, i[[#]][[2]]}] &, r]]},     Transpose[{d = DeleteDuplicates[f], Map[n/d[[#]] &, Range[Length[d]]]}]]      but it is turning out to be more complicated than I thought. Is there a more efficient way of tackling this? # Update Have got a little further, but still missing some:               n = 48;     i = FactorInteger[n];     r = Range[Length[i]];     f = Flatten[Map[Table[i[[#]][[1]], {x, 1, i[[#]][[2]]}] &, r]];     p = Drop[Drop[DeleteDuplicates[Subsets[f]], 1], -1];     d = Split[Drop[Drop[Reverse[Divisors[n]], 1], -1]];     Drop[Map[Sort[Join[p[[#]], d[[#]]]] &, Range[Length[d]]], -1]


For[] or While[] can't be used inside Manipulate[]?

Here is a code sample that creates a control object which calculates the expressions inside `Maniplate` again and again and never stop (it's proved by the code in the note): _Sample 1:_               Manipulate[date = Table[0, {num}];      For[i = 1, i <= num, i++, date[[i]] = Sin[i]];(*Print@i;*)      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      `While` has the same problem: _Sample 2:_               Manipulate[date = Table[0, {num}]; i = 1;      While[i <= num, date[[i]] = Sin[i]; i++];      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      I know if I choose `Do`, the problem will no longer exist: _Sample 3:_               Manipulate[date = Table[0, {num}];      Do[date[[i]] = Sin[i], {i, 1, num}];      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      Still, I know I can solve the problem if I throw the expression into `Module` if what I'm using is `For`: _Sample 4:_               Manipulate[Module[{i}, date = Table[0, {num}];       For[i = 1, i <= num, i++, date[[i]] = Sin[i]];       ListPlot[{date}]], {{num, 2}, 1, 20, 1}]      And…yeah, it doesn't work for the code above with `While`…: _Sample 5:_               Manipulate[Module[{j}, date = Table[0, {num}]; j = 1;       While[j <= num, date[[j]] = Sin[j]; j++];       ListPlot[{date}]], {{num, 2}, 1, 20, 1}]     (*This still creates a problematic control object*)      How to solve the problem with `While`? what actually happens inside `Manipulate`? what's the exact reason for the endless loop? * * * OK, the problem with _sample 5_ turns out to be a collaboration of _Sample 4_ and _Sample 5_ , before I run sample 5, a control object has been already created by _Sample 4_ (let's call it _Object 4_ below, and so we have _Object 5_ for _Sample 5_ ).I think the process should be like this: when `date = Table[0, {num}];` in _Sample 5_ is executed, it's tracked by _Object 4_ , and then `For[i = 1, i <= num, i++, date[[i]] = Sin[i]];` in _Sample 4_ is executed, so it is tracked by _Object 5_ …so this story tells us how important a good programing habit is…


Ordering vertices in GraphPlot

I'm new here, so forgive me if this question is not well-posed/duplicates an earlier question - although I've searched for similar questions without success. I'm trying to present a plot of connections between elements (correlations between student performance on a set of test questions, actually). It's something like (with options omitted):               test = {{1 -> 5, 1}, {4 -> 3, 3.6}, {6 -> 8, 1}, {2 -> 4, 2}, {2 -> 5,          2.5}, {5 -> 4, 0.9}, {7 -> 8, 2}, {3 -> 8, 1}, {8 -> 2, 1}};     GraphPlot[test, Method -> "CircularEmbedding", VertexLabeling -> True,       EdgeLabeling -> False]      ![Mathematica graphics](http://i.stack.imgur.com/pUnUZ.png) where the {1,2,3,...} are the labels for my questions. I want to order the vertices in ascending order (1,2,3,...), i.e. I want vertices with consecutive labels to be adjacent on the circle, like a clock - i.e. as in the image below, which I had to construct by making the connections more or less consecutive:               test2 = {{1 -> 2, 1}, {3 -> 4, 3.6}, {5 -> 6, 1}, {7 -> 8,      2}, {2 -> 5, 2.5}, {5 -> 4, 0.9}, {7 -> 3, 2}, {3 -> 8,      1}, {8 -> 2, 1}};     GraphPlot[test2, Method -> "CircularEmbedding", VertexLabeling -> True, EdgeLabeling -> False]      ![graphics2](http://i.imgur.com/uFOCu.jpg) Mathematica has its own ideas! It insists on ordering the vertices by the order in which it encounters them in the list of connections, (i.e. 1,5,4,3,...) in the above example. Sorting the list of connections doesn't fix this problem. This issue doesn't seem to be well documented. Any suggestions for a workaround? Thanks in advance!


How to suppress undesirable kerning rules in math inline cells?

**Update** : (11/29/2012) Looks like Mathematica 9 has the same behavior. The following graphic shows how Mathematica kerns italic characters in an inline math formula cell ( **first row** ) where an \[InvisibleSpace] has been inserted between consecutive characters (which could represent either multiplication of terms or multi-indices depending on context) _vs._ in an ordinary, non-math text cell which was switched to italics using Ctrl-I ( **second row** ). ![enter image description here](http://i.stack.imgur.com/vC6qM.png) When the letters _ijk_ for example appear together in a subscript as indices, the spacing between the _i_ and the _j_ appears too wide relative to the distance between the _j_ and the _k_. **Original Q** : Is it possible to turn off this special kerning in math formula cells? **Updated Q** : (10/1/2012) A reasonable but nevertheless somewhat inconvenient method to work around this issue has been suggested below. Does anyone know the reason why the kerning rules for juxtaposing italic characters inside math formula cells are different from those for normal, non-math italic text? * * * For ease of copying:               Cell[TextData[{      "Text ",      Cell[BoxData[       FormBox[        RowBox[{        "a", "\[InvisibleSpace]", "b", "\[InvisibleSpace]", "c",          "\[InvisibleSpace]", "d", "\[InvisibleSpace]", "e",          "\[InvisibleSpace]", "f", "\[InvisibleSpace]", "g",          "\[InvisibleSpace]", "h", "\[InvisibleSpace]", "i",          "\[InvisibleSpace]", "j", "\[InvisibleSpace]", "k",          "\[InvisibleSpace]", "l", "\[InvisibleSpace]", "m",          "\[InvisibleSpace]", "n", "\[InvisibleSpace]", "o",          "\[InvisibleSpace]", "p", "\[InvisibleSpace]", "q",          "\[InvisibleSpace]", "r", "\[InvisibleSpace]", "s",          "\[InvisibleSpace]", "t", "\[InvisibleSpace]", "u",          "\[InvisibleSpace]", "v", "\[InvisibleSpace]", "w",          "\[InvisibleSpace]", "x", "\[InvisibleSpace]", "y",          "\[InvisibleSpace]", "z"}], TraditionalForm]],       FormatType->"TraditionalForm"],      " Text"     }], "Text"]


Calculate information entropy integral in infinite square well problem

In the context of information theory, **entropy** is a measure of _uncertainty_ of a random variable. In quantum mechanics, the uncertainty principle states that $\Delta x\Delta k \ge 1/2$. The same can be expressed in terms of information entropy as $S_x + S_k \ge 1 + \ln\pi$. The information entropy $S_x$ is defined as: $$ S_x = \int_{-\infty}^{\infty} {\rho(x) \ln\rho(x) dx} $$ where $\rho(x)$ is the probability density function of the variable $x$. In continuation[1,2,3] of my study of the infinite square well problem, I'd like to check whether the informational version of uncertainty principle holds. For that, I need to calculate $S_x$ and $S_k$, for various numbers of $n=1,2,3,\ldots$, and check if their sum is bounded, knowing the respective probability density functions for position $x$ and momentum $k$. Here is my code for $S_x$:               ClearAll["Global`*"];     (* The length of the well *)     L = 1;          (* The eigenfunctions, n=1,2,3,... u[n,x] is zero outside of [0,L] *)     u[n_, x_] := Sqrt[2/L] Sin[n π x/L]          (* Probability density function for the x(=particle position) variable *)     (* Again, the domain of ρ(n,x) is the [0,L] interval *)     ρ[n_, x_] := u[n, x]\[Conjugate] u[n, x]          integrand =       Simplify[-ρ[n, x] Log[ρ[n, x]],        n ∈ Integers && x ∈ Reals]          (* Out= -2 Log[2 Sin[n π x]^2] Sin[n π x]^2 *)          (* Integrate over [0,L] since we haven't defined u[n,x] outside of [0,L] *)     (* We could have defined it though and then we would be integrating from -inf to +inf *)     Integrate[integrand, {x, 0, L}]          (* Out= -(1/(6 n π))(π (6 n - I π + 6 I n^2 π + n Log[64] -            12 n Log[1 - E^(2 I n π)] + 6 n Log[Sin[n π]^2]) +         6 I PolyLog[2, E^(2 I n π)] -         3 (-1 + Log[2 Sin[n π]^2]) Sin[2 n π]) *)      At this point it's already obvious that the value of the integral cannot be determined, since the terms $\sin(n\pi)$ equal zero and $\ln{0}$ is undefined.               FullSimplify[%, n ∈ Integers]      > During evaluation of In[72]:= FullSimplify::infd: Expression Log[1-E^(2 I n > [Pi])] simplified to -[Infinity]. >> > > During evaluation of In[72]:= FullSimplify::infd: Expression Log[Sin[n > [Pi]]^2] simplified to -[Infinity]. >> > > During evaluation of In[72]:= FullSimplify::infd: Expression Log[2 Sin[n > [Pi]]^2] simplified to -[Infinity]. >> > > During evaluation of In[72]:= General::stop: Further output of > FullSimplify::infd will be suppressed during this calculation. >> > > Out[72]= Indeterminate My book says that $S_x = \ln(2L) - 1$. Any ideas on how to trick _Mathematica_ to calculate the integral ? **Mathematica.SE related (to the physical problem) questions** : Is there a more mathematica-y way to label these plots? Why does FourierTransform converge while same integral manually written does not? Calculate integral for arbitrary parameter n in infinite square well problem


Defining a non-linear optimization-problem

Consider the following non-linear optimisation problem:               WeeklyCapacity = Table[Subscript[maxCapa, t], {t, 6}];     WeeklyDemand = Table[Subscript[weeklyD, i], {i, 10}];     CycleTimes = Table[Subscript[CT, i], {i, 10}];          (*Exemplary data:     WeeklyCapacity = Table[189*7.5, {t, 6}];     WeeklyDemand = Table[RandomInteger[{2000, 5000}], {i, 10}]     CycleTimes = (1/#) & /@ Table[RandomInteger[{40, 125}], {i, 10}]     *)          ProductionProgram =        Table[Subscript[x, i, t], {i, 10}, {t, 6}];     CapaDemand = Transpose@ProductionProgram.CycleTimes;          MinVarProductionProgram = Variance/@ ProductionProgram;     ConstraintDemand =        Map[# == 0 &, Total /@ ProductionProgram - WeeklyDemand];     ConstraintCapa = Map[# <= 0 &, Total /@ CapaDemand - WeeklyCapacity];      A company produces `i` different products and at the end of a week (six working days) has to meet a weekly demand (`WeeklyDemand`). The production manager knows how many pieces of each product can be produced within one hour (`CycleTimes`) and is limited to a maximum capacity of hours per day (`WeeklyCapacity`). The optimal production program (`ProductionProgram`) can be calculated as follows:   1. The variance of the production program of each product must be minimised (see `MinVarProductionProgram`).   2. The production program of each product has to meet its total demand per week (`ConstraintDemand`)   3. The production program must not exceed the available max. capacity (`ConstraintCapa`). `MinVarProductionProgram` represents a non-linear function. Hence I was thinking about a Lagrangian relaxation approach.


Annoying FrontEnd bugs in Mathematica 10

Recently I installed _Mathematica 10_ on _Windows 8 x64_ machine. Before that I had a prerelease version of _Mathematica 10_ installed on my laptop. I observed very annoying bugs in the FrontEnd on both machines: at some random moment during editing a notebook, some keybord shortcuts (e.g. `Ctrl+Z`, `Ctrl+C`, `Ctrl+S` etc) start doing things completely different from they are supposed to do: change the notebook stylesheet, open new windows, comment out the selected text etc. The menu items corresponding to those shortcuts do the same crazy things. To save the current notebook I have to invoke `NotebookSave[]` function because there is no way do it using graphical interface. Restarting _Mathematica_ solves the problem for a while, but soon it reappears. Does anybody else observe this behavior?


How many iterations of Newton's method are needed to achieve a given precision?

Consider using Newton's method to solve the equation $arctan(x) = 0$. Using an initial guess of $x_0 = 1/2$ produces a sequence that converges rapidly. After $8$, iterations, $x_8$ is accurate to well over 2000 decimal places. > (i) Verify with a computer that $x_8$ is a solution accurate to over $2000$ > decimal places. I was just learning Newton's Method and saw this problem. I think I might be going ahead but it seems good to know. Here is my attempt: (Sorry if I'm wrong. I am just really interested in this problem)                        In[1]:newton1[function_, variable_, initial_, iterations_] :=                    Module[{p, f, x},                    Subscript[p, 1] = initial;                    f[x_] := function /. variable -> x;                    Do[                    Subscript[p, i] =                     Subscript[p, i - 1] -                     f[Subscript[p, i - 1]]/f'[Subscript[p, i - 1]];,                    {i, 2, iterations}];                    Subscript[p, iterations]                    ]                         In[1]:Timing[approx = newton1[arctan(x)=0, x, 1/2, 8]]                         Out[1]:{0.826805, Indeterminate}      or I was wondering if the program could be this:                             In[1]: f[x_] := arctan[x] = 0;                        In[1]: mynewton[function_, variable_, initial_, iterations_] :=                          Module[{f, x, p},                          f[x_] := function /. variable -> x;                          Subscript[p, 1] = initial;                          Do[                          Subscript[p, i] =                           Subscript[p, i - 1] -                           f[Subscript[p, i - 1]]/f'[Subscript[p, i - 1]];,                          {i, 2, iterations}];                          Table[Subscript[p, i], {i, 1, iterations}]                          ]                        In[1]: N[mynewton[f[x], x, 1/2, 8], 8]                        Out[1]: {0.50000000, Indeterminate, Indeterminate, Indeterminate, \                           Indeterminate, Indeterminate, Indeterminate, Indeterminate}      Again sorry if I am wrong. I am really interested in learning this part of the program. I will be able to continue to other questions like this after help with this one on my own. I really did try. I was studying various types of Newton's Programs but can not figure this one out. Can someone please help write the input?


Quadruple-precision (128 bit) arithmetic

Is it possible to force Mathematica to perform computations with hardware supported quadruple-precision? The following test suggest, that all of the computations with fixed precision, different than `$MachinePrecision=15.9546`, are performed via the same arbitrary precision algorithm. Am I right? Is it possible to speed up 34 digit accurate computations?               num = RandomInteger[{1, 100}, 5 10^5];     First@AbsoluteTiming[       Sin[N[num]];     ]     (* ==> 0.273485 *)          {#, First@AbsoluteTiming[      Sin[N[num, #]];]} & /@ Range[32, 36]          (* ==>     {{32, 10.224581}, {33, 9.942714}, {34, 10.043138},     {35, 9.856203}, {36, 9.929918}}     *)


What format to use to store expressions in database?

I am storing lists of expressions into a MySQL database. Each list is of form               {_String, {_String, _Real}, _Real}      What data format should each column of the database table be? I am thinking `TEXT`, `TEXT`, `FLOAT`. Any suggestions? I need to be able to import values back to Mathematica (with `SQLExecute[]`, `SQLSelect[]`, etc.) and be able to work with expressions in Mathematica program.


Replace expressions by self defined symbols

I have a list of expressions like the following:               {{X00 ** X10 + X01 ** X10 - X10 ** X01 - X10 ** X00 },       {X01 ** X10 - X10 ** X01 - X02 ** X10},       {X00 ** X12 -  X12 ** X00}, {X01 ** X12 - X12 ** X01}, {X02 ** X13}}      where all `Xij` are just symbols. Now suppose we define an expression like               [X0j,X1k] := X0j ** X1k - X1k ** X0j.      Is it possible to let Mathematica substitute all terms in the list that look like the right side of the last expression by its left side? If necessary I can change the `Xij`'s in the list to something else.


Visualizing how the zeros for this function change as its input parameter changes?

I'm trying to explore how the zeros of a certain parameterized function change as its parameter changes.               dh[n_, k_, a_] :=      dh[n, k, a] = Sum[Binomial[k, j] dh[Floor[n/(m^(k - j))], j, m + 1], {m, a, n^(1/k)}, {j, 0, k - 1}]     dh[n_, 1, a_] := Floor[n] - a + 1     dh[n_, 0, a_] := 1     bn[ z_, a_] := bn[z, a] = Product[ (z - k), {k, 0, a - 1}]/a!     dd[n_, z_] := Sum[bn[z, a] dh[n, a, 2], {a, 0, Log[2, n]}]      The function I'm exploring here is dd[n_,z_]. n is the parameter I want to vary, and is a whole number $>= 1$. The zeros are all values of z such that dd[n,z] = 0. There should be $\log_2 n$ zeros for a given n. Now, I already know that I can see the zeros for an isolated value of n as               zeros[n_] := List @@ NRoots[ dd[n, z] == 0, z][[All, 2]]      For example, if I try zeros[30], I get {-16.1801, -1.66598 - 0.772391 I, -1.66598 + 0.772391 I, -0.0879758} I also know that I could visualize those zeros as               RootLocusPlot[1/dd[30, z], {k, 0, 1}]      But both of these techniques only address single values of n at a time. What I really want is to see how the zeros change as n changes, particularly for different scales of ranges for n. Does Mathematica have any tools to help me do that?


Adjusting Stylesheet Output Format

![enter image description here](http://i.stack.imgur.com/BSRuw.png)I'm using one of _Mathematica_ 's built-in stylesheets, "Standard Report". When I enter an expression into an input cell and evaluate it, the input is shown with a white background, while the output has a grey background. However, when I generate a plot, the numbers on the axes have white boxes around them, which looks stupid next to the grey background. How would I get rid of these white boxes? Thanks!


Calculating groupwise mean in Mathematica

I have a huge panel data with more than 2.5 million observations and more than 15000 groups. I want to calculate group-wise mean and I also need Id variable in my result. This is what I have done.               dat = {{2, .1, .2}, {2, .2, .4}, {2, .3, .6}, {2, .4, .8}, {5, 1,          2}, {5, 2, 4}, {7, 20, 10}, {7, 40, 20}, {7, 60, 30}, {7, 80,          40}, {7, 100, 50}, {10, 30, 50}};          results =  Table[N[Mean[Select[dat, #[[1]] == i &]]], {i, {2, 5, 7, 10}}];       But it is taking too long time. How can we make it quicker. Also, I want to calculate group-wise max value of second column. Any help is greatly appreciated.


Color mixing or blend

Color mixing seems not only one type. Here is RGB_color_model I wrote this one:               coord = 1/2*{{1, -Sqrt[3]/3}, {0, 2 Sqrt[3]/3}, {-1, -Sqrt[3]/3}};     color = {Red, Green, Blue};     MapThread[       Graphics[{##}, PlotRange -> 2, Background -> Black] &, {color,         Disk /@ coord}];     Plus @@ (ImageData /@ %) // Image     Clear[coord, color]      ![enter image description here](http://i.stack.imgur.com/aRkuY.jpg) Another type of mixing is :               {#, Graphics[{#, Disk[]}, ImageSize -> 50]} & /@       DeleteDuplicates[Blend /@ Permutations[{Red, Blue, Green}, {2}]]      ![enter image description here](http://i.stack.imgur.com/q0ALR.jpg) So How can I get the following like this ? ![enter image description here](http://i.stack.imgur.com/iavED.jpg)


How to fix this memory leak

I am using halirutan's code in this thread to unflatten a list. It works very well but the problem is that the Module's local function `f` is not deleted when the function returns the output and I consequently end up with hundreds of thousands of copies of the symbol of the form `f$xxxx`, which eventually crashes Mathematica. I tried other solutions from the same thread, but they don't seem to work. Is there any workaround?


Some Characters From Custom Font Do Not Show Up

I'm using version 8.0.4.0 on a Mac, and recently made my own .otf and .ttf fonts at PaintFont.com. The font can be based on pretty much anything, including handwriting, and covers everything from alpha-numerics, symbols, alphabets from other languages, punctuation, and ligatures. This can be very useful if you want your figures and text to look a little more personalized. The good news is, when I use something like:               Text[Style["This is the text I want in a different font.", FontFamily->"Example Font"]]      basic alpha-numerics, capitals and lowercase, work just fine, but certain symbols, including ! @ # % ^ * ( ) ~ - = + [ ] { } ; : | < >, Greeks, and so forth, show up simply in Mathematica's default font, even though I have characters for my font that definitely work (I've tested them in Word, etc.). Just an example, if I type:               Text[\[CapitalSigma]]      I get a capital sigma in **default font** , even though I definitely have that symbol in my own font. Is there any reason why Mathematica would accept certain characters from a font and not others? Are these characters "reserved" somehow by Mathematica and are "unformatable"? Thanks!


How to make a plot of function over 24 orders of magnitude?

Assume these parameter definitions first:               P0 = 325000000000000000000000000000000/1289899878039;     th = 22 10^-7;     alpha = 15*^6;     p0value = 0.0000697013247924021100000;     Lh = 5 10^-9;     d = 80 10^-9;     A = -2.8490639736294850547486980507937310695688037435690471`40.25650391588118*^\     14;     B = 1.1760120752241583305643404927085980980404601631188207268`37.\     974790074939705*^26;      Define two functions               tmp[x_] := A E^(x/Lh) + B E^(-x/Lh) + p0value ;     tmp2[x_] := -(alpha P0 th)/(1 - alpha^2 Lh^2) E^(-alpha x);      Subtracting them at x=d yields the small number p0value               tmp[d] - tmp2[d]      > 0.000069701324792402 I want the plot of `tmp[x] - tmp2[x]` to have a value of p0value (0.0000697013247924021100000) at `x = d` and not to stop at $10^{20}$.               LogPlot[{tmp[x] - tmp2[x]}, {x, 0, d}, PlotRange -> {{0, d}, {10^-5, 10^25}}]      ![Mathematica graphics](http://i.stack.imgur.com/ExnDN.png) I tried `MeshFunctions` but without success. Can anyone give me a hint?


Testing a certain function over multiple levels

I regularly want to test if a certain function, here foo, gives the expected result when mapping it over n - level - matrices. My naive approach is to write:               m1 = Range@3;     m2 = {m1, m1};     m3 = {m2, m2};     m4 = {m3, m3};      Then I test:               Map[foo, m1, {ArrayDepth@m1 - 1}];     (* ... *)     Map[foo, m4, {ArrayDepth@m4 - 1}];      The m1-case correctly gives:               foo[{1, 2, 3}],      and the m4-case correctly gives:               {{{foo[{1, 2, 3}], foo[{1, 2, 3}]}, {foo[{1, 2, 3}],         foo[{1, 2, 3}]}}, {{foo[{1, 2, 3}],         foo[{1, 2, 3}]}, {foo[{1, 2, 3}], foo[{1, 2, 3}]}}}      (foo should always map over the innermost level). I am now looking for a more elegant and automated solution, possibly a oneliner like:               (m[#] = BuildLevels[Range@3,4]) & /@ Range@4      but don' t know how to implement it in a short and efficient way. Thanks in advance for your help.


How can I pack circles of different sizes into a spiral?

Given a list of circles of different areas, I need to arrange them tangentially in order of increasing area and spiraling outward. An example of the type of packing I'm attempting is shown by the orange circles in the figure below: ![enter image description here](http://i.stack.imgur.com/Pl1du.png) Is there a concise way to calculate the centers of the circles?


Set-generating macro unexpectedly reaches recursion limit

One moment I decided to assign symbolic names to all special spaces since they all look the same when put literally in FrontEnd editor, more or less like `""` or `" "`. I wrote the following macro:               Block[{Set}, Set @@@     ( MapAt[         Composition[Symbol         , StringReplace[#, "[" | "]" | "\"" | "\\" ] -> ""]& ]       , #, {1}] & /@       Select[         {ToString@FullForm@#, #} & /@         FromCharacterCode /@ (-1 + Range[2^16])       , StringMatchQ[First@#, ___ ~~ "Space]\""] &] ) ];      that checks all Unicode chars recognised by Mathematica as “smth-Space”, fetches symbol names and performs the assignments. After macro expansion I expect to get               Block[{Set}, Set @@@     { { NonBreakingSpace, " " }     , {       ThickSpace, " " }     , {        ThinSpace, " " }     ,            (…rest)        }]      However, while the expression in round brackets does evaluate to correct table of symbols and various spaces if evaluated independently, and `Set@@@` on it works perfectly well, the whole macro `Block[{Set}, …]` starts throwing lots of errors, from `$RecursionLimit` and `ToExpression`. (Being a bit too hasty, I put it into pre-loaded packages — naturally, it made Kernel crash every time I attempted to start it.) That said, `Block[{set}, set@@@(…) /. set -> Set]` works OK, but the question remains: what causes the problem in the original macro? This is not the first time I make assignment with `Block[{Set}, Set@@@table];`, and I would like to keep doing it further. The issue is surprising. The only explanation I see is that `Block`ing `Set` somehow interferes with evaluating the expression in round brackets (the one meant to evaluate to the table). But this behaviour is quite unexpectable unless I miss something obvious, and there also does not seem to be a way to trace the evaluation. 1) Is there a way to `Trace` the evaluation? 2) What really causes the problem? (In case it is possible to find out at all without cracking the kernel.)


Include a CDF file in sites.google

I have a website on sites.google and I also have blog on wordpress. I would like to include some CDF files on them. How can it be done?


The same value of VertexSize for vertices in different graphs causes different vertices size

I generated some graphs. The smallest vertices in the 1st graph should be the same size as the smallest vertices in the second graph. The smallest vertices have the same size (`VertexSize` value is the same) in each graph. When I generate those graphs the size of the smallest vertices seems different: ![graph 1](http://i.imgur.com/AnvNAQj.png) ![graph 1](http://i.imgur.com/tXMiZ2l.png) Those 2 graphs in cdf: dropbox link . The size of graphs is set to 'Large'. How it can be fixed? I need that to do some animation. Thanks!


Listing over multiple inputs (tensor rank > 1) in a compiled function

I'm trying to optimize the solution given by Michael E2 to my previous problem (Efficiently determining if 3D points are within a surface composed of polygons) which I figured would be relatively straight forward to do with `Compile` but I'm having trouble listing over two inputs to a compiled function. Starting with Michael's code:               data = Flatten[        Table[{x, y, z, x^2 + y^2 + z^2 + RandomReal[0.1]},          {x, -2, 2, 0.2}, {y, -2, 2, 0.2}, {z, -2, 2, 0.2}], 2];          plot = ListContourPlot3D[data, Contours -> {1}, Mesh -> None];          polygonCoords =        Cases[Normal[plot[[1]]], Polygon[x_, ___] :> x, {0, Infinity}];          g = Graphics3D[{Opacity[.09], EdgeForm[Opacity[.3]],         Polygon[#,            VertexColors -> Table[Hue[RandomReal[]], {Length[#]}]] & /@          Cases[Normal[plot[[1]]], Polygon[x_, ___] :> x, {0, Infinity}]},        Lighting -> "Neutral", ImageSize -> 400, Axes -> True];          side[{P_, Q_, R_, ___}, X_] := Det@Differences[{X, P, Q, R}];     insideQ[polyhedron_, point_] := And @@ Positive[side[#, point] & /@ polyhedron];          points = RandomReal[{-1.5, 1.5}, {1000, 3}];     insideQ[polygonCoords, #] & /@ points; // AbsoluteTiming      Too slow: 0.5 sec for 1000 points and I have millions. I inlined the formula for the `det` and replaced `And` + `Positive` with `Min` + `UnitStep`:               sideC = Compile[{{poly, _Real, 2}, {X, _Real, 1}},         Block[{p1 = poly[[1, 1]], p2 = poly[[1, 2]], p3 = poly[[1, 3]],           q1 = poly[[2, 1]], q2 = poly[[2, 2]], q3 = poly[[2, 3]],           r1 = poly[[3, 1]], r2 = poly[[3, 2]], r3 = poly[[3, 3]],           x1 = X[[1]], x2 = X[[2]], x3 = X[[3]]},          UnitStep[-p3 q2 r1 + p2 q3 r1 + p3 q1 r2 - p1 q3 r2 - p2 q1 r3 +            p1 q2 r3 + p3 q2 x1 - p2 q3 x1 - p3 r2 x1 + q3 r2 x1 +            p2 r3 x1 - q2 r3 x1 - p3 q1 x2 + p1 q3 x2 + p3 r1 x2 -            q3 r1 x2 - p1 r3 x2 + q1 r3 x2 + p2 q1 x3 - p1 q2 x3 -            p2 r1 x3 + q2 r1 x3 + p1 r2 x3 - q1 r2 x3]         ], CompilationTarget -> "C", RuntimeAttributes -> {Listable},         Parallelization -> True, RuntimeOptions -> "Speed"];          insideQC[polyhedron_, point_] := Min@sideC[polygonCoords[[All, ;; 3]], point]      This lists over all the polygons. Lets test it,               insideQC[polygonCoords, #] & /@ points; // AbsoluteTiming      Now this is over 10x faster, 0.04 seconds. Compiling this again, because of the `CompiledFunctionCall` provides only a tiny speed improvment. I think it should be faster to list over both the list of polygon coordinates and the points. I suspect this question is related: Threading a compiled function over multiple arguments of different lengths, specifically ruebenko's last answer which works fine on MMA 9 on Win7 x64, It should be possible? Why doesn't this work:               sideC[polygonCoords, points]      Shouldn't this list over both inputs? How can I make this work? I tried to force inline-ing of the compiled function definition but it doesn't appear to be supported?               insideQC =        Compile[{{polyhedron, _Real, 3}, {points, _Real, 2}},         Min@sideC[polyhedron, #] & /@ points, CompilationTarget -> "C",         RuntimeOptions -> "Speed",         CompilationOptions -> {"InlineCompiledFunctions" -> True,           "InlineExternalDefinitions" -> True},         RuntimeAttributes -> {Listable}, Parallelization -> True];      _Compile::cfinll: "The CompiledFunction could not be inlined because its use requires threading with the Listable runtime attribute."_


How to dynamically toggle curves on/off in a crowded Plot?

When multiple curves appear in a single plot, it is useful to interactively turn certain curves on or off to visually compare smaller numbers of curves. It is trivial to put a quick dynamic together, as in this toy example               funcs = {Sin[x], Cos[x], Tanh[x]};      checked = ltexts = {"sin", "cos", "tanh"};      Column[{TogglerBar[Dynamic[checked], ltexts],         Dynamic[Block[{sel},           sel = Sort[checked /. Thread[ltexts -> Range[Length[ltexts]]]];            Plot[funcs[[sel]], {x, 0, 3*Pi}, PlotLegends -> ltexts[[sel]]]]]}]      ![Trivial example of curve toggling, output from the code above](http://i.stack.imgur.com/7rDLo.png) This approach, is a one-off solution. I am looking for a more elegant solution that can be applied to any plot, with a user interface that is a natural to the problem. The buttonbar above the plot is not a natural interface. Clicking on the curve or legend would be a natural action to toggle a curve's visibility. I intend to answer my own question, which I humbly propose as a reusable solution, but I would like to ask the community for improvements or enhancements.


Any command for group products?

Is there any Mathematica command or well known technique to take the direct product between two symmetric/permutation groups?


Summation for a function having singularity

I need to do summation of this function with Mathematica.               For[t=0,t<500,t++;Sum[-Q*Log[Q],{k,-Infinity,Infinity},{n,-Infinity,Infinity}]]          Q= Q1+Q2+Q3      where               Q1= 1/(Sqrt[(0.2+ 0.2 k)^2] Sqrt[       k^2]) ((0.0220725+ 0.0220725 k) Sqrt[k^2]          Erf[Sqrt[(0.2+ 0.2 k)^2]] -         0.110363 Sqrt[(0.2+ 0.2 k)^2]          k Erf[0.2 Sqrt[k^2]]) (0.886227 Erf[0.8 E^(-0.0004 t) - 0.2 n] +         0.886227 Erf[0.2- 0.8 E^(-0.0004 t) + 0.2 n])          Q2=1/(Sqrt[(0.2+ 0.2 k)^2] Sqrt[       k^2]) ((0.0220725+ 0.0220725 k) Sqrt[k^2]          Erf[Sqrt[(0.2+ 0.2 k)^2]] -         0.110363 Sqrt[(0.2+ 0.2 k)^2]          k Erf[0.2 Sqrt[k^2]]) (-0.886227 Erf[          0.8 E^(-0.0004 t) + 0.2 n] +         0.886227 Erf[0.2+ 0.8 E^(-0.0004 t) + 0.2 n])          Q3=(Erf[0.2+ 0.2 n] -         1. Erf[0.2 n]) (0.0271938 Erf[(0.2+              0. I) - (0.\[VeryThinSpace]+ 0.8 I) Sqrt[            E^(-0.0004 t)] + (0.2+ 0. I) k] +         0.0271938 Erf[(0.2+              0. I) + (0.+ 0.8 I) Sqrt[            E^(-0.0004 t)] + (0.2+               0. I) k] - (0.+ 0.0271938 I) Erfi[          0.8 Sqrt[            E^(-0.0004 t)] - (0.+               0.2 I) k] + (0.+ 0.0271938 I) Erfi[          0.8 Sqrt[E^(-0.0004 t)] + (0.+ 0.2 I) k])      The problem is because `Q` cannot be defined at certain k,Sum cannot be done. (For example, when I try to sum `Sum[-Q*Log[Q],{n,-55,55},{k,-55,55}]` at t=0, the error message is "Power::infy: "Infinite expression 1/Sqrt[0] encountered", "indet: Indeterminate expression 0.ComplexInfinity encountered." Is there a way that i can sum except the points where -Q*Log[Q] cannot be defined? Thanks.


How to obtain from a list, the different data that is in it, and the times that appear each one?

Are there an easy way to do... from               historyobjetivot = {20, 20, 30, 40, 34, 20, 34};      obtain two lists: - One with the each diffrent item number in the original list,i.e, {20,30,40,34} - Other with the number of times that appear in the list {3,1,2,1} Or any similar to do a PieChart


Errors while computing some terms of the Euler–Maclaurin formula

Here is an issue I came across while I was applying one of the well-known versions of   Euler–Maclaurin formula. I try to realize why _Mathematica_ goes wrong with this code below               NIntegrate[-((π Cot[(π x)/100] Csc[(π x)/100])/100) (x - Floor[x] - 1/2), {x, 1, 99}]      and yields > >     4.91483 >   Could you give me a hand to understand what is going on?


FullSimplify giving unexpected result

When I perform a `FullSimplify` on the list $$ \left\{-\sqrt{5-2 \sqrt{6}},\sqrt{5-2 \sqrt{6}},-\sqrt{5+2 \sqrt{6}},\sqrt{5+2 \sqrt{6}}\right\} $$ I get $$ \left\{\sqrt{2}-\sqrt{3},-\sqrt{2}+\sqrt{3},-\sqrt{5+2 \sqrt{6}},\sqrt{2}+\sqrt{3}\right\} $$ Note the third expression did not get simplified to $-\sqrt{2}-\sqrt{3}$ for some reason. Is this a bug or does Mathematica's complexity function genuinely consider $-\sqrt{5+2\sqrt{6}}$ simpler than $-\sqrt{2}-\sqrt{3}$? My expression in input form:               {-Sqrt[5 - 2*Sqrt[6]], Sqrt[5 - 2*Sqrt[6]], -Sqrt[5 + 2*Sqrt[6]], Sqrt[5 + 2*Sqrt[6]]} //        FullSimplify


How to find an asymptote of a logarithmic curve

An exponential decay curve has been plotted asymptoting at approximately x=30 (correct for what I am looking at) How can I find the exact value from the curve? I was hoping to be able to use something similar to the `FindMinimum` function, or draw a line along the asymptote and find the intersection with the x-axis. This is the function used to plot the curve:                   Plot[((5/Log[2])*Log[(80046.8 - ((0.79) (101325 + (1030*9.81*d))))/((313545. + 2.17341d) - ((0.79) (101325 + (1030*9.81*d))))]), {d, 0, 60}, AxesLabel -> {Depth - m, Time - mins}]


Using Table with arbitrary number of variables

Let $P=\{p_1,...p_n\}$. I would like a way to implent Table[Expression,{$p_1$,lim},{$p_2$,lim},...,{$p_n$,lim}] where n and lim are parameters defined by the user. Any ideas?


Issue in displaying a rotated PolarPlot with Show

I can use `PolarPlot` to generate a plot; however, I would like to rotate the plot by 90 degrees and then output the result using Show. Here is the code               Y20 =        PolarPlot[          Abs[Sqrt[5/(16*Pi)]*(3*Cos[Theta]^2 - 1)],           {Theta, 0, 2*Pi},           Ticks -> None       ]     Show[Rotate[Y20, Pi/2]]      > ![enter image description here](http://i.stack.imgur.com/IyEMk.png) and the error > >     Show::gtype: Rotate is not a type of graphics. >   If I wrap `Rotate` with `Graphics` the error message I get is > >     Graphics is not a Graphics primitive or directive. >   Any comments will be welcomed.


Plotting two-variable function as function of one variable with manipulate for both variables

I have a function g(x,y) and would like to plot it as g(x) with a slider to vary y. What I currently have is a g(x,y) plotted as g(x) but with y as a parameter which I can adjust:               Manipulate[Plot[g[x,y],{x,0,10}],{y,0,10}]      That works fine, but now I'd like to be able to vary the upper value of the x-axis so that we can adjust how much of the graph we see (or how much of the x-axis we see). This is what I've tried (but didn't work):               Manipulate[Plot[g[x,y],{x,0,Manipulate[x,{x,0.1,10}]}],{y,0,10}]


DynamicModule/Dynamic CheckboxBar Slow for Large Lists

I am trying to create a dynamic construct that takes a large list of expressions and allows the user to interactively select any number of entries for further manipulation. This is what I have envisioned so far:               Construct[largeListOfEntries_] := DynamicModule[{loadButton, viewPane, testlabels,       valuesPicked, dsFunction, buttonPressed = False},     loadButton = Button["Load Initial List", buttonPressed = True;      testlabels = largeListOfEntries[[;; , 2]]];     viewPane = Panel[      Pane[       Dynamic@If[buttonPressed != False,                  CheckboxBar[Dynamic[valuesPicked],                               MapThread[#1 -> #2 &, {Range[Length@testlabels], testlabels}],                              Appearance -> "Vertical"],                 "Load List..."],       ImageSize -> {500, 340}, ImageSizeAction -> "Scrollable", Scrollbars -> {True, True}],      Style["Sample Pane", 12, Bold, Purple]];     dsFunction = Button["Modify Selected Element",                          Print[largeListOfEntries[[valuesPicked, 1]]]];          Column[{loadButton, viewPane, dsFunction}]]      Given a large list such as this:               largeListOfEntries = {#, "label"} & /@ RandomReal[1, 3000]     Construct[largeListOfEntries]      > ![enter image description here](http://i.stack.imgur.com/KHfxi.png) I would then be able to select any number of elements that I want and apply the downstream function to them (for example purposes here the function just prints the value of the selected element). Everything appears to be working but for large lists simply the act of **clicking the`Checkbox` takes a really long time**. I suspect this is due to the fact that `DynamicModule` stores all the values at the `FrontEnd` and with large lists it can get really slow. If i simply use `Module` or keep the everything global then the process is significantly faster but I need to localize my variables and from what I've read using `Module` with `Dynamic` objects is not recommended and my `Dynamic` variables become red indicating conflict. Is there something that I'm fundamentally doing wrong that is having such a drastic impact on performance? * * * **EDIT (03.18.14)** As Kuba pointed out it is possible to see the hit in performance simply by using:               largeListOfEntries = RandomReal[1, 3000];      CheckboxBar[Dynamic@valuesPicked,largeListOfEntries]      Indicating that the issue may be directly associated with `Dynamic` variables in `CheckboxBar`. However if that construct is then wrapped with a `DynamicModule`, the performance hit is even worse than before, so the `Module` itself is also contributing.


How to eliminate the zero real part of a purely imaginary number?

In _Mathematica 9_ , a purely imaginary number, e.g. `0.9 I`, will display as `0\. + 0.9i` in the output form. How can I eliminate the real part `0.` in the output form?


Function to naming columns

I often import files from excel or csv files and they come in a format like this:               {{"He", "She", "It", "We"}, {8.57167, 0.406351, 1.68575,        5.55309}, {9.16751, 2.57632, 9.20212, 9.8879}, {8.49497, 5.72921,        8.92677, 8.17118}, {3.78541, 2.35875, 4.94475, 3.56491}}      With dimensions in this case {5,4}, I then want to name the columns by the first row. In this case it would mean that row one would be called he, and is equal to `{8.57167, 9.16751, 8.49497, 3.78541}`. I have tried several ways to do this but some how i keep getting different errors. It should be a very simple and efficient solution. This would mean that i want {8.57167, 9.16751, 8.49497, 3.78541} to be shown every time i enter he into mathematica, also if the word starts with a capital as it does for all words in this case I would like it to be transformed from He to he and She to she etc.


Problem ListLinePlot with 2 data sets

I am trying to plot 2 data sets with ListLinePlot and my problem is that no graph shows up. When I plot a single data set i.e. `ListLinePlot[Aluminium]` it looks great, like this: ![enter image description here](http://i.stack.imgur.com/L4rSN.jpg) But when I try to plot **two** data sets with `ListLinePlot[{Aluminium, Steel}]` I just get axis: ![enter image description here](http://i.stack.imgur.com/blQXr.jpg) I'm new to Mathematica and I'm not sure how it interprets the data but here's a sample of a single data set: > {{{-0.00396837, 0.00690848}, {-0.00396786, 0.00696155}, {-0.0039628, > 0.00775434}, {-0.00394408, 0.0105445}, {-0.00392182, 0.0141262}, > {-0.00390765, 0.0165268}, {-0.00389855, 0.0180618}, {-0.00389247, 0.019202}, > {-0.0038864, 0.0203702}}} and a second data set: > {{{-0.0343947, 0.006893}, {-0.0343942, 0.00694899}, {-0.0343897, > 0.00805173}, {-0.0343755, 0.0114375}, {-0.0343644, 0.0144129}, {-0.0343553, > 0.0165506}, {-0.0343477, 0.0177545}, {-0.0343401, 0.0187138}, {-0.0343345, > 0.0196253}, {-0.034329, 0.0209271}, {-0.0343239, 0.0220682}, {-0.0343193, > 0.0230841}, {-0.0343153, 0.0240036}, {-0.0343123, 0.024847}, {-0.0343092, > 0.0257369}, {-0.0343057, 0.0266416}, {-0.0343021, 0.0275453}, {-0.0342986, > 0.0284322}, {-0.0342956, 0.0293173}}}


Bug in ListVectorPlot?

Trying to evaluate the following expression kills my kernel (Mathematica 8.0.0.0):               ListVectorPlot[{{{0.04039190555`,0.00897597901`},{0.1094840396`,-0.4878660114`}},{{0.01346396852`,-0.02692793703`},{-0.4484770638`,-0.2210618086`}},{{-0.01346396852`,0.02692793703`},{0.4484771099`,0.2210617151`}},{{0.04039190555`,0},{6.015064858999999`*^-7,-0.5`}},{{-0.04039190555`,0},{-8.376467958999999`*^-7,0.5`}},{{0.04039190555`,0.004487989505`},{0.05578099204`,-0.4968787387`}},{{0.04039190555`,-0.004487989505`},{-0.0557801133`,-0.4968788373`}},{{-0.04039190555`,-0.004487989505`},{-0.05578124893`,0.4968787098`}},{{-0.04039190555`,0.004487989505`},{0.05577990379`,0.4968788608`}},     {{0.03141592654`,0.004487989505`},{0.0717709292`,-0.4948221233`}}     }]      Is this a bug?


Distribute and analyze large datasets

I need to analyze very large datasets, and they obviously don't fit in a computer memory. I need to produce some statistics on these datasets, and this brings me here: How can I make some statistical analysis on **distributed** datasets? I imagine _Mathematica_ may split (hopefully _automagically_ ) data over many kernels, being local or remote. Anyone had any experience?


Output a symbol from Module or Block

I have troubles to output an entire symbol, a function in this case, from a module or a block. For instance                myf = Block[{f}, f[3] = 33; f[4] = 4; f]      Then I want to get the values of `f` from the module valorization, but I get                In[531]:= myf[3]           Out[531]= f(3)      instead I would like to get the value that I have put in the module, in this case `                "desired behaviour"           In[531]:= myf[3]           Out[531]= 33      I might be asking a RTFM question, but I do not see it answered anywhere. Thanks for your help, Roberto


WeatherData for the 15th day of each month

Suppose we have               WeatherData["Helsinki", "MeanTemperature", {{2007, 1, 1}, {2012, 12, 31}, "Day"}]      How we can have data just for 15th day of each month?


Is it possible to use Find with wild cards?

When making global changes to code and variables Find is a great resource. Is there a way to use Find with wild cards to find and replace any non numerical elements or to find and replace only numbers?


Get path to end nodes in directed (partially cyclic) graph

I have a large directed graph containing small loops. I would like to extract all paths to all end nodes (no `VertexOutComponent`) with a given path length $n$. I have written a function which works, but I would like to know if anybody knows a more "elegant" and sufficient way to perform this task. Please see my minimum working example and the function I am using. In this case, vertices 3 and 4 are end nodes. ![graph](http://i.stack.imgur.com/xq39Y.png)               g=Graph[{1,2,3,4},     {DirectedEdge[1,2],DirectedEdge[1,1],DirectedEdge[2,1],DirectedEdge[2,2],DirectedEdge[2,3],DirectedEdge[2,4]},     {GraphLayout->"SpringEmbedding",ImagePadding->20,VertexLabels->{"Name"},VertexLabelStyle->{Directive[RGBColor[1,0,0],Bold,20]}}];          route[g_,sp_,n_]:=Block[{ep,m,bag},     ep=Cases[{#,VertexOutDegree[g,#]}&/@VertexList[g],{_,0}][[All,1]];     m=1;bag={{sp}};     While[m<n,         bag=Flatten[Thread[Append[#[[1]],#[[2]]]]&/@(Thread[List[bag,(VertexOutComponent[g,Last[#],1]&/@bag)]]),1];         bag=DeleteCases[bag,_?(MemberQ[ep,Last[#]]&&SameQ@@Take[#,-2]&)];         m++;     ];     Cases[bag,_?(MemberQ[ep,Last[#]]&)]     ];      You will get:               route[g, 1, 6] =     {{1,1,1,1,2,3},{1,1,1,1,2,4},{1,1,1,2,2,3},{1,1,1,2,2,4},     {1,1,2,2,2,3},{1,1,2,2,2,4},{1,1,2,1,2,3},{1,1,2,1,2,4},     {1,2,2,2,2,3},{1,2,2,2,2,4},{1,2,2,1,2,3},{1,2,2,1,2,4},     {1,2,1,1,2,3},{1,2,1,1,2,4},{1,2,1,2,2,3},{1,2,1,2,2,4}}      All routes are 6 steps long and end in vertices 3 or 4. _Is there a build-in function or any other code I can use to get this output efficiently?_ My real world data are graphs containing approx. 80 vertices, 5 to 10 loops with 5 to 10 vertices and 5 to 10 end nodes. You can try:               SeedRandom[1];g=RandomGraph[{80, 120}, DirectedEdges->True];     route[g,2,17]      which gives a list of 110807 routes in 16 seconds (on my PC). Thanks!


Generate regularly spaced points from the surface of simplexes

I need to generate regularly spaced samples (points) from the surface of unit simplexes with 2 or greater vertices or end points. I can generate random samples pretty straightforwardly:               sampleSimplex[sampleSize_, vertices_] :=       Module[{s},        s = RandomReal[ExponentialDistribution[2], {sampleSize, vertices}];       Map[Normalize[#, Total] &, s]]          Graphics3D[Point /@ sampleSimplex[1000, 3], ImageSize -> 150,       BoxStyle -> Directive[LightGray], ViewPoint -> {Pi, Pi/2, 2}]      ![simplex samples](http://i.stack.imgur.com/N1chl.png) This works nicely and enables me to specify the number of samples and the number of vertices, but as I stated above I want to generate regularly spaced points, kind of like a `Mesh` on a 3D plot (but not limited to 3 dimensions). I can also do it for 2 vertices pretty simply:               sampleSimplexWith2Vertices[sampleSize_] := Module[{temp},       temp = N[Range[0, 1, 1/sampleSize]];       Transpose[{temp, Reverse[temp]}]]          sampleSimplexWith2Vertices[10]          {{0., 1.}, {0.1, 0.9}, {0.2, 0.8}, {0.3, 0.7}, {0.4, 0.6}, {0.5,        0.5}, {0.6, 0.4}, {0.7, 0.3}, {0.8, 0.2}, {0.9, 0.1}, {1., 0.}}          ListPlot[%, ImageSize -> 200]      ![enter image description here](http://i.stack.imgur.com/OongL.png) but I seem blocked in thinking about a solution that extends further. Any suggestions for how to approach this problem appreciated. I recognize that this may appear too narrow in scope or that it seems more like a conceptual problem of how to think about the problem more than how to implement an idea in Mathematica. I can withdrawal the question, if either of those seems like the consensus. I hoped that the approaches I've tried so far and those the question might draw would have sufficient general interest to merit some responses. * * * In the interest of improving the question I wanted to incorporate @Rahul_Narain's idea from his comment:               sampleSimplexWith3Vertices[pointsPerSide_] := N@Select[        Flatten[         Table[{x, y, 1 - x - y}, {x, 0, 1, 1/pointsPerSide}, {y, 0, 1,            1/pointsPerSide}], 1], #[[3]] >= 0 &]          sampleSimplexWith3Vertices[10];      ![enter image description here](http://i.stack.imgur.com/924MG.png) This works for 3 vertices, where one specifies the number of points per side. But, how does one generalize this for an arbitrary number of vertices (dimensions)? I've thought that `Table` would give one way to go about this, but wouldn't generalizing this with `Table` need a way to change just about everything between its brackets?


How to draw Fractal images of iteration functions on the Riemann sphere?

Prof. McClure, in the work "M. McClure, **Newton's method for complex polynomials.** A preprint version of a “Mathematical graphics” column from _Mathematica in Education and Research_ , pp. 1–15 (2006)", discusses how _Mathematica_ can be applied to iteration functions for obtaining the basins of attraction (or their fractal images). Below, I provide his code for the fractal image of the polynomial $p(z)=z^3-1$:               p[z_] := z^3 - 1;     theRoots = z /. NSolve[p[z] == 0, z]     cp = Compile[{{z, _Complex}}, Evaluate[p[z]]];     n = Compile[{{z, _Complex}}, Evaluate[Simplify[z - p[z]/p'[z]]]];     bail = 150;     orbitData = Table[        NestWhileList[n, x + I y, Abs[cp[#]] > 0.01 &, 1, bail],         {y, -1, 1, 0.01}, {x, -1, 1, 0.01}     ];     numRoots = Length[Union[theRoots]];     sameRootFunc = Compile[{{z, _Complex}}, Evaluate[Abs[3 p[z]/p'[z]]]];     whichRoot[orbit_] :=        Module[{i, z},        z = Last[orbit]; i = 1;       Scan[If[Abs[z - #] < sameRootFunc[z], Return[i], i++] &, theRoots];       If[i <= numRoots, {i, Length[orbit]}, None]      ];     rootData = Map[whichRoot, orbitData, {2}];     colorList = {{cc, 0, 0}, {cc, cc, 0}, {0, 0, cc}};     cols = rootData /. {       {k_Integer, l_Integer} :> (colorList[[k]] /. cc -> (1 - l/(bail + 1))^8),       None -> {0, 0, 0}     };     Graphics[{Raster[cols]}]      ![Newton-Raphson fractal](http://i.stack.imgur.com/Rd9q2.png) My main question is here. He nicely obtained the fractal images on the complex plane, while it would be an interesting challenge to obtain these images on the Riemann sphere, e.g. ![Newton-Raphson fractal on the Riemann sphere](http://i.stack.imgur.com/jFPjV.jpg) It seems the complex plane in this case has been replaced by a sphere, but how? I will be thankful if someone could revise the code given above for obtaining such beautiful fractal images on the Riemann sphere. Any tips and tricks will be fully appreciated as well.


Optimal image quality using Rasterize Function

Based on previous posts about plotting two y axes on the same x axis, I wrote this function:               plotyy[x_, y1_, y2_] := Module[{xy1, xy2, p1, p2},       xy1 = Table[{x[[i]], y1[[i]]}, {i, Length[x]}];       xy2 = Table[{x[[i]], y2[[i]]}, {i, Length[x]}];       p1 = ListLinePlot[xy1, ImagePadding -> 25,          Frame -> {True, True, False, False}, Axes -> False];       p2 = ListLinePlot[xy2, ImagePadding -> 25, Axes -> False,          Frame -> {False, False, False, True},          FrameTicks -> {None, None, None, All}, PlotStyle -> Red];       Rasterize[Overlay[{p1, p2}], RasterSize -> 600, ImageSize -> 600]]      which takes three lists with the same length and plots y1 and y2 on x. I've values for image quality by `RasterSize` and `ImageSize` for using the plot in my report but for different plots it may need different values for those two options. How can I can set the optimum values for `RasterSize` and `ImageSize` in my function? Thanks, Amin.


Color scheme used by Colorize?

The `Colorize` function is often used to display the results produced by `MorphologicalComponents`:               i = ImageTake[        ExampleData[{"TestImage", "Mandrill"}], {1, -1, 10}, {1, -1, 10}];     b = Binarize[i, .5];     mc = MorphologicalComponents[b];     Colorize[mc]      ![mandrill taken](http://i.stack.imgur.com/CiP97.png) The colors represent the integer index values of each foreground component, so the magenta area is 2, the black background is 0, 42 is browney-orange, 19 is violet, and - well, my question is, what is this color scheme? I'm working on images like the following, to try to understand morphological images, but a legend-type approach might be better:               Show[      ArrayPlot[mc,       Epilog -> {         MapIndexed[{Text[Style[#1, 10, Gray],             Reverse[#2 - {.5, .5}]]} &,          Reverse[mc],          {2}]}, PlotRangePadding -> 0],      Colorize[mc]      ]      ![labeled](http://i.stack.imgur.com/cjQAJ.png) # Update Thanks to stefan's amazing detective work, I've got a way to list the colors, although this isn't available until you run `Colorize` once or set up the colors another way first:               colorizeColors[n_] :=       Part[RGBColor[N@#1/256, N@#2/256, N@#3/256] & @@           Image`ColorOperationsDump`hashcolor[#1] & /@ Range[1, 100], n]     Graphics[Table[{colorizeColors[x], Rectangle[{x, 0}, {x + 1, 1}],         White, Text[x, {x + 0.5, -.5}]}, {x, 1, 30}], Background -> Black,       ImageSize -> 800]       ![colorize legend](http://i.stack.imgur.com/NoiP7.png)


Formulas for combining ChebyshevT coefficients?

I have two 5th-order (6th-order?) Chebyshev approximations:               f1[x_] = Sum[a[n]*ChebyshevT[n,x],{n,0,5}]     f2[x_] = Sum[b[n]*ChebyshevT[n,x],{n,0,5}]      and f1[1] == f2[-1]. I now "combine" these functions so f1's domain is mapped to [-1,0] and f2's domain is mapped to [0,1]. The Chebyshev approximation of this combination is:               coeff[n_] := coeff[n] = 2/Pi*(      Integrate[f1[x*2+1]/Sqrt[1-x^2]*ChebyshevT[n,x],{x,-1,0}] +      Integrate[f2[x*2-1]/Sqrt[1-x^2]*ChebyshevT[n,x],{x,0,1}]     )      (coeff[0] actually should be divided by 2, but that doesn't affect my question) Mathematica won't give me a general formula here (getting rid of "coeff[n_] :=" fails), but I believe there is one. What is it? I tried using "f1[1] == f2[-1]" to simplify, but it doesn't help. I calculated coeff[0] through coeff[12]. The multiplier for each of the a[i] is below (the b[i] are easily calculated from the a[i]). I noticed the multiplier is of the form (a+b*Pi)/c (for a,b,c all integers) for the first few entries in each sequence (ie, i < j in some sense), and then become a/Pi for integer a. The first sequence (for a[0]) has alternating 0's and may be a special case (and is also easy to solve). I tried using oeis.org on the numerators and denominators to no avail.               Expand[Table[D[coeff[i],a[j]],{j,0,5},{i,0,12}]] // TeXForm      $ \left( \begin{array}{ccccccccccccc} 1 & -\frac{2}{\pi } & 0 & \frac{2}{3 \pi } & 0 & -\frac{2}{5 \pi } & 0 & \frac{2}{7 \pi } & 0 & -\frac{2}{9 \pi } & 0 & \frac{2}{11 \pi } & 0 \\ 1-\frac{4}{\pi } & 1-\frac{2}{\pi } & -\frac{4}{3 \pi } & \frac{2}{3 \pi } \ & \frac{4}{15 \pi } & -\frac{2}{5 \pi } & -\frac{4}{35 \pi } & \frac{2}{7 \pi } & \frac{4}{63 \pi } & -\frac{2}{9 \pi } & -\frac{4}{99 \pi } & \frac{2}{11 \pi } & \frac{4}{143 \pi } \\ 5-\frac{16}{\pi } & 4-\frac{38}{3 \pi } & 2-\frac{16}{3 \pi } & -\frac{22}{15 \pi } & \frac{16}{15 \pi } & -\frac{2}{21 \pi } & -\frac{16}{35 \pi } & \frac{58}{315 \pi } & \frac{16}{63 \pi } & -\frac{122}{693 \pi } & -\frac{16}{99 \pi } & \frac{202}{1287 \pi } & \frac{16}{143 \pi } \\ 25-\frac{236}{3 \pi } & 21-\frac{66}{\pi } & 12-\frac{188}{5 \pi } & 4-\frac{182}{15 \pi } & -\frac{44}{35 \pi } & \frac{10}{7 \pi } & -\frac{28}{45 \pi } & -\frac{34}{105 \pi } & \frac{76}{165 \pi } & \frac{38}{693 \pi } & -\frac{964}{3003 \pi } & \frac{14}{429 \pi } & \frac{1492}{6435 \pi } \\ 129-\frac{1216}{3 \pi } & 112-\frac{5278}{15 \pi } & 72-\frac{3392}{15 \pi \ } & 32-\frac{3518}{35 \pi } & 8-\frac{2624}{105 \pi } & -\frac{254}{315 \pi } & \frac{64}{45 \pi } & -\frac{1334}{1155 \pi } & \frac{64}{495 \pi } & \frac{8482}{15015 \pi } & -\frac{2752}{9009 \pi } & -\frac{4054}{15015 \p\ i } & \frac{1856}{6435 \pi } \\ 681-\frac{32092}{15 \pi } & 605-\frac{5702}{3 \pi } & 420-\frac{9236}{7 \pi } & 220-\frac{4838}{7 \pi } & 80-\frac{15836}{63 \pi } & 16-\frac{2258}{4\ 5 \pi } & -\frac{316}{693 \pi } & \frac{86}{77 \pi } & -\frac{1132}{819 \pi } & \frac{310}{429 \pi } & \frac{1228}{4095 \pi } & -\frac{1822}{3003 \pi } & \frac{788}{13923 \pi } \\ \end{array} \right) $


Working with means and variances

My goal is to work out on the following equation: $$Mean(P)(1-Mean (P))\left (h + (1 - 2 h) (1 - \frac {Var (P)} {Mean (P) (1 - Mean (P))}) (1 - Mean (P)) + \frac {Var (P)} {Mean (P) (1 - Mean (P))} (1 - h) \right)$$ where $P$ is a sample, $Mean(P)$ is the `Mean` value of the sample $P$: $Mean(P) = 1/n \sum_{i=1}^n p_i$. $Var(P)$ is the `Variance` of the random variable $P$. How can I `Simplify` this kind of equation with _Mathematica_? I thought I could eventually define a sequence of $p_i$ of undefined length and work with it. Is something similar feasible? Here is the _Mathematica_ code:               Mean[P](1-Mean[P])( h + (1-2h)(1-(Variance[P])/(Mean[P](1-Mean[P])))*       (1-Mean[P]) + (Variance[P])/(Mean[P](1-Mean[P])) (1-h))


Sum over all permutations

I have n variables and a function that has all of them as variables. n-3 of them in terms of the entries of two lists. The possible entries in the lists $\alpha$ and $\beta$ range from {2,...n-2}. Now I want to sum over all possible permutations of these n-3 elements (aka $P_{n-3})$, i.e. $$f=\sum_{\alpha,\beta \in P_{n-3}}A[1,\alpha,n-1,n]S[\beta,\alpha]A[n,\beta,n-1,1]$$ with A and S some other functions. How do I program this into mathematica. I thought about writing f as a pure function. But then how to implement this sum over permutations? Thanks for any advice!


StringCases functionality on a varying rows of data

There is a string in this form:               <12> cfg <15.21>  bhg    v<(24)>    e<65>   True     <12> cfg <15.21>  bhg    v<33>      e<(77)> False     <83> fff <67>     bhg     < >       e<(43)> True     <11> fff <14.21>  bff    v<(1.42)>  e<44>   True     <76> cfg <76.3>   fff     < >       e<21>   True     <98> cff <34>     rrs    v<33>       < >    True      The point is the numbers in the parenthesis indicate negative numbers and there are as well some missing values. I need to refine this string in a form to get a vector of output in this form:               {{12,15.21,-24,65,T},{12,15.21,33,-77,F},{83,67,-43,-43,T},     {11,14.21,-1.42,44,T},{76,76.3,NA,21,T},{98,NA,33,NA,T}}      What I did is to apply this:               Partition[StringCases[list, NumberString],4]      But as some rows have different structure then it is not working. And also this is not able to capture the negative numbers, and even this is neglecting the last column!! How is it possible to manage this?


Is it possible to take data from external database for the CDF embedded in webpage?

I have embedded my CDF in facebook.The data for the CDF should be taken from facebook server or my server dynamically.I tried out but its not working in dynamic code iam not able to access the data at all from both servers.Now i have the doubt is it possible to access data for the CDF from external databases.