title: Solving a polynomial equation with a condition of equality on roots

text: Let the following equation have two equal roots:               f[x_] := x^3 - p x^2 + q x - r       And I want to find out what the three roots are. Not knowing how to put this condition within a Solve or Reduce, I have to rely on transcribing some algebra into MMA. So if the above equation has two equal roots, then               fr[x_] := 3 x^2 - 2 p x + q      has one of them, out of a theorem on the depression of equations. If I put this into Solve this leads to:               Solve[x^3 - p x^2 + q  x - r == 0   && 3 x^2 - 2 p  x + q == 0, x]      No error message but MMA is unable to give here one the the duplicate solution. So I put more algebra into the code:               PolynomialRemainder[f[x], fr[x], x]    (* the remainder must he equal to zero *)     rootduplicate = x /. Solve[% == 0, x]  (* gives the value of the two equal roots *)      The third root is within the third factor of f[x]:               PolynomialQuotient[f[x], (x - rootduplicate[[1]])^2, x] // FullSimplify     Solve[% == 0, x]     root3 = x /. {%}      Let's check it up with an example:               Solve[(x^3 - p x^2 + q  x - r /. {p -> 4, q -> 5, r -> 2}) ==  0   && (3 x^2 - 2 p  x + q /. {p -> 4, q -> 5}) == 0, x]    (* now MMA finds a double root *)     Solve[(x^3 - p x^2 + q  x - r /. {p -> 4, q -> 5, r -> 2}) ==  0   , x]      rootduplicate /. {p -> 4, q -> 5, r -> 2}     root3 /. {p -> 4, q -> 5, r -> 2}     root3 == {(p - 2 rootduplicate)} // FullSimplify (* another verification out of algebra   - is there a way with MMA to find out this relation without hardcoding it? *)      My questions:   * Why MMA (V8) is unable to find a solution in my first Solve ?    * Is there a better way relying less on algebra to get these solutions?


title: Issue with setting up docked cells

text: Normally I try to stay away from asking RTFM- questions but concerning docked cells I am currently groping in the dark. The documentation examples tell me how to create a new window containing a docked cell, but not how to setup a cell as docked cell in my existing .nb file. Am I to use (edit) the notebooks stylesheet or is there a command like e.g. SetOptions for that matter?


title: Compiling a spatial predator-prey model and optimising it for speed

text: I just made a spatial predator-prey model but it runs a little slow and I am seeking some advice on how to compile it to optimise it for speed. I first define matrix with 0 for an empty site, 1 for a predator and 2 for a prey present:               e = 0;r = 1;y = 2;     initSpace[n_] := RandomInteger[{0, 2} , {n, n}];     space = initSpace[10];      I then defined a `getCell` function which looks for a neighbour at cell position $(i,j)$ in a matrix `sp` with a certain value `x`, and returns the coordinates of that cell; if it doesn't find a cell with that value it returns coordinates $(i,j)$.               getCell =       Compile[{{sp, _Integer,          2}, {i, _Integer}, {j, _Integer}, {x, _Integer}},        Block[{n, m, k2, l2, cells}, {n, m} = Dimensions[sp];        cells = {{i, j}};        Do[k2 = Mod[i + k, n, 1]; (* This is the neighborhood *)         l2 = Mod[j + l, m, 1];         If[(k2 != i || l2 != j) && sp[[k2, l2]] == x,           AppendTo[cells, {k2, l2}]], {l, -1, 1}, {k, -1, 1}];        If[Length[cells] == 1, {i, j}, RandomChoice[Rest[cells]]]],        CompilationTarget -> "C", Parallelization -> True,        RuntimeOptions -> "Speed"]      I then define a module step which calculates the space matrix in the next time step based on a given birth rate `b` and death rate `mu` after one event at a random location in the space.               step[b_, mu_] := Block[{i, j, k, l, dim},       dim = Dimensions[space];       i = Random[Integer, {1, dim[[1]]}];       j = Random[Integer, {1, dim[[2]]}];       Which[        (* Predator *)        space[[i, j]] == r,        If[Random[Real] < mu,         (* Predator dying *)         space[[i, j]] = e,         (* Predator eating *)         {k, l} = getCell[space, i, j, y];         space[[k, l]] = r;         ],        (* Prey *)        space[[i, j]] == y,        If[Random[Real] < b,         (* Prey reproducing *)         {k, l} = getCell[space, i, j, e];         space[[k, l]] = y         ]        ]       ]      Finally, I do many iterations                gridsize = 200;     space = initSpace[gridsize];     nrsteps = 100;     stepsize = 5000;     b = 0.9; mu = 0.4;     population = Table[0, {nrsteps}];     Do[Do[step[b, mu];, {stepsize}];       population[[i]] = space;       , {i, 1, nrsteps}];         Animate[          ArrayPlot[population[[i]], ColorRules -> {e -> Black, r -> Red, y -> Blue}],          {i, 1, nrsteps/stepsize, 1}, AnimationRepetitions -> 1,           AnimationRunning -> False]      Ideally I would like to have the latter two modules compiled as well, but when I tried to put `Compile[]` around them I got a bunch of errors. Does anyone know what I might be doing wrong? Or have any other advice on how I should optimise my code for speed? Or should I try to put everything in a single compiled `Module`?


title: How combine pure functions of several slots?

