title: Integration of linked PDFs over probability simplex

text: I'm trying to integrate the following expression:               f[a1,p1+p2+p3+p4]*f[a2,p2+p3+p4]*f[a3,p3+p4]*f[a4,p4]      Where               f[x_, u_] := E^(-(x - u)/2)/(2*(1 + E^(-(x - u)/2))^2)      i.e. the PDF of the logistic distribution with s=2. Also, the a's are positive integers. The tricky part is that I want to integrate over all values of the p values that result in them forming a valid probability distribution, ie the p variables must be greater than zero, less than one and sum to 1. I've tried using a definite integral with the following limits (after substituting p4 with $1-p1-p2-p3$:               {p1,0,1},{p2,0,1-p1},{p3,0,1-p2-p3}      This works for a simplified version of the problem (with 3 or 2 "f" terms and p variables but as soon as I use 4 it takes about 20 minutes and then just returns the input. My instinct is that if it can be analytically found for 3 terms, 4 terms should also be findable, just with more terms. My question(s) are: 1) Does anyone have any suggestions to get Mathematica working for this (and larger problems)? 2) I'm not tied to the logistic distribution, I'm using it because I thought it's simple CDF would make the problem easy for Mathematica. Can anyone suggest a similar shaped distribution that would make this problem tractable?


title: BarChart frame labels

text: This barchart was tricky to style, and I had to resort to the legacy `BarCharts``package. Any ideas how to omit the labels from the bottom edge? Ideally I'd also like separator ticks between the column pairs.               data = {{-2.8, -5.8, -7.4, -9.2}, {-3.7, -6.8, -8.9, -11.8}};          colour1 = RGBColor[82/255, 85/255, 255/255];     colour2 = RGBColor[132/255, 178/255, 255/255];          Quiet[Needs["BarCharts`"]]          BarChart[data, Frame -> True, AxesOrigin -> {0, 0},       PlotRange -> {{0.525, 4.825}, {-14, 0}},      BarLabels -> {"March", "June", "September", "December"},      BarGroupSpacing -> 0.3, BarSpacing -> 0,       BarStyle -> {colour1, colour2},      BaseStyle -> {10, FontFamily -> "Verdana"}, AspectRatio -> 0.4,       ImageSize -> 350]      ![enter image description here](http://i.stack.imgur.com/32bOZ.png)


title: Alternative for MapThread in listable functions

