title: PDE plotting assistance needed

text: ![enter image description here](http://i.stack.imgur.com/Dn4o5.png)               ClearAll["Global`*"];     pdeset = {Derivative[1, 0][U][t, x] == Derivative[0, 2][U][t, x],      Derivative[1, 0][T][t, x] == Derivative[0, 2][T][t, x] + E Derivative[0, 1][U][t, x]^2}     ics = {U[0, x] == 0, T[0, x] == 0};     bcs = {U[t, 0] == cos[t], T[t, 0] == 1, U[t, 10] == 0, T[t, 10] == 0 };     bcAll = Flatten[{ics, bcs}, 1];        * For `E=0.1`, when I try to solve `sol = NDSolve[{pdeset, bcAll}, {U, T}, {t, 0, 5}, {x, 0, 4 Pi}]` I get this error NDSolve::bcedge: "Boundary condition U[t,10]==0 is not specified on a single edge of the boundary of the computational domain"   * **How to plot`Derivative[0, 1][T][t, x] as x->0 vs t (0...Pi)` for `E=0.1,0.2,0.3`?**


title: How to define and compute various properties of a variable size matrix

text: I have a rather simple question, but I have not been able to figure out how to implement a solution in _Mathematica_. I would like to define a variable size square matrix, say an N x N matrix A, whose entries A_ij are of the form Kroneceker-delta_ij (N+1-2k)/2. (In fact, the matrices I want to deal with are N dimensional irreducible representations of SU(2)). Eventually, I would like to compute traces of products of certain matrices, but I can not even get tr(IdentityMatrix[N] = N) to work. How should I approach this problem?


title: StreamPlot Label for General Parameter

text: I have a simple DEQ: $$y'(t) = y + C$$ for a constant $C$. It turns out that the equilibrium point of this DEQ is $-C$. I can use the `StreamPlot` command to plot the direction field for 'any' value of $C$, for example, for $C = 2$:                StreamPlot[{1, y + 2}, {t, -4, 4}, {y, -8,  4}]      The `StreamPlot` is: ![enter image description here](http://i.stack.imgur.com/QnvRf.png) This `StreamPlot` would look exactly like this for any value of $C$. is there some way to show the y-axis as a $C$ instead of $-2$ and to show the other values as $C \pm <\rm{offset}>$. That is, the point $-4$ is shown as $C-2$, the point $-2$ is shown as $C$, the point 0 is shown as $C+2$, etc. In other words, the y-axis values are shown as a function of the general equilibrium point?


title: How to speed up given code for evaluating the tensor product of matrix elements?

text: ρ[n_, L_]:=       FixedPoint[         ArrayFlatten,TensorProduct@@Table[Subscript[ρ, l,m][k],{k,n},{l,L},{m,L}]];          list2[n_, L_]:=       ParallelTable[ρ[n,L][[i,j]]->a[i,j],{i,L^n},{j,L^n}]/.        {a[i_,j_]:>ToExpression["a"<>ToString[i]]}//Flatten;          p1[n_, L_] :=        Sum[         Subscript[ρ, L, L][k]*         Product[          If[k == k1, 1,               ParallelSum[Subscript[ρ, l, l][k1], {l, L - 1}]], {k1, n}], {k, n}]//Expand;          P1[n_, L_]:= P1[n,L]= p1[n,L] /. list2[n,L];          p0[n_, L_]:=       ParallelProduct[         Sum[Subscript[ρ, l, l][k], {l, L - 1}], {k, n}] // Expand;          P0[n_, L_]:=P0[n,L]= p0[n,L] /. list2[n,L];      Easy to evaluate...               P0[4, 3]-P0[3, 3]     P1[4, 3]-P1[3, 3]      What kind of changes are needed to speed up this calculation...               P0[5, 3]-P0[4, 3]     P1[5, 3]-P1[4, 3]


title: How to create a Hyperlink within the current Notebook?

text: Using “Create Hyperlink” dialog window I can create a link to a tagged cell in my notebook (it's “Destination notebook: Current notebook” radio button). Now, I can't figure it out how to create such links with `Hyperlink[]` command. I tried               Hyperlink["label", {"", "tag"}]     Hyperlink["label", {None, "tag"}]     Hyperlink["label", {Automatic, "tag"}]      etc., but nothing works.


title: PDE syntax question

text: I am trying to solve a PDE of a reaction diffusion equation, and while I'm getting a decent looking solution, I am also getting inconsistent BC / initial conditions warnings and wanted to check if my logic and coding was ok, or whether it's utterly wrong. I set up the equation like so;               Do2 = 2*10^-9;     a = 7.5*10^-7;     ko = 1;     omega = 3.0318*10^7;     ro = 150*10^-6;          eqn2 = D[P[r, t], t] - Do2*(D[P[r, t], r, r])  + a*omega*((P[r, t])/(P[r, t] + ko));      I then specify my boundary and initial conditions; so initially, in the region from 0 to $r_{o}$, $p = 0$ all across. So I write;               iv = P[r, 0] == 0;      Now, the boundary conditions - at $r = 0$, then is a steady concentration of oxygen diffusing into the region towards $r_{o}$ which is slowly being consumed at the rate $\frac{ap}{p + k_{o}}$, being reduced to zero at $r_{o}$. So I give my boundary conditions (which I believe are Dirichlet BCs) as;               bcs = {P[0, t] == 100, P[ro, t] == 0};      To solve and plot this I write               s11 = NDSolve[{eqn2 == 0, iv, bcs}, {P[r, t]}, {r, 0, ro}, {t, 0, 500}]     Plot3D[P[r, t] /. s11, {r, 0, ro}, {t, 0, 1000}]      Which plots something that looks relatively like what I'd expect - however, it warns me that the boundary conditions are inconsistent - am I plotting what I think I'm plotting, or is there something remiss is my code or logic? I should also add that my guess of $r_{o}$ is likely an underestimate - however, if I increase it to say, $r_{o} = 200*10^{-6}$, I get an error stating * _"Warning: scaled local spatial error estimate of 17.41130212282342`at t = 500.` in the direction of independent variable r is much greater than the prescribed error tolerance. Grid spacing with 25 points may be too large to achieve the desired accuracy or precision. A singularity may have formed or a smaller grid spacing can be specified using the MaxStepSize or MinPoints method options"_ I wonder if this is because the condition is unrealistic (ie: all the oxygen would be consumed by the point and is couldn't be a true boundary) or something more subtle I'm missing?


title: Symbolic Jacobian computation

text: I have an equation for which I would like to compute the Jacobian symbolically. $$f(x)=Ax-diag(x)(Ax+b)$$, where $x\in \mathbb{R}^n$, $A\in \mathbb{R}^{n\times n}$ and $b\in \mathbb{R}^n$. I am new to Mathematica, and I have seen this relevant question, but I am not aware of how to automatically ensure Mathematica recognises the different dimensions. Can someone help me how to code that in Mathematica?


title: Can Button[] generate output without using Print[]?

text: `Button[]` beguiles me. A simple example follows:               b1 = Button["Evaluate", Cos[Pi/6], Method -> "Queued"]     b2 = Button["Evaluate", Print[Cos[Pi/6]], Method -> "Queued"]      Both of the above statements produce buttons. When one clicks on `b1`, it appears to evaluate something, but does not output or display anything. Clicking on `b2` displays the expected output. But clicking a second time on `b2` prints the expected result a second time. Continuing to click on `b2` just increases the list of printed results. This uselessly clutters the notebook I want to distribute. I want a `Button[]` to execute a function and simply display its results as near as possible to what pressing **`Shift + Return`** in an input cell would do. I further want it to overwrite previous output. Ideally I would place the `Button[]` expression in a hidden initialization cell so only the actual button appears in the deployed notebook. Does anyway exist to get a Button to do what I've described? How?


title: Nested list to graph

text: The following nested list can be regarded as a representation of a (tree) graph:               li = {"fig", {"date", {"kumquat"}, {"papaya", {"peach"}, {"apple"}}},                  {"mango", {"orange", {"pear"}, {"avocado"}}},                   {"banana"}}      In the above, a string is a node in the tree, and any lists that follow it are subtrees rooted at that node. What are some of the ways by which this can be converted into a graph (or more concretely, a list of `DirectedEdge`s)? I've come up with one way, listed below. But I wanted to learn about other interesting approaches - for instance, pattern replacements might be used? This is what I came up with:               h[{str_String}] := Sequence[];     h[{str_String, ls__List}] := {DirectedEdge[str, #[[1]]], h@#} & /@ {ls};          edges = Flatten@h@li          (*      {"fig" \[DirectedEdge] "date", "date" \[DirectedEdge] "kumquat",       "date" \[DirectedEdge] "papaya", "papaya" \[DirectedEdge] "peach",       "papaya" \[DirectedEdge] "apple", "fig" \[DirectedEdge] "mango",       "mango" \[DirectedEdge] "orange", "orange" \[DirectedEdge] "pear",       "orange" \[DirectedEdge] "avocado", "fig" \[DirectedEdge] "banana"}     *)          TreePlot[Rule @@@ edges, Automatic, "fig", DirectedEdges -> True,       VertexLabeling -> True]      ![Don't you wish this were an actual tree?](http://i.stack.imgur.com/qF7wN.png)


title: Mma 10: Half the parallel power (Macs)?

text: Here is a comparison of the parallel kernels launched under _Mathematica_ under v9 and v10, on the same identical current 2014 R2-D2 Mac Pro ... [ Update: Valerio has commented that the same issue arises on the Macbook Air.] # Under v9.01               $ProcessorCount       > 12 Issuing:                LaunchKernels[]      ... launches 12 kernels, and actually uses them ... notice that the `ParallelTable` is 12 times the speed of `Table[]` for this construct:               In[5]:= Table[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[5]= {12.003106, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}}               In[6]:= ParallelTable[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[6]= {1.010648, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}} So, to perform the same operation, the parallel result under v9 is 12 times the speed of the single kernel result. # Under v10 -- half my potential processing power has gone               $ProcessorCount      > 6 ... down from 12 - even though I am running on the identical machine. Now, I know that my Mac Pro actually has 6 processors, and each runs 2 threads ... and under v9, that yielded 12 processor kernels for Mma 9 ... but under v10, it is only yielding 6 kernels ... ON THE SAME MACHINE. And this has real effects ... it effectively reduces by 50% the maximum potential power of my Mac:                LaunchKernels[]      ... launches 6 kernels (not 12 kernels as under v9). Compare the performance:                In[3]:= ParallelTable[Pause[1]; f[i], {i, 12}] // AbsoluteTiming      > Out[3]= {2.009933, {f[1], f[2], f[3], f[4], f[5], f[6], f[7], f[8], f[9], > f[10], f[11], f[12]}} So, under the new v10, I am getting half the parallel performance here and half the kernels that I got under v9. Even more perplexing is that this worked fine in an earlier pre-release version of v10. I am very confused. Anyone have any ideas how I can get my missing kernels back? Or why a decision may have been made to hobble the performance of the Mac Pro under v10? # Addendum Just noticed that if I go to:   * `Evaluation Menu -> Parallel Kernel Configuration` ... the automatic setting for:   * `Number of kernels to use: is set to: Automatic` (which Mma sets to 6) If I change this to:   * `Manual setting` and set it to 12 ... then it seems to use 12. But I am still confused as to why, if _Mathematica_ 10 can actually support 12 kernels on the machine, ... why would Wolfram set it to use only half of them by default, when v9 supported all of them by default? # Reply to Szabolcs: real-world test Szabolcs suggests below that _Mathematica_ may not practically use more kernels than physical cores, even if your processor supports virtual cores ... so there is no real difference. In reply, here is a quick timing test of a real-world application (kernel density estimation) from the _mathStatica_ benchmarking test suite. The task is to plot 12 kernel density estimates, corresponding to 12 different bandwidths.               bandwidths = {.2, .35, .45, .55, .65, 1, 1.5, 2, 2.2, 2.5, 3, 3.2};      ![](http://www.tri.org.au/se/kerneldensitytiming.png) Here are the results running under:   * v9 (default: 12 kernels): 3.38 seconds   * v10 (default: 6 kernels): 9.53 seconds   * v10 (manual overide to 12 kernels): 7.46 seconds I don't know what has changed to cause such a performance hit under v10 ... but even so, that is not the point. The point is that the v10 default kernel setting fails to take advantage of the power of the Mac Pro ... and results in worse performance in a typical parallel-processing application. # More extensive real-world test: _Update: 1 August 2014_ I have now had the opportunity to run the full _mathStatica_ (primarily symbolic) benchmark suite under both:   * the default v10 parallel setting (6 kernels)   * the manual override v10 setting (12 kernels) Here are the results: ![](http://www.tri.org.au/se/v10with6versus12kernels.png) The results fall into 2 categories:   * _For problems that have more than 6 separate components to them_ : ... For such problems, using 12 kernels is ALWAYS unambiguously faster, and significantly so.    * _For problems that have 6 or less separate components_ : ...For instance, Examples 7 and 9 can only be broken down into 2 symbolic components, so the benefits of parallelism max out with 2 kernels. In these cases, the 6 automatic kernels case is sometimes marginally faster than the 12 kernel case (presumably due to running overheads etc) ... but the difference is tiny, and essentially unnoticeable. **In summary:** for problems that CAN benefit from more than 6 kernels, the default Mma 10 (automatic) setting of 6 kernels on a Mac Pro appears to be sub-optimal, and fails to take advantage of the full capability of the machine. This problem is new to v10, and does not occur under v9.


title: How do you multiply out integer powers in a symbolic expression?

text: I have the following problem: I want to transform integer powers into a series of multiplications within symbolic expressions. E.g. `x^3` should be written as `x*x*x`. I tried applying the rule `a_^b_ -> a a^b-1` with a `ReplaceRepeated`, but Mathematica "simplifies" this again to `x^3`. Any suggestions?


title: Mathematica equivalent of regex '\w{2,3}'

text: It beats me to write the Mathematica pattern equivalent to the regex:               \w{2,3}      Any ideas?


title: How to present a Graphic and a Table in close proximity to each other

text: Often, with a `Plot` or within `Manipulate` I want to display a graph and, in close proximity to it, a table showing the results of relevant computations. The quickest way to do this is with `GraphicsColumn`, but that always seems to create cells of identical height and width, which is usually not what I want. Here is a trivial example:               Manipulate[      GraphicsColumn[{Plot[Sin[x + c], {x, 0, 2*Pi}],         TableForm[{{c}}, TableHeadings -> {{"c"}, {"value"}}]}], {c, 0, 3}]      ![GraphicsColumn makes me sad](http://i.stack.imgur.com/Tgeha.jpg) Is there some other convenient way to place the table below the graph without an ocean of whitespace, or a way to specify that GraphicsColumn can use cells of differing size?


title: Q-Multinomial Coefficient

text: How can one compute the q-Multinomial Coefficient as a function of q,m and a list {n1,n2,n3,...} in Mathematica? See http://mathworld.wolfram.com/q-MultinomialCoefficient.html for the definition.


title: How to evaluate the sum over a hyperplane

text: I have difficulties in evaluating the following expression: $$\sum_{\small n_1+...+n_{k}=m-k}\; \prod_{i=1}^{k}\frac{1}{(n_i+1)(n_i+2)}$$ I have tried the function `RootSum`, but it doesn't work and gives the following warning:               RootSum[Sum[Subscript[n, j], {j, 1, k}] - m + k,                  Product[1/((Subscript[n, i] + 2) (Subscript[n, i] + 1)), {i, 1, k}]]       > "RootSum::pfn - m + k + $\sum\limits_{j=1}^{k} n_j$ is not a pure function". I will really appreciate it if someone could give me some hints. Thanks!


title: How can locators be added to the points on a 3D grid?

text: Here is a pared down example of some 3D data that I want to make dynamic and add locators to each set of points. Is that possible?               dimension1 = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},                   {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},                   {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},                   {5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5},                   {6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6},                   {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7},                   {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},                   {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},                   {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}};          dimension2 = {{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},                   {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}};          dimension3 = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10},                   {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}};          firstDimension = ListPlot3D[dimension1, BoxRatios -> {1, 1, 1},        PlotStyle -> {Cyan, Opacity[0.2]}, Background -> White];          secondDimension = ListPlot3D[dimension2, BoxRatios -> {1, 1, 1},        PlotStyle -> {Magenta, Opacity[0.2]}, Background -> White];          thirdDimension = ListPlot3D[dimension3, BoxRatios -> {1, 1, 1},        PlotStyle -> {Yellow, Opacity[0.2]}, Background -> White];          Show[firstDimension, secondDimension, thirdDimension]      ![Mathematica graphics](http://i.stack.imgur.com/Vq0Yd.png) The locators should move the points on the grid, and affect the other surrounding points depending on a variable.


title: How can I set constraints on parameters in NelderMeadMinimize package?

text: I read about NelderMeadMinimize package. How can I set constraints on the parameters? For example I want to minimize an equation with $10$ parameters such as ${a_1, a_2, ....}$. I want to put the condition $a_1 > 0$. How can I do that? **EDIT 1:** As an example I have $10$ equations and $10$ unknown parameters which I want to find them by minimizing `problem1`:               problem1 = (-30 + A3/A1)^2 + (4 e3a α1 α3 + 2 d2 β1)^2        + (-2 A3 - 2 c2 α3 + 4 c4a α3^3 + 8 e3a α1 β1)^2 + (4 e3a α1^2 + 2 d2 β3)^2        + (-3.13995 - 2 c2 + 2 d2 + 12 c4a α1^2 - 4 e3a β3)^2        + (-1.49499 - 2 c2 + 2 d2 + 4 c4a α1^2 + 4 e3a β3)^2        + (-2.10157 - 4 c2 d2 + 24 c4a d2 α1^2 - 16 e3a^2 α3^2 - 8 d2 e3a β3)^2        + (-0.0277073 - 4 c2 d2 + 8 c4a d2 α1^2 - 16 e3a^2 α3^2 + 8 d2 e3a β3)^2        + (-2 A1 - 2 c2 α1 + 4 c4a α1^3 + 4 e3a α3 β1 + 4 e3a α1 β3)^2        + (0.00429025 α1^2)/((β1 Sqrt[1 - (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)/Sqrt[ 64               e3a^2 α3^2 + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)^2]])/(Sqrt[2] α1)        + Sqrt[1 + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)/Sqrt[64 e3a^2 α3^2                             + (2 c2 + 2 d2 - 4 c4a α1^2 - 4 e3a β3)^2]]/Sqrt[2])^2;                  parameters1 = {c2, d2, e3a, c4a, α1, α3, β1, β3, A1, A3};              function1 = Function @@ {parameters1, problem1};              minimizer =        With[{nelderMead = NelderMeadMinimize`Dump`CompiledNelderMead[function1, parameters1],              bounds = {-1, 1}, dimension = Length[parameters1],              tolerance = Sqrt[$MachineEpsilon]},                   Compile[{{dummy, _Integer, 0}},                 nelderMead[RandomReal[bounds, {dimension + 1, dimension}], tolerance, -1],                 CompilationOptions -> {"ExpressionOptimization" -> True,                                        "InlineCompiledFunctions" -> True},                 RuntimeOptions -> {"CompareWithTolerance" -> False,                                    "EvaluateSymbolically" -> False},                 RuntimeAttributes -> Listable(*"Parallelization"->True*),                 CompilationTarget -> "C"]];                   ans = {First[#], Thread[parameters1 -> Rest[#]]} & /@                      Take[minimizer@Range[3000] // Sort, 10]           I know that $\alpha_1$, $\alpha_3$, $\beta_1$, $\beta_3$, $A_1$, and $A_3$ should be positive. How can I put these constraints on these parameters when applying NelderMead minimization? Is it possible? **EDIT 2** First one should download the package and also needs to run:               Needs["CCompilerDriver`"]


title: Position of First nonzero number

text: I want to know is there any one line code to find position of first nonzero number without calculating position of all non zero numbers. For example,               A = {0, 0, 0, 1, -2, -1, 0};     First[Flatten[Position[A, _?(# != 0 &)], 1]]      will give me position of first non zero number. But first it calculate position of all non zero number. Is there any way to stop position function when it found first non zero number?


title: How to parallel the computation tasks according to machines instead of kernels

text: On a HPC, there are many computation nodes, each node corresponds to an independent machine. Every node has several cores, for example 8 per node. _Mathematica_ can launch remote kernels on different nodes (see method here). After all the kernels were launched, _Mathematica_ seems to regard all the kernels as the same thing. We can use `ParallelMap` and different options `"FinestGrained"` or `"CoarsestGrained"` to distribute computation tasks to different kernels regardless of which node a kernel belongs to. But I am in a case where I want to distribute my computation task according to machines instead of kernels, because my computation involves matrix eigenvalues. When the matrix is large, the memory usage is considerable while each node has limited memory resources. So I can not parallelize the computation to `"FinestGrained"` to kernels, as that will exhaust the memory and probably would cause the node to break down. One way to solve this is to launch a limited number of kernels on each node, for example, only launch one kernel per node, and the one kernel on each node won't eat up all the memory. But in this way, I will lose the **multi-thread feature** of `Eigenvalues` computation (see here), because memory usage is determined by the dimension of the matrix. Using 1 core or 8 cores to compute the same matrix needs the same amount of memory, but obviously 8 cores will be faster. So if I launch only one kernel on each node I am wasting the remaining 7 cores on each node. So here is the question. **How to distribute the computation tasks according to machines instead of kernels, and preserve multi-thread feature of built-in functions**? I mean to create a new option `"FinestGrainedToNodes"` which will distribute computation tasks evenly to different node.


title: How do I make the color of arrowheads in a graph different from the colors of the arrows?

text: I'm graphing a Markov process               mp = DiscreteMarkovProcess[{1, 0, 0}, ({          {0.6, 0.1, 0.3},          {0.2, 0.7, 0.1},          {0.3, 0.3, 0.4}         })];      and would like to have arrows whose thicknesses corresponds to the transition probabilities, with arrowheads of a different color in the exact center of each edge. But all my attempts end up a mess.               g = Graph[mp];     Scan[(PropertyValue[{g, #}, EdgeLabels] =           PropertyValue[{g, #}, "Probability"]) &, EdgeList[g]];     Scan[(PropertyValue[{g, #}, EdgeStyle] =          Directive[Arrowheads[{{.045, .575}}], GrayLevel[.7],            Thickness[PropertyValue[{g, #}, "Probability"]/20]]) &,        EdgeList[g]];     g      ![](http://i.stack.imgur.com/wdQaA.png) ![enter image description here][1] The thick edges leave gaps between their ends and the nodes of the graph, and I can't figure out how to change the color of the arrow heads so that they stand out against the color of the edges. How can I change the color of the arrowheads in my figure. How can I avoid the gaps that appear between nodes and the ends of the edges?


title: How to fix Ticks in Gauges?

text: Ticks is an option for Gauges. I fail, however, to apply custom Ticks to Gauges. For instance, compare these two:                {ThermometerGauge[50, {0, 100}, Ticks -> Automatic],       ThermometerGauge[50, {0, 100}, Ticks -> {0, 50, 100}]}      What you see is this: ![enter image description here](http://i.stack.imgur.com/D2vDP.jpg) _No difference!_ I also tried with the Horizontal- and VerticalGauge with the same success. _Do you know a workaround?_ EDIT 11.07.13: I have seen the answers to my question. They all are good and fascinating, and in another case I will certainly use them. They do not answer my question though. For this reason I would like to give some more explanation of what I am really after. I will give it within an example of a different problem, where it is easy to obtain such a result. So let us consider two simple plots. First is this               Plot[x, {x, -0.3, 0.3}, ImageSize -> 250]      second is this:                Plot[x, {x, -0.3, 0.3}, Ticks -> {{0, 3/16, 1/4}, Automatic},       ImageSize -> 250]      ![enter image description here](http://i.stack.imgur.com/VBURg.jpg) Here you can see it. The y axis in both plots is automatic - do not look at it. The x axis of the first plot is automatic for comparison, while the x axis of the second plot is what I am after. I would like to achieve the same on the ThermometerGauge, if possible by easy means. The easy means are here important, since looking at programs below I feel that it is easier to draw such a Gauge from scratch. For example, like this:                 thermo[x_] := Show[{        Graphics3D[{Text[Style["-0.3", 12], {-0.15, 0, -0.3}],           Text[Style["0", 12], {-0.15, 0, 0}],          Text[Style["3/16", 12], {0.14, 0, 3/16}] ,           Text[Style["1/4", 12], {0.15, 0, 0.25}] ,           Text[Style["0.3", 12], {-0.13, 0, 0.3}]},          ViewPoint -> {0, -1.5, 0}, Boxed -> False,          ImageSize -> {120, 300}],        Graphics3D[{LightBlue, Specularity[White, 20], Opacity[0.5],           Sphere[{0, 0, -0.4}, 0.11]}],        Graphics3D[{Red, Specularity[White, 20],           Sphere[{0, 0, -0.4}, 0.1]}],        Graphics3D[{LightBlue, Opacity[0.5],           Tube[{{0, 0, -0.4}, {0, 0, 0.35}}, 0.05]}],        Graphics3D[{Red, Specularity[White, 20],           Cylinder[{{0, 0, -0.45}, {0, 0, x}}, 0.04]}],             Graphics3D[{Thickness[0.015],           Line[{{-0.07, 0, #}, {-0.09, 0, #}}] & /@            Table[i, {i, -0.3, 0.3, 0.1}]}],        Graphics3D[{Red, Thickness[0.015],           Arrow[{{0.09, 0, 3/16}, {0.03, 0, 3/16}}],           Arrow[{{0.09, 0, 0.25}, {0.03, 0, 0.25}}]}]        }]      Try it:               Manipulate[      thermo[x], {{x, 0}, -0.3, 0.3}]      It looks as shown here: ![enter image description here](http://i.stack.imgur.com/2MjjY.jpg)


title: Computing derivatives of a moment generating function

text: Dear Mathematica users, I'm trying to compute higher order derivatives of a moment generating function and then evalutate them in 0 (in order to get some moment conditions for a GMM estimation). Although I try to declare constants at the beginning of my script, which follows:               % Declaring constants         Constants -> {kappa, theta, sigma, gamma, b, dt, Uy, J, phi, lambda}          %     A[Uv_] = (-(kappa *theta)/(sigma^2))*((gamma + b)*dt +        2*Log[1 - ((gamma + b + (sigma^(2))*Uv)/(2*gamma))*(1 -              exp[-gamma*dt])]) + (exp[Uy*J] - 1 - Uy*phi*J)*lambda*dt;          %     B[Uv_] = -(a*(1 - exp[-gamma*dt]) -        Uv*(2*gamma - (gamma - b)*(1 - exp[-gamma*dt])))/(2*       gamma - (gamma + b)*(1 - exp[-gamma*dt]) -       Uv*(sigma^(2))*(1 - exp[-gamma*dt]));          % My moment generating function     EVPsi[Uv_] = exp[A[Uv]]*(1 - B[Uv]/omega)^(-v)      My problem is due to the fact that when I compute the first order derivative by using               EVPsi'[Uv] /. Uv -> 0      I get the following expression               % First derivative of the mgf evalueated in Uv=0     -v (1 + (a (1 - exp[-dt gamma]))/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))))^(-1 -       v) (-((2 gamma - (-b + gamma) (1 - exp[-dt gamma]))/(      omega (2 gamma - (b + gamma) (1 - exp[-dt gamma])))) + (     a sigma^2 (1 - exp[-dt gamma])^2)/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))^2)) exp[     dt lambda (-1 - J phi Uy + exp[J Uy]) - (     kappa theta (dt (b + gamma) +         2 Log[1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)]))/     sigma^2] + (     kappa theta (1 + (a (1 - exp[-dt gamma]))/(     omega (2 gamma - (b + gamma) (1 - exp[-dt gamma]))))^-v (1 -      exp[-dt gamma]) Derivative[1][exp][     dt lambda (-1 - J phi Uy + exp[J Uy]) - (     kappa theta (dt (b + gamma) +         2 Log[1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)]))/     sigma^2])/(     gamma (1 - ((b + gamma) (1 - exp[-dt gamma]))/(2 gamma)))      What I'm missing here is why I get in the last lines an expression such as               Derivative[1][exp][product of constants!!]      instead of a 0. I would be thankful if you could shed some light on this. Thank you.