text: How can one define _in a functional way_ a 1st-order linear differential operator involving several independent variables that can then be applied to a function of that many variables? Consider an example with two variables, where one wants to form `D[f[x, y], x] + 3 D[f[x, y], y]` from a function `f`. Of course one could define                   diff[f_][x_, y_] := D[f[x, y], x] + 3 D[f[x, y], y]      so that for a function such as                   g[x_, y_] := x^2 y + Cos[x + 2 y]      we just evaluate:                   diff[g][x, y]     2 x y + 3 (x^2 - 2 Sin[x + 2 y]) - Sin[x + 2 y]   (* desired final output *)      But how can such an operator be defined functionally, that is, _without_ explicitly using variables initially? We could try                   diffOp[y_] := Derivative[1, 0][y] + 3 Derivative[0, 1][y]      and then                   diffOp[g]     3 (-2 Sin[#1 + 2 #2] + #1^2 &) + (-Sin[#1 + 2 #2] + 2 #1 #2 &)      But now how does one use such a combination of pure functions of several variables so as to produce the same result as from `diff[g][x,y]`? The crux of the difficulty appears in the following simpler problem. Consider two functions of two variables:                   g1 = (#1^2 + #2) &         g2 = Cos[#1 #2] &      How can one produce the same result as, say,                   g1[x, y] + 3 g2[x, y]     (* x^2 + y + 3 Cos[x y] *)      directly from the functional linear combination `g1 + 3 g2` \-- by forming an expression of the form `oper[g1 + 3 g2][x, y]`? By contrast with the single-variable situation, where a simple `Through` would serve as the `oper',`Through` will _not_ work in the multi-variable situation here:                  Through[(g1 + 3 g2)[x, y]]     (* x^2 + y + (3 (Cos[#1 #2] &))[x, y] *)      A pure function embedded in that output. Note that a simple sum `g1 + g2` instead of the linear combination `g1 + 3 g2`, `Through` will work (just as it does for a single variable):                   Through[(g1 + g2)[x, y]]     (* x^2 + y + Cos[x y] *)


title: How to form a block-diagonal Matrix from a list of matrices?

text: like this: ![enter image description here](http://i.stack.imgur.com/3E6A8.jpg) I know join[...] works, but it is a bit troublesome for multiple matrices.I tried DiagonalMatrix[...], but DiagonalMatrix can only form matrix from a list of elements.


title: Direct sum of matrices

text: Is there a simple way (perhaps even a built-in function) that allows one to compute the direct sum of two square matrices?


title: How can I adjust matrices into the same ItemSize and aligned well in Notebook?

text: ![enter image description here](http://i.stack.imgur.com/F2KWJ.png) I typed three matrices, but they are not aligned well, and the `Items` in one matrix are also not aligned well and with differenct `ItemSize`. How can I adjust them into the same `ItemSize`? Better is that I can click the buttons/menus to do the thing something like `align paragraph` in `writing assistant`. And I found the matrix typed is `GridBox`, so I can adjust them by options of Grid.


title: Is "MaxMessageCount" broken or is its function counter-intuitive?

text: As noted by kguler the Front End option: `MessageOptions -> "MaxMessageCount"` does not appear to have any affect on the number of times a Message is repeated before `General::stop` is issued and that particular Message is suppressed. I would like to know if supposed to have this effect but is broken, or if it does something else entirely. I cannot find any documentation for this Option, and I cannot find any examples of its use either here or in the MathGroup archives.


title: Errors in Compile

text: I defined a function               getCell[sp_, i_, j_, x_] := Block[{target, n, m, k, l, k2, l2, cells},       n = Dimensions[sp][[1]];       m = Dimensions[sp][[2]];       cells = {};       Do[        Do[         (* This is one neighbor *)         k2 = Mod[i + k, n, 1];         l2 = Mod[j + l, m, 1];         If[(k2 != i || l2 != j) && sp[[k2, l2]] == x,           AppendTo[cells, {k2, l2}]],         {l, -1, 1}],        {k, -1, 1}];       If[Dimensions[cells][[1]] != 0,        target = RandomSample[cells, 1][[1]],        (* The default, if none was found, is to return the cell itself,         just for convenience *)        target = {i, j}        ];       Return[target];       ]      `getCell` given a square matrix `sp` filled with Integers attempts to find a cell neighboring `[[i,j]]` that contains a value equal to `x`. If it finds such a cell, it returns the coordinates of that cell; if not, it returns the input coordinates `{i,j}`. I now wanted to compile `getCell` to try to speed it up, but when I do so by putting `Compile` around the function and inserting type definitions, I get several error messages:               Compile::cset: Variable cells of type {_Integer,1} encountered in assignment of type {_Integer,2}. >>          Compile::cpts: The result after evaluating Insert[cells,{k2,l2},-1] should be a tensor. Nontensor lists are not supported at present; evaluation will proceed with the uncompiled function. >>          Compile::cset: Variable target of type {_Integer,2} encountered in assignment of type {_Integer,0}. >>          Compile::cset: Variable target of type {_Integer,2} encountered in assignment of type {_Integer,1}. >>      Does anyone know what I might be doing wrong, and how I could get this simple function compiled?


title: What algorithm is Mathematica using for FirstPassageTimeDistribution[]?

text: What algorithm is _Mathematica_ 9 using for `FirstPassageTimeDistribution[]`? Is it attempting to use `PseudoInverse[]` on the Laplacian of the graph underlying the discrete Markov process?


title: Peirce's quincuncial projection

text: The Peirce quincuncial projection is the cartographic projection of a sphere onto a square. In short, I would like to see it implemented in _Mathematica_. Here is my code:               Clear[InversePeirceQuincunicalMapping];      InversePeirceQuincunicalMapping[x_Real, y_Real] :=       Module[{cn, m = 1/2, th, phi},             cn = JacobiCN[x 2 EllipticK[m] + I 2 y EllipticK[1 - m], m];             {th, phi} = {2 ArcTan[Abs[cn]], Arg[cn]};             {th, phi}]          zf[{th_, phi_}] := Cos[th]     xf[{th_, phi_}] := Sin[th] Cos[phi]     yf[{th_, phi_}] := Sin[th] Sin[phi]      The contours that correspond to the equation $\theta=\frac{\pi}{2}$, besides the expected tilted square, also includes the diagonal and anti-diagonal. This is not an artifact and can be proven. ![contour of inverse Peirce mapping](http://i.stack.imgur.com/IQF89.png) These lines make me suspect that I am not doing the projection the right way. I would be glad to see a prototype implementation of it in _Mathematica_. Thank you.


title: How do you draw a straight line with PolarPlot?

text: I can't figure how to draw a line with `PolarPlot`. A vertical line through a is $r \cos(\theta) = a$, so               PolarPlot[a/Cos[theta], {theta, -Pi, Pi}]      works. A horizontal line through b is $r \sin(\theta)=b$, so               PolarPlot[b/Sin[theta], {theta, -6, 6}]       works. (Using `{theta, -Pi, Pi}` doesn't work because of dividing by $\sin(0)=0$ I guess.) How do I draw a radial line with $\theta = \pi/3$? Should be a line with slope $\tan(\pi/3)$. Can it be done with `PolarPlot`? I guess not since you have to give a function of $r$.


title: iterate method to find roots

text: This code gives the roots (lambda-values) of `eq1` by using iteration.               eq1[n_, β_, λ_] := Hypergeometric1F1[1/4 (2 - λ/β), n + 1, β]     rootslist[n_Integer, k_Integer, β_] :=        Rest @ FoldList[FindRoot[eq1[n, #2, λ] == 0, {λ, #1}][[1, 2]] &          BesselJZero[n, k]^2, Range @ β]     Table[rootslist[n, 1, 30], {n, 0, 4}]      The table contains all the λ-values for each β from 1 to 30. Using this I want to know how to find a table with $\frac{\lambda}{\beta}$ values? For example, I have produced the following table > {6., 6.63583, 7.64905, 8.97767, 10.5495, 12.2936, 14.1498, 16.0735, 18.0349, > 20.0161, 22.0073, 24.0032, 26.0014, 28.0006, 30.0003, 32.0001, 34., 36., > 38., 40., 42., 44., 46., 48., 50., 52., 54., 56., 58., 60.}, for $n=0$. How can I get $\\{\frac{6.}{1}, \frac{6.63583}{2}, \frac{7.64905}{3}, \frac{8.97767}{4}, \frac{10.5495}{5}, \frac{12.2936}{6}, \frac{14.1498}{7}, \frac{16.0735}{8},\frac{ 18.0349}{9}, \frac{20.0161}{10}, \frac{22.0073}{11}, \frac{24.0032}{12}, \frac{26.0014}{13},\frac{ 28.0006}{14}, \frac{30.0003}{15},\frac{ 32.0001}{16}, \frac{34.}{17}, \frac{36.}{18}, \frac{38.}{19}, \frac{40.}{20}, \frac{42.}{21}, ..., \frac{60.}{30}\\}\text{?}$


title: How to solve two non-linear equations in two variables

text: I am a new user of _Mathematica_. I have the following non-linear equations in two variables: ![enter image description here](http://i.stack.imgur.com/hGz6z.png) How can I solve this system with _Mathematica_?


title: How do you add options to a function that is being mapped?

text: Simple example: Normally: `ListPlot[list, Joined->True]` If I want to map `ListPlot` how do I keep the `Joined` option? thanks.


title: Eliminate some temporaries from a set of equations

text: I have a long set of equations, mostly obtained by introducing physics related quantities which stand for some kind of temporary variables:               eqns = {       lx == Log[10., en] + 0.3,       xmax == 0.849 + 0.0537 lx,       nmu == 1.37 en^-0.04,       fem == ((s - xmax + 0.689)/0.802)^(0.802/0.113) Exp[(0.113 - s + xmax)/0.113],       fmu == ((s - xmax + 0.228)/0.573)^(0.573/1.267) Exp[(0.345 - s + xmax)/1.267],       cic == 22.3 fem + 15.6 nmu fmu,       en == (s1000/cic)^(1/0.97)     };      This is 7 equations with 9 variables. I would like to eliminate all of the variables except for `{en, s, s1000}` and then obtain the solution in the form `en[s, s1000]`. I tried Solve, Reduce, Eliminate, tried taking them pairwise etc. but while there are some results for equation pairs, for the whole system Mathematica just runs for ever... For example, while this works as expected               Eliminate[eqns[[{1, 2}]], lx]      giving `0.86511 + 0.0233216 Log[en] == xmax`, trying one more               Eliminate[eqns[[{1, 2, 4}]], {lx, xmax}]      returns a result which imho does not make any sense. Looking around StackExchange one finds Mathematica (at least in v9) has a hidden 3rd argument for elimination               Solve[eqns[[{1, 2}]], xmax, lx]      which gives a warning that `lx` is not a proper domain specification and that `lx` will be used for elimination. Unfortunately, trying this trick on three equations               Solve[eqns[[{1, 2, 4}]], fem, {lx, xmax}]      returns an empty list while we would like to see a rule for `fem` expressed in terms of `en` and `s`. Please, help! I remember in older versions `Solve` used to be more flexible and more like a universal tool for solving. How particularly equation-solving cases are divided into usage of `Solve`, `Eliminate`, `Reduce` etc. is also not very clear, neither from the Help nor from tutorials, mostly since too simple examples are used as illustrations. A word from an expert on this subject is very welcome...


title: How can I use Pick[] to select items in one list when a value in a corresponding list is $\leq$ some value?

text: Imagine I have two list:               List1 = {0, 1, 0.6, 0.5, 1.2, 0.4};     List2 = {"a","b","c","d","e","f"};      How can I use Pick to return a third list consisting of items in List2 that have a array position corresponding to an array position with a value $\leq N$ in the first list? Here, for example, for $N = 0.5$ we should have:               List3 = {"a", "d", "f"}


title: Working with functions

text: I am required to write a function that takes a function as a parameter.               moveTwoPoints[function_, {sliderMin_, sliderMax_}] :=       DynamicModule[       {sliderValue = sliderMin,        plot},       f[x_] := function;       Column[        {     (*Display slider *)     Slider[Dynamic[sliderValue], {sliderMin, sliderMax}],     (*Display updating slider value *)     Dynamic[sliderValue],     (*Display the graph with points moving*)     Dynamic[      Show[       Plot[f[x], {x, sliderMin, sliderMax}],        Graphics[        {Red, PointSize[Large], Point[{sliderValue, f[sliderValue]}],          Green, PointSize[Large], Point[{0, f[sliderValue]}]             }            ]           ]          ]         }        ]       ]      The problem I am running into is the fact that when I try f[sliderValue] is won't return a point just the value of function. Is there a way I can manipulate this function?


title: How to plot an Operating Characteristic Curve using Hypergeometric distribution?

text: I"m trying to plot an OC curve (y-axis Probability of acceptance, x-axis Lot Percent Defective) and there should be a way to plot using a hypergeometric distribution.               In[117]:= NProbability[x <= 0,       x \[Distributed] HypergeometricDistribution[8, 7, 500]]          Out[117]= 0.89262      is great for one point. The 7 in the distribution is the number defective in the lot of 500, I'd like to plot this for 1, 2, etc. Then alter the x-axis labels to represent the percent defective in the lot of 500, .1%, 1%, 2%, etc.... I can get the individual values as above, yet not able to get a plot. I can do this using `PoissonDistribution`               Plot[{N[Probability[x <= 0,          x \[Distributed] PoissonDistribution[13*lpd]]],        N[Probability[x <= 0,          x \[Distributed] PoissonDistribution[8*lpd]]]}, {lpd, 0, .5}]      which assumes a very large lot size. I have the situation with smaller lot sizes and using hypergeometric is the right way to do the calculation for the OC curve - just not able to sort out the plotting. Any suggestions? cheers, Fred


title: How to make the imaginary part of a +0. I zero globally?

text: Values like a +0. I are really annoying. Answers from How to reduce expressions with complex coefficients in the form of a+0.*I？ Is there a way to globally set when to treat a very small number as zero? give me some clue, but I find `$Post = Chop[#, 10^-16] &;` doesn't work, for example :               Print[MatrixForm[FourierDCT[FourierDCT[{0, 0, 1, 0, 0}, 2], 3]]]      gives (0. -5.55112*10^-17 1. 1.38778*10^-17 1.38778*10^-17 ), which means the small digits still exist.


title: Why is arithmetic faster for inexact arithmetic?

text: I have been trying to compute eigenvalues of a rather sizable matrix `A`, about $500 \times 500$ (but sparse). I asked Mathematica to compute `Eigenvalues[A]`, and left it to work. After a night of computation, Mathematica still failed to produce the answer. Just out of curiousity, I tried to see what happens if I replace `A` by it's numeric approximation (before, `A` had integer entries, hence exact). (I didn't quite expect it to make a difference, but I was trying some random things). Much to my surprise, the answer appeared immediately. Hence my question: How does it happen that Mathematica produces the answer so much faster for inexact input? To what extent can this output be trusted?


title: What's wrong with my calculation of the expectation of the Laplace distribution?

text: f2[x_, mu2_, sigma2_] =  1/Sqrt[2*sigma2^2]*Exp[-Sqrt[2]*Abs[(x - mu2)/sigma2]]          Integrate[x*f2[x, mu, sigma], {x, -Infinity, Infinity},  Assumptions -> sigma > 0]      I am pretty sure that the above should produce `mu`, but it doesn't. What's wrong with it? I did the same thing in Sage, and it worked all right.


title: how to Compile user-defined function like this

text: the following function can be compiled successfully               Clear[mat]         mat = Compile[{e, kx, {ii, _Integer}, {label, _Integer}, η},            Inverse[{{e - I η,               -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0,                0}, {-E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0,                0, 0, 0, 0, 0, 0}, {0, -E^(((I kx)/2)),                e - I η, -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0,                0, 0}, {-E^(-((I kx)/2)), 0, -E^(I kx),                e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0,                0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0}, {0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,                0}, {0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2)), 0, 0, 0, 0}, {0, 0, 0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0,                0}, {0, 0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),                e - I η, -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0}, {0, 0, 0,                0, 0, 0, -E^(-((I kx)/2)), 0, -E^(I kx),                e - I η, -E^(-((I kx)/2)), 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0,                0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),                0, -E^(((I kx)/2))}, {0, 0, 0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),                0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0}, {0, 0, 0, 0,                0, 0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),                e - I η, -E^(-I kx)}, {0, 0, 0, 0, 0, 0, 0, 0, 0,                0, -E^(-((I kx)/2)), 0, -E^(I kx), e - I η}}][[            2*(ii - 1) + label, 2*(ii - 1) + label]], CompilationTarget -> "C"]      as you can see the function calc the one of the matrix element of the inverse matrix. the result of the above code is               CompiledFunction[{e,kx,ii,label,\[Eta]},Block[{Compile`$498,Compile`$502,Compile`$503,Compile`$507,Compile`$508,Compile`$509,Compile`$510,Compile`$504,Compile`$505,Compile`$506,Compile`$514,Compile`$515,Compile`$516,Compile`$511,Compile`$512,Compile`$513,Compile`$518,Compile`$519,Compile`$520},Compile`$498=I \[Eta];Compile`$502=-Compile`$498;Compile`$503=e+Compile`$502;Compile`$507=1/2;Compile`$508=I kx Compile`$507;Compile`$509=E^Compile`$508;Compile`$510=-Compile`$509;Compile`$504=-I kx;Compile`$505=E^Compile`$504;Compile`$506=-Compile`$505;Compile`$514=-Compile`$508;Compile`$515=E^Compile`$514;Compile`$516=-Compile`$515;Compile`$511=I kx;Compile`$512=E^Compile`$511;Compile`$513=-Compile`$512;Compile`$518=ii-1;Compile`$519=2 Compile`$518;Compile`$520=Compile`$519+label;Inverse[{{Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0,0,0,0,0},{Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0,0,0,0,0},{0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0,0,0},{Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0,0,0},{0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0,0,0},{0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0,0,0},{0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0,0,0},{0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0,0,0},{0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510,0,0},{0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0,0,0},{0,0,0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506,0,Compile`$510},{0,0,0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503,Compile`$516,0},{0,0,0,0,0,0,0,0,0,0,0,Compile`$510,Compile`$503,Compile`$506},{0,0,0,0,0,0,0,0,0,0,Compile`$516,0,Compile`$513,Compile`$503}}][[Compile`$520,Compile`$520]]],-CompiledCode-]      I want to speed it a little, So I defined a function                Clear[invmat]     invmat[m_?MatrixQ, i_, j_] :=       Det[Drop[m, {j}, {i}]]*(-1)^(i + j)/Det[m]      which gives (i,j)th element of the inverse matrix of m directly with calc the whole matrix inverse. and then I compile the function below               Clear[mat2]     mat2 = Compile[{e, kx, {ii, _Integer}, {label, _Integer}, η},        invmat[{{e - I η,          -E^(-I kx), 0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0, 0,           0}, {-E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0, 0, 0, 0, 0}, {0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0, 0, 0}, {-E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0, 0, 0}, {0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0, 0, 0}, {0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0, 0,           0}, {0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0, 0, 0}, {0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0, 0, 0}, {0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2)), 0, 0}, {0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0, 0, 0}, {0, 0, 0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)), e - I η, -E^(-I kx),           0, -E^(((I kx)/2))}, {0, 0, 0, 0, 0, 0, 0, 0, -E^(-((I kx)/2)),           0, -E^(I kx), e - I η, -E^(-((I kx)/2)), 0}, {0, 0, 0, 0, 0,           0, 0, 0, 0, 0, 0, -E^(((I kx)/2)),           e - I η, -E^(-I kx)}, {0, 0, 0, 0, 0, 0, 0, 0, 0,           0, -E^(-((I kx)/2)), 0, -E^(I kx), e - I η}},         2*(ii - 1) + label, 2*(ii - 1) + label], CompilationTarget -> "C"]      **But`mat2` cannot be compiled because the output is the same. I think at least it should compile the matrix variable in `invmat`** the output of `mat2` is               CompiledFunction[{e,kx,ii,label,η},invmat2[{{e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0,0,0,0,0},{-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0,0,0,0,0},{0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0,0,0},{-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0,0,0},{0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0,0,0},{0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0,0,0},{0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0,0,0},{0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0,0,0},{0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2)),0,0},{0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0,0,0},{0,0,0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx),0,-E^(((I kx)/2))},{0,0,0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η,-E^(-(1/2) (I kx)),0},{0,0,0,0,0,0,0,0,0,0,0,-E^(((I kx)/2)),e-I η,-E^(-I kx)},{0,0,0,0,0,0,0,0,0,0,-E^(-(1/2) (I kx)),0,-E^(I kx),e-I η}},2 (ii-1)+label,2 (ii-1)+label],-CompiledCode-]      So how to Compile `mat2`?