text: How can I rewrite this more efficiently taking advantage of `flo`, `dem`, and `Nsup` being `Listable` and utilize parallel computation?               MapThread[flo[#1, #2, #3] &, {Most /@ kr, Rest /@ Rk, Most /@ qsum}, 2]           kr = Table[RandomReal[50], {10}, {5}];     Rk = Table[RandomReal[150],{10}, {5}];     qsum = Table[RandomReal[6000], {10}, {5}];          flo =        Compile[{{p1, _Real, 0}, {p2, _Real, 0}, {p3, _Real, 0}},          Min[dem[p1], Nsup[p2, p3]],          Parallelization -> True,          RuntimeAttributes -> {Listable},          CompilationOptions -> {"InlineExternalDefinitions" -> True}];          dem =        Compile[{{p1, _Real, 0}},          Min[100 p1, 2500],         Parallelization -> True,          RuntimeAttributes -> {Listable}];          Nsup =        Compile[{{p1, _Real, 0}, {p2, _Real, 0}},          Min[(150 - p1) 100 - p2, 2500],          Parallelization -> True,          RuntimeAttributes -> {Listable}];      I am thinking it to be of the form (currently does not work)               flo1[kr, Rk, qsum];          floR1 =        Compile[{{p1, _Real, 0}, {p2, _Real, 0}, {p3, _Real, 0}},          MapThread[Min[demR[#1], NsupR[#2, #3]] &, {Most /@ p1, Rest /@ p2, Most /@ p3}, 2],          Parallelization -> True,          RuntimeAttributes -> {Listable},          CompilationOptions -> {"InlineCompiledFunctions" -> True}];      or something that avoids `MapThread` altogether, because I suspect `MapThread` does serial computation.


title: Using Gather to rearrange my data

text: I have a list of elements:               {{1, 2}, {1, 5}, {2, 6}, {3, 7}, {4, 8}, {5, 6},       {5, 9}, {9, 13}, {10,11}, {11, 12}, {11, 15}, {15, 16}}      I have to divide it into sublists, so that:               #1[[1]] == #2[[1]] || #1[[1]] == #2[[2]] || #1[[2]] == #2[[1]] || #1[[2]] == #2[[2]] &      i.e. at the end I need to obtain:               {{{1, 2}, {1, 5}, {2, 6}, {5, 6}, {5, 9}, {9, 13}},      {3, 7}, {4, 8}, {{10,11}, {11, 12}, {11, 15}, {15, 16}}}      However, I cannot find a solution to do it with `Gather`. How can I accomplish this task?


title: Assumptions on unknown functions

text: I'm trying to do analytic calculations in a quantum mechanic harmonic oscillator basis. Specifically I want to be able to evaluate functions of the many particle density. I define the following functions: [ _definitions_ ]               (* Harmonic Oscillator Eigenstate *)     basis[i_, z_] = Pi^(-1/4)/Sqrt[2^i Factorial[i]] Exp[-z^2/2] HermiteH[i, z];     (* Orbital *)     orb[i_, z_] = Sum[c[i, k] basis[k, z], {k, 0, t}];     (* Particle density of one orbital *)     orbitaldens[i_, z_] = Conjugate[orb[i, z]] psi[i, z];     (* Total density *)     dens[z_] = Sum[a[i] orbitaldens[i, z], {i, 1, n}];      To help Mathematica I define some assumptions beforehand: [ _assumptions_ ]               $Assumptions = Element[z, Reals] && (* Real-space coordinate is real *)                    Element[{n, t}, Integers] && n > 0 && t > 0 && (* Just indices *)                    Element[c[i_, j_], Complexes] && (* Complex state vector *)                    Element[a[i_], Reals]; (* Real filling factor *)      What is the correct way to define assumptions on an unknown function? Here `c[i_, j_]` should take integers `i`, and `j` and return a complex number. `a[i_]` on the other hand should take on integer `i` and return a positive real number. Unfortunately, the evaluation of the _definitons_ takes very long if I include these _assumptions_. Without them the _definitions_ block takes about a second to evaluate. However, I need those assumptions, so Mathematica can do useful simplifications. For example `Conjugate[orb[i,z]] orb[i,z]//FullSimplify` should simplify to `Abs[orb[i,z]]^2`. But the same should work, if I only apply the complex conjugation to `c[i,k]` inside `orb[i,z]`, because `basis[i,z]` is real. So far, this takes too long to evaluate. Is it possible to speed this whole thing up? Another problem I found is the codomain of the Factorial The following two expressions do not evaluate to True, neither to False. They just repeat the first parameter of `Refine`:               Refine[Element[Sqrt[Factorial[i]], Reals], Element[i, Integers] && i > 0]     Refine[Factorial[i] > 0, Element[i, Integers] && i > 0]      In words, the factorial of a positive integer is not necessarily positive. What is wrong there? I don't see how the factorial of a positive integer could become negative. (In symbolic maths)


title: Graphics3D flickers in Mathematica 10 and Linux

text: In the official Mathematica version 10.0, I get a very weird behavior when I try to rotate a 3d graphics > ![enter image description here](http://i.stack.imgur.com/65Qz6.gif) The moment I click on the graphics to drag it, it seems like it zooms the whole graphics for a fraction of a second. I'm here on Ubuntu 12.04 64-bit with Gnome 3.4.2 and an NVidia GeForce GTX 590 with NVidia driver. I have reported this to Wolfram, but do others experience this and is there any known solution to the problem?


title: How to close the (local) Debug window/palette

text: I have this local debug window that is so annoying ![enter image description here](http://i.stack.imgur.com/txOLw.jpg) How can I hide it? What is the purpose of it?


title: Problem with files size

text: I need to work with long time series, but I notice that this generates huge files that Mathematica doesn't handle well at all: even opening/saving one of this files is difficult, and the kernel quits often while doing simple tasks. I attach an example: the TemporalData object generated and stored in 'data' is 150 MB (and it's not even a half of what I need). Graphics are huge: each one of the Manipulate objects are ~ 150 MB, and they include no more than 300 stills. The total size of this notebook, once compiled, 650 MB circa, more or less a low quality AVI of a standard movie of one hour and a half. Is this standard for Mathematica? Should I send the output to external files and in this case which is the right way to do this, without losing the nice interactive features of the program? Thanks               force[x_] := (a x - b x^3)     drive[t_] := \[ScriptCapitalA] Sin[2 π (ω t + α)]               ClearAll[paramrule, forceRule]     forceRule = {ϵ -> 0.003, a -> 1,      b -> 1, \[ScriptCapitalA] -> 0.35, ω -> ϵ/(     2 π), α -> 0}; paramrule =      Join[forceRule, {σ -> 0.2, Subscript[x, 0] -> -1.5,      Subscript[T, range] -> {0., 15000, 0.1}}]     {ϵ -> 0.003, a -> 1,      b -> 1, \[ScriptCapitalA] -> 0.35, ω -> ϵ/(     2 π), α -> 0, σ -> 0.2, Subscript[x, 0] -> -1.5,      Subscript[T, range] -> {0., 15000, 0.1}}          proc := ItoProcess[{force[x] + drive[t], σ}, {x, Subscript[x,      0]}, t] //. paramrule          data = RandomFunction[proc, Subscript[T, range] , 100] //. paramrule          Histogram[data["SliceData", 10000], Automatic, "PDF"]          Manipulate[     Histogram[data["SliceData", t], {-2, 2, 0.1}, "PDF"], {t, 10000,      12000, 100}, SynchronousUpdating -> False, SaveDefinitions -> True]     Manipulate[     Histogram[data["SliceData", t], {-2, 2, 0.1}, "PDF"], {t, 12000,      15000, 10}, SynchronousUpdating -> False, SaveDefinitions -> True]     Manipulate[      Histogram[data["SliceData", t], {-2, 2, 0.1}, "PDF"], {t, 12000,        15000, 10}, SynchronousUpdating -> False, SaveDefinitions -> True]


title: Expressing a joint distribution for use in ContourPlot

text: I have $$X_1=T + W$$ $$X_2=2 T + 3 W$$ where $$W \sim N(3,5) \,\text{;}\,\, T \sim N(1,2)$$ and $$P(X=X_1)=P(X=X_2)=\tfrac{1}{2}$$ which I have awkwardly expressed as               X2 = TransformedDistribution[       2 T + 3 W, {W \[Distributed] NormalDistribution[3, Sqrt[5]],         T \[Distributed] NormalDistribution[1, Sqrt[2]]}]          X1 = TransformedDistribution[       T + W, {W \[Distributed] NormalDistribution[3, Sqrt[5]],         T \[Distributed] NormalDistribution[1, Sqrt[2]]}]          XX = TransformedDistribution[       i a + (1 - i) b, {a \[Distributed] X1, b \[Distributed] X2,         i \[Distributed] BernoulliDistribution[0.5]}]      This serves fine for generating `RandomVariate`s and for calculating `Mean`, `Variance`, etc.; but I would like to plot the PDF of $T$ vs $X$ and am struggling with how to correctly construct the joint PDF to do this. How should I go about constructing these distributions so that the joint PDF, $f_{X,T}(x,t)$, can be plotted using, for example with `ContourPlot` or `Plot3D`?


title: How to calculate volume of convex hull and volume of a 3D object

text: I have a set of random 3D data points. How can I calculate the volume of the convex hull?


title: Boundary condition is not specified on a single edge of the boundary of the domain

text: I am attempting to solve a PDE as prescribed in a paper I am reading; however, Mathematica doesn't seem to be happy with the way I am posing the problem. Im my case, r(t,100) is an approximation of r(t,inf).               d = 27;     k = 10;     s = 1;          sol = NDSolve[       {D[u[t, r], t] == d*(1/r^2) D[r^2*D[u[t, r], r], r],         u[0, r] == 1,         Derivative[0, 1][u][t, s] == (k/d)*u[t, s], u[t, 100] == 1},             u, {t, 0, 10}, {r, 0, 100}]      I am receiving an error stating that my boundary condition u(t,100)==1 is not specified on a single edge of the boundary of the computational domain. The answer is probably very simple, however I am just not seeing it.


title: Bifurcation diagrams for system of equations

text: I am interested in constructing a bifurcation diagram for parameter a in the dynamical system given in the code below. I want to see how parameter changes affect the stability of the system. The answer in bifurcation-diagrams-for-multiple-equation-systems does not apply for Mathematica 8. The following code include the system of differential equations:               Derivative[1][x][t] == -10^12 x[t] - y[t],      Derivative[1][y][t] == x[t] - 10^12 y[t] + a z[t],      Derivative[1][z][t] == -a y[t],      x[0] == y[0] == 0, z[0] == 1      Thanks


title: Optimization without evaluating the analytical expression?

text: Firstly, forgive me for my lack of knowledge of programming and Mathematica. I have an optimization problem involving very large matrices when they are in analytical form. If I tried to generate analytical expressions for what I want to optimize it would be computationally intractable (the matrices are only on the order of 10x10 but each element is many pages worth of analytical expression). But, if for each iteration of the optimization I could plug in the guessed values, compute the numerical value of each cell of the matrix, the problem would become very tractable. Is there a way I can do this with the existing Minimize, NMinimize or FindMinimum functions? To be even more specific, when I try to evaluate Minimize[A(x,y,z) . B(x,y,z) . C(x,y,z), {x,y,z}], where A, B and C are matrices and their dot product would become a huge analytical mess, Mathematica hangs trying to compute the expression before plugging in test values for optimization. How can I fix this or get around it by just plugging in values, evaluating each matrix to just a ~10x10 array of numbers, without building an analytical expression? I'm not even aware of the jargon I would use to search for similar or relevant answers, if anyone could point me in the right direction it would be greatly appreciated.


title: Problem with ViewVector

text: I am trying to have a satellite (camera) move around the earth (unit sphere) and take picture of the earth. The satellite keeps constant distance from the earth, and always looks toward earth center.               Manipulate[         Graphics3D[Sphere[{0, 0, 0}, 1], ViewVector -> {2*{Cos[t], 0, Sin[t]}, {0, 0, 0}}],         {t, 0, 2*Pi}]      This should produce the same size of circle no matter what angle `t` is being used, but the above code scales the images. I think I am not using `ViewVector` correctly here. Any clarification would be greatly appreciated.


title: function of derivative of a function

text: I know a similar question is answered somewhere, but it doesn't work for my case for some reason. I have the following problem in Mathematica. I want to compute f[h[x]]= x^2 + D[h[x],x]. Here, h[x] can be some function of x, say Sin[x]. I have written the following code in Mathematica,               SetAttributes[{f, D}, HoldAll]     f[h_, x_] := x^2 + D[h[x], x]     h := Sin[x]      But then the output of               f[h, 10]      is an error "General::ivar: 10 is not a valid variable." Any better way of doing the composition of functions in Mathematica?   * Sarah


title: Elegant way to match a list with only certain types of elements

text: I'm working on learning Mathematica programming for personal edification and am trying to find a more elegant way to do a matching expression which will match only a list containing elements that are three types, in this case a (sub)list (of any type), integer or string. (It is similar to a problem from chapter 4 of Wellin.) I came up with this answer, using a helper function, but it doesn't seem very elegant. I couldn't figure out a way to do this without a helper function after trying a bunch of syntactical variants.               exp2 = {4, {a, b}, "g"}          integerListStringQ[x_] := IntegerQ[x] || ListQ[x] || StringQ[x]          MatchQ[exp2, {__?integerListStringQ}]     MatchQ[{a, 1, "a"}, {__?integerListStringQ}]     MatchQ[{}, {__?integerListStringQ}]      Expected results: True, False, False. In any event, what I would like is something that looks more like this, perhaps? (Expecting a "True" answer.)               MatchQ[exp2, {__?IntegerQ|ListQ|StringQ}]     MatchQ[exp2, {__?Integer|List|String}]      Anyway, I don't know, but these construction I did above don't work, and the solution I did that does work seems inelegant. I feel that I shouldn't need a helper function for something this basic in a functional language. Thanks!


title: Gröbner basis on a particular set of equations

text: This question is very similar in gist to equation solving with `GroebnerBasis`, but hopefully when I say that I make the system a little larger I mean **little**. I have uploaded the code here for those who are trusting enough to download it. There is a lot of code, and my question of interest is related to the particular system of equations in my uploaded notebook, but I will try to give the general gist here. I have a system of 20 polynomials and 13 variables. If I make one of these variables 0, the `GroebnerBasis` computes instantly. If I do not, the `GroebnerBasis` process maxes out 8GB of RAM after a day or two. I'm interested in knowing what characteristic of the more general set of polynomials is causing the `GroebnerBasis` process to take so long. As you will see if you download the notebook, the system of equations is generated through an iterative process, and I can generate as many polynomials as desired (although they do get more and more complicated). If you have downloaded the notebook, you can generate more polynomials by adjusting the `iterate[22222]` command to, say, `iterate[222222]`. A solution is guaranteed, due to Hilbert's Nullstellensatz (and more specifically in this case because I am able to explicitly show such a solution when I set a particular variable equal to zero). The question I initially referenced uses a few commands (`CoefficientArrays` in particular), and I am curious if the output of those commands would be at all useful in my problem, though I don't know what to look for (and that is the more general gist of my question). I guess what I'm hoping is that someone can tell me, "Ah, yes, when that variable is not zero your system is .... < insert property here >, so a Gröbner basis will be very difficult to compute". * * * By request, I added my code inline here:               deg = 3;     d = Table[        x^i*y^j*z^k, {i, 0, deg}, {j, 0, deg - i}, {k, 0, deg - i - j}];     d = Flatten[d];     v = Table[a[i], {i, 1, Length[d]}];     f = d.v;     cf = CoefficientList[f, {x, y, z}];     Evaluate[cf[[1]][[1]][[1]]] = 0;     Evaluate[cf[[2]][[1]][[1]]] = 0;     Evaluate[cf[[1]][[2]][[1]]] = 0;     Evaluate[cf[[1]][[1]][[2]]] = 1;     Evaluate[cf[[2]][[2]][[1]]] = 0;          cf[[3]][[1]][[1]]     cf[[1]][[3]][[1]]          (* a[17] and a[8] are dependant on a principal curvature assumption. *)          fx = D[f, x];     fy = D[f, y];     fz = D[f, z];     Nf = fx^2 + fy^2 + fz^2;     Lf = D[fx, x] + D[fy, y] + D[fz, z];     NNfNf = fx*D[Nf, x] + fy*D[Nf, y] + fz*D[Nf, z];     g = 2*Nf*Lf - NNfNf - 4*(Nf)^(3/2);     G[0] = g;     Q[0] = Block[{x = 0, y = 0, z = 0}, Simplify[G[0]]]          (* We want Q[0] to be zero, so at the very least we can make the \     following substitution: *)     a[17] = 1 - a[8];          cross1[h_] := D[h, y]*fz - D[h, z]*fy     cross2[h_] := D[h, z]*fx - D[h, x]*fz          nextIndex[index_] := (in = index;       rem = Mod[in, 10];       If[rem != 2, Return[in + 1],        retindex = nextIndex[(in - rem)/10];        Return[retindex*10 + Mod[retindex, 10]]        ];       )          stats[letter_, index_] :=        Print[letter <> "[" <>          ToString[          NumberForm[index, DigitBlock -> 3, NumberSeparator -> " "]] <>          "] (" <> ToString[TimeUsed[]] <> " / " <>          ToString[          NumberForm[MemoryInUse[], DigitBlock -> 3,            NumberSeparator -> " "]] <> " / " <>          ToString[          NumberForm[MaxMemoryUsed[], DigitBlock -> 3,            NumberSeparator -> " "]] <> ")"];          Gdone = {};     Qdone = {};          iterate[num_] := (i = 0;       While[i < num,        i = nextIndex[i];        stats["G", i];        If [Mod[i, 10] == 1, G[i] = cross1[G[(i - Mod[i, 10])/10]],          G[i] = cross2[G[(i - Mod[i, 10])/10]]];        AppendTo[Gdone, i];        stats["Q", i];        Q[i] = Block[{x = 0, y = 0, z = 0}, Simplify[G[i]]];        AppendTo[Qdone, i];        ];       )          iterate[22222]          q = Table[Q[Qdone[[i]]], {i, Length[Qdone]}];          r = q /. {a[8] -> 0};          GroebnerBasis[r, Variables[r]]          GroebnerBasis[q, Variables[q]]      It was designed to be taken in steps, so running it all in one cell may not be very enlightening, but you have the notebook file above if you want it spaced out as well.


title: order items of a table

text: I am trying to change order of a table.               n1 := {6.`, 3.31791383741595`, 2.549684922097378`, 2.2444170593578363`,     2.109892159984955`, 2.0489264006542918`, 2.0214035890309514`, 2.009186379955868`,     2.0038735759286572`, 2.0016085340677456`, 2.0006594467480365`, 2.000267493804639`}          ListLinePlot[n1, DataRange -> {0, 11}]      This is for the graph with the datarange from 0 to 11. However I want to get the graph start at -11 and end at 0. (From the table, n1, 6 is at 0 and 3.3179 is at -1, 2.54 is at -2,...,2.0002674 is at -11.) Is there any good way to do this?


title: Line Intensity Profile From Image

text: I can get line profiles from images using imagej but it would be nice to be able to do this in my mathematica notebooks. I found this http://library.wolfram.com/examples/intensityprofiles/ after some google searches and it is exactly what I want to be able to do. However it seems they removed this package. I cant seem to figure out how to do this in v 9.0. Anyone know how to do this? Edit: I added a picture to make it more clear what I'm talking about. Its important that I can take an arbitrary (diagonal) line and that mathematica interpolates between pixels in a way that makes sense. Sorry if my formatting is off, this is my first post. ![I'm basically trying to do this](http://i.stack.imgur.com/2nytg.png) UPDATE: This is what I think I'm going to use to do what I want. Obviously the display isn't made, and details need to be sorted out, but ImageValue interpolates automatically and seems like the Built-In to use. Thanks for the help everyone.                 img = Import["http://i.imgur.com/szcChXh.png?1"]         (*First Argument of ImageProfile is the arc length along the line profile,         incremented in steps of 1/(npts-1)*)         (*Second Argument of ImageValue is the parametric form of a line, incremented in                steps of 1/(npts-1)*)              ImageProfile[img_, x1_, y1_, x2_, y2_, npts_] :=           Table[{N@((i - 1)/(npts - 1)) Sqrt[(x1 - x2)^2 + (y1 - y2)^2],             ImageValue[             img, {x1 + (x2 - x1) (i - 1)/(npts - 1),               y1 + (y2 - y1) (i - 1)/(npts - 1)}]}, {i, 1, npts}]         pt1 = {500, 300};         pt2 = {600, 600};        Show[img, Graphics[{Red, Thick, Line[{pt1, pt2}]}]]         ListPlot[ImageProfile[img, pt1[[1]], pt1[[2]], pt2[[1]], pt2[[2]],1000], Joined -> True]


title: Supply parameter values in NormFunction of FindFit

text: As I understand the input to the NormFunction is a list of residuals. Is there a way to get parameter values into the NormFunction as well? I ran into a problem where the norm depends on the values of parameters that are being fitted.


title: Open an MX file used by the kernel

text: I am working on a graph, and I am using _Mathematica_ function `FindGraphCommunities` to analyze the properties of this graph, but I have no idea about the algorithm used by _Mathematica_ , and the documentation center is not clear enough. So I decide to look at the defintion of this function to better understand it. I have found a serialized package called "network"(\Mathematica\9.0\SystemFiles\Kernel\SystemResources\Windows\Network) containing files with the MX extension. I opened it with `Import`, but I can not read the files and the defintion of function. My goal is to understand how this function is coded to improve my understanding of what I do with my graph. Hope this is clear.


title: Don't understand why Mathematica is complaining about my Graph expression; how can I fix it?

text: In _Mathematica_ 9.0.1, when I evaluate               Graph[PolyhedronData["GreatRhombicosidodecahedron", "SkeletonRules"],       VertexCoordinates ->          Thread[Table[i, {i, 1, 120}] ->            PolyhedronData["GreatRhombicosidodecahedron", "VertexCoordinates"]]]      No error message was printed, so `Quiet` is ineffective, yet the output is highlighted in 'error red' and on mouseover it states: > Coordinate index -1 is out of range for the enclosing GraphicsComplex. However, the coordinates have clearly been implemented in the `Graph`, so I would like to simply silence this error _just as_ `Quiet` _or_ `Off` _would_ for error messages. I've only encountered this problem in the above context, but suspect the solution is simple. Does anyone know of a solution?


title: Problem with Sort - unexpected order with Sqrt

text: Sort[{13, Sqrt[157], Sqrt[163]}]          (*{13, Sqrt[157], Sqrt[157]}*)          Sort[{13, Sqrt[157], Sqrt[157]}, #1 < #2 &]          (*{Sqrt[157], Sqrt[157], 13}*)      This seems totally broken to me, 13 should always be > `Sqrt[163]` and `Sqrt[157]`. And I only figured out what the problem was when I pasted this into this message - seeing the Sqrt[] funtion rather than the radical sign in the notebook. From my (admittedly limited) understanding of Mathematica, I can sort see how the Sqrt[] would get in the way, but it seems quite painful to have to run output from functions such as Minimize through N before being able to use Sort or SortBy. So, I guess my question is, is this expected behaviour that I just have to learn to live with, or a bug?


title: Extracting coefficients from multiple equations and generating coefficient matrix

text: after 6 hours reading about string patterns, string manipulations and trying ..and trying..I officially give up (for now) and ask for some help. I have some unorderly equations you will find here Note: I only have 6 equations shown here, but actually it's 50 equations. I want to 1) extract the coefficients of every equation and 2) put them in a 50x50 matrix (to get a nice coefficient matrix for this linear system) on the right position, which is indicated by the number behind the name of the variable. For example:               ba5 = 255.587802741733 + 0.416407328023007*ba4 + 0.347918861182194*ba7 + 0.256752019528632*ba42 + 0.142629613367709*ba38 - 0.153600910218342*ba27 - 0.157696503802691*ba39      ba5 means that I want to fill the 5th row of the matrix. ba4 is the 4th column, ba7 is the 7th column, ba42 is the 42th. So in the 4th column the coefficient 0.4164... should be copied and in the 7th the coefficient 0.3479..and so on. As another example look at the second equation:               ba6 = 0.387399976154608*ba8 + 0.343433662895965*ba4 + 0.17517619838171*ba7 + 0.116548914112818*ba44 - 6.80424536420765      Here it is row 6 I want to fill. But this time it should copy the coefficients to the 8th(ba8), 4th(ba4),7th(ba7) and 44th(ba44) column. Additionally I need to copy the independent variable (in this case ba5 and ba6) on the right side of the equation and the constant to the left side to get a system in the form of A*x=y with A as my 50x50 matrix, x as my vector of ba's (ba4, ba5,ba7 asf) and y as my constants (255.587 in the first equation and 6.80 in the second). Right now, my brain is a little bit messed up and I hope you guys can understand what I mean. If not, please ask. EDIT: You can download all equations here Note: They are not continuously numbered and it's 41 equations, my bad :/ EDIT: I tried it like this, but I get some error messages:                 Table[Normal@       CoefficientArrays[        ToExpression[equations[[x]]], {Ba1, ba2, ba3, ba4, ba5, ba6, ba7,          ba8, ba9, ba10, ba13, ba17, ba18, ba19, ba20, ba21, ba22, ba23,          ba24, ba25, ba27, ba28, ba29, ba30, ba31, ba32, ba33, ba34, ba35,          ba36, ba37, ba38, ba39, ba40, ba41, ba42, ba43, ba44, ba45, ba46,          ba47}], {x, 1, 41}]      Errors: http://www.pic-upload.de/view-22173402/errors.png.html I guess it's because ToExpression assigns a value to my Ba's. The same which I use in the list of CoefficientArrays. But I can't use this function when I'm reading strings :/


title: Getting an InterpolatingFunction from a ContourPlot

text: I have a function, say               minimizeme[Ω_][β_][ϵ_] = ϵ^2 Ω - Log[2 (Cosh[2 β] + Cosh[2 β ϵ])]/(2 β);      I want to find its critical points in $\epsilon$ for a given value of $\omega$, varying $\beta$, within certain ranges, i.e. $\omega\geq 0$, $\beta\geq 0$ and $-1\leq \epsilon \leq 1$. When I pick, say, $\omega$ equal to $0.2$, e.g. I define               min20 = minimizeme[0.20];      I can make a `ContourPlot` of the locus of couples $(\beta, \epsilon)$ for which $\frac{\partial m}{\partial \epsilon }=0$, using code               ContourPlot[D[min20[β][ϵ], ϵ] == 0, {β, 0, 10}, {ϵ, -1, 1}, Evaluated -> True]      while I cannot get the software to solve the related equation:               Solve[D[min20[β][ϵ], ϵ] == 0, β, MaxExtraConditions -> All]      yields a `Solve::inex:` message, while               Solve[D[minimizeme[Ω][β][ϵ], ϵ] == 0, β, MaxExtraConditions -> All]      yields `Solve::nsmet:`. Furthermore,               Table[NSolve[D[min20[β][ϵ], ϵ] == 0, ϵ], {β, 1.*^-10, 10}]      results in a few `NSolve::nsmet:` until `General::stop:` kicks in. Finally, `Reduce` behaves just like `Solve`, resulting in either a `Reduce::inex:` or a `Reduce::nsmet:` message. Yet I think that since `ContourPlot` manages to produce a result somehow, Mathematica has a way to find what I need. So, to summarize:   1. How does `ContourPlot` work "internally"? How does it manage to produce the results I see when even `Solve`, `NSolve` and `Reduce` fail?   2. Can I turn the results of this `ContourPlot` into one (or more) `InterpolatingFunction` objects?   3. (bonus question) Are there any alternatives for solving my equation beyond Taylor series expansion? (I have already solved this with Taylor expansion, so I'd like to avoid that at all if possible) Thanks a lot.


title: Cropped pdf file after export

text: I have plot generated by `Plot[]` function that I want to export to pdf file. The problem is that `Export[]` function somehow cuts a tiny bit of plot on the left side which results in something like this: ![Exported image](http://i.stack.imgur.com/RVEQr.png) I'd like to know what should I do to get exported file without cropped $0$.


title: ItoProcess for stochastic reaction-diffusion equation

text: I am trying to simulate a stochastic differential equation in time and space, but I'm unsure if this can be done in Mathematica. The sde that I would like to study is: $$ dN[x,t]=N[x,t](1-N[x,t])dt+\sqrt{N[x,t]}dw+\partial^2_xN[x,t]dt $$ With an exponential decreasing (in space) initial condition N[x,0]=Exp[-|x|]. Is this possible to simulate with ItoProcess? Thank you, Best, Andrea


title: Reflection transform of function

text: I am trying to find the reflection function. Here is my function and its graph.               eq[n_, \[Beta]_, a_] :=  Hypergeometric1F1[1/2 - 1/4 a, n + 1, \[Beta]]     ED[n_, a_, k_Integer: 1] := \[Beta] /.   FindRoot[eq[n, \[Beta], a] == 0, {\[Beta], 0}]     rootslist[n_Integer, k_Integer, a_Integer] :=  Rest@FoldList[     FindRoot[eq[n, \[Beta], #2] == 0, {\[Beta], #1}][[1, 2]] &, 0,Range@a]     firstroot = Table[rootslist[n, 1, 50], {n, 0, 5}]     gr = ListLinePlot[firstroot, PlotRange -> Automatic, AxesLabel -> {(2 - 4 a), \[Beta]},     frame -> False]      If I tried this I can get the function of a graph, (x-axis:a and y-axis:$\beta$). I am wondering how to get the reflection function of this? (x-axis:$\beta$ and y-axis:a)? I have tried this code, but it didn't work.               Show[gr, Plot[a, {a, Automatic}, PlotStyle -> Black],      gr /. L_Line -> {Red, GeometricTransformation[L, ReflectionTransform[{-1, 1}]]}, PlotRange        -> All]


title: Rescale axes (e.g change from Hz to THz)

text: I have multiple plots of permittivity against frequency, but they're hard to read because the frequency labels go from 4x10^14 to 1x10^15 in Hz. I want to label the frequency with THz instead of Hz, so each value would just get divided by 10^12. How do I do this?


title: How to define a function that operate with a base case recursively?

text: Let's start from the simplest case: say I have a function $f(x)=x$, and let's say I want to define a new function (of $x$) to be its $n$-th power $(f(x))^n$. How should I write the code? I tried:               f[n_, x_] := f[n - 1, x]*f[n - 1, x]     f[1, x] = x      But the result is much different from what I wanted.


title: Iterative Function Mapping

text: > **Possible Duplicate:**   >  How to nest my own “times” function to get powers What I want to do is something like :               Sin[...Sin[Sin[Sin[Sin[x]]]]]      Basically, defining a function that maps a said function on an argument said number of times.


title: Outline around sphere

text: Is there an easy way to draw an outline around a sphere? Is there something like `EdgeForm[]` that will work? I'm looking for perhaps a thick red line; I'm making a plot with many spheres of different colors and opacities, and I need a way of visually distinguishing the ones that are "in use" from the ones that are "inert".


title: Applying different color to result of a geometric transformation

text: Background: consider the following two snippets.                 GeometricTransformation[{Cyan, Polygon[{{0, 0}, {.2, .6}, {.8, .2}}]},          Table[RotationTransform[2 \[Pi] k/6], {k, 0, 5}]] // Graphics      ![Mathematica graphics](http://i.stack.imgur.com/m1f93.png)                 Table[GeometricTransformation[{Opacity[.15*k], Cyan, Polygon[{{0, 0}, {.2, .6}, {.8,.2}}]},          RotationTransform[2 \[Pi] k/6]], {k, 0, 5}] // Graphics      ![Mathematica graphics](http://i.stack.imgur.com/OdLnw.png) I make most of my graphics as in the first example. Because that is ( supposedly ) the most efficient way. But I have to add gradient colors ( and other options later ), I found no other way to do it as in the second example. What I in fact want is this:                 GeometricTransformation[g, {ListOfTransformations}]       where g is some geometry. I want to be able to apply different colors to the transformed g's. But not in the way as done in example 2. **Question: How can I apply a different color to the result of a geometric transformation?**


title: Plot3d of explanation of partial partial derivatives

text: I want to plot a two functions together that looks like this: ![enter image description here](http://i.stack.imgur.com/JyJHB.png) But I am only able to come up with this;"which is clearly wrong"               Plot3D[{x^2 + x + y^2, x + y}, {x, -20000, 20000}, {y, -20000, 20000}]      I have looked through the help section but somehow I am not getting how to change it. Ps: I do not care about the range that its plotted in.


title: How do I find an equilateral triangle whose vertices have integer coordinates?

text: In geospace, how do I find coordinates of the vertices of an equilateral triangle whose vertices have integral coordinates? How do I tell _Mathematica_ to do that?


title: Printing a success message if no errors have yet been thrown in the current session

text: I plan to run a lengthy Mathematica script on a Linux terminal (by "a Linux terminal," I mean that I have text output only -- no GUI), using the program `math`. To be able to track the execution progress of my script, I would like to `Print` "success messages" to the terminal when no errors or warnings have been thrown by Mathematica in the current session. For example, here is a very basic script that `Import`s two text files, `test1.txt` and `test2.txt`, using the `"Table"` specification. I would like to write a function or expression that sets the variable `success` to `True` when no error or warning messages have yet been thrown by Mathematica.               Import["test1.txt", "Table"]     success = f;     If[success, Print["test1.txt import successful!"];, Print["General failuire!"];];          Import["test2.txt", "Table"]     success = f;     If[success, Print["test2.txt import successful!"];, Print["General failure!"];];      where `f` is a function or expression that evaluates to `True` when _no error or warning messages have yet been thrown by Mathematica_. Please note that I am _not_ trying to write a function or expression `f` that determines if `test1.txt` or `test2.txt` exists. Rather, I am trying to write an `f` that determines whether **any** errors or warnings **at all** have been thrown during the current Mathematica session. If any have been thrown prior to when `f` is called, then `success` should _always_ be set to `False`, for the remainder of the Mathematica session. Do you have any advice on this? Thank you for your time.


title: How can I solve the equation with integers as a solution?

text: I want to solve the equation $$(x-1)^2 + (y-1)^2 + (z-1)^2 = 49$$ where $x$, $y$, $z$ are integer and $x \neq 1$, $y \neq 1$, $x \neq 1$. How do I tell Mathematica to do that?


title: How do I subtract two contours?

text: Suppose I have this contour described by the equation the root $z$ of this equation $$ \frac{1}{x^2 + y^2} + \frac{1}{xz} = 2y $$ Now suppose the equation is tweaked slightly, with an addition of $w$, where $w$ is a number: $$w + \frac{1}{x^2 + y^2} + \frac{1}{xz} = 2y$$               eq1[x_, y_, z_]  :=  1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq1[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq2[x_, y_, z_]  :=  2 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq2[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq3[x_, y_, z_]  :=  4 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq3[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]      ![enter image description here](http://i.stack.imgur.com/Czleg.png) By visual inspection we see that the curves shift upwards as $w$ increases. However, I need a better way to describe it. Is there a way to **"differentiate the contour"** to find the contour $\frac{\partial z}{\partial w}$? Now suppose the equation is tweaked slightly, with an addition of $w$, where $w$ is a number. Is there a way to **"differentiate the contour"** to find the contour $\frac{\partial z}{\partial w}$? I tried "subtracting" the roots then plotting the contour, but mathematica can't seem to execute this:               eq1[x_, y_, z_] := 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq1[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          eq2[x_, y_, z_] := 2 + 1/(x + y^2) + 1/(x*z) == 2 y     ContourPlot[      z /. FindRoot[eq2[x, y, z], {z, 1}], {x, -5, 5}, {y, -5, 5}]          sol[x_,y_] := FindRoot[eq2[x, y, z], {z, 1}] - FindRoot[eq1[x, y, z], {z, 1}]          ContourPlot[ sol[x,y], {x, -5, 5}, {y, -5, 5}]


title: C interface for Mathematica

text: I would like to write a small C program which starts a Mathematica session, executes some user defined code and retrieves the output and finally quits the session. Basically I like to have a simple custom made user interface for Mathematica based on standard C. I am confident that such libraries exist since I am using a program of this kind for Maple (based on OpenMaple libraries). I just do not know where to start. Maybe somebody can point me to the documentation. Ideal would be a small sample application. Maybe something like this ships with Mathematica? * * * Don't be confused by the comments. Eventhough the answer "see the Documentation" seems obvious here (as I ask for it), the by far best resource for the solution is on the Wolfram webpage. See also my answer below. As far as I can see it is neither referenced in the documentation nor contained in the builtin examples. Not knowing the words to search for it took some effort to find it.


title: replace is not happening for specific vector valued expression

text: Given               x[t_] := {Subscript[x, 1][t], Subscript[x, 2][t]}      following replace works fine               x[t] /. x[t] -> 0     0      but following one is a problem               x[t] - 1 /. x[t] -> 0     {-1 + Subscript[x, 1][t], -1 + Subscript[x, 2][t]}      because I expect there '-1'.


title: How to apply a trigonometric identity to a formula

text: The product of cosines is given by (Wikipedia): $ \prod_{k=1}^{n} \cos{\theta_k} = \frac{1}{2^n}\sum_{e\in S} \cos(e_1\theta_1+\ldots+e_n\theta_n) $ where $S={1,-1}^n$. How can I apply this to a formula in Mathematica, say the formula: $ \cos{n_1}+\cos{n_2}+\cos{n_3}\cos{n_4}+\cos{n_5}\cos{n_6}\cos{n7} $


title: Solve pair of recurrence relations

text: [Corrected equations and added simple example] Can you solve a system of (loosely) coupled recurrence relations like this in _Mathematica_ somehow?               {A[k] ==1+((n-k-2)/n) A[k+1] +(2/n) B[k+1] + (k/n) (A[0]),       B[k]==1+((n-k-1)/n) B[k+1] + (k/n) A[0]}      We want to solve it for $A[0]$ as a closed form function of $n$. $A[k]$ is defined for $0 \leq k \leq n-2$ and $B[k]$ is defined for $1 \leq k \leq n-1$. Version 8 doesn't do anything useful but I suspect I am not asking it in the right way. As a simple example, if you set $n=3$ then you get four simulataneous equations.               A[0] == 1 + (2/3)*B[1] + (1/3)*A[1]     B[1] == 1 + (1/3)*A[0] + (1/3)*B[2]     B[2] == 1 + (2/3)*A[0]     A[1] == 1 + (2/3)*B[2] + (1/3)*A[0]      Solving for $A[0]$ gives you $33/5$ I believe. To start things off, how do you get _Mathematica_ to do this? **Update.** If you just take the second recurrence alone.               B[k]==1+((n-k-1)/n) B[k+1] + (k/n) A[0]      How can you get _Mathematica_ to give a sensible solution for $B[k]$ in terms of $n$ and $A[0]$? It seems Rsolve ought to be able to do this. I even tried               RSolve[{B[k] == 1 + ((n - k - 1)/n) B[k + 1] + ((k)/n) (A[0]),        B[n - 1] == k A[0]/n}, B[k], k]      which should be identical. However this now gives an empty solution with the following warning.               RSolve::bvnul: For some branches of the general solution, the given boundary conditions lead to an empty solution.      I would like to tell _Mathematica_ to only try to solve it for the defined range of $k$. Is that possible?


title: Solving an Integral equation

text: I would like to solve the equation $$\frac{2}{p}\int_0^1((1-u)^{1-p}+u^{1-p})^{\frac{1}{p}}\text{d}u=42$$ for p numerically. I tried               NSolve[2/p*Integrate[(u^(1 - p) + (1 - u)^(1 - p))^(1/p), {u, 0, 1}] == 42, p]      and               FindRoot[2/p*Integrate[(u^(1 - p) + (1 - u)^(1 - p))^(1/p), {u, 0, 1}] == 42, {p, 0.08}]      and               h[p_?NumericQ] := 2/p*NIntegrate[((1 - u)^(1 - p) + u^(1 - p))^(1/p), {u, 0, 1}]     FindRoot[h[p] == 42, {p, 0, 1}]      (I know the answer is approximately 0.0804670), however I still would like to know how it is computed. In both cases, I received errors:               NSolve::nsmet: This system cannot be solved with the methods available to NSolve      and               GCD::exact: "Argument 0.92` in GCD[0,0.92] is not an exact number.     FactorSquareFree::lrgexp: Exponent is out of bounds for function FactorSquareFree.     GCD::exact: "Argument 0.9195355178111501` in GCD[0,0.919536] is not an exact number.      How do I solve this equation? Preferably with as little Integral evaluations, because they are horribly slow. **EDIT** nevermind, sorry. There was a typo in the third try. Thank you for your time >_<


title: How to get full-screen graphics canvas?

text: Is it possible to create a full-screen graphics without any front end elements like cell brackets and scrollbars? The zero approximation can be               {{{z, w}, {z, h}}} = FullScreenArea /. (ScreenInformation /.           Options[$FrontEnd, ScreenInformation]);     CreateDocument[       Graphics[{EdgeForm[Green], Rectangle[{0, 0}, {w, h} - 1], Red,          AbsolutePointSize[1], Point[{100, 100}]},        PlotRange -> {{0, w - 1}, {0, h - 1}}, ImageSize -> {w, h}],       WindowSize -> Full];      As a result I expect a black screen with green border of one pixel width and one red pixel. I guess some options are missing to do the job, but there are quite many places one could try to put them to, so I expect someone more familiar with this functionality will respond.


title: Old notebook (Version 3) not opening in version 9

text: I have some old notebook files in version 3 format from the book "Mathematica for Physicists". These files are blank except for the chapter header when opened in Mathematica 9. I have similar problems with other old notebooks. For example, there is an old notebook called Mir Space Station and it exhibits similar behavior, opening it shows only headers, no formulas or calcuable cells. How can I recover these notebooks and use them in Version 9?


title: How to add an entirely new menu

text: Is it possible to add an entirely new menu, say menu "CustomApp" on the fly? For example a _CustomApp_ package could add its own menu "CustomApp" with submenus, ect, once _Needed_. Former examples I have seen, only dealt with adding to an existing menu.


title: Moles/Liters doesn't get simplified to Molar even though Molar*Liters gets simplified to Moles

text: Why can't Mathematica 9 simplify mol/L to M, when it can simplify M*L to mol?                Quantity["Moles" / "Liters"] // UnitSimplify      (* => 1 mol/L *)           Quantity["Molar" * "Liters"] // UnitSimplify      (* => 1 mol *)      And is there a way to fix this behaviour?


title: Running PlotLegends in Mathematica 8

text: I will like to get a density plot (in _Mathematica 8_ ) as in: Make legend same height as plot.   However, anytime I run               DensityPlot[ Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, PlotLegends -> Automatic]      I get a red coloured `"PlotLegends"` within the input text followed by an error message. I need your help!


title: Can styles be exported in EPS as simple text tags for use by LaTeX's psfrag?

text: Is there a way to export graphics as EPS so that _LaTeX_ can perform style substitutions or modifications on them? I know that it is possible to replace simple text elements in imported EPS files using _LaTeX's_ `psfrag`; but if this is all that is possible, it is not sufficient to enforce a consistent appearance for graphics. That requires the ability to make substitutions to things like line weights and colors. Is there a way to use Mathematica to export EPS files in such a way that style elements are represented as simple text tags that can be easily replaced using `psfrag` (or a similar technique) in _LaTeX_?


title: How to solve an overdetermined system in Mathematica

text: I would like to understand the reasons and find a way to avoid such behaviour of the `Solve` function in Mathematica 8.               Solve[x + y + z == 5 && y == 3 , {x, y}]     (* Out[1]= {{x -> 2 - z, y -> 3}} *)          Solve[x + y + z == 5 && y == 3 , {x}]     (* Out[2]= {} (why empty?) *)      I need to get an answer in the second case. Any suggestions on how to persuade the program to calculate an answer that is even simpler than the first?


title: Package function not called from button in a DockedCell expression

text: Consider the following minimal example package:               BeginPackage["Test`"];          DuplicateNotebook::usage = "Makes a copy of the notebook";          Begin["`Private`"];          DuplicateNotebook[] :=        NotebookPut @ NotebookGet[EvaluationNotebook[]];       ex2 =          Grid[{{Item[ButtonBar[{             Style["Duplicate", 10] :> DuplicateNotebook[],             Style["Quit Kernel", 10] :> FrontEndTokenExecute["EvaluatorQuit"]}],            Alignment -> {Right, Top}]}}];       SetOptions[EvaluationNotebook[],          DockedCells -> Cell[BoxData[ToBoxes[ex2]], "SystemDockedCell"]];          End[];          EndPackage[];      **So what's happening?** The function `DuplicateNotebook[]` defined in the package doesn't get called when the button is clicked, but calls of type `FrontEndTokenExecute["EvaluatorQuit"]` work. What's more, this code was working perfectely well in _Mathematica_ V9, but now in _Mathematica_ V10, I can't get it working without putting the function body directly into `DockedCells`, which of course is a very messy solution. Therefore I'm looking for better workarounds. This seems to be a problem with `DockedCells` context, because putting the cell in the notebook (not in `DockedCells`) works. However adding context information to the call didn't work (I've tried `Test`DuplicateNotebook[]`) Zipped version of the test package http://cl.ly/2C3U2O2n0y21


title: Using new symbol in WhenEvent in NDSolve

text: This is an example in Mathematica's help document.               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,          WhenEvent[y[t] == 0, y'[t] -> -0.95 y'[t]]}, y, {t, 0, 10}];     Plot[y[t] /. %, {t, 0, 10}]      I do a modification like this:               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0, a = y[t]; b=y'[t];        WhenEvent[a == 0, b -> -0.95 b]}, y, {t, 0, 10}];     Plot[y[t] /. %, {t, 0, 10}]      It doesn't work. If I want to keep a new symbol just as here `a` to represent the `y[t]` or some expression about `y[t]` in the `WhenEvent`, what can I do to achieve this goal? (The error may be caused by the `HoldAll` attribute of `WhenEvent`. Why I want to replace the `y[t]` by `a`? It is important to me. Bucause I will use a dynamic `a` in the WhenEvent )


title: Trying to study the three points theorem of the Mobius Transformation

text: I am trying to study the three points theorem of the Mobius transformation. This theorem says that the Mobius transformation $M$ maps three distinct points p, q, r to three distinct points p', q', r'. Based on this formula $$\frac{(z-p)(q-r)}{(z-r)(q-p)}=\frac{(w-p')(q'-r')}{(w-r')(q'-p')}$$, I solved for $w$ and came up with this function.               mobius[z_, z1_, z2_, z3_, w1_, w2_, w3_] :=      (w1 (-w2 (z1 - z2) (z - z3) + w3 (z - z2) (z1 - z3)) -        w2 w3 (z - z1) (z2 - z3))/(w3 (z1 - z2) (z - z3) -        w2 (z - z2) (z1 - z3) + w1 (z - z1) (z2 - z3))      If I substitute z with a eaquation of plane, then I can see how the $M$ maps the plane. What I want to know is that is there a way to mark these points on the graph so that I can see how these points behave?? I am using parametric plot to see the graph. Thanks! \--------Edit---------               plane[x_, y_] := x + y I;     Manipulate[      ParametricPlot[       {{plane[x, y] // Re, plane[x, y] // Im},         {mobius[plane[x, y], z1, z2, z3, w1, w2, w3] //Re,         mobius[plane[x, y], z1, z2, z3, w1, w2, w3] // Im}},        {x, 0, 40}, {y, 0, -40}, PlotRange -> {{-50, 50}, {-50, 50}}],       {z1, {10, 20}}, {z2, {10 I, 20 I}},       {z3, {15, 25}},       {w1, {10, 20}}, {w2, {10 I, 20 I}},       {w3, {15, 25}}]


title: Can Apple's Numbers spreadsheet link to a Mathematica function?

text: I use Apple's Numbers spreadsheet for a single thing, a double entry accounting model to understand complicated financial transactions. A current model depends on the value of a single initialization cell. I calculate this value in Mathematica using `Solve[]` as Numbers can't solve a system of equations. Currently I have to manually input this value in the Number's spreadsheet. Ideally I'd like the cell in Number's to call the Mathematica function. Does any means exist to do this? Excel/Link or Math/Link would appear to provide functionality similar to this, but reading through their respective documentation doesn't provide any clear way to do this with Numbers. I can write command-line code to do this (generally):               $ MathKernel -script file.m      which suggests that AppleScript or some other scripting language could do this if callable/runnable from Numbers. Perhaps all of this suggests a better or more general question: What means exist, if any, for calling a Mathematica function or script from applications outside of Excel or specifically applications programmed for J/Link or Math/Link?


title: How to vary line thickness to add a sense of perspective?

text: Is there a simple way to vary the line thickness relative to the viewpoint so as to add a sense of perspective? Take for example the following:               Manipulate[      lines = Table[{RandomInteger[{-1, 1}] a, RandomInteger[{-1, 1}] a,          RandomInteger[{-1, 1}] a}, {2^a}];       Graphics3D[Line[lines], Boxed -> False], {a, 1, 12, 1}]      ![enter image description here](http://i.stack.imgur.com/4nS3T.png) which generates some lines projected in a 3-dimensional fashion with a clearly visible perspective i.e. the lines of similar length appears longer when closer to the viewer. Since the information regarding apparent distance to the viewpoint is known to the system, it should be possible to retrieve this and modify the thickness of lines accordingly. Is this possible in a simple manner? ![enter image description here](http://i.stack.imgur.com/rt6J9.png) The sketch above illustrates my point, although somewhat clumsy.


title: Select/Delete with Sublist elements?

text: Probably easy and short question, I still didn't fully figure out how to easily select/delete sublists from a list. Example: > tt = {{2, 4}, {4, 8}} I want to delete/select all the elements where the difference between them (`Abs`) is greater than four.


title: Filtering Lists in Mathematica

text: > **Possible Duplicate:**   >  Select/Delete with Sublist elements? I need help in filtering long lists of `x,y` coordinates.Lets use the following list as an example:               list={{3,5},{7,6},{15,6},{23,123}}      I need to filter out all the data points for which `x<10`. Therefore once the filtering is complete the new list should be:               newlist={{15,6},{23,123}}      Please help.Thank you!


title: How to cut elements from set of data based on function restrictions?

text: For example, say I have a set of data which takes the form               list = {{1,2,4,5,3,2},{2,3,4,2,1,6},{2,3,4,5,4,3}}        where all of the elements have a length of 6. Then I have to run this `list` through many functions each with various restrictions e.g.:               ptOf[event_]:=px+py/;(px+py)<4,       where `px` is the first element in the 6 vector `{px,py,_,_,_,_}` and `py` is the second element. How would I cut the elements from the original list that do not satisfy this condition?


title: Picking certain pairs according to a condition

text: I'm a Mathematica beginner and can't find out a solution to my problem. I have a list of pairs of numbers, for example something like this, but much longer: list={{2., 3.}, {3., 2.}, {5., 4.}, {4., 0.}, {5., 0.}, {5., 0.}, {4., 0.}, {5., 4.}}. And now I need to get only pairs for which some rule is true. For example, I'd like Mathematica to give me pairs {x,y} from the aforementioned list, where x=5 and y is any. So in this case I'd get pairs {5., 4.},{5., 0.},{5., 0.} and {5., 4.}. Is there any way to do this? Thanks :))


title: Select {x,y} pairs from a list where x conforms to a rule

text: I'm working on some pet project and I have a very large list of {x,y} pairs. I want to make a new list containing all {x,y} pairs where x is, let's say, even (I actually need something more complicated, but I assume same principle will apply). I just don't get how I'm even supposed to do it, Select doesn't work (or can't make it work) on pairs. I've read Select documentation but it seems I'm missing something essential.


title: What is the best way to create a correlation matrix heatmap with values?

text: This may have been asked somewhere else, but I couldn't find an answer by searching. I'm trying to create a correlation table that colors the background behind the numbers as a heatmap. I've been trying to use `ArrayPlot` with `ColorFunction -> "TemperatureMap"`, but I'm kind of stuck. Example:               data = {{1, 0., -0.8}, {0., 1, 0.}, {-0.8, 0., 1}};     ArrayPlot[data, ColorFunction -> "TemperatureMap", Frame -> None, Mesh -> True]      ![enter image description here](http://i.stack.imgur.com/962mg.png)


title: Manipulate a Differential Equation result

text: I want to Manipulate the result of Differential Equation like :               F[x_] = y[x] /. First@DSolve[x - y'[x] + y''[x] == 0, y[x], x]     Manipulate[Plot[F[x], {x, -10, 10}], {C[1], 1, 6}, {C[2], -2, 5}]      the result of the equation is :               x + x^2/2 + E^x C[1] + C[2]      but I don't get any Curve on the display. ![enter image description here](http://i.stack.imgur.com/zRcut.jpg)


title: Retain values between sessions

text: This is a real newbie question, so apologies in advance for may seem a very dumb question ... I'm trying to understand the various ways in which information can be retained in a notebook between sessions, using `DynamicModule[]` etc. Understanding how a good MMA user would solve the following simple task would be really helpful: Say I want to load a video file and then create a simple slider to scroll through the frames. This works:               frames = Import["myvideofile.avi", {"Frames", All}];      Manipulate[frames[[f]], {f, 1, Length[frames],1}]      But, say I want to remember which frame the slider was left at between Mathematica sessions, how would I do that elegantly? If I re-open the code above, there's an error because 'frames' isn't defined until the video is imported. In other words, upon re-opening the notebook, the first thing I'd like to happen is for 'frames' to be imported. I'm speculating that I need `DynamicModule`, with `Initialization` but have tried many different ways and can't get it to work.


title: Variables Inside Functions Not Evaluating

text: x = 5*y     function1[y_] := x     function1[5]      Am I wrong in thinking that function1[5] should equal 25? Instead this comes out.               5y     5y


title: How does Return work?

text: It is not completely clear to me how `Return[]` works. The documentation says: > `Return[expr]` returns the value expr from a function. But in _Mathematica_ it is not clear where are the boundaries of a "function" defined using patterns and `Set(Delayed)`. The system simply applies replacement rules until there's nothing to change anymore. Consider these examples:               a := (Module[{}, Return[0]; 1]; 2)         a     (* 0 *)      It is not completely clear to me why `Return` breaks out from `a`, and not from `Module` or one of the `CompoundExpression`. The following doesn't work, and simply returns the `Return` expression. It reminds me a bit of how `Unevaluated` is handled.               (Module[{}, Return[0]; 1]; 2)     (* Return[0] *)      If we add another layer of definitions, the effect of `Return` will stop there:               b := (a; 3)     (* 3 *)      Why do these three inputs give different results? What is the general rule for deciding where `Return` breaks out to precisely? The answer lies somewhere in fully understanding the evaluation process. Would someone care to elucidate this point, perhaps with pointers to the parts of the documentation which make this clear?


title: Fourier Transform of a Step Function

text: I'm trying to obtain the form of a sinc function that I know I'm supposed to get in _Mathematica_. I'm doing this because I intend to do a lot with Fourier transforms (FT) and I'd like to know I'm not missing constants or something of the like. For example, consider: $$ f(x) = \begin{cases} A && -\frac{a}{2} ≤ x ≤ \frac{a}{2}\\\ 0 && \text{otherwise}\\\ \end{cases}$$ Employing the following:               FourierTransform[UnitStep[a/2 + x] UnitStep[a/2 - x], x, k, FourierParameters -> {1, -1}]      It gives: `(2 Sin[(a k)/2] UnitStep[a])/k` Is this _Mathematica_ 's way of giving the sinc function? I guess I was expecting something more like `(2 Sin[(a k)/2])/(k a)`. I know there are different parameters that can be used, but none of them have given the form I was expecting. When I try to do the FT directly as an integral:               Integrate[A Exp[-I k x], {k, -a/2, a/2}]      It gives: `(2 A Sin[(a x)/2])/x` Are these the same? I was expecting something that would lead to $\rm{sinc}[k a/2]$. I have not found previous questions that can help, and the documentation in _Mathematica_ (version 8) also has not helped either.


title: Mathematica inserts extra \left and \right for absolute values in LaTeX output

text: Type the following in a _Mathematica_ DisplayFormula cell(other styles may also encounter this problem): `Esc`+`l`+`|`+`Esc` and `Esc`+`r`+`|`+`Esc`, and save as LaTeX. ## Note: See the difference of the character between | |. $z$ and $z_1$, $|z|$, $|z_1|$               Cell[BoxData[      RowBox[{"\[LeftBracketingBar]",       SubscriptBox["z", "1"], "\[RightBracketingBar]"}]], "DisplayFormula"]      with subscript, then... _Mathematica_ inserts extra `\left` and `\right` for absolute values in the LaTeX output:               %% AMS-LaTeX Created by Wolfram Mathematica 9.0 : www.wolfram.com     \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}     \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}     \newcounter{mathematicapage}          \begin{document}         \[         \left\left| Z_1+Z_2\right\right| \leq \left\left| Z_1\right\right| +\left\left| Z_2\right\right|         \]         \end{document}      What should I do to get valid output that LaTeX will accept?


title: What is the most elegant way to see if an expression is affected by a certain symbol?

text: > **Possible Duplicate:**   >  Determine whether some expression contains a given symbol Let's say I have some expression:               sample = {1, 1/q, f[m]}      And I want to check it if it has the symbol `m` in it. My question: Is there a clean or fast way of checking if `m` is in the equation? * * * What I came up with so far:               Do[StringFreeQ[ToString[sample], "m"], {i, 300}] // AbsoluteTiming     (* {0.0120007, Null} *)      and               Do[(sample /. m -> Unique[]) === (sample /. m -> Unique[]), {i, 300}] // AbsoluteTiming     (* {0.0100005, Null} *)      These solutions work, but I feel like there might be a faster, functional way of doing this.


title: Check if a matrix is Positive Semidefinite

text: I have a question concerning the check whether a given matrix is positive semidefinite or not. In mathematica the function `PositiveDefiniteMatrixQ[m]` tells me whether the matrix `m` is positive, but not semidefinite. I wanted to ask whether there exists an implementation for that purpose, and if not, how to implement a code that is as fast as possible.


title: Problems with DumpSave and memoization

text: I defined a function that takes some time to compute using memoization:               y[a_, b_, c_] := y[a, b, c] = First[$y /. NDSolve[.........]       so that if I call y[a,b,c] a second time it doesn't do the `NDSolve` computation all over again if it has already done it. How can I save the result of this to file? I tried `DumpSave["test.mx", y[3/10, 2, 0]]` after calling `y[3/10, 2, 0]` (i.e. it is now an `InterpolatingFunction`; the result of `NDSolve`), but I get the error               "DumpSave::bsnosym: y[3/10,2,0] is not defined as a symbol or a context. >>"      If I call `y[3/10,2,0][2]` etc I get the correct numeric result. Is there some reason this is not working?


title: Why doesn't FullSimplify work properly on this?

text: I wish to simplify the simple expression `fac[n_] := Sum[R^i, {i, 0, n}];` as much as possible for various $n$. `FullSimplify` or `Factor` work on this, but not always, as good as it should be. For example, in the sixth line of               Table[{fac[j], fac[j] // FullSimplify, fac[j] // Factor}, {j, 1, 8}] // TableForm      it seems that `FullSimplify` does not work at all!? ![enter image description here](http://i.stack.imgur.com/hEAEv.png) $1+R+R^2+R^3+R^4+R^5+R^6$ has not been simplified! It is well-known that $$1+R+R^2+R^3+R^4+R^5+R^6=1+(R+R^4)(1+R+R^2).$$ So, now my question is: Is there any way in _Mathematica_ to obtain the very simplified form of the expression `fac[n_] := Sum[R^i, {i, 0, n}];`, just like $1+(R+R^4)(1+R+R^2)$ or even simpler for various $n$? I will be grateful if anyone can give me some tips.


title: Passing a function as an argument of another function

text: > **Possible Duplicate:**   >  Pass function or formula as function parameter I am trying to implement a simple Plot[]-like function, with the same synopsis; my first (and unique so far) try would be something along these lines:               MyPlot[f_, {var_, xmin_, xmax_}] := ListPlot[Table[{y, f[y]}, {y, xmin, xmax, (xmax - xmin)/100}]]      however I have to call the function as follows               MyPlot[Sin,{x,0,1}]      while I would prefer calling the function just like Plot[]               MyPlot[Sin[x],{x,0,1}]      I just don't know how to strip the "[x]" when a function is used as an argument to another function. This is not only a matter of consistency with Plot[], it is also needed in order to use a multi-argument function as the argument, such as:               MultiSin[x_,y_]:=Sin[x+y]/(Sqrt[x^2+y^2])     MyPlot[MultiSin[x,1],{x,0,1}]      which is not possible AFAIK with my simple re-implementation.


title: Multi-Factorial and Series with Triple-factorial terms

text: > Let $n!^{(k)}$ denote a multi-factorial which is defined by $$ n!^{(k)} = > \begin{cases} 1 & n \leqslant 0, \\\ n, & 0 < n < k,\\\ n\times(n-k)!^{(k)}, > & n \geqslant k. \end{cases} $$ > > _E.g._ $8!^{(3)}=8\times5!^{(3)}=8\times5\times2!^{(3)}=8\times5\times2=80$. > For $k=3$ we may also put down $8!!!$. For the case of $k=1$, _Mathematica_ has `Factorial[]` or `!` at hand. For the case of $k=2$, there is `Factorial2[]` or `!!` which calculates double factorials. For the general case of a $k$th factorial, I could define by recursion               In[1]:= MultiFactorial[n_, k_] := If[n < k, If[n <= 0, 1, n], n MultiFactorial[n - k, k]]      which correctly outputs $8!^{(3)}$ as               In[2]:= MultiFactorial[8, 3]     Out[2]:= 80      But when I have a multi-factorial in every term of an infinite series, _Mathematica_ spits out the original input:               In[3]:= Sum[((-1)^n MultiFactorial[3 n, 3])/MultiFactorial[3 n + 1, 3], {n, 0, +∞}]     Out[3]:= (* More or less the same *)      [ ** _Edit_** ] Definition by `Product[]`               In[4]:= MultiFactorial[n_, k_] := Product[i, {i, n, 1, -k}]     In[5]:= Sum[((-1)^n MultiFactorial[3 n, 3])/MultiFactorial[3 n + 1, 3], {n, 0, +∞}]      suggests that the sum is divergent. Yep, I'm trying to verify if $$\sum\limits_{n=0}^{+\infty} \frac{(-1)^n (3n)!^{(3)}}{(3n+1)!^{(3)}} = -\frac{\sqrt[3]{2}}{4} \ln\left(\sqrt[3]{2}-1\right)+\frac{\sqrt{3}\sqrt[3]{2}}{6}\arctan\frac{\sqrt{3}}{1+2\sqrt[3]{2}}.$$ **Question** : Are there any built-in functions for the cases of $k\geqslant3$ which is OK to sum?


title: Pattern matching in subscripted variables

text: I am trying to use subscripted variables as symbols and provide assumptions elegantly for them, e.g. in order to simplify logs, I'd like to have               Simplify[ Log[Subscript[x,1]^2] - Log[Subscript[x,2]^2], Assumptions -> Subscript[x,_] > 0]      be simplified to               Log[Subscript[x,1]^2 / Subscript[x,2]^2]      I am aware of the Notation package, but symbolizing any subscripted variable prevents me from pattern matching variable names. I am as well aware of the fact, that this is an incarnation of the same old story of "Don't put data in your variable names". Apart from that it makes the output hard to read, I couldn't get               Simplify[Log[y[1]^2] - Log[y[2]^2], Assumptions -> y[_] > 0]      to make the desired simplification, either. Hence, putting the subscript as an extra parameter of a "function" fails as well. What would be the elegant and formally correct way to implement the desired behaviour without enumerating the different variables as x1, x2, ... and having to explicitly state the assumption for every single variable in the game? Scope: I have a whole lot of different masses in my calculation, hence I wanted to keep track of them by using subscripts. In the end, I'd like to give certain linear combinations of fundamental masses special names and have logarithms like the ones above simplified. Thank you very much in advance! Best Ben


title: Is there SVM packages available for free?

text: I want to do date minings. And do you know some packages that have been made available online? I am using Mathematica 8 and 9. Thanks.


title: I ran into an error when I was trying to solve a PDE with a piecewise initial condition by NDSolve

text: This is a very simple one-dimensional heat-conduct equation, the only special part of it is the piecewise initial condition:                   b = NDSolve[{D[tes[t, x], t] == D[tes[t, x], x, x] + Exp[-1/(tes[t, x])],                       tes[t, 0] == 1, tes[t, 1] == 1,                       tes[0, x] == Piecewise[{{-100 (x - 0.1)^2 + 2, 0 <= x <= 0.1},                                              {2, 0.1 <= x <= 0.9},                                              {-100 (x - 0.9)^2 + 2, 0.9 <= x <= 1}}]},                      {tes[t, x]}, {t, 0, 100}, {x, 0, 1}]      If you run the code, you will get this warning message: > NDSolve::mxsst: Using maximum number of grid points 10000 allowed by the > MaxPoints or MinStepSize options for independent variable x Why does this message come out? I read the help but I don't think my initial condition has that kind of fault: it's piecewise but smooth, right? * * * I'd like to add another sample here since its behavior makes a interesting contrast to the sample above:               c = NDSolve[{D[tes[t, x], t] == D[tes[t, x], x, x] + Exp[-1/(tes[t, x])],                  tes[t, 0] == 1, tes[t, 1] == 1,                   tes[0, x] == Piecewise[{{-Exp[-1000 x] + 2, 0 <= x <= 0.1},                                          {2, 0.1 <= x <= 0.9},                                           {-Exp[-1000 (1 - x)] + 2, 0.9 <= x <= 1}}]},                 {tes[t, x]}, {t, 0, 100}, {x, 0, 1}]      This example choose `Exp` as the transition between initial condition and boundary conditions, in fact this initial condition is not even continous at `x=0.1` and `x=0.9` in the view of math, and I think the change of `Exp` is more drastic than the polynomial function, but it gets no warning message. Well, I should say, after all this time (notice the time I posted this question) I've already treat this as some kind of bug, but I still expect an in-depth explain for it.


title: Problem creating MeanPredictionBands

text: I have a problem creating `MeanPredictionBands` for my function which I fitted using `NonlinearModelFit`. I have a complex-valued function and I am fitting the real part of the function. Mathematica 8 gives me back a fitted function and with it the `BestFitParameters`. But as soon as I try to feed it the `"MeanPredictionBands"` command, it gives me back the following line: > Experimental`NumericalFunction::nnum: The function [...] is not a number at > {fitparameters}. I have also tried using the `ComplexExpand` function on the real part of my function, which still doesn't help with my situation. Has anybody encountered this particular problem before? All my variables are real, as are the fit parameters. Thank you all for your help! * * * From the file linked in comment a reduced code sample that exhibits the same problem:               ClearAll[msymm2fit];     msymm2fit =  Re[0.145` mV^6 Log[-(0.5929`/mV^2)] + 12 b0V \[Nu]^2 + 8 bDV \[Nu]^2]          MyData2 = {{0.332, 0.807^2}, {0.386, 0.821^2}, {0.447, 0.855^2}};     MyError2 = {0.027, 0.011, 0.029};     MyFit2 = NonlinearModelFit[MyData2, msymm2fit, {mV, b0V, bDV}, \[Nu],        VarianceEstimatorFunction -> (1 &), Weights -> 1/(MyError2)^2,        Method -> {NMinimize, Method -> "DifferentialEvolution"}]          MyFit2["BestFitParameters"]     MyFit2["MeanPredictionBands"]      * * * The inability to create the Bands apparently comes simply from taking the Real part of the function. I tried this out on another, really easy function. If you take               ComplexExpand[Re[]]      of a real valued function, this problem with creating the error bands goes away. In my case, taking the Real part analytically (i.e. by hand) is not that easy, since it is created while i am fitting the data. TL;DR Simply taking the Real part of any function will hinder Mathematica 8 from creating error bands from the fitted function.


title: Import Fortran unformatted binary

text: I have an unformatted binary file generated using the Compaq Visual Fortran compiler (big endian). Here's what the little bit of documentation states about it: The binary file is written in a general format consisting of data arrays, headed by a descriptor record:   1. An 8-character keyword which identifies the data in the block.   2. A 4-byte signed integer defining the number of elements in the block.   3. A 4-character keyword defining the type of data. (`INTE`, `REAL`, `LOGI`, `DOUB`, or `CHAR`) The header items are read in as a single record. The data follows the descriptor on a new record. Numerical arrays are divided into block of up to 1000 items. The physical record size is the same as the block size. Additional keyword info:   1. `SEQHDR` \- 1 item - `INTE` \- Sequence header, with data value. If number is present it is an encoded integer corresponding to the time the file was created.   2. `MINISTEP` \- 1 item - `INTE` \- Ministep number is essentially the data number (ex: psi on day 1)   3. `PARAMS` \- n items - `REAL` \- Vector parameter at ministep value. Attempts to read such data into _Mathematica_ including `Import`               data=Import["file", "Binary", ByteOrdering -> +1];     data = FromCharacterCode[data]      and `OpenRead`               OpenRead["file", BinaryFormat -> True]      ![enter image description here](http://i.stack.imgur.com/f2NYv.jpg) show me some identifiable text, but no useful numerical values. A file in question is available here. Is _Mathematica_ able to parse this file type, and if so, what is the best way?


title: How to switch off all messages?

text: How can I want to switch off **all** messages in a _Mathematica_ session? `Quiet[expr]` allows me to evaluate `expr` without messages. `Off[msg]` switches off the particular message `msg`. Is there a command that, once evaluated, guarantees that all further evaluations will run quietly? (Unless some messages are turned back `On`)


title: Using Table[ ] vs using Do[Append [ ] ]

text: Is it generally better/faster to use the `Table` function over using `Do[Append []]`? For example, I have this piece of code:               inttstar[1] = (tstar[2] - tstar[0])/8;      inttstar[j_] :=       inttstar[j] = (1/4)*(tstar[j + 1]/(j + 1) -            tstar[Abs[j - 1]]/(j - 1)) -              ((-1)^j*tstar[0])/(2*(j^2 - 1))     G = Table[        Coefficient[inttstar[i], tstar[j], 1], {i, 0, m - 1}, {j, 0,          m - 1}];          Gt=Transpose[G];     cmat = T {{0, 1}, {-a, -d}};     cmatk = Outer[Times, cmat, Gt];          aI = {};     Do[      Do[       Do[aI = Append[aI, cmatk[[i, k, j]]], {k, 1, 2 n}], {j, 1,             m}], {i, 1, 2 n}]      As is, it runs correctly. But, can I improve performance by replacing the `Do[Do[Do[....]]]` section with a `Table` function? If so, how would I do that?


title: Text Annotation Disappears in Wrapped 3D Graphics

text: In a 3D graphic, if I wrap a figure, for example,               imagewrapped =       With[{Lx = 10, Ly = 10, Nx = 5, Ny = 5, r0 = 2, ftsz = 12},        Graphics3D[{Table[{Sphere[{ix Lx, iy Ly, 0}, r0]}, {ix, 1, Nx}, {iy,            1, Ny}], Red,          Table[Text[Style[ix, ftsz, Bold], {ix Lx, 0, 0}], {ix, 1, Nx}],          Cyan, Table[          Text[Style[iy, ftsz, Bold], {0, iy Ly, 0}], {iy, 1, Ny}]},         Boxed -> False, Lighting -> Automatic, ViewPoint -> {1, 1, 1},         ImageSize -> {Automatic, 100}, Method -> {"ShrinkWrap" -> True}]]      ![image wrapped](http://i.stack.imgur.com/toGNV.png) some text disappear. How can I wrap the figure without loosing information?


title: unlisting a nested list

text: I have a list like this:               list = {{a,{1,2,3}},{b,{1,2,4}},{c,{{1,4,5,5},{6,3,2,1}}}}      This is a nested list which each element has a name. I want to export it to CSV so I want to un-nest it to look like:               unlist = {{a,{1,2,3}},{b,{1,2,4}},{c1,{1,4,5}},{c2,{6,3,2,1}}}      As the list is very dynamic, the solution solution should be dynamic as well. I mean in different files the `list` has different lengths but the nesting structure is the same. How can I deal with this?


title: Animation of tube with fixed height

text: the problem is following: my task is to make an animation: tube changes its radius but doesn't change its height. With command               Animate[Graphics3D[{CapForm["Square"], Tube[{{0, 0, 0}, {0.5, 0.5, 0.5}}, r]}],              {r, 10^(-9), 1}, AnimationRunning -> False]`      It changes both radius and length. How to make the fixed length?


title: Conditions for proper integrals with DSolve on Mathematica

text: DSolve[{RCS'[s] == SNPH[s] - Sqrt[R2[s] - RCS[s]^2]/b,SNPH'[s] == RCS[s]/a^2, R2'[s] == 2 RCS[s] SNPH[s], RCS[0] == 0., SNPH[0] == snal, R2[0] == ri2}, {RCS, SNPH, R2}, s ]; Here {a,b,snal,r12} are constants.In NDSolve a small shift given in boundary value trick works fine, showing that it is a proper integral. However, what are standard procedures as a workaround in DSolve ( no limits of integration assigned) when the integrand is not improper ?


title: Series expansion of an inverse

text: I have to find the series expansion of the inverse function of : $\arctan\left(\frac{\ln(1+x)}{1+x}\right)$ How do I find out the series expansion of any inverse ? Note: The inverse of a function $f$ is the unique function $f^{-1}$ that verifies $f(f^{-1}(x))=x$ (given $f$ is a bijection)


title: Mouse gestures or keyboard shortcuts for navigating forward/backward in the documentation center

text: Is there any way to get gestures (e.g. trackpad- or Magic-Mouse-swiping left/right) to work for navigating forward and backward in the _Mathematica_ help browser, particularly on a Mac? If not, what are the keyboard shortcuts to navigate forward and backward?


title: Extract urls from list

text: If I have a list like               list = {"my element 1 http://link.com", "http://link2.com my element 2"}      how do I get a list of the links inside each element? Something like               StringCases[list, "http" ~~ _]      probably but I wasn't able to know how to end my pattern.


title: Optimized subset algorithm implementation

text: I was reading a paper from Mathematica Journal.It mentions a code for calculating subsets.                   subSets[s_List] := Variables /@ (Expand[Times @@ (1 + s)] /. Plus -> List) // Sort      Then it mentions the following code as optimized code,               subSetsV[s_List] :=  Distribute[{{}, {#}} & /@ s, List, List, List, Union] // Sort      My problem is I could not get both of these.Can someone please help me with bit of explanation of these snippets.


title: How to make Graphics3D object with different colors

text: Here is a sample `Graphics3D` object:               gr1 = Graphics3D[       GeometricTransformation[        {Red, Sphere[]},         Table[TranslationTransform[{i, 0, 0}], {i, 10}]       ]     ]      ![enter image description here](http://i.stack.imgur.com/tglYM.gif) How do I apply different colors (or other directives) when using `GeometricTransformation`? I get something like the following effect               gr2 = Graphics3D[       GeometricTransformation[{RGBColor @@ RandomReal[{0, 1}, {3}], Sphere[]}, #] & /@        Table[TranslationTransform[{i, 0, 0}], {i, 10}]     ]      ![enter image description here](http://i.stack.imgur.com/3Xngq.gif) So, how to change `gr1` to `gr2`? `Normal@gr1[[1]]` does not change it to many spheres.


title: Clearing memory of a subkernel in a Do loop

text: I have a `Do` loop, which saves data directly to a `.txt` file. However when I leave it running for long periods of time the RAM starts to run out till finally my laptop crashes. I've read similar posts on here but nothing seems to have worked. After each run of the `Do` loop, I no longer need the data because it has been saved in a `.txt` file. This means I don't require _Mathematica_ to use up my RAM remembering it... but I can't get it to stop! I tried putting `ClearSystemCache[]` inside the `Do` loop at the end but this didnt work. I read somewhere that this could be because I need to clear the memory of the individual subkernels. What is meant by subkernel? I run `ParallelEvaluate[]` and it launches four kernels, one for each CPU. Are these 4 kernels called subkernels? If so what is 'sub' about them? But the main question is how do i go about clearing the memory of the subkernals? My set up is               ParallelEvaluate[             Do[                 (bulk of formulae)                If[ (condition), PutAppend[ ]     ]               ]                     ]      I have tried putting               ParallelEvaluate[             Do[                (bulk of formulae)               If[ (condition), PutAppend[ ]     ]               ClearSystemCache[]               ]                     ]      However this doesnt seem to work. I've also tried:   * putting `$HistoryLength = 0;` at the start of the `Do` loop (doesn't change anything)   * putting `Clear["Global`*"]`   * putting `Remove["Global`*"]` inside end of `Do` loop (gives an error) If someone could explain how to clear memory of subkernels and/or give any other suggestions that would be great. Thanks


title: How to open Mathematica from the terminal in OS X

text: So far, when I was working in Linux, I would open my _Mathematica_ files from the terminal by typing:               mathematica filename.nb &      But now, I got a mac, and when I try it says               -bash: mathematica: command not found      So, I have to open the _Mathematica_ files by going to Finder and double clicking the file in a Finder window, which is annoying! I tried to google it, and I expected that it would be easy to find info about it, but I did not find any. Can anybody help me?


title: Problems with For statement

text: I'm trying to iterate some expression through for loop:                a = 0; b = 0.1; ϵ = 0.01; Ns = 100;      lhr[t_] := Normal[Series[-k7 x[t] y[t] /. Nsol /. initConst, {t, 0, Ns}]][[1]]; lhr[t]      rhr1[t_] := Normal[Series[-k7 x[t] y[t] /. Nsol /. initConst, {t, 0, Ns}]][[1]]; rhr1[t]      h = 0.01      For[t = a, t < b, t += h;         If[Abs[lhr[t]] < ϵ*Max[Abs[rhr1[t]]], Print[t]]]      I'm getting following errors: > General::ivar: 0.01` is not a valid variable. >>   >  General::ivar: 0.01` is not a valid variable. >>   >  General::ivar: 0.01` is not a valid variable. >>   >  General::stop: Further output of General::ivar will be suppressed during > this calculation. >> Can you help with this problem?


title: Loading graphics consumes execution time

text: I have created a grid, and also made a list of control objects(ex:inputfields, buttons, etc..). Then, I lay the list in my grid. There is no problem. However, the final layout takes a lot of time. I timed each operation and realized that the final grid layout is the one that takes up a huge chunk of time. Is there a better way of controlling the execution time of the graphics grid. `mygrid = ConstantArray["", {100, 100}]; mybutton1 = Button["Example", ImageSize -> {40, 50}]; myinput2 = InputField[x]; updatedlist = {}; updatedlist = ReplacePart[mygrid, {1, 2} -> mybutton1]; updatedlist = ReplacePart[updatedlist, {2, 3} -> myinput2]; Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]` The above code takes a lot of time to execute. I used the `Timing` function of mathematica to figure out which part took the long time to execute and it was the `Panel[GraphicsGrid[updatedlist, ImageSize -> {30, 40}, ContentSelectable -> True]]` part that was the longest. Because of this, my entire application has slowed down. Can I finetune my code to improve the performance? Look forward to hearing your inputs! Based on the comments blow, I tried to use a grid for the `updatedlist` above, but the problem is, how can I set the `ImageSize` of the `Grid`which is an option for the `GraphicsGrid` and not `Grid`? Thanks in advance,Anuk


title: How to change element color in Periodic Table?

text: The command               ColorData["Atoms", "Panel"]      generates a periodic table. As I don't want to reinvent the wheel, I asked myself how to change the color of each cell in the periodic table, (hydrogen -> pink, iron, gray etc.). I want to do it in the simples way. How can I do that? Since               ElementData[Element, "IconColor"]      is protected I dont have any idea.


title: Debugging with Breakpoints

text: re: Version 9. I typically write concise code and make a real effort to refactor. As such debugging has tended to take care of itself. Recently, I've needed to assemble applications of more complexity, in that it they have deeper hierarchies of functions, lots of them, and often from multiple packages. So I've started to want just a bit more debugging help. I prefer as simple development environment as possible, so I'd like to focus on debugging with native functionality of `Breakpoints`, rather than debugging functions from third parties or Workbench. I just need to see what goes on in the code. While, several questions on the site explore strategies and tactics for debugging. I have not found a concise description of how to effectively use the `Breakpoints` debugging functionality accessible from the menu items:               Evaluation > Debugger Controls > Show Breakpoints Window      either on this site, on Wolfram's site, or in the Mathematica documentation. Opening the Breakpoints debugging window doesn't tell one much. ![enter image description here](http://i.stack.imgur.com/HpqAZ.png) One would expect a clear way to set up breaks and variables to watch, and a way to run code to the specified point. In particular can and how can one:   * set a series of breakpoints both at a functional level and within a function and   * step through processing, point to point? Some examples or mini-overview? Thx.


title: Higher RAM handling by 32bit Mathematica

text: Can 32 bit Mathematica run program which requires more than 4GB RAM ?


title: Legend for ListContourPlot

text: Consider this example below for ListContourPlot.               ListContourPlot[       Table[Sin[j^2 + i], {i, 0, Pi, 0.02}, {j, 0, Pi, 0.02}],        PlotLegends -> Automatic]      I wish to make the Legend look like this: ![enter image description here](http://i.stack.imgur.com/iPTNc.png) I have searched the net but did not find any way of doing this. I'm sure this can be done because that legend in the link is created using _Mathematica_ but I can't figure out how. Maybe it's something very trivial but I would really appreciate if someone could help me with this because I always had a hard time dealing with legends in _Mathematica_. The example that I gave above was just for illustration. My actual function is more like this:-               ListContourPlot[     Table[Cos[Sqrt[bx^2 + by^2]], {bx, -1, 1, 0.1}, {by, -1, 1, 0.1}],      ContourLabels -> All, ColorFunction -> "Rainbow",        PlotLegends -> BarLegend[Automatic, All]]      So the plot looks like this:- ![enter image description here](http://i.stack.imgur.com/GJAtx.jpg) This legend has clear color bands which can be separated like that shown in the legend above. So my question is whatever may be the case can we make a legend that looks like the one I showed.


title: Why is Mathematica limiting the execution time of my calculation?

text: Is there a Front End option (or programming option) in Mathematica 9 that limits the amount of time that functions take to execute? I have a function (as part of a Mathematica Application) that shows page breaks and iterates though each cell of a notebook. The function operated on large notebooks without problem in Mathematica 8, however in Mathematica 9, it reaches a different point of the notebook each time (and almost gets to the end if page breaks are already showing). The function operates without problem on each half of the notebook (and on smaller notebooks). I have not used any TimeConstraint options. Also note, that I am able to execute the function using Workbench (with Mathematica 9). **EDIT** The function is to create a table of contents (a slightly modified version of the code given on Stack Exchange: Generating a Table of Contents). It includes cells that are already tagged. The code is executed via a button.


title: Button doesn't evaluate variable containing Module

text: I have a huge set of code to accomplish a data transformation. I have saved this set of code as eg:                codeset:=Module[{},                 FileNameSetter[Dynamic[Tab2excelFileLocation]];                 RawDataTonnages =Import[Tab2excelFileLocation, {"Sheets", "Tonnages"}];       (*...blah blah blah...data transformation and setting up graphs and stats tables...*)                 FileNameSetter[Dynamic[Tab3excelFileLocation]];                 Tab3RawDataTonnages =Import[Tab3excelFileLocation, {"Sheets", "Tonnages"}]      (*...blah blah blah....data transformation and setting up graphs and stats tables...*)                 ];      Button["Recalculate", codeset]      Later I want to use the two `FileNameSetter` buttons to locate new files. Once this has been done I then want to press the `Recalculate` button to re- evaluate `'codeset'` so that my answers reflect the data from the new files. I have get this to work partially - when I press the button the codeset re- evaluates for the 1st filename setter only even though I have changed both. If I test not by using the button but by re-evaluating the code using shift+enter it works for both filename setters. Why is this happening, I can't understand it.


title: Series of piecewise  functions

text: Let $f_{0}(x):[0,1]\to[0,1]$ be defined by $$f_{0}(x):=\begin{cases} 3x, & \text{if } x\in [0,\frac{1}{3}] \\\ \\\ -3x+2, & \text{if } x\in (\frac{1}{3}, \frac{2}{3}] \\\ \\\ 3x+2, & \text{if } x\in (\frac{2}{3},1] \end{cases} $$ Construct a sequence of function such that $$f_{n+1}(x):=\begin{cases} \frac{1}{3}f_n(3x), & \text{if } x\in [0,\frac{1}{3}] \\\ \\\ \frac{1}{3}+\frac{1}{3}f_n(3x-1), & \text{if } x\in (\frac{1}{3}, \frac{2}{3}] \\\ \\\ \frac{2}{3}+\frac{1}{3}f_n(3x-2), & \text{if } x\in (\frac{2}{3},1] \end{cases},\;\; \forall n\in\mathbb{N}. $$ And then, take the series associated with this sequence. $$f(x):=\sum_{i=0}^{\infty}(-1)^{i}f_i(x).$$ How do I plot some $f_n(x)$ (in function of n) and a good approximation for $f$? I want a plot of then separately and one in the same picture (with more than one $f_n$). Is it possible to make a "zoom" on the picture? Furthermore, is it possible to create a simulation in which one gives a natural number $p$ as an input, and receives as output the graph of some $f_n$ (in function of n) and a good approximation for $f$? $$f_{n}(x):=\begin{cases} \frac{1}{p}f_{n-1}(px), & \text{if } x\in [0,\frac{1}{p}] \\\ \\\ \frac{1}{p}+\frac{1}{p}f_{n-1}(px-1), & \text{if } x\in (\frac{1}{p}, \frac{2}{p}] \\\ \\\ .\\\ .\\\ .\\\ \\\ \frac{p-1}{p}+\frac{1}{p}f_{n-1}(px-p-1), & \text{if } x\in (\frac{p-1}{p},1] \end{cases} $$


title: How to partition three years of data into daily samples

text: I'm trying to find mean of temperature data list. The temperature data list has 3 hours steps which means I have 365*8=2920 temperature measurements per year. My data are temperatures of 13 years. First I found mean temperature of 13 years "t" one by one list by the following:                MeanTemp={Mean[Transpose[Partition[t[[1 ;; 365*8]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8 + 1 ;; 365*8*2]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*2 + 1 ;; 365*8*3]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*3 + 1 ;; 365*8*4]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*4 + 1 ;; 365*8*5]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*5 + 1 ;; 365*8*6]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*6 + 1 ;; 365*8*7]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*7 + 1 ;; 365*8*8]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*8 + 1 ;; 365*8*9]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*9 + 1 ;; 365*8*10]], 8], {2, 1}]],       Mean[Transpose[Partition[t[[365*8*10 + 1 ;; 365*8*11]], 8], {2, 1}]],       Mean[Transpose[        Partition[n[[365*8*11 + 1 ;; 365*8*12]], 8], {2, 1}]],       Mean[Transpose[Partition[n[[365*8*12 + 1 ;; 365*8*13]], 8], {2, 1}]]};      Then I subtract mean temperature of all years from it. Which means I found variance of temperature:               TempVariance={Mean[Transpose[Partition[t[[1 ;; 365*8]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8 + 1 ;; 365*8*2]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*2 + 1 ;; 365*8*3]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*3 + 1 ;; 365*8*4]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*4 + 1 ;; 365*8*5]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*5 + 1 ;; 365*8*6]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*6 + 1 ;; 365*8*7]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*7 + 1 ;; 365*8*8]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*8 + 1 ;; 365*8*9]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[Partition[t[[365*8*9 + 1 ;; 365*8*10]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*10 + 1 ;; 365*8*11]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*11 + 1 ;; 365*8*12]], 8], {2, 1}]] -        meanofyear,       Mean[Transpose[         Partition[t[[365*8*12 + 1 ;; 365*8*13]], 8], {2, 1}]] -        meanofyear}      I think this manuscript would be so long if the data increases.How to decrease the manuscript and increase flexibility?


title: Automatically counting the number of lines of code in a set of notebooks

text: How can I automatically count the number of lines of code "Input" existing inside all the notebook files contained in a specified folder? I know there is the issue of considering or not the automatic line breakings as new lines. But considering the purpose of this exercise (statistically convince that the amount of developed work on Mathematica justifies keeping a license), I'm not searching for exact values.


title: Visualize the output of Trace in a tree structure

text: The output of `Trace[expr]` can be nicely represented as a tree, I guess. Here is an example trace.               x = 5;     Trace[Mod[(3 + x)^2, x - 1]]          (* {{{{x,5},3+5,8},8^2,64},{{x,5},5-1,4},Mod[64,4],0} *)      How can I make a tree graph from this list?


title: Differentiation w/o assiging concrete values

text: v = Subscript[v, 0]*Sin[(Pi*S)/Subscript[S, 0]];     a = dv/ds v;     a = D[v, s]      returns               $RecursionLimit::reclim: Recursion depth of 256 exceeded.      Reference in the link shown by error msg doesn't give me a relief. I'm assuming the root cause is that I'm not assigning concrete values to the variables. But here I want to operate differentiation w/o assigning values (is there explicit name in math for this kind of operation?). Don't even know if it's differentiation specific or general issue for an operation not assigning concrete values (and thus can't assign proper tags to this question either). I haven't been able to find the corresponding reference. Thanks. * * * Update) Code @acl gave works for me now. However, I'm just curious why my code returns the same error even after I corrected "S" to "s", and also removed 2nd line which I didn't really expect `Mathematica` to do anything for.


title: Attaching persistent assumptions to symbol definition

text: _Is it possible to attach assumptions to a symbol?_ This relates to this question. Most of my work involves physical equations, i.e. there are basic assumptions on variables that will always hold true (in a physical sense). My current example involves higher-order Laguerre Gaussian modes:               u[p_, m_, λ_, w_, R_, ψ_, ψ0_, r_, θ_] :=      Sqrt[(2 p!)/((1 + DiscreteDelta[0, m]) π (m + p)!)]     Exp[I (2 p + m + 1) (ψ - ψ0)]/w      ((Sqrt[2] r)/w)^m LaguerreL[p, m, (2 r^2)/w^2]     Exp[-I (2 π)/λ r^2/2 (1/R - I λ/(π w^2)) + I m θ]      For this example, consider $p=m=\psi=\psi 0=0$, which gives the electric field distribution for the basic Gaussian mode. I can get the mode intensity with (I'm sure there is a more concise way of writing the assumption):               Assuming[(And @@ (# > 0 && # ∈ Reals & /@ {λ, w, R, r, θ})) ~And~          (r > 0 && r ∈ Reals && -π < θ <= π && θ ∈ Reals),          Abs[u[0, 0, λ, w, R, 0, 0, r, θ]]^2 //Simplify]      $$\frac{e^{-\frac{2 r^2}{w^2}}}{\pi w^2}$$ Back to the question, _how can I define a function that "simplifies" without explicitly listing the assumptions every time a I perform an algebraic operation on said function?_ Looking at the previously linked question, I can define a function               v[p_, m_, λ_, w_, R_, ψ_, ψ0_, r_, θ_] :=      Assuming[(And @@ (# > 0 && # ∈ Reals & /@ {λ, w, R, r, θ})) ~And~          (r > 0 && r ∈ Reals && -π < θ <= π && θ ∈ Reals),          u[p, m, λ, w, R, ψ, ψ0, r, θ]]      but the `Simplify` operation applies only to the definition, any operation such as               Abs[v[0, 0, λ, w, R, 0, 0, r, θ]]^2 // Simplify      $$\frac{e^{-2 \text{Re}\left[r^2 \left(\frac{1}{w^2}+\frac{i \pi }{R \lambda }\right)\right]}}{\pi \text{Abs}[w]^2}$$ does not simplify. Defining functions using pattern conditions, i.e. `f[a?Positive]:=...` do not allow for algebraic manipulation, as `f[a]` will remain unevaluated. I am hesitant to use `$Assumptions`. Whilst it would work in this specific example, I can see several problems where I'd like to use the same approach, but setting global assumptions would cause other issues.