title: Extracting RHS from Rule

text: In an example from another question, the rhs of a list of rules can be simply extracted:               In[1]:= rules1 = Solve[x + y == 3 && x - y == 6, {x, y}][[1]]                        9         3     Out[1]= {x -> -, y -> -(-)}                   2         2          In[2]:= rules1 /. Rule -> (#2 & )                    9    3      Out[2]= {-, -(-)}               2    2      However, when I try the same replacement with a list of rules where the RHS is a pure function, it does not result in a list of the RHS.               In[3]:= rules2 = {MySum -> Total[#1] & , MyProd -> Times[#1] & }          Out[3]= {MySum -> Total[#1] & , MyProd -> Times[#1] & }          In[4]:= rules2 /. Rule -> (#2 & )          Out[4]= {(#2 & )[MySum, Total[#1]] & , (#2 & )[MyProd, Times[#1]] & }      How do I correct this?


title: Multiple instrument chord

text: I would like to create a chord using multiple instruments. This started as an attempt to explain music to a friend but my curiosity has taken over. I am familiar with the SoundNote function. I know that SoundNote can create a chord using the same instrument:               Sound[SoundNote[{"C4", "G3"}, 1, "Harpsichord"]]      And it can create a series of notes with different respective instruments:               Sound[{SoundNote["C", 0.5`, "Oboe"], SoundNote["G", 0.5`, "SynthVoice"], SoundNote["C5", 0.5`, "Organ"]}]      What I'm wondering is if there is a way to play more than one sound with specific notes at the same time.


title: Using a compiled function inside NIntegrate gives "CompiledFunction::cfsa" message

text: The following function is defined for Real input:               FFc = Compile[{{x, _Real}, {EF, _Real}},If[x > EF, 0., If[x == EF, 0.5, 1.]]]      FFc is now used in the function called foo:               EBoundary = 6.5;     foo[Ef_?NumericQ] := NIntegrate[FFc[x, Ef] , {x, -EBoundary, EBoundary}]      When I call foo like               foo[3.2]      I get an error message:               CompiledFunction::cfsa: "Argument x at position 1 should be a \!\(\"machine-size real number\"\)."      Since I'm using real numbers I have no idea why I get this message. What is the problem? Is it, because If[] can return 0?


title: PrintTemporary in ParallelTable

text: I thought of a possible answer to Monitor doesn't work with ParallelTable but it doesn't work as I hoped it would. This accumulates print cells instead of deleting them as intended. Can it be fixed?               ParallelTable[       NotebookDelete[x]; x = PrintTemporary[i];       Pause[1]; i,       {i, 1, 15}     ]      I thought that `x` would be local to each kernel, and this would print four cells (for four cores) that would be deleted and replaced with each iteration. I then thought that the value of `x` was lost between iterations, but this also fails to delete the print cells:               ParallelTable[       x = PrintTemporary[i]; NotebookDelete[x];       Pause[1]; i,       {i, 1, 15}     ]


title: Plotting a floor function with endpoints?

text: Would someone mind showing me how to plot a floor function with the appropriate endpoints? I tried Google, but the best I could find was something posted from 2004 that no longer appears to work. Sorry if this is overly basic, I've only got a couple of weeks of experience with Mathematica and no one to work with on it. Edit: I'm looking to create a graph similar to the one shown on the wiki page for floor/ceiling functions. I'm not too concerned with the frame or the tick marks.


title: Prevent Cell Deletion

text: How might I be able to prevent a `Cell` form being deleted when you press the Delete key? Maybe there is a way to display some type of `Dialog` when you attempt to delete(or cut) a cell?


title: How to add FindDivisions to the plot commands?

text: I used these instructions to make a legend bar next to my plot (I can't comment there) But I'm lost to where and how can I add FindDivisions to the DensityPlot under "Edit: illustrating additional options"?               {densityPlot, densityColors, densityRange} =        reportColorRange[        ListStreamDensityPlot[data, VectorScale -> Small,          DataRange -> {{0, 2 Pi}, {-0.5, 0.5}},          ColorFunction -> ColorData["Rainbow"]]];           With[{plotWidth = .85, aspectRatio = .9},       density =       display[{densityPlot // at[{0, 0}, plotWidth],        colorLegend[densityColors, densityRange, LabelStyle -> LightGray,         FrameStyle -> Orange, "ColorBarFrameStyle" -> LightGray,         Background -> Darker@Darker@Darker@Blue, "ColorSwathes" -> None,        Contours -> 10, RoundingRadius -> 0, BoxFrame -> 3,         "Digits" -> 2] //        at[{plotWidth, 0}, {1 - plotWidth, plotWidth/aspectRatio}]},        AspectRatio -> aspectRatio, ImageSize -> 400]]      Also how can I add another plot to the existing one? I would need to draw a sinusoid on it. Show command ruins it. It's obvious where sinusoid should be. This is my plot: ![](http://i.stack.imgur.com/sICZ2.jpg) I would like my numbers in a bar legend rounded. Thanks in advance. P.S. Just in case you need data I used for my plot.               a = 0.05     z = -1     data =      Table[With[{x = 0 + 2 Pi/5 (i - 1),        y = -0.5 + 0.2 (j - 1)}, {{NIntegrate[        a*z*Cos[t]/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -            3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[               t]) a), {t, -Infinity, Infinity},        Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,          Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,        MaxRecursion -> 20],       NIntegrate[-z/((t^2 - 2 t x + x^2 + y^2 + z^2)^(3/2) -           3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[              t]) a), {t, -Infinity, Infinity},        Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,          Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,        MaxRecursion -> 20]},       NIntegrate[(y +          a*(t*Cos[t] - x*Cos[t] - Sin[t]))/((t^2 - 2 t x + x^2 + y^2 +             z^2)^(3/2) -          3 (y Sqrt[t^2 - 2 t x + x^2 + y^2 + z^2] Sin[             t]) a), {t, -Infinity, Infinity},       Method -> {"GlobalAdaptive", "MaxErrorIncreases" -> 800,         Method -> "GaussKronrodRule"}, AccuracyGoal -> 20,       MaxRecursion -> 40]}], {i, 1, 6}, {j, 1, 6}]


title: Is there a way to hide or toggle the visibility of code?

text: Many of my notebooks have a similar repeating structure, which is very convenient and reliable for my workflow: a chunk of code defining a `Manipulate` for exploring some phenomenon, the output of the `Manipulate`, where the phenomenon can be explored, and then some notes or observations about the phenomenon. When I'm focused on coding, this is fine, but as my focus shifts to the phenomenon itself, the code is distracting and takes up a lot of space, so I'd like to be able to hide or collapse it. Is there a way to hide or toggle the visibility of code, independently of the results it produces? In effect, what I'm seeking is there _reverse_ of the default behavior, in which code and results that are grouped together can be collapsed to show just the code. Note that I'm not seeking a way to move the code elsewhere: the point is the be able to easily move back and forth between having the code behind some data or visualization visible, and associated with the output, and having it hidden or collapsed.


title: Organizing similar datasets using DownValues instead of Contexts

text: In his answer to this question, Leonid helped me find a way to programmatically generate contexts for holding sets of symbols with the same names. Perhaps a simpler way is to use `DownValues` so:               dataRaw["Paris"] = Import["Paris.csv"];     data["Paris"] = Differences[dataRaw["Paris"]];     dataMax["Paris"] = Max[dataRaw["Paris"]];          dataRaw["Madrid"] = Import["Madrid.csv"];     data["Madrid"] = Differences[dataRaw["Madrid"]];     dataMax["Madrid"] = Max[dataRaw["Madrid"]];      lets me make a plot using               ListLinePlot[data /@ {"Paris", "Madrid"}]      and can be implemented with a simple function               importCity[cityName_String] := (         dataRaw[cityName] = Import[cityName ~~ ".csv"];         data[cityName] = Differences[dataRaw[cityName]];         dataMax[cityName] = Max[dataRaw[cityName]];     )      Other than cluttering everything with a lot of `[cityName]`, are there hidden perils to using `DownValues` in this way? Is there some disadvantage to storing every `dataRaw` as `DownValues` of the same symbol instead of individually in multiple contexts?


title: Ubuntu 12.10 no window focus on help browser

text: The help browser is not getting window focus when clicked on it. Clicking links or buttons in the help browser works without window focus, but copying code or typing in it doesn't. I can get window focus on the help browser by using the alt+tab or the Window menu. I'm running Mathematica 8.0.4.0 on Ubuntu 12.10. Mathematica is the only software that has this behavior, that's why i post this question here. Has anyone else experienced this behavior or know a solution to it? edit: switching focus between notebooks behaves normally.


title: CDF and MediaWiki

text: Recently there was a handful of CDF embedding-related topics. However I would like to ask whether anyone has succeeded in embedding CDF into MediaWiki page? I've attempted to do so with the Widget extension but it fails to load fully. Is there any way to fix this?


title: Tool to locate bloat in a notebook?

text: In developing a notebook, I often find I have created a very boated file that takes a long time to save. I would like to slim it down. It is usually the result of graphics and images, but they may be hidden deep in the hierarchy of the notebook. Finding the wasted space is a pain. A very useful tool would be something that graphically indicated (perhaps in the cell marker) the number of bytes (or similar) that are within a cell. Anyone know of such a thing, or have a pointer on how to create?


title: Light Weight Grid and core limitation

text: I am trying to figure out what would be best for running some simulations using multiple computers where **each has it's own mma 8 licence**. The main part of the computation involves a parallelized table which runs the algorithm for different values. The computers are :   * intel i7 quad core PC   * intel core duo laptop (from where I will be controlling the PC) Looking around I found two basic options :   * using ssh on Mathematica to run parallel computations   * using remote desktop to control the PC I am leaning towards the second for two main reasons. First, I assume that I can only use a total of 4 cores in the whole grid given the home licensing (am I wrong or does this only apply to a single license for the whole grid). Given this limitation, if I use remote desktop, I can run two simulations. This would allow me to fully benefit from the quad core PC, while still running stuff on my laptop or even work on some more code. Is my thinking flawed? Did I miss something in the ssh options/licencing limitations that would make me lean more towards this option? ## EDIT : So it turns out that with multiple licences you can have more than 4 kernels running. Quoting Jagra : > each license will typically grant access to a minimum of 4 parallel kernels > + a control kernel So in my case, I would have 4 kernels on the quad core and 2 on my core duo, plus one control kernel. So I could really see the benefits of running the Grid for parallel kernels, even though I would only be able to use one instance of Mathematica, and not work on code while the algorithm is running. The positive side of LW Grid, as Jagra pointed out, is that you don't need to be sending input/output files between the remote PC and your control PC which can be very time and resource consuming if they are very large. ## EDIT 2: After contacting Wolfram support, they informed me that Trial licences also provide 4 kernels to the grid. (I was thinking of adding a PC which only has a trial licence for MMA9)


title: Can plot a function, NSolve takes too long

text: I'm new to Mathematica, so maybe mine is an easy to solve issue, but I haven't been able to figure it out. I have a series of linear ODEs I solve using for:               sol = ConstantArray[0, 1];     For[i = 2, i < 20, i++,           sol = Append[sol,                  First[y[t] /.                  DSolve[{y''[t] == -121/150*y'[t] - 1/10*y[t] -                       3 + (2/3)*D[sol[[i - 1]], t] + 1/10*sol[[i - 1]],                       y'[0] == 25, y''[0] == 0}, y, t]]]]      It runs fast and fine (takes a couple of seconds). I get the first derivative of every solution:               vels = D[sol, t];      Again, everything OK... Then I plot all of them:               Plot[vels, {t, 0, 80}]      ![plot of vels](http://i.stack.imgur.com/Odo0c.png) Pretty fast. I want to know the value of t for which each solution crosses a numeric boundary:               For[i = 2, i < 15, i++,       t10 = AppendTo[t10,         First[t /. NSolve[{vels[[i]] == 10, t < 40, t > 5}, t]]]]      It takes like a second or two for, say, the first 8 terms, but the 9th won't end after like an hour. It's funny because I can 'see' the result, and with a zoom large enough I could estimate the value by myself from the plot. Am I missing something important? Does it have anything to do with the methods used? Do I have to use some other command? Thanks in advance.


title: Build a refined grid based on intersecting line

text: I honestly have no idea where to begin with this problem. In summary, I have a 2D coarse grid with an intersecting line. For an easy example, let's assume it's a 4x4 grid. ![Coarse Grid with intersect.](http://i.stack.imgur.com/nOJ7L.png) I wish to pass through each grid block multiple times and subsequently divide each grid block in half that either has the line passing through it (or possibly through one of its vertices). ![1st pass](http://i.stack.imgur.com/UKWAk.png) ![3rd pass](http://i.stack.imgur.com/zrkKl.png) ![4th pass](http://i.stack.imgur.com/Mz2AE.png) ...etc. After a set number of passes, I want to assign a property to each grid block that is intersected. (example, set color to blue). ![Assign properties](http://i.stack.imgur.com/9qWON.png) The only requirement is the algorithm provide the final set of refined grid blocks have at least one shared side until the termination points. The final output would be a list of vertices and their cartesian coordinates. Thanks in advance. **UPDATE:** The grid blocks (which will eventually total in the millions) will have CPU intensive calculations performed on them. So the ideal solution will only refine the grid block size close to the line while leaving the areas away from the line in their "coarse" state.


title: Excel Headers --> Mathematica

text: I have a large Excel .xls file. Miniature version shown below: (formatting should appear as two columns...)               Test1   Test2     75        64     58        85     81        55     64        63     70        94     88        90     78        96     96        98     54        97     75        61      I would like to do some statistical analysis on the file in Mathematica 8.0.4. Additionally I am using Mathematica Link for Excel 3.5. The issue I'm now attempting to address concerns the "headers," or "column labels." I need to tell Mathematica to disregard the headers. I want to use each respective header, however, as the name for the "variable stream" (Mathematica-speak for each column of data.) What might be the best ways of dealing with such headers? ===== Additional edit: The "one-liner" version seems to work just fine. Thank you Vitaliy. Follow-up Question: If the Excel .xls spreadsheet being imported is rather large -- 200 columns, 5000 rows -- will that present a problem with the Mathematica "one-liner" approach Vitaliy has suggested? i.e., memory inadequacy, inability to make subsequent steps? What I mean here is, is it completely okay to import an entire large Excel .xls all at once? Or is it far better to ONLY import "columns" as needed, that will immediately be used in subsequent Mathematica steps? I'd prefer to import all at once -- using Vitaliy's method -- if that's totally acceptable.


title: PDE Solving in mathematica

text: I'd like to ask how I might go about solving this equation: # $\frac{\partial Ci}{\partial t} + \frac{1}{r^2}\frac{\partial (r^2 Ci)}{\partial r} = D\frac{1}{r^2}\frac{\partial}{\partial r}(r^2\frac{\partial Ci}{\partial r})$ as suggested a simplification # $\frac{\partial Ci}{\partial t} + \frac{1}{r}2Ci +\frac{1}{r^2}\frac{\partial Ci}{\partial r} = D(\frac{2}{r}\frac{\partial Ci}{\partial r} +\frac{\partial^2 Ci}{\partial r^2})$ $r = 0, t = 0 \rightarrow Ci = 0$   $r = 1, t = 0 \rightarrow Ci = 0$ I am fairly new to Mathematica and I don't really know how to go about this; I've also tried the steps outlined in this post here but while I understood what to do I get recursion limit reached errors (using the code provided). Could you please help me out on how to solve this equation? a partial and first attempt on solving this taking in account the notes of the posted link is the following:               Clear[y];     f1[r_ /; r > 0] := 1;     f1[r_ /; r == 0] := 2;     f2[r_ /; r > 0] := 1/r^2;     f2[r_ /; r == 0] := 0;     f3[r_ /; r > 0] := 1/r;     f3[r_ /; r == 0] := 0;          eqns = {         Derivative[0, 0, 1][y][t, r, z] +         f3[r]*2*y[t, r, z] +       f2*Derivative[0, 1, 0][y][t, r, z] -       2*f3[r]*Derivative[0, 1, 0][y][t, r, z] -       Derivative[0, 2, 0][y][t, r, z] == Derivative[1, 0, 0][y][t, r, z],       y[t, 0, z] == 0,       y[t, r, 0] == 0,       Derivative[0, 1, 0][y][t, 0, z] == 0,       Derivative[0, 0, 1][y][t, r, 0] == 0,       y[0, r, z] == (1 - r^2)*(1 - z^2)}           $RecursionLimit = 1536           y[t_, r_, z_] =           y[t, r, z] /.                First[NDSolve[eqns, y[t, r, z], {t, 0, 1}, {r, 0, 1}, {z, 0, 1},                Method -> {"MethodOfLines", Method -> "StiffnessSwitching",                "DifferentiateBoundaryConditions" -> {True,                "ScaleFactor" -> 1}}]];      This gives me a lot of errors but the first one is the following: ![partial error output](http://i.stack.imgur.com/xZT5s.png)


title: The correct way to linearize colorspace before resizing, blurring etc

text: There was an interesting discussion on MathGroups dealing with the fact that image-processing functions in _Mathematica_ (and many other software, including Adobe Photoshop) work with RGB, Grayscale etc. intensity values as if they would be linear and additive while in fact these values are powers of the _physical_ intensity values and consequently must be linearized before making additive operations on them. This topic is expanded in the linked article where examples of incorrect default image resizing and blurring are given along with the general explanation of the correct algorithm and images generated with it. Matthias Odisio (Wolfram Research) replied: > This genuine issue will be properly addressed in a future release of > Mathematica. So, _Mathematica_ 9 is released. But I cannot find any example in the Documentation on how to linearize a colorspace correctly. Obviously, the linearization algorithm must depend on the colorspace used. The question is: is there efficient and straightforward way to linearize a colorspace in _Mathematica_ correctly? ## UPDATE Here is an excerpt from the documentation for Adobe After Effects which highlights some benefits of linear color space: > By performing operations in a linear color space, you can prevent certain > edge and halo artifacts, such as the fringing that appears when high- > contrast, saturated colors are blended together. Many color operations > benefit from working in a linear color space, including those operations > involved in image resampling, blending between layers with blending modes, > motion blur, and anti-aliasing. > > <...> > > _Note: A linearized working color space works best with higher color > depths—16 bpc and 32 bpc—and is not recommended for 8-bpc color._ Also, good explanation of the difference between linear RGB and sRGB color spaces can be found here.


title: A lot of matrix multiplication

text: So I have a set of 15 $4\times 4$ matrices which I call $X_i, (i=1,2..15)$ and a set of 6 $4\times 4$ matrices which I call $y_j, (j=1,2...6)$. Now I have to calculate $(X_i y_j)-(y_j X_i^*)$ for different values of $i$ and $j$, where $*$ stands for Complex conjugate. Is there a simple command (with perhaps loops) in mathematica using which I can calculate all the 90 results instead of multiplying these matrices individually 90 times?


title: Running out of memory when partitioning an image with ImagePartition

text: I have an `Image3D` object of image type _"Bit16"_ with the dimensions 1472 x 1472 x 1472 that I would like to split into small image cubes of dimension 64 x 64 x 64 which would give me a total of 23^3 = 12167 small `Image3D` objects. I want to apply an adaptive thresholding algorithm I already implemented which computes separate thresholds for each image block and then interpolates the computed threshold values (adaptive thresholding). For this purpose I use the function `ImagePartition`. The following code illustrates the partitioning:               croppped = ImageCrop[image, {1472, 1472, 1472}];     parts = ImagePartition[cropped, {64, 64, 64}];      I use `ImageCrop` to add a border to the original image which results in the mentioned `Image3D` object of dimensions 1472 x 1472 x 1472. If I try to run the partitioning my _Mathematica_ kernel crashes with an out of memory error. I have 96 GB RAM installed on my machine. I'm not sure, but the memory should be a sufficient amount of memory available to do the partitioning. What surprised me is that i can create multiple huge `Image3D` objects and the kernel doesn't crash, but when I partition an `Image3D`, using ImagePartition it does. See the following code for the memory usage when I create another `Image3D` object:               MemoryInUse[]     cropped2 = ImageCrop[image, {1472, 1472, 1472}];     MemoryInUse[]      > 14461079560 > > 20840097904 Questions:   1. Is there a simple explanation for this problem?   2. What would be a suitable workaround in order to perform the splitting? **Edit (08/01/2014)** First of all thanks very much UDB for this nice solution you posted. I now had the time to try out the function `MyImagePartition` on my data and here are the results I obtained so far. First, to get a feeling for the timings and memory usage I created the same test volume and partitioned it on my machine. I then checked whether the original volume can be assembled again to give the volume again.               volume = Image3D[RandomInteger[{0, 255}, {8, 9, 10}*64], "Byte"];     First@AbsoluteTiming[ip = ImagePartition[volume, {64, 64, 64}]]      > 10.899000               MaxMemoryUsed[]         First@AbsoluteTiming[mip = MyImagePartition[volume, {64, 64, 64}]]     MaxMemoryUsed[]      > 248907056 1.505000 542529936               Image3D[ImageAssemble@ip] == volume      > True               Image3D[ImageAssemble@mip] == volume      > True Then I tested the function `MyImagePartition` on a real image I have. In between the partitioning of the test volume and the real data i quit the kernel to get a fresh Mathematica session. Fortunately, the function is very fast in partitioning my data and memory consumption seems to be no issue. When reassembling it again I checked for the image dimensions of the assembled image.               ImageDimensions@testImage      > {458, 403, 202}               MaxMemoryUsed[]     First@AbsoluteTiming[mip = MyImagePartition[testImage, {64, 64, 64}]]     MaxMemoryUsed[]      > 249027112 0.278000 542635024               ImageDimensions@Image3D[ImageAssemble@mip]      > {448, 384, 192} Obviously the dimensions of the reassembled image do not match the original image dimensions. I have to admit that I didn't fully understand the usage of the second parameter 'dwdh'. Is it the option for image padding such that the image matches up with the partitioning block size? I tried several options but failed continuously ;) Besides that issue, would it be possible to add the functionality to create an overlapping partitioning of the image (e.g. give the overlap of the blocks in voxels as an additional parameter). With the built-in function `ImagePartition` this works quite good as follows:               parts = ImagePartition[spheroid3d, {64, 64, 64}, {60, 60, 60},         Padding -> 0];


title: Color of a plane in Contourplot3D

text: I have the following code example:               cylinder = ContourPlot3D[y^2 + z^2 == 32, {x, 0, 5}, {y, -6, 6}, {z, -8, 8},                               Mesh -> 1, ContourStyle -> FaceForm[{White, Red}, Opacity[0.0]],                               AxesLabel -> {"x", "y", "z"}];     areaR = ContourPlot3D[{1, 0, 0}.({x, y, z} - {0, 1.5, 1.5}) == 0,                            {x, 0, 5}, {y, -6, 8}, {z, -6, 8},                            ContourStyle -> Directive[White], Mesh -> False];     Show[cylinder, areaR]      ![enter image description here](http://i.stack.imgur.com/69IX9.png) Can anyone tell me how I get the plane `areaR` to be `White`?


title: Manipulate and Turning Expressions into Functions

text: I've been trying to use Manipulate to do interactive plotting, but I've been running into a few problems with saved expressions. I have an expression saved as "func" and I want to work with it and then plot it later. But I can't seem to get it to work. For example, this works fine               Manipulate[Plot[Sin[a x + b], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      while this does not               func = Sin[a x + b];     Manipulate[Plot[func, {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      I assume that this has something to do with when expressions are evaluated and the difference between expressions and functions, but I'm new to Mathematica and and I'm not sure on on the difference between the two. I have tried other things like the following. For example, this works               Manipulate[Plot[Function[{a, b, x}, Sin[a x + b]][a, b, x], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      and this works               func2 = Function[{a, b, x}, Sin[a x + b]]     Manipulate[Plot[func2[a, b, x], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      but this does not               func = Sin[a x + b];         func2 = Function[{a, b, x}, func];     Manipulate[Plot[func2[a, b, x], {x, 0, 6}], {a, 1, 4}, {b, 0, 10}]      How could I fix this and why doesn't it work the way I have it written?


title: Computing the mean difference between elements in a list with index $i$ and the closest elements with index $(i+1)$

text: I have a list that looks like this:               preprocessedList = {{1,5.3},{1,5.566},{1,1.4322},{2,3.443543},{2,3.444},{3,0.1223},{4,1.3243},{4,1.554343}}      Each element in the list is of the form $(i,j_k)$, where $i = 1,2,3,...,N$ is an integer index (which may be degenerate, i.e. there may be multiple list entries with the same $i$ value), and $j_k$ is some value associated with each list item. I want to create a new list $L$ where, for each index starting with $i = 2$, we compute the median or mean of the difference between elements with the index $(i-1)$ and the nearest elements with index $i$ (in terms of one- dimensional Euclidean distance). Using the about example list: Starting with $i = 2$, we first take {1,5.3}, we compute that {2,3.444} is closest since the different between 3.444 and 5.3 is the minimum for all items with the index $i=2$. We compute this difference as $(3.444 - 5.3) = -1.856$. We then move on to {1,5.566}, notice again that {2,3.444} is closest to {1,5.3}, and compute this difference as $(3.444 - 5.566) = -2.122$. Finally, we move on to {1,1.4322}, notice that this is closest to {2,3.443543}, and compute the difference $(3.443543 - 1.4322) = 2.011343$. We then average these differences: $(-1.856 + -2.122 + 2.011343) / 3 = -0.6555...$ and place this at position $(i-1)$ in $L$. So we have $L = (-0.6555..., ...)$ thus far. We then move on to $i = 3$ and so forth. Note that if there is no $i = 3$ elements, we'd just enter $0$ at that position in $L$. Is there a fast and slick way to do this with a large initial preprocessedList? Here's the naive (very slow) way to do this:               preprocessedList = {{1, 5.3}, {1, 5.566}, {1, 1.4322}, {2, 3.443543}, {2, 3.444}, {3, 0.1223}, {4, 1.3243}, {4, 1.554343}};          L = Array[0 &, Max[preprocessedList[[All, 1]]] - (Min[preprocessedList[[All, 1]]])];          counter = 0;     For[i = Min[preprocessedList[[All, 1]]] + 1,        i <= Max[preprocessedList[[All, 1]]], i++,            counter += 1;            highIndexList = Select[preprocessedList, #[[1]] == i &];       lowIndexList = Select[preprocessedList, #[[1]] == (i - 1) &];            If[Length[highIndexList] > 0 && Length[lowIndexList] > 0,                differenceArray = Array[0 &, Length[lowIndexList]];           For[k = 1, k <= Length[lowIndexList], k++,            differenceArray[[k]] =               Nearest[highIndexList[[All, 2]], lowIndexList[[k, 2]]] - lowIndexList[[k, 2]];           ];       L[[counter]] = {i, Mean[Flatten[differenceArray]]};       ,       L[[counter]] = 0;       ];           ];      The output is:               L = {{2, -0.655552}, {3, -3.32147}, {4, 1.202}};      Perhaps there's a way to compile this?


title: How to check if a Polynomial has a specific form

text: I have a polynomial `F[x]`, for example `F[x] = 1 - 2x + x^2`. I wanna check whether F[x] has the form of `(1 + kx)^n`. For the example above, `k = -1` and `n = 2`. I have searched on several documents but found nowhere has the answer. So can I do this on Mathematica? If yes, how can I get k and n?


title: FinancialData property value at a given date

text: I was trying to get the volatility value of a specific equity on a given day. Based on the _Mathematica_ Help, the syntax is > `FinancialData["name","prop",{start,end,...}]` gives a list of dates and > values of a property for a sequence of dates or periods. So I tried this with the specific request.               FinancialData["SPY", "Volatility20Day", {{2012, 10, 11}, {2012, 10, 11}}]      which generates a long error message that starts with `DatePlus::date: Argument {{2012,10,11},{2012,10,11}} cannot be interpreted as a date. >>` By the way, the syntax does work with other properties such as close, open, return, etc. Is there any specific syntax that is different for `Volatility20Day`?


title: How to stop a single function to be evaluated?

text: See this example:               AA = {x} \[Function] Normalize[x]     BB = {x} \[Function] Evaluate[AA[x]*5]      I need BB to be Normalize[x]*5. Some context:I call evaluate because I'm using CForm later to do some optimizations, so my functions need not to call other user-defined functions which would translate into something that is not really valid C code. Normalize though just evaluates to a version which makes some sense only for complex numbers, this is not what the definition of Normalize does... Also, afaik Evaluate doesn't take assumptions, so I don't know how to "hint" it not to incorrectly expand Normalize... I've tried various hold/replace/single step evaluate tricks, all not working. Any ideas?


title: Preserving a bijection between arrays when shuffling elements in one array

text: Imagine I have two lists of elements like the following:               listOne = RandomReal[{0,2}, {100,2}];     listTwo = RandomReal[{0,2}, {100,2}];      Let $f: X \to Y$ be a bijection or one-to-one correspondence between the elements in `listOne` and the elements in `listTwo`. I can shuffle the elements in `listOne` as follows:               listOne = RandomSample[listOne, Length[listOne]];      However, is there a way for me to perform the above shuffling operation while preserving the bijection $f$? In other words, can I shuffle the elements in `listOne` and `listTwo` in precisely the same manner?


title: Is this the expected behaviour from Partition when padding is inserted at the start of the list?

text: The documentation for `Partition` shows an example of partitioning without padding, so that no elements are dropped, but the last sublist can be shorter.               Partition[Range[50], 8, 8, 1, {}]     (* {{1, 2, 3, 4, 5, 6, 7, 8}, {9, 10, 11, 12, 13, 14, 15, 16}, {17, 18,         19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30, 31, 32}, {33, 34,         35, 36, 37, 38, 39, 40}, {41, 42, 43, 44, 45, 46, 47, 48}, {49, 50}} *)      The documentation for `Partition` in the Wolfram Language documentation (and presumably for the forthcoming version 10) has an additional example, where the partitioning starts from the end, and the first list is the shorter one. A similar example (but with actual padding not an empty list) is in the version 9 documentation under the _Padding Alignment_ section of the documentation page. However, partitioning from the end does not seem to result in all elements of the original list being preserved, regardless of whether padding is used or not. Notice that the last value (50) is missing from the result. (Output from version 9, but I have reason to believe that the behaviour from the current version of the Wolfram Language is similar.)               Partition[Range[50], 8, 8, -1, x]        (* {{x, x, x, x, x, x, x, 1}, {2, 3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13,        14, 15, 16, 17}, {18, 19, 20, 21, 22, 23, 24, 25}, {26, 27, 28, 29,        30, 31, 32, 33}, {34, 35, 36, 37, 38, 39, 40, 41}, {42, 43, 44, 45,        46, 47, 48, 49}} *)     Partition[Range[50], 8, 8, -1, {}]     (* {{1}, {2, 3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13, 14, 15, 16, 17}, {18,        19, 20, 21, 22, 23, 24, 25}, {26, 27, 28, 29, 30, 31, 32, 33}, {34,        35, 36, 37, 38, 39, 40, 41}, {42, 43, 44, 45, 46, 47, 48, 49}} *)      Is this a bug? Is there a way to ensure that partitioning from the end preserves all original elements of the list? The context for this question is that I'm trying to create a little function that implements local shuffling, for inclusion in a little genealogical simulation I'm writing (on the theory that people in bygone eras were more likely to marry people form nearby than people from far away, but didn't systematically always marry the person next door).               localshuffle[list_List, window1_Integer?Positive, window2_Integer?Positive] /;        Length[list] > window2 && window2 > window1 :=      Flatten[RandomSample /@         Partition[ Flatten[RandomSample /@ Partition[list, window1, window1, 1, {}],           1], window2, window2, -1, {}], 1]      The number of elements should be the same as in the input but it is not. It does work if the `-1` in the outer `Partition` is replaced with `1`.               test = localshuffle[Range[50], 5, 8]     (* {3, 8, 6, 1, 4, 5, 2, 10, 7, 14, 13, 11, 12, 9, 18, 17, 15, 19, 22, \     16, 24, 20, 21, 23, 25, 32, 27, 29, 28, 33, 30, 31, 26, 41, 38, 39, \     36, 37, 40, 34, 35, 48, 50, 46, 49, 43, 45, 44, 42} *)          Length[test]     49


title: Writing NDSolve-like functions

text: I've been using _Mathematica_ for a while now, and there are multiple common tasks that I end up doing. I'd like to learn how to convert them into functions so that I can store them in some file and load them at startup. Most of these common tasks involve taking a set of equations and doing something with them. Thing is, I don't want to fix the variables the equations are written in, and would like behavior similar to `NDSolve` where one can specify the functions as well as which variable is which. For example, take this task:               Pd = ParametricNDSolve[{v'[t] == (v[t] - v[t]^3/3 - ω[t])/0.2,             ω'[t] == (1 + v[t])/0.2,             ω[0] == b, v[0] == a}, {v[t], ω[t]},              {t, 0, 20}, {a, b}];     PVec[x_, y_] := {D[(v[t] /. Pd) [x, y], t] /. t -> 0,                       D[(ω[t] /. Pd) [x, y], t] /. t -> 0};     VectorPlot[PVec[x, y], {x, -2, 1}, {y, -1.2, 0.5}]      Here, I'm parametrically solving the pair of equations $$ \begin{align} v'(t)&=\frac{-\frac{1}{3} v(t)^3+v(t)-\omega (t)}{0.2}\\\ \omega'(t)&=\frac{v(t)+1}{0.2} \end{align} $$ with the parameters being the initial state of $v$ and $\omega$. Now, I take the vector field of their derivatives at $t=0$, and vector plot it. Basically, I want to get a quick map of how the initial trajectories ($(v'(t),\omega'(t))$) change for different initial conditions without having to open `EquationTrekker` and do things manually. * * * So now, I want to take this task and write it as a function akin to `TrajectoryMap[{eqn1,eqn2},{{var1,varmin,varmax},{var2,varmin,varmax}},{{timevar,timepoint},tmin,tmax,tpoint}]` where this particular code would run as               TrajectoryMap[{v'[t] == (v[t] - v[t]^3/3 - ω[t])/0.2,          ω'[t] == (1 + v[t])/0.2}, {{v[t],-2,1}, {ω[t],-1.2,0.5}}, {{t,0},0,20}]      (or something similar) Here, `timepoint` is the value of `t` for which the derivative of the interpolating function is calculated. I can tell that this will probably need some combination of `Hold`s and `Evaluate`s, but I can't seem to get the right one. How should I go about converting this code (or any arbitrary code of a similar type) into a custom function?


title: Find Lists with intersecting sublists

text: I have a list of the following form:               l = {{"label1", {1, 2, 3}}, {"label2", {4, 5}},            {"label3", {3, 6, 9, 8}}, {"label4", {11, 25, 24, 14}}, {"lable5", {4, 5}}}      I would like to retrieve only those labels whose corresponding list has an intersection with the corresponding list of another label, along with the intersecting elements. So, for `l` I would get               {{"label1", "label2", "label3", "label4"}, {3, 4, 5}}      (I'll add my answer, but I'd like to see if someone can come up with a simpler one)


title: Bound on number of function evalulations in FindMinimum

text: I am minimizing a nonlinear constrained problem using `FindMinimum`. The problem involves about 200 variables and the function is a black-box which cannot be compiled/optimized (I have set the Method as Automatic). During evaluations, I collect the value of the objective function at intermediate evaluations using `EvaluationMonitor` option. I have a `Monitor` statement enclosing the `FindMinimum` which plots the objectiveFunction against the number of function evaluations. This was the picture. ![objective_fn_against_num_of_fn_evals](http://i.stack.imgur.com/Juk0H.jpg) Is there an option to **(gracefully) terminate** the `FindMinimum` after `nMax` number of function evaluations, returning the best solution of those so far evaluated (like position 25 in the image)? ( `MaxIterations` does not achieve it, since it is a bound on the number of **steps taken** and not the function evaluations).


title: Finding roots of nontrivial equation

text: I am trying to solve the following nontrivial equation:                   fun[z_] := (Log[Gamma[n]] + n Log[Gamma[z + 1]] + z n Log[n] - Log[Gamma[n (z + 1)]])/n         fun[z] /. n -> 8         m = Table[i, {i, -1, 1, 0.1}]          sols = Table[FindRoot[fun'[z] + 0.5 == m[[i]], {z, 1}], {i, Length[m]}]         sols2 = Table[FindRoot[fun'[z] + 0.5 == m[[i]], {z, sols[[j]]}], {i, Length[m]},              {j,   Length[sols]}]      Basically, I get roots from the equation that are stored in `sols`. However, I also need all values from `sols` as starting values for the next iteration that will be executed in `sols2`. However, this doesn't work and produce the following errors:                   {{FindRoot[\!\(\*SuperscriptBox["fun", "\[Prime]",MultilineFunction->None]\)[z] +0.5 == m[[i]], {z, sols[[j]]}],          FindRoot[\!\(\*SuperscriptBox["fun", "\[Prime]",MultilineFunction->None]\)[z] + 0.5 == m[[i]], {z, sols[[j]]}],          FindRoot[\!\(\*SuperscriptBox["fun", "\[Prime]", MultilineFunction->None]\)[z] + 0.5 == m[[i]], {z, sols[[j]]}],          ....      Any suggestion on how to fix this?


title: MathLink and CDF

text: So far I have read that some things are not supported in CDFs. Istvan-zachar mentioned very useful things in his post. Unfortunately he mentioned that > MathLink operations, including J/Link and .NET/Link, are not supported. This is taken straight from wolfram.com under the "Interactivity in .cdf Files" section. In the past I was messing around with MathLink because I wanted to create functions that would execute faster. For an example of a complete MathLink program look at this old post of mine. In there I created an interactive program that uses the MathLink program. The question now, regardless of what wolfram says about no support for MathLink operations is, Has anyone been able to export this type of programs? Is it possible to embed the MathLink program in the cdf file? If not, can we make the cdf file create the link to the MathLink program? I suppose that we need to be aware that if this is possible then it would only work in computers running the same operating system that compiled the MathLink program. That is, if I compiled in Mac OS X, then the CDF would not run properly under Windows. # Update: Thanks to Mark McClure now I know how to make the function available to the cdf document. The problem now is that I get this: ![Non-working CDF](http://i.stack.imgur.com/iocMC.png) Only after I click on Enable Dynamics the desired result: ![Working CDF](http://i.stack.imgur.com/z1tNH.png) This tells me that the CDF was able to load the MathLink program but it will not let it run. I'm aware that this is do to security. I was reading here about the trusted path. Well, instead of adding a path I moved the cdf file and the MathLink program to a trusted directory. If I open it with Mathematica then it opens with no problem. But, if I were to open it with the CDF Player then I run into the issue I just mentioned. It requires me to click on the "Enable Dynamics" button. I believe this is what makes the CDF not being able to be displayed online. Any thoughts?


title: ListPolarPlot Labelling Points on the Plot

text: I have created a ListPolarPlot using the code below. I need to label the lines that extend from the centre to the outer ring. I do not want to label them with the values that these lines represent but rather with the values 1 to 7. I have tried LabelingFunction and some other things but these options don't work for ListPolarPlot. Can anyone help me with this ? As a second best solution I could just label the plotted points themselves from 1 to 7 (starting at the right hand horizontal and working anticlockwise).               ListPolarPlot[      Tooltip /@ {0.01422, 0.3425217, 0.30036, 0.013, 0.152, 0.3762,         0.122}, Joined -> True,       PlotMarkers -> Graphics@Disk[{0, 0}, Scaled[0.025]],       Axes -> {True, False}, PolarAxes -> Automatic,       PolarGridLines -> {{0.897, 0.897*2, 0.897*3, 0.897*4, 0.897*5,          0.897*6, 0.897*7}, {0.1, 0.2, 0.3}}, PolarTicks -> None,       AspectRatio -> 1/1, ImageSize -> {300, 300}]


title: Assumptions seem not to be considered

text: In the following `a`,`b` is a probability distribution, i.e. `a+b==1` with `a`,`b` real, and in the interval `[0,1]`. If we try to maximize the Shannon entropy over this distribution using Mathematica, we can either set `b=1-a`, or state the total probability condition as an assumptions. Maximizing using `b=1-a` works as expected. This input `Maximize[{-Log[2, a]*a - Log[2, 1 - a]*(1 - a), a <= 1 && a >= 0}, a, Reals]` yields `{1, {a -> 1/2}}`. However, when we give `Maximize[{-Log[2, a]*a - Log[2, b]*b, a + b == 1 && a >= 0 && a <= 1 && b >= 0 && b <= 1}, {a, b}, Reals]` as input, Mathematica does not find the solution. Any suggestions how the later input can be altered to find the correct solution?


title: Start Mathematica without the menu bar?

text: Is there any way to start Mathematica without the main menu bar? To be precise: ![what is the menu bar](http://i.stack.imgur.com/qizbK.png) Sometimes I make standalone mini-applications that I would like to just have in their own little windows without the cognitive weight of the entire Mathematica system bearing down upon my little one-off uses.


title: Pass an empty list object into a function and dynamically generate its list elements

text: I have another question on passing a list which needs to be generated dynamically. (Sorry for posting two questions in one day...) I did some search and found a similar post here, but I think it was for a fixed-length list. I hope I didn't misunderstand it... Here is my code:               FindRootsOfResult[i_, points_] := Module[{a, c},         Result = 2 E^(2 I \[Pi] w x) (2 + E^(I \[Pi] w x)) ((-100 + 0.55 I) + w)^3 /. x -> i;         a = FindRoot[Result == 0, {w, j}] // Hold;         c = ParallelTable[{Re[(a // ReleaseHold)[[1, 2]] - 100], Im[(a // ReleaseHold)[[1, 2]]]}, {j, 100 - 6, 100 + 6, 0.001}];         c = DeleteDuplicates[c, (Abs[#1[[2]] - #2[[2]]] < 10^-2 &) || Abs[#1[[1]] - #2[[1]]] < 10^-8 &];         points = Join[points, c];     ]      What I'm trying to do is to assign a value for the variable x and to pass a list into the `FindRootsOfResult` function, and then compute the corresponding roots of the function of w in a certain region. Finally I get rid of duplicate roots and save the roots in the list I passed in for further calculation. Since the number of roots in the given region changes for different x, the length of the list should be dynamically changed as well. I use `Join` in the last line because I'd like to assign many different x, compute the roots, and save all of them in the same list. A simple example would be               FindRootsOfResult[1/100, ans]      and I expect `ans` contains all the roots for x=1/100. However Mathematica gives me many error messages like               $RecursionLimit::reclim: Recursion depth of 256 exceeded. >>     Join::heads: Heads Join and List at positions 1 and 2 are expected to be the same. >>      and the list `ans` has nothing useful inside. Then I think, OK maybe Mathematica doesn't know that `ans` should be a list object, so I make `ans` be an empty list and do it again:               ans = {};     FindRootsOfResult[1/100, ans]      but I still get error messages               Set::shape: Lists {} and {{-1.82878*10^-6,-0.55},{-1.81874*10^-6,-0.55},{-1.80871*10^-6,-0.55},{-1.79868*10^-6,-0.55},{-1.78866*10^-6,-0.55},{-1.77864*10^-6,-0.55},{-1.76862*10^-6,-0.55},<<38>>,{-2.06832*10^-6,-0.55},{-2.05815*10^-6,-0.55},{-2.04798*10^-6,-0.55},{-2.03781*10^-6,-0.55},{-2.02765*10^-6,-0.55},<<344>>} are not the same shape. >>      Now I really don't know why I can't pass a list as I expected. If I execute the commands in `FindRootsOfResult` line by line manually, it works perfectly. I guess I don't really understand how Mathematica passes list objects. If anyone could give me a brief explanation or any previous discussion, I would so appreciate it!


title: Using Outer with Compiled functions that accept more than 2 arguments

text: How does one use `Outer` with a compiled function that accepts 3 or more arguments. Alternatively, how does one create a compiled function with 3 or more arguments that can be used with `Outer`? I am trying to use the following function:               minimumImagePD =  Compile[{{x, _Real, 1}, {y, _Real, 1}, {z, _Real}},                       Total[( (x - y) - z * Round [ (x - y) / z]) ^ 2]]      This function compiles just fine but you can't use it with `Outer`. Trying the following doesn't work because `Compile` does not "see" the argument 'z':               minimumImagePD2[z_Real] =  Compile[{{x, _Real, 1}, {y, _Real, 1}},                       Total[((x - y) - z * Round[ (x - y)/z] ) ^ 2]]              Outer[minimumImagePD2[3.2], {{2.1, 3.2, 4.3}}, {{3.2, 4.3, 2.8},                                 {1.1, 2.2, 3.3},   {3.4, 2.0, 6.5}}, 1].      Now, If I replace `z` in `minimumImagePD` with a number as follows:               minimumImagePD3 =  Compile[{{x, _Real, 1}, {y, _Real, 1}},        Total[((x - y) - 3.25026*Round[(x - y)/3.25026])^2]]      The function compiles and works fine as with the following example:               Outer[minimumImagePD3, {{2.3, 4.3, 6.5}}, {{2.1, 4.8, 7.3}, {2.2,         1.1, 4.3}, {2.1, 3.3, 4.7}}, 1] // Flatten      Which gives:               {0.93, 1.11557, 3.14325}      As noted by Oleksandr R. below, using set-delayed in `minimumImagePD2` solves the problem.


title: Dynamically Updating Function

text: I use Mathematica 8 and am working with DynamicModule. I'm trying to enter a function in an InputField then later apply it to two values entered in subsequent Input Fields. The function just does not seem to be dynamically applying to the new values I input. The issue probably lies in my definition of the function.                    DynamicModule[{dydx = Null, xi = Null, yi = Null},            Deploy[            Panel[             Grid[Transpose[{{"Differential equation: (dy/dx)=", "x:", "y:",              "slope:"}, {InputField[Dynamic[dydx]], InputField[Dynamic[xi]],             InputField[Dynamic[yi]],              InputField[               Dynamic[Function[{x, y}, Dynamic[dydx]][Dynamic[xi],                 Dynamic[yi]]], Enabled -> False]}}]]]]]


title: Showing the empty space in a Graphics3D plot

text: I would like to be able to visualize the empty space in a Graphics3D plot. For example, if I plot hexagonally close packed spheres using something like:               Show[Graphics3D[Sphere[#, Sqrt[2]/2] & /@ Select[Tuples[{-1, 0, 1}, 3],      Mod[Total[#], 2] == 0 &], Boxed -> False]]      ![Mathematica graphics](http://i.stack.imgur.com/XZzVA.png) Then how would I show the space between the spheres? That is, I would like the space occupied by the spheres to be empty and the space between them to be filled in.


title: "Show" with Manipulate runs fine normally, but gives errors as a CDF

text: I've simplified my code to what can reproduce my error. Basically, I have two lines:                spherePoint[x_] := Graphics3D[Sphere[{x, 0, 0}, 1]];       Manipulate[Show[spherePoint[m]], {{m, 1}, -Pi/2, Pi/2}]      This runs perfectly fine when I evaluate it in a mathematica notebook, but when I do a CDF preview (or export), it gives me the error               Show::gtype: spherePoint is not a type of graphics. >>      What gives?! Show should accept Graphics3D, and spherePoint is a graphics 3D object! (I'm not sure about the last part of that sentence, because it's a function that gives a graphics 3d object, but I don't know what that implies for the program) What am I doing wrong?


title: Manual CellGrouping option causes crash at cell evaluation

text: **Update: Try to reproduce this behaviour with`CellGrouping` set to manual**. To do that:   * either evaluate `SetOptions[$FrontEnd, CellGrouping -> Manual]`,   * or hit `CTRL`+`SHIFT`+`O` to bring up the **Option Inspector** window, **Lookup** (among **Global preferences** ) the option `CellGrouping` and set it to `Manual`.  Please test whether the phenomen is reproducible for you with the changed setting. You can reset cell grouping to its default behaviour by:               SetOptions[$FrontEnd, CellGrouping -> Automatic]      * * * Strangest bug ever. Copy the following piece of code to the same notebook **two times** , below each other, as two identical cells. Be sure to run a fresh kernel.               DynamicModule[{x}, Print[1]; Dynamic@x, Initialization :> Print[2]]      Now evaluate the **second cell**. Fine, it returns and prints stuff. ![Mathematica graphics](http://i.stack.imgur.com/a3nBf.png) And now, without quitting the kernel, **evaluate the first cell**. It crashes _Mathematica_. Every time, and only when the first cell is evaluated. If (after a restart) I only evaluate the first cell, _Mathematica_ crashes again. **How come that the outcome of evaluating two identical cells depends on whether the cell is the last one or not?** Furthermore, this one causes a crash on its own:               DynamicModule[{x}, Dynamic@x, Initialization :> Print[2]]      * * * _Mathematica_ 9.0.1.0 Windows 7 (64-bit), no packages, problem persists after full reboot, suggestion bar is turned off.


title: Run kernel script in cygwin without window popping up

text: I'm calling mathematica scripts running kernels through a cygwin terminal, which are again executed from c++ code. When I do this a window pops up, prints warnings and errors if there are any, and then disappears when the computation is done. This gets annoing because the window automatically opens on top of whatever else I'm doing. I've tried to find solutions without any luck - for example this thread gives the answer for some other situations but wouldn't work from cygwin I think. Any ideas? EDIT: To clarify: I'm trying to run a Mathematica script from the cygwin terminal without a Mathematica window popping up. That is, I'm running a command in cygwin with something like `./MathKernel -script myScript.m 45 3` where 45 and 3 are parameters in the computation. Everything works fine but a Mathematica window pops up un top of everything and disappears after a little while, something I'd like to avoid.


title: Evaluating the tensor product many times for a given list

text: I need to evaluate the tensor product 10 times in a given list( {g,e,r}) Here I have evaluated for 3 times...               #\[TensorProduct]#\[TensorProduct]#&[{g,e,r}]     ..     ..      Evaluated for 6 times...               #\[TensorProduct]#\[TensorProduct]#\[TensorProduct]#\[TensorProduct]#\[TensorProduct]#&[{g,e,r}] (*n=6*)      Each time I need to include the tensor product on the list. Is there any better way to do this for large no.?


title: Aborting from inside a ScheduledTask

text: If you have an `Abort[]` inside a `ScheduledTask` expression, what does it abort? The scheduled task evaluation, or any main kernel evaluation that is ongoing?


title: Image levels: how to alter 'exposure' of dark and light areas?

text: I was working with some less than ideal photographs, and wanted to adjust them before continuing. I wanted to raise the levels of the very dark areas and lower the levels of the very light areas. I couldn't find a function in Mathematica 8 that would allow me to do this. As a quick work-round, I wrote a function that quickly adjusted the levels. It looks terrible in this simplified example (I had more levels going, for one thing), but you get the idea (I hope!).               image1 = Image[         ReliefPlot[            Table[i - 3 Sin[i^2 + j^2],                 {i, -4, 4, .03},                 {j, -4, 4, .03}]]];      tweakC = Compile[{pixel}, Module[{ p = pixel},        m = Mean[p];        Which[             m < 0.3, p = pixel * 1.5,                 m > 0.85, p = pixel * 0.8 ,                 m > 0, p = p ]]];     image2 = ImageAdjust[ImageApply[tweakC, image1]];     ImageAssemble[{image1, image2}]      ![before and after](http://i.stack.imgur.com/8vYOs.png): What's the best way to do this? I don't think `ImageAdjust` or `ImageClip` do what I want.


title: How to map an image to get an illusion of 3D

text: I would like to distort or map a given jpg so it looks 3D as in the following youtube video: http://www.youtube.com/watch?v=IfCCUd8mFtg. I usually use conformal mapping (a complex function) to do my distortions. Can you help me with figuring out which function to use for this?


title: Write numbers to a file

text: I want create file with some text (and numbers). This is my code.               str=OpenWrite["f:\\1.txt",PageWidth->Infinity, FormatType->StandardForm,NumberMarks->True];     Write[str, "a = ", 0.123456789];     Close[str]      The problem is there is rounded number (0.123457) in the output file. but I actually want file with text               a = 0.123456789      **Explaining** : I want parse a test suite files (*.mt) with data for check. Rows looks like               dataAcc = {{1.865987700, 1.920469000, 1.811506300, ...},...}     Get[childTestLocation<>"nameOfChildTest.mt"]      I have a numbers for dataAcc list. But when i create testfile numbers becomes rounded.


title: step by step interactive indefinite integral

text: WolframAlpha can give step by step solution for indefinite integral. There seems to be similar question but for derivatives. Is there a way that I can generate my own step by step solution for indefinite integrals (for simple integrals having closed form)? Sorry, if the question is inappropriate.


title: How do I plot points on a sphere using spherical coordinates?

text: Currently, I have a matrix containing a list of spherical coordinates. Column 1 is r; r=1 for all points. Column 2 is theta and column 3 is phi. Each row is an ordered triple (r,theta,phi). Is there a function that I can get to operate on this matrix and plot these points on a sphere of radius 1? Thank you! -Chase


title: Manipulate is evaluated slowly

text: I have this function:               f[k_, θ_, ϕ_] := Cos[k*Cos[θ]*x + k*Sin[θ]*y - ϕ]      I want to change the parameters $\theta, \phi,$ and $k$ to see the effects on the function. I use the command below to achieve that:               Manipulate[       ContourPlot[f[k, θ, ϕ], {x, 0, 50}, {y, 0, 50}, PlotLegends -> Automatic],     {k, 0, 10}, {θ, 0, 2*Pi}, {ϕ,0, 2*Pi}]      The problem is that when I change one of the parameters, say $\theta$, continuously the plot is evaluated slowly so that during the running you cannot see the actual graph. How can I change those parameters and see the real evaluated result immediately?


title: Why doesn't a Composition[] hold its arguments and what can be done about it?

text: Now that `Composition` (also `RightComposition`) has shorthand syntax I am more inclined to use it, however what I feel _should_ be one of its best advantages over the plain `foo @ bar @ ## &` doesn't exist: **held arguments.** For example I wish for the following behavior:               Composition[ToString, HoldForm][2 + 2]          (* desired output: "2 + 2" *)      I am aware that the form `head[a__][b__]` doesn't normally allow holding of arguments `b` but this has always seemed like a place an exception should have been made. ~~Unless the first head applied has hold Attributes this would not alter behavior.~~ Does anyone regularly make use of the evaluation of arguments that I am seeing as undesirable? Presumptuously assuming that others find desirable the behavior that I want I see this as a sorely missed opportunity:   * the shorthand forms `foo @* bar` and `foo /* bar` could have been made to parse as `LeftComposition` (hypothetical) and `RightComposition`   * these new operators could have been made to hold arguments as I describe without breaking backwards-compatibility with `Composition` in past versions. I wonder what can now be done to improve the situation.   1. I suppose it is too late to get such changes made to natively. Has such a change _ever_ been made to _Mathematica_ (or Wolfram Langauge) after an initial release?   2. I am tempted to try to force this behavior myself using one of the methods available. All public code except what I see as edge cases would work on my machine but my own code would fail on others.   3. Sadly it is not possible to define custom compound operators so there is no true alternative, but I could define e.g. `comp[fn1, fn2]` to work as I desire. My questions therefore: **Is there some reason _not_ to have a `Composition` expression hold its arguments?** **Is there another option that I am failing to consider?** **How can one robustly implement option #2 or #3?**


title: Problem When Trying to Export Graphics with Transparency to SVG

text: I'm trying to export a graph as a graphic to an SVG file with transparent background. When the background is specified as a color (or unspecified), it works just fine. When the background is specified as `None`, it offsets the graphic down and to the right a bit and ends of cutting off part of the graphic.               g = CompleteGraph[7];     g = GraphicsGrid[{{g}}];     Export["good.svg", g, Background -> Pink];     Export["bad.svg", g, Background -> None];      Transparency works perfectly as expected when the graphic is exported to PNG. Is this a bug, or am I just missing something here? I'm running Mathematica 9.0.0.0 on Linux 64-bit. Here's a screenshot of what I am seeing when I open the bad.svg in the gnome image viewer (with some style changes made to the graph for visibility). Note that the image is cut off on the bottom and on the right. When I open bad.svg in chromium or in firefox, it appears fine. ![1](http://i.imgur.com/tAkcEye.png)


title: V10's Operator Forms - what are they good for?

text: V10 introduces an operator form for several functions perhaps primarily due to their role in queries as part of introducing data science functionality. At first pass it seems a lot of effort to add some syntactic sugar (given an equivalent pure functional form only ever requires an extra couple of symbols - (`#`, `&`) )? For example,`Map[f,#]&[{a,b,c}]`can now be shortened to `Map[f][{a,b,c}]`, - slightly more compact but then again perhaps not such an improvement on an existing operator (short) form - `f/@{a,b,c}`. So, are there some compelling examples that illustrate the rationale behind the introduction of this new construct? **Conclusion** To summarize the points made in all the informative responses:   * In addition to avoiding the symbols (`(#&)`) operator forms can eliminate the need for `Function` in nested definitions.   * The gains of using operator form are cumulative as they are chained together either in postfix, prefix or for some, infix form.   * While not necessarily restricted to this area the motivation and applicability of operator forms stems from the need to provide functions as arguments in `Dataset`.   * Many operator forms are built-in but when not they can be readily defined.   * The pure and operator forms are not always semantically equivalent (natively or user-defined) with, for example, `Query` using their different patterns to interpret differently.   * They can potentially be used to improve efficiency not just via code's reduced leaf-count but in reduced algorithmic complexity.   * They are potentially a rich source of language improvement from mimicking natural language patterns, code refactoring, debugging or automated and non-deterministic parsing via corpus-derived context.


title: Plotting confidence intervals

text: The documentation for PDF has an example for plotting a confidence interval of a standard normal distribution:               pdf = PDF[NormalDistribution[], x]     Show[Plot[pdf, {x, -1.7, -1}, Filling -> Axis, FillingStyle -> Green],       Plot[pdf, {x, -1, 1}] ,       Plot[pdf, {x, 1, 1.7}, Filling -> Axis, FillingStyle -> Green],       PlotRange -> {0, 0.4}, AxesOrigin -> {0, 0.1},       Ticks -> {Automatic, None}]      The plot range is set such that this code would not work in a generalized case for `NormalDistribution[u,s]`. **What is the appropriate format for {x, xmin, xmax} in the`Plot` function above for the general case of a normal distribution with mean = u and standard deviation = s?**


title: smooth kernel distribution

text: I just want to know what is "x" in a code line like "SmoothKernelDistribution[Data,x], when it is a real number?!! when it is integer I know that it is the number of bins but what is this factor when it is something like "0.5"?


title: How to force the RegionPlot to shade a narrow region?

text: I have an interactive demonstration, which (very simplified to leave out unnecessary details) looks as follows:                   Manipulate[      Show[{        Plot[{x, a*x}, {x, -1, 1}, PlotRange -> {-1, 1}],        RegionPlot[x < y < a*x, {x, -1, 1}, {y, -1, 1}]        }], {a, 0.5, 1.5}]      On the screen I see this: ![enter image description here](http://i.stack.imgur.com/Q8NIX.jpg). I draw the arrow to point out a defect in the shading: the shading does not cover a narrow triangle in the vicinity of the coordinates origin, though it should. More than that. The degree of shading varies as I move the slider. I could, of course, use the option "Filling" in the Plot statement and remove the RegionPlot at all. I need, however, the filling to show the region where one of the lines is above the other. It seemed that the RegionPlot is in this case a more natural choice. Can you imagine a workaround with the RegionPlot, or I should inevitably go to Filling in the Plot statement?


title: Linearized Einstein Equations with Mathematica

text: I need to compute the linearised Einstein Equations around a fixed metric $g_{\mu \nu}$ which is not the flat metric. Someone knows some Mathematica package or some review that can help me?


title: How to load FORTRAN libraries through Librarylink

text: First, the main reference is the thread Linking FORTRAN with Librarylink, which teaches how to make the link between a FORTRAN subroutine and a Mathematica code, by using Librarylink. This must done through a C code, from where the FORTRAN subroutine is called. The C code is, then, compiled via Mathematica. I have studied the examples and tried them myself. My doubt is on how to load FORTRAN libraries, e.g. for using the FORTRAN command `open` within the subroutine. Whenever I try to call a subroutine that contains `open`, I read an error message on the screen. Read below my minimal example. **FORTRAN subroutine** The subroutine reads `a,b,c` and stores `a+b+c` into the variable `sum`. Additionally it open,reads and close `file.dat`.                   !fadd.f90         subroutine add(a,b,c,sum)               implicit none               integer a,b,c,sum               sum=a+b+c               open(1,file='file.dat')               read(1,*)               close(1)               return         end subroutine      `file.dat` only contains the number `1`, for the minimal example. This value is not used anywhere, for simplification. My actual code would use dat files to make complicated computations. **Calling the subroutine from C**               //MMA.cc     //Link directly to fortran object file     #include "WolframLibrary.h"          DLLEXPORT mint WolframLibrary_getVersion(){         return WolframLibraryVersion;}     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){         return 0;}          //declare fortran subroutine     extern "C" { void add_(mint* a, mint* b, mint* c, mint* sum);}           EXTERN_C DLLEXPORT int add(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){         mint I0 = MArgument_getInteger(Args[0]);         mint I1 = MArgument_getInteger(Args[1]);         mint I2 = MArgument_getInteger(Args[2]);         mint sum;         add_(&I0,&I1,&I2,&sum);//call fortran subroutine         MArgument_setInteger(Res,sum);         return LIBRARY_NO_ERROR;     }      **Mathematica: create library and load library function**               Needs["CCompilerDriver`"];     CreateLibrary[{"MMA.cc", "fadd.o"}, "myadd", "Debug" -> True, "TargetDirectory" -> "."]          funcadd = LibraryFunctionLoad["./myadd", "add", {Integer, Integer, Integer}, Integer]          Print[ funcadd[2,2,2] ]     Exit[]      **ERROR** (Running Mathematica 8 through Linux terminal)               (*   /optifi/Wolfram/Mathematica/8.0.4/SystemFiles/Kernel/Binaries/Linux-x86-64/MathKernel: symbol lookup error: (...)/myadd.so: undefined symbol: _gfortran_st_open   *)      For compiling the FORTRAN code, I have run on LINUX terminal               gfortran -c -fPIC fadd.f90      where `-fPIC` has been added as requested by an error message telling `recompile with -fPIC`.


title: Image3D and Graphics3D

text: also I guess that the topic was tackled in Combining Image3D and Graphics3D. My question is quite similar: How do I match the coordinate Systems of Graphics3D and Image3D? Here some code:               z = 1;     p = RandomInteger[100, {z, 3}];     r = RandomInteger[10, {z}];     spheres = MapThread[RotateLeft[DiskMatrix[#1, {100, 100, 100}], #2] &, {r, p}];     i = Image3D[Plus @@ spheres, Axes -> True, AxesLabel -> {"x", "y", "z"}]     obj = GraphicsComplex[p, Sphere[Range[z], r]];     gr = Graphics3D[obj,                     Axes -> True,                     AxesLabel -> {"x", "y", "z"},                     PlotRange -> {{0, 100}, {0, 100}, {0, 100}}]     Show[i, gr, Axes -> True]      Can anyone explain to me how to match the coordinate systems, that the spheres match? Thanks in advance!


title: How do I define an argument pattern for a Head of NOT a given value?

text: I want to define a function f with an argument that matches only when an argument Head is NOT of a given value. I know I can define a pattern that matches the Head for an argument:               f[a_Integer] := 2 a      Now, how do I define a version that matches only when argument a is NOT an Integer?               f[a_NotAnInteger] := <something else>