title: why there is a small imaginary part

text: I encountered a problem. I have a eigenvector `eigvsI[1]`               eigvsI[1]={0.0161028 - 0.0119647 I, 0.111551 - 0.0828846 I, 0.20484 - 0.1522 I,      0.249467 - 0.185359 I, 0.28268 - 0.210037 I,      0.301895 - 0.224314 I, -0.190871 + 0.141821 I, -0.271275 +      0.201562 I, -0.244686 + 0.181807 I, -0.204743 +      0.152128 I, -0.148422 + 0.11028 I, -0.0281275 + 0.0208993 I}      and a hermite matrix `hI[1]`                   hI[1]={{0, Sqrt[5]/2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {Sqrt[5]/2, 0, Sqrt[2],     0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, Sqrt[2], 0, 3/2, 0, 0, 0, 0, 0, 0,      0, 0}, {0, 0, 3/2, 0, Sqrt[2], 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, Sqrt[     2], 0, Sqrt[5]/2, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, Sqrt[5]/2, 0, 0,      0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, Sqrt[5]/2, 0, 0, 0, 0}, {0, 0,     0, 0, 0, 0, Sqrt[5]/2, 0, Sqrt[2], 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0,      Sqrt[2], 0, 3/2, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 3/2, 0, Sqrt[2],      0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, Sqrt[2], 0, Sqrt[5]/2}, {0, 0, 0, 0,     0, 0, 0, 0, 0, 0, Sqrt[5]/2, 0}}      theoretically               Conjugate[eigvsI[1]].hI[1].eigvsI[1]      should be Real number. But _MMA_ gives               -0.253172 - 8.00544*10^-18 I      where does this small imaginary part come from? On the other hand,               Conjugate[eigvsI[1]].eigvsI[1]      gives perfect zero imaginary part               0.811081 + 0. I


title: A question about transforming one List into two Lists with additional requirements

text: Background: I create geometric patterns by applying many linear transformations on geometries, I need functions to weed out the exponentially increasing number of ( unnecessary ) points involved which slow down the production of Graphics code. The problem: Suppose I have the following array of arrays, for example two 2D vectors, a 2-by-2 matrix and one 3D vector in an array as follows: This format is not fixed however. ( Originates from reading data stored in Excel which can be 'dirty'. )                 { {1,2},{1,3}, {{1,0},{0,1}}, {10,20,30} } This format is invalid.       ( Because it contains {10,20,30} , a 3D vector at the lowest level. )            { {1,2},{1,3}, {{1,0},{0,1}}, {1,2} } This format is valid       ( Because it contains only 2-D vectors at the lowest level, note the 2-by-2 matrix )      I want to replace the valid array with:                 { {1,2},{1,3},{1,0},{0,1} }        ( a list of 2D vectors. )       { 1, 2, {3,4}, 1 }       a list with the position of the row vectors in the list above.      Key part of the problem =>: Note that (1,2) is stored only once in the first list while it occurs twice in the original array. <= Ideally I seek a validQ function that validates the input and a toGraph function that splits a valid row into two new rows. ( Although not a Graph Theory problem, there are similarities. I attempt to make the geometric pattern independent from its ( Cartesian ) coordinates. ) A complication is that the numbers are real ( square roots ) or involve Pi, and / or originate from spreadsheet calculations. Rounding or cutting to two places behind the decimal point is not a problem. My attempts to solve this involved Map and Position, but my attempts failed, I can show no working snippet to start with. I hope that the example data suffices. **Question: Is there a clean functional style code to tackle this problem ?**


title: How to create a composite function from a variable number of components?

text: Background of the problem: A patient takes a drug every $X$ hours with a half- life of $Y$ hours. How much of the drug will be (exactly) in his system after $h$ hours? For $X=24$, and $Y=24$ I made the following function showing the concentration of the drug for the first 96 hours.                Clear[m]      m[h_] := Exp[-(h/48)] /; h < 24      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] /; ( h >= 24 && h < 48)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] +           Exp[-((h - 48)/48)] /; ( h >= 48 && h < 72)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] + Exp[-((h - 48)/48)] +          Exp[-((h - 72)/48)] /; ( h >= 72 && h < 96)      m[h_] := Exp[-(h/48)] + Exp[-((h - 24)/48)] + Exp[-((h - 48)/48)] +          Exp[-((h - 72)/48)] + Exp[-((h - 96)/48)] /; ( h >= 96 && h < 120)      Plot[m[h], {h, 0, 120}, AxesOrigin -> {0, 0}]      This is exactly what I want. But now I want to optimize the code, so that I can also `Plot[]` for periods up to several weeks. Question: How can I rewrite `m[h]` such that there will only be one line involved, i.e. add the `Exp[-((h - 72)/48]` type of terms automatically?


title: Cropping a Voronoi diagram

text: Someone know how can I get the correct crop of this Voronoi image using `RegionFunction`? ![Voronoi Diagram](http://i.stack.imgur.com/K6ATs.png) As you can see, there is a lot of undesired white regions inside the left polygon. Some clue on how to correct it? Here is the code using `PointInPoly` and `RegionFunction`:               PointInPoly[{x_, y_}, poly_List] :=       Module[{i, j, c = False, npol = Length[poly]},        For[i = 1; j = npol, i <= npol, j = i++,         If[((((poly[[i, 2]] <= y) && (y <                   poly[[j, 2]])) || ((poly[[j, 2]] <= y) && (y <                   poly[[i, 2]]))) && (x < (poly[[j, 1]] -                   poly[[i, 1]])*(y - poly[[i, 2]])/(poly[[j, 2]] -                    poly[[i, 2]]) + poly[[i, 1]])), c = \[Not] c];];       c]          pts=MapIndexed[Flatten[{##}]&,RandomReal[{0,1},{20,2}]];          poli={0.5,0.5}+#&/@Table[0.3{Cos[2\[Pi] k/6],Sin[2\[Pi] k/6]},{k,0,6}];     opt={ColorFunction->Hue         ,InterpolationOrder->0         ,ImageSize->500         ,PlotRange->{{0,1},{0,1}}         ,Epilog->{PointSize[.01],Point[Most/@pts],Line[poli]}         };          g1=ListDensityPlot[pts         ,Sequence@@opt         ,RegionFunction->Function[{x,y,z},PointInPoly[{x, y}, poli]]         ];          g2=ListDensityPlot[pts         ,Sequence@@opt         ];          GraphicsRow@{g1, g2}      Important point, I can't use image manipulate functions. What I really need is the list of polygons inside the cropped area. I get it using `g1[[1]]`


title: Using perpendicular offsets in FindFit

text: I want to use perpendicular offsets in the built-in `FindFit` function. Are there any possible ways or do I have to code everything by myself?


title: How to save animation in mp4 format instead of avi?

text: I'd like to save `Manipulate[]` output so that I can embed an mp4 in my pdf document (using the media9 latex package). I've done this successfully in the past by manually constructing a table of Graphics objects, and then saving that to .avi format. That .avi can then be converted to .mp4 by ffmpeg. A cleaner way to do this is pointed out in this answer but the .avi file that is generated causes ffmpeg to choke:               Output #0, mp4, to 'MyAutorun.mp4':         Stream #0:0: Video: h264, yuv420p, 412x345, q=-1--1, 90k tbn, 15 tbc     Stream mapping:       Stream #0:0 -> #0:0 (rawvideo -> libx264)     Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as     bit_rate, rate, width or height      I'm not really sure what this tool is complaining about, but wondered if there was a way to avoid using external tools to do this conversion and just export the animation data in mp4 format directly from Mathematica?


title: using Mathematica's matrix multiplication in C++

text: Is there any way that I can utilize Mathematica's matrix multiplication in a C++ program? I'm making a 3D graphics engine (for class) in C++ and I would really like to use Mathematica for all of my math. Thank you. I have Mathematica 8, and Visual Studio 2010 that I am using to develop with.


title: How can I mix the behaviors of StringReplace and ReplaceAll in a single rule?

text: I'm trying to take a list of the form `{ {"65 + 3 months", 75}, {"65 + 4 months", 75.1} }`, and transform the string part to a number such as 65.25 or 65.333, respectively. What I really want to do is something like:               list = { {"65 + 3 months", 75}, {"65 + 4 months", 75.1} };     list /. {y:NumberString~~" + "~~m:NumberString,p_}:>{y+m/12,p}      That form doesn't work, I believe, because I need to use StringReplace to cause the `StringExpression` to do any matching. So since I can't make that work, I tried something like:               list /.{ys_String, p_} :>         {StringReplace[ys, y:NumberString~~" + "~~m:NumberString~~" months":>y+m/12], p}      But in that case, I'm getting `{ { StringExpression[3/12 + 65], 75}, {StringExpression[4/12 + 65], 75.1} }`, and have no idea where the `StringExpression` heads came from in that case or what to do with them without making my expression uglier and even further from just describing the patterns that I'm trying to transform from/to. Is there a simple way to compose a pattern that does some string matching and some structure matching? If not, what's the best way to write the `StringReplace` version for the problem above.


title: Random Geometric Graphs

text: I'm trying to implement an application which uses random geometric graphs in Mathematica, but it seems Mathematica lacks the functionality. I need the following functionalities:   1. Generate a set of uniformly distributed vertices on $[0,1]^2$ with certain properties (this really helps)   2. Add an edge in between the vertices that are closer than a given radius $d$   3. Display the graph (this is not like a regular graph display since the location of each vertex is important)   4. Generate some random source-destination pairs and find the shortest path between them   5. Highlight the path on the displayed graph. Note that, Mathematica has all of the required functionality for non-geometric graphs. However, when it comes to the geo-graphs, the functionality is quite useless. Here is the code I already have:               Module[      {nOld, kOld, v, edges},      nOld = -1;      kOld = -1;      Manipulate[       If[        n != nOld,        v = RandomReal[{0, 1}, {n, 2}];        nOld = n        ];            edges =         Select[Flatten[Table[{a, b}, {a, v}, {b, v}],           1], (#[[1, 1]] > #[[2, 1]] &&             EuclideanDistance[#[[1]], #[[2]]] < d) &];            Graphics[        {Red, Point[v],         Blue, Thin, Line /@ edges         }        ]       ,       {n, 10, 100, 10},       {d, 0, 1}       ]      ]      ![Mathematica graphics](http://i.stack.imgur.com/Fw8Rz.png) It generates and shows the random graph. But generating and highlighting the shortest paths are not so simple since I don't have any data-structure to keep the graph. What is the best way to implement a geo-graph in Mathematica? `Sparse matrices` or `System`Graph` or `Combinatorica`Graph`? Can I use some of the built-in graph functions of Mathematica to implement geo-graphs?


title: Exporting images as .avi

text: Here's a list of images:               images = Table[ExampleData[i], {i, ExampleData["TestImage"]}];      And according to the reference "Export exports a list of graphics, images, or arbitrary expressions, taking each element to be an animation frame." This is on the reference page for .avi. However,               Export["animation.avi", images]      causes this: > Export::errelem: "The Export element !(\"ImageList\") contains a malformed > data structure and could not be exported to !(\"AVI\") format." What's the problem? (Export["film.avi", ListAnimate[images]] works, but I want to know why the above doesn't work...)


title: LibraryFunctionLoad hangs under Windows

text: I'm running the Wolfram Finance Package version of Mathematica 8, under Windows 7 Professional. Any time I attempt to call `LibraryFunctionLoad`, the Kernel seems to hang; I have to kill it (Evaluation->Quit Kernel->Local) in order for any further input in the notebook to be taken into account. (When I kill it, it leaves an orphaned `java.exe` still running, which I have to kill using the Task Manager.) I originally thought it might be something to do with the way I generated the DLL, but even when giving it the name of an non- existent file, it hangs (rather than giving an error message). I was able to load and execute my program under Linux (with a demo version of Mathematica 8). What is different, and why don't I at least get an error message when the file doesn't exist? Also, I get similar symptoms when I use a `\` as a path separator, rather than a `/`, even for simpler operations like               Join[$LibraryPath, {"C:\Users\jkanze"}]


title: Mutual Information involving two matrix states

text: I basically retrieved the following technique of evaluating the mutual information involving two matrices from this site at http://bmia.bmt.tue.nl/People/BRomeny/Courses/8C080/default.htm The original code was written for image-processing, but could perhaps apply to other areas as well. Mutual Information = H(A)+H(B)-H(AB), where H(X) is the entropy of X My question: How to do you generalize this to apply to a matrix of arbitrary elements (including decimals less than 1, and negative numbers)? Can this also be extended to matrix of any dimension (i.e. larger than 2?). The program follows as:               imA = ({        {0, 1, 3, 0},        {0, 0, 2, 5},        {3, 2, 0, 1},        {0, 0, 3, 4}       });           imB = ({        {1, 1, 0, 4},        {3, 0, 4, 5},        {0, 0, 2, 5},        {0, 1, 4, 5}       });           histogramA = BinCounts[Flatten[imA], {0, 6, 1}]     hA = Total[-(histogramA/nA) Log[histogramA/nA]] // N     nA = Total[histogramA]          histogramB = BinCounts[Flatten[imB], {0, 6, 1}];     nB = Total[histogramB];     hB = Total[-(histogramB/nB) Log[histogramB/nB]] // N     imAB = Transpose[{imA, imB}, {3, 1, 2}]     histogramAB = BinCounts[Flatten[imAB, 1], {0, 6, 1}, {0, 6, 1}];     nAB = Total[histogramAB, 2];     fh = Flatten[histogramAB]     fh2 = DeleteCases[fh, 0]     hAB = Total[-(fh2/nAB) Log[fh2/nAB]] // N     MI = hA + hB - hAB


title: How to make Excel-like data bars?

text: I would like to make a grid where each cell background is partially filled according to the numerical value being represented (on a scale from 0 to 1). Similar functionality to the one requested in this TeX.SE question. How can I achieve this with _Mathematica_?


title: Defer parts of the expression

text: Is there a way to Defer only parts of the expression? For example, I have               a=1;      and then I want the expression to be shown as`a = 1;`by using`Defer[a = Evaluate[a]]`,But the actual output is just               a = Evaluate[a]]      Is there away to only Defer part of an expression?


title: How can I get the color of overlapping disks to be equal in any order?

text: When Graphics is used, necessarily the objects come in order. This affects which ones obscure others. When Opacity is not 1, it also affects the color. I would like the color of overlaps to depend only on the colors of the objects and their opacities and not on the order. Can this be done? For example, this simple code illustrates the problem:                Graphics[{Opacity[.5],       Inner[{#1, #2} &, {Red, Blue, Red}, {Disk[{0, 0}, 1],       Disk[{1, 0}, 1], Disk[{2, 0}, 1]}, List]}]      The result is this: ![Red Disk, Blue Disk, Red Disk with overlaps](http://i.stack.imgur.com/BxZuo.jpg) Further info in response to the wonderful answers received so far: I will use this in Manipulate with the disks (or perhaps rectangles) moving around at random. There will also be many of them, such as 1000. So time is important and thus using all permutations is out of consideration (for this particular application). I have now tested the suggestions. Unfortunately, rasterizing and computing with that takes much too long. If I sort, then that will not give what I want either. So no answer seems to work, sadly. In response to @Mr.Wizard, here is my example. It is not minimal, but you will want to experiment with various things, I think. In the end, it is not too bad; I used Opacity[0.1] to handle my aesthetic complaint.                   Manipulate[      If[startover == "start over",        current = PadRight[{}, nmparticles, {{-torus/2, 0}, {torus/2, 0}}];        startover = False];       While[run, Pause[1/rate];        If[Length[current] == nmparticles,         current =          Clip[current +            RandomVariate[            NormalDistribution[0, 1], {nmparticles, 2}], {-torus, torus}],         current =          PadRight[current, nmparticles, {{-torus/2, 0}, {torus/2, 0}}]]];       Dynamic@Show[        Graphics[{Opacity[.1],           Transpose[{Table[If[OddQ[i], Red, Blue], {i, Length[current]}],             Disk[#, 1] & /@ current}]},          PlotRange -> {{-torus, torus}, {-torus, torus}},          ImageSize -> {475, 475}]],       Style["             Diffusion",        Large], Delimiter, {{run, False, "run"}, {True,         False}}, {{nmparticles, 2, "number of particles"}, 1, 5000, 1,        Appearance -> "Labeled"},      {{rate, 10, "rate"}, 3, 1000, 1,        Appearance -> "Labeled"}, {{torus, 20, "half-size of box"}, 3, 100,        1, Appearance -> "Labeled"}, {{startover, False,         ""}, {"start over"}, ControlType -> Setter, Background -> LightRed},      ControlPlacement -> Right,       Initialization :> (current = {{-torus/2, 0}, {torus/2, 0}})]


title: Error when trying to run Mathematica 9 on Ubuntu 12.04 from the command line

text: When I type : mathematica or math on terminal, generates following error:               Traceback (most recent call last):     File "/usr/bin/test", line 8, in <module>     call([command,parameter])     File "/usr/lib/python2.7/subprocess.py", line 493, in call     return Popen(*popenargs, **kwargs).wait()     File "/usr/lib/python2.7/subprocess.py", line 679, in __init__      errread, errwrite)      File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child      raise child_exception      OSError: [Errno 8] Exec format error  Mathematica front end executable      /usr/local/bin/SystemFiles/FrontEnd/Binaries/Linux-x86-64/Mathematica      not found. Your Mathematica installation may be incomplete or corrupted.      Mathematica front end executable      /usr/local/bin/SystemFiles/FrontEnd/Binaries/Linux/Mathematica not found.      Your Mathematica installation may be incomplete or corrupted.      Tried following:   1. Re-installing   2. installing lib32stdc++6   3. uname -a : returns : X86_64 machine


title: Unexpected behavior: CForm converts rationals to floating numbers

text: **One line question:** How to make `CForm[1/2]` generate `1/2` instead of `0.5`? (Thanks Nasser's comment!) * * * I've been using `CForm` to convert _Mathematica_ expressions to C codes for a long time. Although the built-in C strings are a little bit annoying (e.g., `Sqrt[2]` is translated to "Sqrt(2)" instead of "sqrt(2)"), it works. However, recently I found an even more annoying behavior which I cannot find a workaround so far. Consider converting the following simple piece extracted from a rather complicated expression               3/40007 + (2 test )/40007//CForm      > 0.00007498687729647311 + (2*test)/40007. which is totally bizarre! What I expect is simply > 3/40007. + (2*test)/40007. which is trivial yet crucial to my following work. (To be clear, I don't mean the presence of the decimal point is crucial! Rather, I mean the form of numbers should no be changed.) Can anyone come up with a solution, at least to tell `CForm` stop doing such a floating number conversion? Certainly I could manually rewrite this piece (or use `Together`) like this               (3 + 2 test)/40007 // CForm      > (3 + 2*test)/40007. But given that I have tons of complicated expressions to be converted, it is super inefficient for sure. Besides there's a possibility that `test = I`, and `3/40007 + (2 I)/40007 // Together` returns itself. PS. It is surprising that the discussions related to `CForm` and other C utilities are so rare on this site! Am I missing something?


title: What exactly is "ParameterErrors" of NonlinearModelFit?

text: I am trying to get what I call a "$\chi^2$ fit". This means taking a function $f(x,p)$ of the variable $x$ with a parameter $p$ and finding the value of $p$ that minimizes the "distance" from a data set $\\{x_i, d_i\\}$, i.e. minimizes the quantity $$\chi^2=\frac{\left(f(x_i,p) - d_i\right)^2}{d_i}$$ See this Yale course notes for a reference. You can find the value of the parameter $p$ with `NMinimize`, of course, or use `NonlinearModelFit`. I figured out that to get the same result, i.e. perform the same minimization, you need to use               nlm = NonlinearModelFit[data, 1 + p x^2, {p}, x, Weights -> (1/#2 &)]      where I have taken `f[x,p] = 1 + p*x^2` just to give an example This procedure is supposed to give you the best estimate of the parameter $p$ and an error is associated to to this estimate. I thought that `nlm["ParameterErrors"]` would give this error, but I do not find any documentation for this. Usually, for a one parameter estimation at 68% confidence level, the error comes from looking at the curve $\chi^2=1+\chi_\min^2$ where $\chi_\min^2$ is the value of the function $\chi^2$ for the parameter $p$ that minimizes $\chi^2$ (in other words the value at the best fit). By direct computation and confronting with `"ParameterErrors"` it seems that `"ParameterErrors"` does not give this type of error estimate. Now, is anybody aware of what exactly `"ParameterErrors"` does and how to instruct `NonlinearModelFit` to do what I need to do?


title: Orderless pattern matching of rule lists

text: I am looking for a compact way to specify a pattern to match a rule list with `MatchQ` that allows for enumerating the rules in the rule list in an arbitrary order. E.g. given:               ruleList1 = {"a" -> 10, "b" -> 2.2, "c" -> "str"}     ruleList2 = {"b" -> 2.2, "c" -> "str", "a" -> 10}      the following pattern will match both `ruleList1` and `ruleList2`               MatchQ[ruleList,  {___, "a" -> _, ___, "b" -> _, ___} | {___, "b" -> _, ___, "a" -> _, ___}]      Can this pattern be written in a more compact form (e.g., by using `OptionsPattern[]`)?


title: Importing a stack of images

text: I have a stack of images with the file names `C0001996_0000` , `C0001996_0001` etc. In total I have $600$ images. I would like to import the complete stack and then `Binarize` them (threshold `0.7)` and then export them. Could someone help me with the code for this?   At present I am importing a single image, binarizing it and then exporting.


title: Numerical solution of a differential equation with NIntegrate coefficients

text: I am trying to solve a linear ODE with a variable coefficient which is given in terms of an integral I can only do numerically. That is, I have an equation of the form $$ u'(t)=u(t)\int_0^t\sqrt{1+e^{-\tau^2}\sin(\tau)}d\tau, $$ where the integrand could be pretty much any well-behaved function - but which in general will cause _Mathematica_ to choke when given to `Integrate` and eventually say it can't do it. I know that such a lack of an analytic handle on the coefficients in the equation essentially disqualifies me from an analytic solution of the equation. However, given that I am, or should be, perfectly able to numerically compute this coefficient, _Mathematica_ ought to be able to numerically solve the equation. My initial guess as to how to do this would be to simply indicate the integral should be done numerically:               NDSolve[{D[u[t], t] == NIntegrate[          Sqrt[1 + E^tt^2 Sin[tt^2]], {tt, 0, t}] u[t], u[0] == 1}, u, {t, 0, 1}]      but this simply outputs the error `NIntegrate::nlim: tt = t is not a valid limit of integration. >>`. I've also tried with plain `Integrate` and setting `GenerateConditions->False`, but none of them work and they also take a long time to return their errors, which I assume is because they're trying to symbolically solve the integral - and I specifically _don't_ want that. Can someone provide a way to make _Mathematica_ understand it just needs to buckle down and calculate?


title: Parallelising the solving of polynomials

text: I'm working on finding solutions to a, not so very nice, system of equations. They are all polynomials of degree $4$ with $5$ parameters and all terms are of even order. I'll post the code on request, it's not that I don't want to post it, but it is rather lengthy and I thought I'd spare you the sight of it. I did solve a similar system of equations last week using `Reduce` but then I had three equations and three unknowns. It took the computer some time to solve the system, like $30$ minutes or such. Though it seems that the same procedure is now failing to produce a solution. I use the following code:               Reduce[equation1==1/4 && equation2==1/4 && equation3==1/4 && equation4==1/4,{x1, x2, x3, x4}, Reals]      I know that the system to be solvable. I understand that solving this system should take considerably more time. That's why I'm now wondering whether this problem could be parallelised in some way. I've read that reduce it isn't possible to parallelise `Reduce`, but perhaps there are some other means of parallelise the procedure? Or, well, is there means of making it run faster in general, of course?


title: Drawing graphics part by part

text: What I want to do is to draw graphics part by part, because I made a function that generates coordinates according to which I will draw graphics. The problem is that MMA does not operate as I expected. To figure out what I'm doing here's simplified example:               Graphics[{       a = 1;       Label[tag];       If[a < 3,        {Circle[{a, 1}, 1],         a = a + 1;         Goto[tag];},        {Text["It's finished", {0, 0}]}]       }]      And what I get as output is simply text "It's finished". But what I want as output is graphics with two circles with radii 1 and centers positioned at {1,1} and {2,1} together with text "It's finished". I figure out the way MMA thinks, and why it gives me this as output. But how can I accomplish my desired output? **Edit:** Here's the code, It's really messy and tips on how to neatly write code in MMA would be appreciated.                  Manipulate[              Graphics[{              (*calculating incident angle*)         α = ArcSin[H/R];         (*calculating x-coordinate where incident ray leaves prism*)         p = Sqrt[R^2 - H^2];         (*Drawing incident ray*)         {Red, Thick, Line[{{-2, H}, {p, H}}]},              (*Drawing prism*)         {Blue, Opacity[.5], Disk[{0, 0}, R, {0, Pi/2}]},              (*checking whether it's reflection or refraction*)         If[H < R/n,                 {(*refraction*)                 (*calculating x-coordinate where refracted ray hits surface*)                 l = (R^2 n)/(Sqrt[R^2 - H^2] n - Sqrt[R^2 - H^2 n^2]);                 (*Drawing refracted ray*)                 {Red, Thick, Line[{{p, H}, {l, 0}}]}                 },              {(*internal reflection*)                     (*calculating x-coordinate where after internal reflection ray hits \     surface*)                     new = H;                     k = 1;                 Label[tag];                 s = R Cos[α] - new/Tan[2 α];                     If[s <= R,                     {                     {Red, Thick, Line[{{p, new}, {s, 0}}]}                     },                            {                     θ = (2 k + 1) α - k Pi;                     f = R Cos[θ];                     h = R Sin[θ];                     k = k + 1;                     Line[{{{p, new}, {f, h}}}],                     new = h;                     p = f;                     Goto[tag];                     }                     ]                 }             ]                 }],              {{H, 3, "Height"}, 0.0001, R - 0.0001, Appearance -> "Labeled"},         {{n, 1.5, "Refraction"}, 1.001, 2, Appearance -> "Labeled"},         {{R, 10, "Radius"}, 0, 10, Appearance -> "Labeled"}                 ]


title: can I evaluate multiple cells at the same time?

text: my laptop has 2 cores, can I assign a core to evaluate one code, and the other core for another code in parallel instead of evaluating in sequence? thanks


title: How to prevent simplification of hypergeometric functions resulting from integrations?

text: Definite integrals from `0` to `Infinity` over a product of two hypergeometric (including exponential, trigonometric, hyperbolic, Bessel, etc) functions (optionally times a power of the integration variable) always result in a hygergeometric function (`HypergeometricPFQ` or `MeijerG`). With some experience, many important properties such as the asymptotic behavior at small or large argument can be immediately seen from the hypergeometric notation. Unfortunately, _Mathematica_ takes this nice, compact and very informative output and "simplifies" it into a combination of simpler functions, often resulting in rather lengthy outputs where all the useful information contained in the original hypergeometric notation is lost. How can I prevent this simplification?   Integrate should result in a `HypergeometricPFQ` or `MeijerG` without further simplification unless explicitly requested via `Simplify` or `FullSimplify`.


title: What's reliable way of finding declared but undefined functions/symbols in several interrelated packages?

text: I have many packages some of which use some of others. I have many symbols defined in them. Is there a reliable way of finding declared/exported but undefined functions/symbols in several interrelated packages?


title: How can I independently move vector components (in 2D)?

text: Here's what may well be a simple problem that I have been having difficulty with: There are two connected vectors, **v1** and **v2** , such that:   * **v1** begins at the origin and and ends at point _a1_   * **v2** begins at point _a1_ and ends at point _a2_ The default constraints are such that moving point _a1_ (via the locator at the arrowhead):   * Affects the length and direction of both _v1_ and v2,    * Does _not_ affect the position of _a2_. In other words, the resultant, **v1+v2** remains unchanged. Under other circumstances, this would be fine. However I want to implement the composition of vectors such that displacing _a1_ will affect neither the length nor direction or **v2**. To do so, moving _a1_ must move _a2_ so that _a1-a2_ remains invariant. I want to maintain the effect of "my" moving of _a2_ (It has no effect on **v1** and should not have any effect on **v1** ). In other words, changing **v1** should not change **v2** , and vice-versa. That's what I mean by "independent" components. The figure on the left is a "before" scenario. Notice that a1 is located at {3,-1}; a2 is located at {4,1}. The figure on the right shows the situation after a1 is displaced to {6,-1}. Notice that **v2** has stretched and rotated slightly in a clockwise direction. I would prefer that the **v2** would have been displayed like the dashed black arrow is displayed. That would correspond to the idea that we changed **v1** without changing **v2**. Any ideas about how this can be done? ![vectors](http://i.stack.imgur.com/IlZbE.png) Here is the code:               Manipulate[      Graphics[{PointSize[Large], Point[{0, 0}],      {Red, Arrow[{{0, 0}, a1}]}, Text["a1", Offset[{0, 15}, a1]],      {Dashed, Arrow[{a1, a1 + {5, -2}}](*,Text["a3",Offset[{0,-15},a2]]*)},      Blue, Arrow[{a1, a2}], Black, Text["a2", Offset[{0, 15}, a2]]},      PlotRange -> {{-8, 8}, {-8, 8}},     BaseStyle -> 16, Axes -> {True, True}],     {{a1, {-1, 3}}, {-4, -4}, {8, 8}, Locator},     {{a2, {4, 1}}, {-3, -3}, {6, 6}, Locator}]


title: ParallelMap and Sow/Reap - not behaving as expected?

text: **Is ParallelMap and Parallelize@Map expected to work with Sow and Reap construct.** _This is a rather brief toy code to find all Primes just to force the use of Sow/Reap inside Map_               Reap[Map[        If[PrimeQ@#, Sow@#] &,        Range[10]        ]][[2]]      and the output is, as expected               {{2, 3, 5, 7}}      But when I do               Reap[Parallelize@Map[         If[PrimeQ@#, Sow@#] &,         Range[1000]         ]][[2]]      I got the output               {}      And the same was the output when I ran               Reap[       ParallelMap[        If[PrimeQ@#, Sow@#] &,        Range[10]        ]       ][[2]]      **2 questions :** 1) How is this explainable ? 2) If this is the case, how do I efficiently I spawn parallel jobs which accumulate something ?


title: Strategies for avoiding and handling shadowing

text: When dealing with namespaces in Mathematica (`BeginPackage`, `$ContextPath` ...) one is unavoidably confronted with the problem of shadowing (see e.g. question 1, question2). What are good strategies to handle or avoid these problems? As a package developer, the most obvious strategy is to use unique names, but to be on the save side one would probably need to use very long names and prefixes like               MyPackageMyNameAndMyBirthday      This has drawbacks: the code will be harder to read than necessary, you still can't be sure about uniqueness and the names will be hard to remember and type, just to name some. (And yes, it spoils most of the fun and beauty of Mathematica). Thus I have used other strategies like using strings instead of symbols for option names. I just have learned that this also has drawbacks and of course it is not applicable to function names. Another problem is that as a user of a package, you can't control what the symbol names in these are: It might happen that you want to load two packages that define symbols with the same name. It might happen that you want to use a package written for an older version of Mathematica that defines a symbol with a name that meanwhile exists in the `System`` context. I have loaded packages (`Needs`) and explicitly removed the corresponding context from `$ContextPath` in such situations, but I feel that's somewhat hacky. Are there better ways to deal with this? (I found an article available by Wagner which discusses some ideas about the topic, but don't think it gives answers to the examples I gave)


title: How do you determine the optimal autocompilation length on your system

text: When you pack lists there is an overhead therefore packing a list with, say, 2 elements is likely to cost more than you get back in efficiency. Mathematica has default list lengths for which functions creating those lists will pack the list (i.e. if the list length is less than the numbers shown below the list will not be packed):               SystemOptions["CompileOptions"]          {"CompileOptions" -> {"ApplyCompileLength" -> \[Infinity],         "ArrayCompileLength" -> 250, "AutoCompileAllowCoercion" -> False,         "AutoCompileProtectValues" -> False, "AutomaticCompile" -> False,         "BinaryTensorArithmetic" -> False, "CompileAllowCoercion" -> True,         "CompileConfirmInitializedVariables" -> True,         "CompiledFunctionArgumentCoercionTolerance" -> 2.10721,         "CompiledFunctionMaxFailures" -> 3,         "CompileDynamicScoping" -> False,         "CompileEvaluateConstants" -> True,         "CompileOptimizeRegisters" -> False,         "CompileReportCoercion" -> False, "CompileReportExternal" -> False,         "CompileReportFailure" -> False, "CompileValuesLast" -> True,         "FoldCompileLength" -> 100, "InternalCompileMessages" -> False,         "ListableFunctionCompileLength" -> 250, "MapCompileLength" -> 100,         "NestCompileLength" -> 100, "NumericalAllowExternal" -> False,         "ProductCompileLength" -> 250, "ReuseTensorRegisters" -> True,         "SumCompileLength" -> 250, "SystemCompileOptimizations" -> All,         "TableCompileLength" -> 250}}      So, for example, if you make a list using `Table`               Developer`PackedArrayQ[Table[i, {i, 1, 249}]]     False          Developer`PackedArrayQ[Table[i, {i, 1, 251}]]     True      I am assuming that if you plotted the time to make uncompiled lists using `Table`, vs making compiled lists, the lines would intersect at ~250, beyond which packed lists become more efficient. Is that a correct interpetation of what the autocompilation length represents? I would expect that the optimal lengths for compilation (incl. packing) vary on system to system, therefore I want to know the best way to construct a set of tests to test that proposition, and to determine the optimal list length for packing for the functions listed above. **Edit** For clarity, as per Albert's comments, there are cases when the evaluations taking place prevent compilation so these discussions are redundant, i.e. compilation is prevented regardless of the default settings. But I am curious about the optimal list lengths in cases where compilation occurs.


title: Fitting points to tilted, off-center ellipse

text: I have 24 x-y points that are supposed to form an ellipse.               points={{31.4799,432.849},{-195.826,356.419},{210.029,121.779},{76.1586,-4.47992},{26.6061,-6.97711},{160.236,27.0398},{203.248,241.865},{-225.351,218.912},{-159.899,109.93},{-106.465,58.164},{-1.98952*10^-11,442.},{-229.146,324.489},{-31.4799,9.15114},{195.826,85.5807},{-210.029,320.221},{-76.1586,446.48},{-26.6061,448.977},{-160.236,414.96},{-203.248,200.135},{225.351,223.088},{159.899,332.07},{106.465,383.836},{-1.98952*10^-11,1.83076*10^-11},{229.146,117.511}};     points//ListPlot      ![points](http://i.stack.imgur.com/osA77.png) I want to numerically fit an ellipse around those points. I tried to use the NMinimize method with least-square shown in this Q&A but the issue in this problem is that x and y are related parametrically (through t), and not directly like that other problem was. Worse, the ellipse will be off-center and tilted, so I can't use the nice $$\left(\frac{x}{a}\right)^2+\left(\frac{y}{b}\right)^2=1$$ but had to use this equation I found on Wikipedia (surprisingly without citation!): ![ellipsewiki](http://i.stack.imgur.com/fXPZD.png) My strategy was to generate 24 X(t) equations and 24 Y(t) equations, or more specifically, X(t1), Y(t1), ..., X(t24), X(t24) with xc, yc, a, b in them. Then, I would use NMinimize to optimize all of the square differences between my points and the ellipse. I would eventually get back xc, yc, a, b, CurlyPhi, and every single t values from t1 to t24. I tried to find a more elegant way of using NMinimized for parametric equations, and I believe the multivariate examples of NMinimized in the documentation are not exactly parametric equations. See also the linked Q&A above for an example. Here's my code to find xc, yc, a, b, t1, ... , t24:               tList = ToExpression["t" <> ToString[#]] & /@ Range[1, 24];     equations = Join[        MapThread[#1 - xc - a Cos[#2] Cos[\[CurlyPhi]] +            b Sin[#2] Sin[\[CurlyPhi]] &, {points[[All, 1]], tList}],        MapThread[#1 - yc - a Cos[#2] Sin[\[CurlyPhi]] -            b Sin[#2] Cos[\[CurlyPhi]] &, {points[[All, 2]], tList}]];     solution = NMinimize[       #.# &[equations],       Join[tList, {xc, yc, a, b, \[CurlyPhi]}]]      ![equations](http://i.stack.imgur.com/v7Req.png) And this is what the ellipse looks like:               Show[           (* Tilted ellipse/disk drawn using Disk and Rotate *)      Graphics[       {Yellow,         Rotate[Disk[{xc, yc}, {Abs@a, b}], \[CurlyPhi]] /.          solution[[2, 25 ;; 29]]}],           (* Starting points *)      points // ListPlot,           (* Ellipse outline plotted by the 2 parametric equations *)      ParametricPlot[{xc + a Cos[t] Cos[\[CurlyPhi]] -           b Sin[t] Sin[\[CurlyPhi]],          yc + a Cos[t] Sin[\[CurlyPhi]] + b Sin[t] Cos[\[CurlyPhi]]} /.         solution[[2, 25 ;; 29]], {t, 0, 2 \[Pi]}, PlotStyle -> Red],           (* Point on ellipse corresponding to t1 to t24 *)      ListPlot[{xc + a Cos[#] Cos[\[CurlyPhi]] - b Sin[#] Sin[\[CurlyPhi]],            yc + a Cos[#] Sin[\[CurlyPhi]] + b Sin[#] Cos[\[CurlyPhi]]} /.           solution[[2, 25 ;; 29]] & /@ solution[[2, 1 ;; 24, 2]],        PlotStyle -> Red],           Axes -> True]      ![ellipse](http://i.stack.imgur.com/bhLQE.png) Even though I got what I want, I just feel that this is clunky way to solve the problem, not least because I don't need to solve for t1 to t24--I just needed xc, yc, a, and b. Another issue is that for some reason the value of my a (supposed to be the long axis) is negative and smaller in magnitude than the other axis*, and the rotate angle of the ellipse is crazy high (88.7 radian). I tried to apply some constrains to NMinimize (a>0 or 90 [Degree] < [CurlyPhi] < 150 [Degree]) but kept getting errors. ![NMinimized error](http://i.stack.imgur.com/81Px2.png) * ![ellipse wiki reference](http://i.stack.imgur.com/nEj9v.png) Lastly, I'd really appreciate any general comment to make my code better as I'm still a beginner in MMA (you probably could tell by my zeal of pure functions in this example; I've just been reading a chapter about them).


title: Dynamically choosing which Manipulate controls to use

text: I have some stuff I would like to manipulate, using two different kinds of control, one at a time, using another variable as a switch. These controls are similar in principle to               Evaluate@(Sequence @@ {{controlA1, 0, 0.8}, {controlA2, 0, 2}})      and               {controlB, {-1, -1}, {1, 1}}      Therefore I tried using the code               Manipulate[           If[ChooseControlMode,       stuffA,       stuffB],           {{ChooseControlMode, False, "Choose control mode: "}, {True -> "A",         False -> "B"}, PopupMenu},           Dynamic@If[ChooseControlMode,      Evaluate@(Sequence @@ {{controlA1, 0, 0.8}, {controlA2, 0, 2}}),        {controlB, {-1, -1}, {1, 1}}]           ]      However, for some reason MMA behaves as if what I meant to be my controls were actually simple text (and also splices the `Sequence` inside `If`, therefore preventing even this simple text from being displayed at the right time). I also tried using something like               ReleaseHold@Dynamic@If[ChooseControlMode,        Hold@(Evaluate@(Sequence @@ {{controlA1, 0, 0.8}, {controlA2, 0,                2}})),        Hold@{controlB, {-1, -1}, {1, 1}}]      In this case instead I run into error > Manipulate::vsform: Manipulate argument `ReleaseHold[...]` does not have the > correct form for a variable specification. How can I get MMA to treat my input as additional controls and thus display them with their standard input (i.e., two `Manipulator`s and a `Slider2D`)?


title: Collecting terms in an expression

text: I have an expression:               (C1*R*(10*k12*k21 - 20*k11*k22 - k21^2*Cos[4*t] + 10*k11^2 + 10*k12^2 + 3*k21^2 + 10*k22^2 -       4*k12*k21*Cos[2*t] - 2*k12*k21*Cos[4*t] + 4*k11*k21*Sin[2*t] + 2*k11*k21*Sin[4*t] -       4*k21*k22*Sin[2*t] - 2*k21*k22*Sin[4*t]))/32       and I would like to factor this in terms of squares of the `k`s. (e.g., `(k12^2 - k21^2)`, `(k22 - k11)^2`, `(k12 + k21)^2`, etc.) If the trigonometric identities can be simplified, then that's perfect. Any help would be appreciated.


title: Sum of roots of a trigonometric equation

text: The equation $$ \sin x + \sqrt{3} \cos x = 1,$$ where $x \in [-2\pi, 2\pi]$ has four roots $-\dfrac{3\pi}{2}$, $\dfrac{\pi}{2}$, $\dfrac{\pi}{2}$ and $\dfrac{11\pi}{6}$. Sum of roots of the given equation is $\dfrac{2\pi}{3}$. How do I tell Mathematica to do that? I tried               Solve[{Sin[x] + Sqrt[3]*Cos[x] == 1, -2*\[Pi] <= x <= 2*\[Pi]}, {x}]         **edit** from comment I repaired the given equation to               Solve[{Sin[x] + Sqrt[3]Cos[x] == 1, -2[Pi] <= x <= 2*[Pi]}, {x}]       and used               Simplify@Total[ x /. Solve[{Sin[x] + Sqrt[3] Cos[x] == 2, -2 Pi <= x <= 2 Pi}, {x}]],       and I got the answer               -4 [Pi] + 8 ArcTan[1/(2 + Sqrt[3])].        How do I get the answer -((5 [Pi])/3)?


title: g00 (metric tensor) not explicitly evaluated in FeynCalc

text: I am learning _Mathematica_ and `FeynCalc` by doing some basic cross section calculations. I have an issue with trace calculations: When I plug in for instance the interference term for `ee->tautau`, the result comes out with the `g00` component of the metric tensor explicitly written, i.e. not set to `1` as it should be. This means I have to manually remove it before the next step in the calculation. I have tried doing something like `MetricTensor[0,0]:=1`, but it did not help. I am probably missing some syntax, but can you point me to the correct way of doing it? Here is my code:               DiracSimplify[       Contract[e^2*gz^2/4/(s*(s - Mz^2 + Mz*Gammaz))/4*         Tr[GA[mu].(GS[q2] - M).GA[0].(cV - cA GA[5]).GA[0].GA[            nu].(GS[q1] + M)]*         Tr[GA[mu].(GS[p1] + m).GA[0].(cV - cA GA[5]).GA[0].GA[            nu].(GS[p2] - m)]]];


title: MATLAB to Mathematica: coneplot

text: Does Mathematica have a function, similar to the one called `coneplot` in MatLAB? Given some spatial coordinates $x, y, z$ and velocity components $v_x,v_y,v_z$, it is able to produce the following graphs: ![enter image description here](http://i.stack.imgur.com/tcFWG.gif) When I plot my data with `ListVectorPlot3D`, I don't get any arrows shown. Here is a sample data, in the form $((x,y,z),(v_x,v_y,v_z))$:               data={{{0., 0.847912, 9.48902}, {0., 0., 0.}}, {{0.00773322, -0.0110065,         9.09927}, {0., 0., 0.}}, {{-1.00008, -0.0623481, 9.49984}, {0., 0.,         0.}}, {{0., 0.847912, 10.8969}, {0., 0., 0.}}, {{0., 0.847912,         12.5007}, {0., 0., 0.}}, {{0., 0.847912, 14.1046}, {0., 0.,         0.}}, {{0., 0.847912, 15.5729}, {0., 0., 0.}}, {{0., 0.847912,         16.6107}, {0., 0., 0.}}, {{0., 0.847912, 17.3334}, {0., 0.,         0.}}, {{0., 0.847912, 18.0983}, {0., 0., 0.}}, {{0., 0.847912,         18.8639}, {0., 0., 0.}}, {{0., 0.847912, 19.9409}, {0., 0.,         0.}}, {{0., 0.847912, 21.3189}, {0., 0., 0.}}, {{0., 0.847912,         22.822}, {0., 0., 0.}}, {{0., 0.847912, 24.6036}, {0., 0.,         0.}}, {{0., 0.847912, 26.2343}, {0., 0.,         0.}}, {{-1.08457, -0.0217237, 10.6779}, {0., 0.,         0.}}, {{-1.11085, -0.0731095, 12.19}, {0., 0.,         0.}}, {{-1.1131, -0.0651947, 13.7893}, {0., 0.,         0.}}, {{-1.10496, -0.0720509, 15.108}, {0., 0.,         0.}}, {{-1.12255, -0.0365039, 16.0888}, {0., 0.,         0.}}, {{-1.12699, -0.00227834, 16.8818}, {0., 0., 0.}}, {{-1.15057,         0.0126093, 17.6497}, {0., 0., 0.}}, {{-1.13931, -0.015588,         18.4211}, {0., 0., 0.}}, {{-1.03192, -0.0742988, 19.1016}, {0., 0.,         0.}}, {{-1.24186, -0.0317904, 19.9972}, {0., 0.,         0.}}, {{-1.14942, -0.0360112, 20.9677}, {0., 0.,         0.}}, {{-1.09896, -0.0167395, 21.9511}, {0., 0.,         0.}}, {{-1.117, -0.0452791, 23.2337}, {0., 0.,         0.}}, {{-1.1522, -0.056303, 24.8936}, {0., 0.,         0.}}, {{-1.09607, -0.110654, 26.195}, {0., 0.,         0.}}, {{0.103537, -0.0647147, 26.6637}, {0., 0., 0.}}, {{0.,         0.847912, 41.3051}, {0., 0., 0.}}, {{-0.012139, -0.0295375,         40.9221}, {0., 0., 0.}}, {{-0.857944, -0.0671514, 41.3642}, {0.,         0., 0.}}, {{0., 0.847912, 42.4678}, {0., 4.67035*10^-7, 0.}}, {{0.,         0.847912, 43.5378}, {0., 0., 0.}}, {{-0.979967, -0.033538,         42.2371}, {0., 0., 0.}}, {{-1.14769, -0.0351505, 43.0033}, {0., 0.,         0.}}, {{-0.979351, -0.0342237, 43.8374}, {0., 0.,         0.}}, {{-1.23767, -0.0499179, 44.5971}, {0., 0.,         0.}}, {{-1.13972, -0.0000850668, 45.3128}, {0., 0.,         0.}}, {{-1.12545, -0.00826265, 46.0778}, {0., 0.,         0.}}, {{-1.1223, -0.0359113, 46.8929}, {0., 0.,         0.}}, {{-1.12465, -0.055138, 47.8623}, {0., 0.,         0.}}, {{-1.09846, -0.0144483, 49.0776}, {0., 0.,         0.}}, {{-1.10899, -0.0625359, 50.4507}, {0., 0.,         0.}}, {{-1.14579, -0.108309, 52.0417}, {0., 0.,         0.}}, {{-1.12848, -0.01126, 54.0108}, {0., 0.,         0.}}, {{-1.11299, -0.0970175, 55.2159}, {0., 0., 0.}}, {{0.,         0.847912, 44.6206}, {0., 0., 0.}}, {{0., 0.847912, 45.3961}, {0.,         0., 0.}}, {{0., 0.847912, 46.2075}, {0., 0., 0.}}, {{0., 0.847912,         47.3219}, {0., 0., 0.}}, {{0., 0.847912, 48.6172}, {0., 0.,         0.}}, {{0., 0.847912, 50.0586}, {0., 0., 0.}}, {{0., 0.847912,         51.6502}, {0., 0., 0.}}, {{0., 0.847912, 53.7857}, {0., 0.,         0.}}, {{0., 0.847912, 55.2595}, {0., 0.,         0.}}, {{0.119852, -0.0804816, 55.6719}, {0., 0.,         0.}}, {{1.38231, -0.0646805, 9.63683}, {0., 0.,         0.}}, {{3.08676, -0.0356642, 10.2185}, {0., 0., 0.}}, {{3.98277,         0.0329428, 10.6312}, {0., 0., 0.}}, {{1.64587, 0.847912,         10.1128}, {0., 0., 0.}}, {{2.94532, 0.847912, 10.6054}, {0., 0.,         0.}}, {{3.0844, 0.847912, 26.2343}, {0., 0., 0.}}, {{6.37314,         0.847912, 26.2343}, {0., 0., 0.}}, {{8.83598, 0.847912,         26.2343}, {0., 0., 0.}}, {{2.68672, -0.0254293, 26.6613}, {0., 0.,         0.}}, {{5.13989, -0.0481681, 26.6588}, {0., 0.,         0.}}, {{7.07074, -0.0263853, 26.6521}, {0., 0., 0.}}, {{8.87196,         0.0308362, 26.6941}, {0., 0., 0.}}, {{0.908045, -0.0256653,         41.2951}, {0., 0., 0.}}, {{0.90812, -0.0305627, 42.1266}, {0., 0.,         0.}}, {{1.09331, -0.0723344, 42.9721}, {0., 0.,         0.}}, {{1.03446, -0.06788, 43.5403}, {0., 0.,         0.}}, {{1.9443, -0.0212229, 43.8278}, {0., 0., 0.}}, {{2.52323,         0.00655421, 44.1426}, {0., 0., 0.}}, {{1.47266, 0.847912,         44.0959}, {0., 0., 0.}}, {{1.47266, 0.847912, 44.6541}, {0., 0.,         0.}}, {{3.48462, 0.847912, 55.2595}, {0., 0., 0.}}, {{9.45979,         0.847912, 55.2595}, {0., 0., 0.}}, {{15.9244, 0.847912,         55.2595}, {0., 0., 0.}}, {{20.8183, 0.847912, 55.2595}, {0., 0.,         0.}}, {{24.5798, 0.847912, 55.2595}, {0., 0., 0.}}, {{27.9807,         0.847912, 55.2595}, {0., 0., 0.}}, {{4.19646, -0.079758,         55.6822}, {0., 0., 0.}}, {{9.8436, -0.111618, 55.6824}, {0., 0.,         0.}}, {{17.6324, -0.0328765, 55.6789}, {0., 0.,         0.}}, {{23.6589, -0.044735, 55.6773}, {0., 0.,         0.}}, {{27.8005, -0.0722351, 55.6708}, {0., 0., 0.}}, {{2.94532,         0.847912, 11.1635}, {0., 0., 0.}}, {{2.62106, -0.0129568,         44.6594}, {0., 0., 0.}}, {{3.34577, -0.0199615, 44.9502}, {0., 0.,         0.}}, {{3.9942, 0.0362858, 45.2367}, {0., 0., 0.}}, {{2.27968,         0.847912, 44.96}, {0., 0., 0.}}, {{2.94532, 0.847912,         45.2124}, {0., 0., 0.}}, {{2.94532, 0.847912, 45.7705}, {0., 0.,         0.}}, {{4.30519, -0.0509312, 11.19}, {0., 0., 0.}}, {{5.04605,         0.847912, 11.9598}, {0., 0., 0.}}}


title: How do I place vertical GridLines in front of horizontal ones?

text: By default horizontal GridLines are placed in front of vertical GridLines:               style = Directive[#, AbsoluteThickness[5]] &;     Graphics[Circle[], Frame -> True, ImagePadding -> 1, GridLines -> Automatic,          GridLinesStyle -> style /@ #] & /@ {{LightGray, Black}, {Black, LightGray}} // GraphicsRow      ![Mathematica graphics](http://i.stack.imgur.com/Bxm7H.png) **How can I place the vertical lines in front so that they appear uninterrupted?** I do not wish to resort to manually drawing `Line` expressions.


title: Tips for efficiently solving large system coupled (nonlinear) ODEs

text: I'm trying to solve a system of nonlinear, coupled ODEs, where the governing equation for the $n-th$ ODE is of the form: $\sum_k^M Q_{nk} \ddot{a}_k -\sum_{\ell}^M\sum_k^M S_n(\ell,k) \dot{a}_{\ell} \dot{a}_k + \frac{1}{2}U_n = 0 $ where $Q_{nk}=\frac{1}{2}\sum_{j=1}^MP_{jn}P_{jk}$, with $P_{jn}=\frac{1}{\sqrt{m}n}(a_{n-j}+a_{j+n}-a_ja_n)$, (and $a_{n-j}=0$ for $j>n$), $S_n(\ell,k)=-\frac{1}{2}\left(\frac{\partial Q_{k\ell}}{\partial a_n}-\frac{\partial Q_{n\ell}}{\partial a_k}-\frac{\partial Q_{nk}}{\partial a_{\ell}}\right)$ and $U_n=\frac{\partial}{\partial a_n} \frac{1}{2\pi} \int_0^{2\pi}\left\\{ \left(-\sum_{j=1}^M \left(\frac{a_j^2}{2j}-\frac{a_j}{j}\cos j\theta \right)\right)^2*\left(1+\sum_{j=1}^M a_j \cos j\theta \right) \right\\}d\theta$. Note, $(Q_{k\ell}, S_N(k,\ell), U_n)$ are all polynomials (of maximum order 4) in the dependent variables $a_i(t)$ and M is the total number of dependent variables under consideration (i.e $a_j\equiv 0$ for $j>M$). I have been able to solve for low M cases (i.e. M less than 10) using NDSolve. For fixed initial conditions, I have been increasing M and finding a significant increase in computation time. I'm wondering if there are any obvious ways to decrease computation time that I have overlooked. (Ideally, for the system I'm trying to model, I'd like to increase the number of dep. variables to around 200. I'm new to Mathematica, and I'm sure I'm making some 'rookie mistakes' that are costing me in computation time. Also, if I'm barking up the wrong tree, that is I should be using a different platform, I'd like to find out before I invest too much effort into this project.) Some questions I have on basic problem set-up: i) Is it more efficient to isolate the dependent variables in question. That is, have equations of the form $\ddot{a}_i =...$ versus $\sum_k^M Q_{nk} \ddot{a}_k =...$? ii) Is it worth fully simplifying the governing equations (i.e. using FullSimplify[]) before executing the NDSolve command? iii) Should I rewrite each second order ODEs as a pair of first order ODEs? Any advice on this would be greatly appreciated. Thanks, Nick Here is the code:               M = 10; (*Number of modes*)     f[r_, s_] := If[r > s, 0, 1]; (*Will ensure we have no negative modes*)     α[i_, t_] := If[i <= M, A[i, t], 0]; (*Truncate series at Mth mode*)     A[0, t_] := 1; (*By definition*)          P[m_, n_, t_] :=      1/Sqrt[m*n^2]*(f[m, n]*α[n - m, t] + α[n + m,      t] - α[m, t]*α[n, t]) ;            Q[n_, l_, t_] := 1/2 Sum[P[m, n, t]* P[m, l, t], {m,1,M}] ;           S[n_, k_, l_, t_] :=      1/2 (D[Q[k, l, t], A[n, t]] - D[Q[n, l, t], A[k, t]] -      D[Q[n, k, t], A[l, t]]);           F[t_] := 1/(2 π) Integrate[     Sum[((A[j, t]*Cos[j*ξ])/j -             A[j, t]^2/(2j)),{j,1,M}]^2*      (1+Sum[1+A[j, t]*           Cos[j*ξ],{j,1,M}]), {ξ, 0, 2π}];      U[n_, t_] := D[F[t], A[n, t]];     Table[A[j, t_] = B[j][t], {j, 1, M}]; (*Redefine dep variables so that independent     variable is distinguished from dep var index*)     Gov[n_, t_] := Sum[B[l]''[t]*Q[n,l,t],{l,1,M}]-Sum[Sum[S[n,k,l,t]B[k]'[t]B[l]'[t],      {k,1,M}],{l,1,M}]+1/2U[n,t];          eqns = {Table[Gov[j, t] == 0, {j, 1, M}], B[1][0] == 0.3, B[2][0] == 0.1, Table[B[j][0] ==   0, {j, 3, M}], Table[B[j]'[0] == 0, {j, 1, M}]};          TenMode = NDSolve[eqns, Table[B[n][t], {n, 1, M}], {t, 0, 10}]      I apologize for any errors in the code since I had some issues parsing from the symbolic notation present in my editor to a code that would be easily copied into this forum.


title: Performance: Collapsing repeated contiguous rows & cols from a matrix

text: In this answer I needed to remove contiguous zero-valued cols and rows from a matrix, _leaving only two of them in place_ , no matter what the original number was. I made up this code:               m = RandomVariate[BinomialDistribution[1, 10^-3], {400, 400}];      rule = {h__, {0 ..}, w : {0 ..}, {0 ..}, t__} -> {h, w, w, t};     mClean = Transpose[Transpose[m //. rule] //. rule];     Dimensions@mClean      But it is way too slow.   I'm pretty sure this code can be enhanced. Any better ideas?


title: How do I make a 3DPlot using cylindrical coordinates?

text: I'm trying to plot a function of the form $z(r,\theta)$ where $r \in [0, R]$ for a finite R, $\theta \in [0,2\pi[$, and z is the third coordinate, a function of the first two. I couldn't find anything to do it natively, so I went back to Cartesian coordinates. But the result does not satisfy me, because the range of x is a function of y, a consequence of the constraint $ x^2+y^2 < R^2$. Is there already something in _Mathematica_ to handle this kind of plot?


title: Set the style of a cell

text: I know it's possible to programmatically change options on the selection in a notebook. I'd like to create a button that lets me change the style of a cell. It's a style that doesn't have a keyboard shortcut, "ItemParagraph" Something like               SetOptions[NotebookSelection[SelectedNotebook[]], CellStyle->"ItemParagraph"]      but CellStyle is for NotebookFind. Is there some way to do this? I just couldn't find the cell option I needed. I checked the Options for Cell but there are hundreds and I couldn't see anything that looked right...


title: Plot result from the function of NDSolve

text: I have a solution that I got from NDSolve which are ua and uw.               eq1=Derivative[2, 0][uw][z, t]*cwv-Derivative[0,1][ua][z,t]*cw == Derivative[0, 1][uw][z, t];     eq2=Derivative[2, 0][ua][z, t]*cav-Derivative[0,1][uw][z,t]*ca == Derivative[0, 1][ua][z, t];          ic1 = {uw[zmax, t] == ui + p0, uw[z, tmin] == ui};     ic2 = {ua[z, tmin] == uatm};     sol2 = NDSolve[Flatten[{eq1, eq2, ic1, ic2}], {uw, ua}, {z, zmin, zmax}, {t, tmin,      tmax}, MaxSteps -> Infinity, MaxStepSize -> dt/step, InterpolationOrder -> All];          result = (ua[z, t] /. sol2) - (atm[z, t]) - (uw[z, t] /. sol2);      I manage to solve this equation and I can plot "result" by using Plot3D.               Plot3D[result, {z, zmin, zmax}, {t, tmin, tmax},             PlotRange -> All, AxesLabel -> {z, t, "result"[z, t]},             BoundaryStyle -> Thick, ImageSize -> 500]      However, I also wants to plot this equation by using manipulate command in Plot but I failed. Here is how I do it               Manipulate[Plot[result, {t, tmin, tmax}, PlotRange -> Full,                      AxesLabel -> {t, "result"[z, t]}], {z, zmin, zmax}]      or by using this code               Manipulate[result[z,t], {t, tmin, tmax}, PlotRange -> Full,                 AxesLabel -> {t, "result"[z, t]}], {z, zmin, zmax}]      Can someone please tell me how to plot "result" by using manipulate command?I can do it for each ua[z,t] and uw[z,t] For the complete set of code               kw = 1*10^(-10);(*m/s*)     ka = 8*10^(-13);(*m/s*)     gw = 10;(*kN/m^3*)     m2w = 2.41*10^(-4);(*coefficient of compressibility of water phase with respect to matric suction*)     m1w = 0.8*10^(-4);(*coefficient of compressibility of water phase with respect to axial stress*)     m2a = 1.11*10^(-4);(*coefficient of compressibility with air phase with respect to matric suction*)     m1a = 0.37*10^(-4);(*coefficient of compressibility of air phase with respect to axial stress*)     p0 = 100;(*applied pressure -kPa*)     tmin = 0;(*minimum or time when the pressure is applied*)     tmax = 5000;(*latest inspected time*)     zmin = 0;(*top elevation*)     zmax = 0.02;(*bottom elevation*)     uatm = 101;(*kPa-atmospheric air pressure*)     step = 1000;(*The higher the step, the higher the accuracy*)     ui = -400;(*Initial matric suction*)          temp = 300;(*temperature in kelvin*)     wa = 28.97;(*kg/kmol*)     s = 0.7887;     n = 1.0696/(1 + 1.0696);     (*CALCULATION*)     r = 8.31432;(*Universal gas constant in j/(mol K*)     g = 9.8;(*gravity acceleration-m2/s*)     da = ka/g;(*function varies with matric suction, havent been defined yet*)     cwv = kw/(gw*m2w);     cw = ((1 - m2w/m1w)/(m2w/m1w));     ca = (m2a/m1a)/(1 - (m2a/m1a) - (1 - s)*n/(uatm*m1a));     cav = (da/(wa/(r*temp)*uatm))/(m1a*(1 - m2a/m1a) - (1 - s)*n);     dt = tmax - tmin;          eq1 = Derivative[2, 0][uw][z, t]*cwv - Derivative[0, 1][ua][z, t]*cw == Derivative[0, 1][uw][z, t];     eq2 = Derivative[2, 0][ua][z, t]*cav - Derivative[0, 1][uw][z, t]*ca == Derivative[0, 1][ua][z, t];          ic1 = {uw[zmax, t] == ui + p0, uw[z, tmin] == ui};     ic2 = {ua[z, tmin] == uatm};     sol2 = NDSolve[Flatten[{eq1, eq2, ic1, ic2}], {uw, ua}, {z, zmin, zmax}, {t, tmin,tmax}, MaxSteps -> Infinity, MaxStepSize -> dt/step, InterpolationOrder -> All];          Column[Plot3D[uw[z, t] /. sol2, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t, uw[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500], Plot3D[ua[z, t] /. sol2, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t, ua[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500]]          Column[Manipulate[Plot[uw[z, t] /. sol2, {z, zmin, zmax}, PlotRange -> Full, AxesLabel -> {z, uw[z, t]}], {t, tmin, tmax}],Manipulate[Plot[uw[z, t] /. sol2, {t, tmin, tmax}, PlotRange -> Full, AxesLabel -> {t, uw[z, t]}], {z, zmin, zmax}]]          Column[Manipulate[Plot[ua[z, t] /. sol2, {z, zmin, zmax}, PlotRange -> Full, AxesLabel -> {z, ua[z, t]}], {t, tmin, tmax}],Manipulate[Plot[ua[z, t] /. sol2, {t, tmin, tmax}, PlotRange -> Full, AxesLabel -> {t, ua[z, t]}], {z, zmin, zmax}]]          Column[Manipulate[Plot[{uw[z, tmin] /. sol2, uw[z, t1] /. sol2, uw[z, t2] /. sol2, uw[z, t3] /. sol2, uw[z, t4] /. sol2, uw[z, tmax] /. sol2}, {z, zmin, zmax}, AxesLabel -> {z, uw[z, t]}, PlotRange -> Full, AxesLabel -> {z, uw[z, t]}], {t1, tmin + dt/1000, tmin + dt/51}, {t2, tmin + dt/50, tmin + dt/16}, {t3, tmin + dt/15,tmin + dt/3}, {t4, tmin + dt/3, tmin + dt/1}], Manipulate[Plot[{ua[z, tmin] /. sol2, ua[z, t1] /. sol2, ua[z, t2] /. sol2, ua[z, t3] /. sol2, ua[z, t4] /. sol2, ua[z, tmax] /. sol2}, {z, zmin, zmax}, AxesLabel -> {z, ua[z, t]}, PlotRange -> Full], {t1, tmin + dt/500, tmin + dt/51}, {t2, tmin + dt/50, tmin + dt/16}, {t3, tmin + dt/15, tmin + dt/3}, {t4, tmin + dt/3, tmin + dt/1}]]          atm[z, t] = uatm     result == (ua[z, t] /. sol2) - (atm[z, t]) - (uw[z, t] /. sol2);     Plot3D[result, {z, zmin, zmax}, {t, tmin, tmax}, PlotRange -> All, AxesLabel -> {z, t,"result"[z, t]}, BoundaryStyle -> Thick, ImageSize -> 500]     Manipulate[result, {t, tmin, tmax}, PlotRange -> Full, AxesLabel -> {t, "result"[z, t]}], {z, zmin, zmax}]      Regards Martin Wijaya


title: Using graphics primitives to draw a cross as inset in graphics

text: I would like to draw a cross as an inset in a Graphics environment. I tried the following:               Graphics[{Inset[Style["\[Cross]", 100], {0, 0},{Center,Center}], Circle[]},           Frame -> True]      ![Inset of cross in circle](http://i.stack.imgur.com/vYuvb.png) Unfortunately, the `{Center,Center}` command for specifying the exact point of the cross that is drawn at the `{0,0}` position does not use the intercept of the two parts of the cross. Is there an easy way to produce a cross using graphics primitives rather than special characters? I have not done much with graphics yet and would really appreciate your help.


title: Selection of the position of the variable

text: I defined a function `funloglogplot` to make a loglogplot of a function (`function1`) depending on several variables               funloglogplot[function1_, xmin_, xmax_, numpoints_] :=        Module[{list1, listRe, listIm},              list1 = {#1, function1[eps1, 1, #1, R1ideal, R2, ordre]}& /@               logspace[xmin, xmax, numpoints];              listRe = {#1[[1]], Re[#1[[2]]]}& /@ list1;              listIm = {#1[[1]], -Im[#1[[2]]]}& /@ list1;              ListLogLogPlot[{listRe, listIm}, Joined -> True]              ]      Nevertheless I would like to be able to choose the variables I am using for the plot (in this case I plot `function1` as a function of its 3rd argument and I would like to be able to select the argument).   Can anyone see a solution?


title: Measuring the percentage of a given color in an area?

text: Given this image I would like to measure how much (in percentage relative to the square area) of each black delimited square is filled with green:               i = Import["http://i.imgur.com/62buGws.png"]      ![enter image description here](http://i.stack.imgur.com/8gBm6.png) I am a bit lost with the usage of the image processing functions. It seems like `MorphologicalPerimeter`and `PixelValuePositions`or `ImageData`could be useful. If I can find a way to detect each square then it is a matter of calling `ImageData` on that area and count the number of green pixels. Any tips please?


title: ImageSize as absolute (metric) value

text: I have wondered more and more often lately how the size of an image is handled when displayed or exported. The documentation implies that the via `ImageSize` the size could be set in printer points (per inch). That does however not correspond with the displayed graphics (for instance `ImageSize-> {72 1, 72 1 }`) does not render a generic plot with the expected size of one inch square. (UI magnification at 100%) I am using Mathematica 9 on OS X 10.9 and usually use .eps for exporting plots (since .pdf export doesn't really work that well with fonts and all)


title: Can CUDAVolumetricRender be combined with other 3D graphics?

text: I have volumetric data, which I can render using `CUDAVolumetricRender[]`. However, I cannot seem to find a way to combine it with other 3D graphics, such as adding a bounding box, axes, labels, etc. How is `CUDAVolumetricRender[]` supposed to be customized? It returns a `DynamicModule`, which is pretty opaque.


title: How to make a volume CUDA rendering isometric?

text: I just realized that the output of `CUDAVolumetricRender[]` uses (quite marked) perspective, which I do not want (for scientific data representation, it can be very misleading). How do I turn it off? (i.e. make it use an isometric projection)


title: Is it possible to style multiple Plot or ListPlot curves using a color gradient?

text: I am using Mathematica 8. In Mathematica, there is a default `PlotStyle` coloring in `Plot` and `ListPlot`. For example, suppose I have a series of nine functions stored in the list `functions`. Mathematica styles the different curves in a cyclic way (I think that the default is cycles of **"blue", purple, dark yellow, green** ), as in this example:               functions = Table[a*Cos[x], {a, 0.2, 1, 0.1}]     Plot[functions, {x, 0, 2 Pi}]      > >     {0.2 Cos[x], 0.3 Cos[x], 0.4 Cos[x], 0.5 Cos[x], 0.6 Cos[x], 0.7 Cos[x], > 0.8 Cos[x], >      0.9 Cos[x], 1. Cos[x]} >   > > ![plot1](http://i.stack.imgur.com/Z46qR.png) This is nice, but now suppose that I want to color the multiple curves using some sort of gradient (perhaps one of the gradients in `ColorData`). Is this possible in `Plot` and `ListPlot`? I could do this somewhat manually. For example, if I wanted a blue gradient, I could write the following (although this choice of colors could somehow be improved):               Plot[functions, {x, 0, 2 Pi}, PlotStyle -> {        Lighter[Lighter[Lighter[Lighter[Blue]]]],        Lighter[Lighter[Lighter[Blue]]],        Lighter[Lighter[Blue]],        Lighter[Blue],        Blue,        Darker[Blue],        Darker[Darker[Blue]],        Darker[Darker[Darker[Blue]]],        Darker[Darker[Darker[Darker[Blue]]]]        }]      > ![plot2](http://i.stack.imgur.com/mGczA.png) However, this becomes complicated if I have many curves or if I want to use a more complex gradient such as rainbow (e.g., `ColorData["Rainbow"]`), temperature map (e.g., `ColorData["TemperatureMap"]`), etc. Do you have any suggestions?


title: How does bandwidth selection work for low-variance dimensions with KernelMixtureDistribution?

text: I am puzzled because this toy example (in Mathematica 8)               dist = KernelMixtureDistribution[{{0, 1}, {0.0, 0}, {0, -1}},"Silverman",                                       MaxMixtureKernels -> All];     DensityPlot[PDF[dist, {x1, x2}], {x1, -3, 3}, {x2, -3, 3}]      ![enter image description here](http://i.stack.imgur.com/xrcCl.gif) produces a density estimate with quite a large extent in x-direction although it has zero standard deviation. I would not have been surprised if that had produced an error because it should be a delta impulse in x-direction and I don't know if that can be represented by Mathematica. But this result does not make sense. If I change it to               dist = KernelMixtureDistribution[{{0, 1}, {0.01, 0}, {0, -1}},"Silverman",                                      MaxMixtureKernels -> All];     DensityPlot[PDF[dist, {x1, x2}], {x1, -3, 3}, {x2, -3, 3}]      ![enter image description here](http://i.stack.imgur.com/0t2Oz.gif) the result is a very thin distribution as expected. The behaviour is similar for Silverman's and Scott's rules of thumb. **Can someone shed some light on how the standard deviations are interpreted here? Is this a bug maybe ?**


title: Differentiating with respect to vectors of unspecified length

text: Given a function defined by               f[x_,y_] := Sum[ x[[i]] (g[y[[i]]] - g[Total[y]] - Log[x[[i]]]), {i, 1, Length[x]}]      I can easily calculate the derivative for a fixed `n` by               D[f[{x1, x2, x3}, {y1, y2, y3}], {{x1, x2, x3}}]      which yields               {-g(y1 + y2 + y3) + g(y1) - log(x1) - 1,      -g(y1 + y2 + y3) + g(y2) - log(x2) - 1,      -g(y1 + y2 + y3) + g(y3) - log(x3) - 1}      I want to differentiate w.r.t. `x` in the general case, by something like this:               D[f[x, y], x]      yielding something like this:               {-g(Total[y]) + g(y[[i]]) - Log[x[[i]]], {i, 1, Length[x]}}      Is this possible? Ideally it chains with `Solve` as well so that I can write something like:               Solve[D[f[x, y], x] == Table[0, {Length[x]}], x]      and get something like               {{x[[i]] -> E^(-g(Total[y]) + g(y[[i]]) - 1), {i, 1, Length[x]}}


title: HighlightGraph with style

text: In this picture you see a graph. The shortest path between vertex 5 and vertex 3 is highlighted in red. Instead I want blue highlighted edges of thickness 10.               HighlightGraph[WheelGraph[6, EdgeStyle -> Directive[Black,AbsoluteThickness[10]]],      PathGraph@FindShortestPath[WheelGraph[6], 5, 3],       GraphHighlightStyle -> {"Red", AbsoluteThickness[10]}]      ![a](http://i.stack.imgur.com/aZ1c9.png) I tried this. The thickness went to 10, but why is the highlighted path not blue?                 HighlightGraph[WheelGraph[6, EdgeStyle -> Directive[Black, AbsoluteThickness[10]],       VertexSize -> 0], PathGraph@FindShortestPath[WheelGraph[6], 5, 3],       GraphHighlightStyle -> {"Blue", AbsoluteThickness[10]}]      ![b](http://i.stack.imgur.com/d9Ykm.png)


title: ListPlot coloring by density of points

text: I have a set of points on a circumference:               points = Map[Normalize, RandomReal[{-1, 1}, {3000, 2}]]      And I want to plot them and color the plot according to the density of points. You see, `ListPlot[points]` will just give me that, a simple plot, on which I can't see the distribution of the points on the circle. Maybe there is an option? I hope you guys can understand what I'm asking. **Edit/Follow-up** I used `SmoothDensityHistogram[points, ColorFunction -> "Rainbow"]` ![This is what it looks like](http://i.stack.imgur.com/hWd6a.png) Now, it's not really what I'm looking for. I kind of wanted it to look like the original plot, just the circumference.


title: Symmetric sum and Muirhead's Inequality

text: I was able to find some reference for symmetric polynomials but not for the _symetric sum_ (see http://en.wikipedia.org/wiki/Muirhead%27s_inequality#Symmetric_sum- notation_tricks ) Please could anyone tell if there is an implementation of the symmetric sum in Mathematica? Any other tools (packages) to deal with Muirhead's inequality? Thanks!


title: How to relate memory usage with occupied positions of SparseArrays?

text: What is the relation of memory usage of a SparseArray   and the number of its occupied positions? Let's say you build a 100.000.000 by 10 element SparseArray.   And fill the two position 1/1 and 100.000.000/10 with a value.               num = 999999;       idSparse = SparseArray[{{1, 1} -> num, {100000000, 10} -> num}]        There are two elements in the Array. Memory usage is:               ByteCount[idSparse]       400000968        Disk usage is:               Export["idSparse.rsa", idSparse];       FileByteCount["idSparse.rsa"]       380