Mathematica: finding min/max in list

I have a list of coordinates like this one:               {{x1,y1},{x2,y2},{x3,y3},...,{xn,yn}}      I need to get the minimum and the maximum of all x-values and the minimum and maximum of all y-values. Is this possible? If I use the in-built `Min` function for example gives me just the minimum of all x and y values...


Can CDF file embedded in a web page receive external parameters?

I know that I can embed a CDF file inside a web page by using:   1. The embed tag.   2. An object tag with an embed tag inside (better than 1).   3. Using the JavaScript provided by Wolfram (better than 2). My question is how can I pass some data to the CDF file. In the case of Flash, there is a flashvars attribute precisely for this, but I can't find the equivalent for this in Wolfram's CDF deployment documentation. I need this because I plan to embed a CDF in a set of pages that are similar but each for a different set of data. And I want to generate a single CDF for all of them. If this is not possible in this direction, I would be interested in knowing about solutions in the opposite direction: reading the DOM from the CDF file as this would solve my problem too.


Finding specific compositions of an Integer

I need to find all compositions of an integer L wherein all parts do not exсeed l and parts less then l cound not be neighbor. Here is my code               test[arr0_, ll0_] :=       Module[{arr = arr0, ll = ll0},        result = True;        For[i = 1, i < Length[arr], i++,          If[arr[[i]] < ll && arr[[i + 1]] < ll, result = False]];        result        ];     frag[L0_, l0_] :=       Module[{L = L0, l = l0},        part = IntegerPartitions[L, 2*Ceiling[L/l] + 1, Range[l]];        part = Flatten[Map[Permutations[#] &, part], 1];        Select[part, test[#, l] &]        ];     frag[9, 3]          Output: {{3, 3, 3}, {3, 2, 3, 1}, {3, 1, 3, 2}, {2, 3, 3, 1}, {2, 3, 1, 3}, {1, 3, 3, 2}, {1, 3, 2, 3}, {1, 3, 1, 3, 1}}      I guess Mathematica allows to solve this problem much more easier


Can I use SelectComponents with measurements that take into account the value of underlying pixels?

Normally, we can ask for the mean, median, etc. underlying pixel values for morphological components with the command:               ComponentMeasurements[{MorphologicalComponents[img], img}, "MeanIntensity"]      I'm looking to use SelectComponents to select components based on their mean or median underlying pixel values. However, commands like the following:               SelectComponents[{MorphologicalComponents[img], img}, "MeanIntensity", # < 0.4 &];      Seem to simply fail. Is there a way to proceed? Clarification - Actually, let me be a bit more specific about my question. I mean to first select MorphologicalComponents of a modified version of the image, specifically after running a filter on it. I then want to prune morphological components based on pixel values in the original unfiltered image. So I'd like to do something like this:               SelectComponents[{MorphologicalComponents[LaplacianFilter[img,3]], img}, "MeanIntensity", # < 0.4 &];


Visualizing vector spherical harmonics

I have painstakingly derived the vector-spherical harmonics $\mathbf{V}_{J,\,M}^\ell(\theta, \phi)$, which are the generalization of ordinary spherical harmonics $Y_\ell^m(\theta, \phi)$ to vector fields. But now, I would like to visualize them. The vector-spherical harmonics takes three integers ($\ell$, $J$, $M$), and yields a 3D vector field on the surface of a sphere ($\theta$, $\phi$). The integers are subject to the constraints: $J\geq0$, $\ell\geq0$, $|J-\ell|\leq 1$, $|M|\leq J$. The function `VectorSphericalHarmonicV` below generates a 3-component _complex_ vector.               Clear[ϵ]; (*Polarization vector*)     ϵ[λ_] = Switch[λ,        -1, {1, -I, 0}/Sqrt[2],         0, {0, 0, 1},         1, {1, I, 0}/Sqrt[2]   ];          Clear[VectorSphericalHarmonicV];     VectorSphericalHarmonicV[ℓ_, J_, M_, θ_, ϕ_] /;        J >= 0 && ℓ >= 0 && Abs[J - ℓ] <= 1 && Abs[M] <= J :=        Sum[         If[Abs[M - λ] <= ℓ, ClebschGordan[{ℓ, M - λ}, {1, λ}, {J, M}], 0]*         SphericalHarmonicY[ℓ, M - λ, θ, ϕ]*ϵ[λ], {λ, -1, 1}   ]          (*Examples*)     VectorSphericalHarmonicV[1, 1, -1, θ, ϕ]     VectorSphericalHarmonicV[1, 1, 0, θ, ϕ]     VectorSphericalHarmonicV[1, 1, 1, θ, ϕ]      Honestly, not sure what the best visual representation is. But, I am thinking a good one is to display a bunch of vectors on the surface of a sphere in the spirit of this one: ![enter image description here](http://i.stack.imgur.com/e0U38.png) A sticking point for me is how do I tell _Mathematica_ to display vectors ONLY an the surface? Also, because these vectors are complex, maybe the vectors can be colored to indicate the phases? Perhaps you have a better way to represent these functions?


Need Help Writing (a Pascal) Matrix in Mathematica

I want to write a function $f[n]$ in Mathematica which gives me an $n\times n$ lower triangular Pascal matrix with a row of zeros in between each nonzero row. That is, I want the matrices \begin{pmatrix} 1&0&0\\\ 0&0&0\\\ 1&1&0\\\ \end{pmatrix} \begin{pmatrix} 1&0&0&0&0\\\ 0&0&0&0&0\\\ 1&1&0&0&0\\\ 0&0&0&0&0\\\ 1&2&1&0&0\\\ \end{pmatrix} \begin{pmatrix} 1&0&0&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&1&0&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&2&1&0&0&0&0\\\ 0&0&0&0&0&0&0\\\ 1&3&3&1&0&0&0\\\ \end{pmatrix} Thanks for your help.


Simplify the multiplication such as $a*(b+c)$ to $a*b+a*c$

I am trying to solve this problem here but have to understand basics. Suppose I have a multiplication such as $a*(b+c+d+...+x)$. How can I multiply it to the result $a*b+a*c+...+a*x$? **Trials** > **[Not working]** Reduce[(a + b)*c] > > **[Not working]** Simplify[(a + b)*c] or FullSimplify[(a + b)*c]


Read return value as string by Mathlink.h

I'm using "mathlink.h" to call _Mathematica_ from a C program. I send a computation to _Mathematica_ and its return result is a very big number (100 digits). Hence, I want to read that number as a string. How can I do it using _MathLink_? Thanks,


Can I compile a function containing ArcTanh?

Can I compile a function that contains ArcTanh[]? The following doesn't work               Needs["CCodeGenerator`"]     c = Compile[ {{x}}, ArcTanh[x]^2];     c[2.5]      _Mathematica_ gives me > >     "CompiledFunction::cfn: Numerical error encountered at instruction 1; >      proceeding with uncompiled evaluation>>" >   However, in the answer to this question, a reply indicates that `ArcTanh` can be compiled.


Removing an extra curly braces when using Grid with an If statment

I use `Grid` to align controls in Manipulate. Here is a simple example               Grid[{          {name1,Control2,value1},          {name2,Control1,value2}         }]      The 3 fields above come out aligned automatically, even when one field, such as name, is longer than another, and `Spacing` can be used to control field width for all controls at once. A problem shows up when I need to use an `If` statement to build controls based on selection used in previous control:               Grid[{          {name1,Control2,value1},               (*now make a control based on above value*)               {Dynamic[If[name1==1,                      {name2,Control1,value2},                      {name3,Control3,value3}                     ]                  ]          }         }]      This works well, and allows me to change the controls that appear on the UI based on a selection that was made in another control but the problem with the above is that it gives an extra set of `{}` coming out from inside the `If` needed grouping which ends up messing up the alignment. I think I need to use `Sequence` or some other function to remove the inner `{}` but can't figure the syntax. I made below a simple working code to illustrate               Manipulate[      eq,           Grid[{             {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {Dynamic[If[eq == 1,                {"v1",            Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],            Dynamic[v1]            },                {"v2",            Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}],            Dynamic[v2]            }           ]], SpanFromLeft         }}       ],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      which gives ![enter image description here](http://i.stack.imgur.com/IUdoe.png) You can see that the whole expression was treated as if I wrote               Grid[{          {name1,Control2,value1},          {{name2,Control1,value2}}         }]      I tried using `First`, `Sequence` but can't get it to come out correct. Again, I need to keep the 3 fields in each `Row` separate and in a List. I can't just use `Row` since it means each row will collapse to become one field, not three fields, and I lost the alignment I needed, i.e. I can't just write               Manipulate[      eq,           Grid[{             {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {         Dynamic[If[eq == 1,                Row[{"v1",             Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],             Dynamic[v1]             }],                Row[{"v2",             Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}],             Dynamic[v2]             }]           ]], SpanFromLeft         }        }            ],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/SzDCS.png) Any idea how to make the above work and remove those extra `{}`? **edit** Let me just clarify why using `Row` as a solution does not work. Compare the following 2 examples               Manipulate[eq,           Grid[{        {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {Dynamic[If[eq == 1,               Row[{"v1", Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],Dynamic[v1]}],               Row[{"v2", Manipulator[Dynamic[v2, {v2 = #} &], {0, 2, .1}], Dynamic[v2]}]         ]]        }             }],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/abtcG.png) We can see that the whole `Row` was treated as one field. I want to the above to come out _as if_ I have written this               Manipulate[eq,           Grid[{        {"eq", SetterBar[Dynamic[eq], {1, 2}], Dynamic[eq]},             {"v1", Manipulator[Dynamic[v1, {v1 = #} &], {0, 2, .1}],Dynamic[v1]}             }],           {{eq, 1}, None},      {{v1, 1}, None},      {{v2, 1}, None}      ]      ![enter image description here](http://i.stack.imgur.com/5uBzq.png) You see the difference? This is the important part. thanks.


Compute Correlation between two binary variables

> $X_1$ and $X_2$ are two binary stochastic variables with simultaneous > probabilitydistribution: > > $$ \begin{matrix} &X_2=0&X_2=1\\\ X_1=0&0.30&0.17\\\ X_1=1&0.08&0.45 > \end{matrix} $$ I want to calculate the correlation between $X_1$ and $X_2$.               Correlation[{{0.30, 0.17}, {0.08, 0.45}}]      The output I get is `{{1,-1},{-1,1}}` The solution I seek is: `0.05011` It should be pretty simple, but I have no idea where I am wrong.


How to calculate expected return, row by row in matrix?

Please help me, I'm writing my project and dont know how to solve this big matrix: ![enter image description here](http://i.stack.imgur.com/SOxL2.png) I have to compute return row by row: 1st row: (18.32-17.14)/17.14 ; (19.17-18.32)/18.32 .... 2nd row:(11.79-13.86)/13.86 ; (11.37-11.79)/11.79 ....


Problem when defining function through NIntegrate and NDSolve and Interpolation - Bug?

More than a single question, I have some doubts about the output of certain functions when defined through the result of other calculations. I am an active user of Mathematica, but maybe I haven't read deeply enough about Attributes or related things. Here is the following minimal example:               {tini, tfin} = {-Log[100], 0};     firstFuncK=NDSolve[{D[f[t,k],t]+f[t,k]^2+(1-t)*f[t,k]==3/2*     (1+k^2),f[tini,k]==1},f,{t,tini,tfin},{k,0.001,10}]          secondFuncK[t_?NumberQ, k_] :=      Exp[NIntegrate[f[et, k] /. firstFuncK, {et, tini, t}]]          thirdFuncK[t_,k_]:=Log[N[secondFuncK[t,k]/secondFuncK[-Log[100],k]]][[1]]      Here comes the first question, why exactly do I need the `[[1]]` or `First` and the `N`. Without them I get:               thirdFuncK[-1,0.01]     {Log[4.11782/secondFuncK[-Log[100],0.01]]}      It is weird that Mathematica doesn't output a number, since secondFuncK is already numerical. And I don't understand why I get a List in this case:               thirdFuncLin[et_]=thirdFuncK[et,0.01];      Output:               thirdFuncLin[-1]     {1.41532}          Plot[thirdFuncLin[tt],{tt,-4,0}]      ![thirdFuncK](http://i.stack.imgur.com/poJ4F.png) But the real problem is when I use this function to interpolate:               thirdInterp=Interpolation[Table[{et,thirdFuncLin[et][[1]]},{et,-Log[100],0,0.01}]]      I get a completely different result:               Plot[thirdInterp[tt], {tt, -4, 0}]      ![thirdInterp](http://i.stack.imgur.com/39TyC.png) I know there are related questions of simple mistakes people do, but I haven't found anything that helps me really to understand the core of this problem. Thanks for any suggestions also on style or optimization.


Listing matrices up to symmetry

I am interested in the equivalence relation on N x N binary matrices, in which two matrices are equivalent if one can be obtained by rotating/reflecting the other. I would like to obtain a list `binclasses = { {B1, m1},...{Bk, mk} }`, where Bi is a representative element of class i, and mi is the size of that class. (Of course the requirement of binary matrices is somewhat artificial here, so the question could be rephrased for matrices taking values in a finite set). For N =2, I am looking to obtain the list `binclasses = {{{{0, 0}, {0, 0}}, 1}, {{{0, 0}, {0, 1}}, 4}, {{{0, 0}, {1, 1}}, 4}, {{{0, 1}, {1, 0}}, 2}, {{{0, 1}, {1, 1}}, 4}, {{{1, 1}, {1, 1}}, 1}}` My thought process so far has been as follows:   1. Define a list `binlist` of all N x N binary matrices.   2. Choose an element `currmat` from `binlist`, and generate a list `currsym` of all rotations and reflections of `currmat`.    3. Define a new list `binminsym` which is `binlist` with all elements of `currsym` removed.   4. Add the pair `{currmat, Length[currsym]}` to a new list `binclasses`.   5. Set `binlist = binminsym`, return to step 1.  I am guessing that this is not a particularly efficient approach, and am curious to know how one could better go about the problem. **EDIT** A second update, I have improved on the original code, however, it still runs slowly (original edit left below this for information). In this variation I first group binary matrices by the number of 1s, and the number of adjacent 1s; this means that fewer list elements need be checked against each other. At the moment for the 4 x 4 case, this version takes a little over 4 minutes to identify the 8548 equivalence classes, compared to the 17 minutes of the previous method.               (* sTotal function gives total of all matrix entries *)     sTotal[matrix_] :=        Sum[matrix[[i, j]], {i, 1, Length[matrix]}, {j, 1, Length[matrix]}];          (* eTotal function gives total number of adjacent non-zero entries *)          halo[matrix_] :=      Module[{cmat},       cmat = ConstantArray[0, {Length[matrix] + 1, Length[matrix] + 1}];       cmat[[1 ;; Length[matrix], 1 ;; Length[matrix] ]] = matrix;       cmat]          eTotal[matrix_] :=        Sum[halo[matrix][[i, j]] (halo[matrix][[i, j + 1]] +            halo[matrix][[i + 1, j]]), {i, 1, Length[matrix]}, {j, 1,          Length[matrix]}];               Timing[      Clear[mdim, blist, bgrlist, binclasses, binreps, currbg, currmat,         currsym]            mdim = 4; (*matrix dimensions*)      blist = Tuples[{0, 1}, {mdim,          mdim}];  (* All square binary matrices of size mdim *)            (* blist grouped into sets of matrices with equal number of 1s, and \     equal adjacent 1s *)      bgrlist = GatherBy[blist, {sTotal, eTotal}];            (* Initialise list of equivalence classes *)      binclasses = {};      binreps = {};      ]               Timing[      Do[       Do[         currbg = bgrlist[[i, j]];         While[Length[currbg] >= 1,          currmat = currbg[[1]];          currsym = symlist[currmat];          binclasses = Append[binclasses, {currmat, Length[currsym]}];          binreps = Append[binreps, currmat];          If[i != 1 + (mdim^2 /2 ),           binreps =              Append[binreps, ConstantArray[1, {mdim, mdim}] - currmat];           ];          currbg = DeleteCases[currbg, x_ /; MemberQ[currsym, x] == True];          ]         , {j, 1, Length[bgrlist[[i]]]}];       , {i, 1, Ceiling[Length[bgrlist]/2]}];      Length[binreps]      ]      **EDIT** Here is my code for the above algorithm. Note, that I have defined the symmetries of the square as functions, even though some of them (eg. reflection in diagonal) are simply transposing the matrix. I did this for clarity (for readers on here), rather than efficiency!               (*Symmetry functions.*)     vsym[matrix_] := Reverse[matrix, {2}];     hsym[matrix_] := Reverse[matrix];     d1sym[matrix_] := Transpose[matrix];     r1sym[matrix_] := vsym[d1sym[matrix]];     d2sym[matrix_] := r1sym[vsym[matrix]];          (*List of all distinct symmetries of given matrix *)     symlist[matrix_] :=        DeleteDuplicates[{matrix, vsym[matrix], hsym[matrix], d1sym[matrix],          d2sym[matrix], r1sym[matrix], r1sym[r1sym[matrix]],          r1sym[r1sym[r1sym[matrix]]]}];          (* All square binary matrices of size mdim *)      binlist[mdim_] := binlist = Tuples[{0, 1}, {mdim, mdim}];          (* Initialise list of equivalence classes *)     binclasses = {};          binlist[2];          While[ Length[binlist] >= 1,      (currmat = binlist[[1]];        currsym = symlist[currmat];        binclasses = Append[binclasses, {currmat, Length[currsym]}];        binlist = DeleteCases[binlist, x_ /; MemberQ[currsym, x] == True]);      ]


How to plot logarithmic scales

How can a simple logarithmic number line be drawn between any 2 integer values? ![logarithmic number line of integer values](http://i.stack.imgur.com/gvIsj.png) The closest function I found in the documentation is `LogLinearPlot[]` and I've been racking my brains trying to figure out how to do this with no luck...


How to add the position of an added vertical line to the plot itself?

In this question it is answered how to add a vertical line to a graph. However, it has not been shown that how can someone add the position of that vertical line to the axis. How can I add the coordinate of a vertical line to the graph itself? I want to be able to change the font size of the coordinate too. By using the code below I can change the font size of the coordinate of axes. I want similar thing for the solution to this question too.               FrameStyle -> Directive[Black, Bold, 80]      Here is an example:               line3 = Line[{{2.33, -2}, {2.33, 2}}];     Plot[Sin[x], {x, 0, 2*Pi}, PlotStyle -> {Thick, Red}, Frame -> True, FrameStyle ->Directive[Thick, Bold, 20], Epilog -> {Directive[Thick, Blue], line3}]      Result: ![enter image description here](http://i.stack.imgur.com/0Giig.jpg)


Determining all possible traversals of a tree

I have a list:               B={423, {{53, {39, 65, 423}}, {66, {67, 81, 423}}, {424, {25, 40, 423}}}};      This list can be visualized as a tree using `TreeForm[B]`: ![TreeForm\[B\]](http://i.stack.imgur.com/ORXFl.jpg) and I would like to find all possible traversals of this tree:               {{423,53,39},{423,53,65},{423,53,423},{423,66,67},{423,66,81},      {423,66,423},{423,424,25},{423,424,40},{423,424,423}}      It seems that `Subset` might be usable, but when I tried `Subset[B,{3}]`, it gave me the null set. Another possible problem with `Subset` is that it perhaps does not respect the leveling of the tree. I looked at the `Combinatorica` package, but I don't see a way to traverse the tree -- in the direction from top to bottom -- in all possible ways.


Is there a way to increase the smoothness of a cylinder?

I am using `Cylinder` to produce wide flat disks (in _Mathematica_ 8). This works just fine except that the circular base of such a cylinder turns out to be really just a 40-gon which is simply too coarse an approximation to a circle for what I have in mind. Is there a way to convince _Mathematica_ to use say a 200-gon as a circular base for a cylinder? Here is an example of the kind of picture that I am trying to create. Zoom in to see how coarse the cylinders' curved surfaces pan out.               Graphics3D[{Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, -0.9510565162951536`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 0.9510565162951536`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.85065080835204`, 0.`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.85065080835204`, 0.`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, -0.5`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, 0.5`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, -0.5`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, 0.5`, 0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, -0.8090169943749475`, \     -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`,            0.8090169943749475`, -0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, -0.8090169943749475`,            0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, 0.8090169943749475`,            0.42532540417601994`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 0.`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, 1.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.42532540417602`, 0.3090169943749474`,            0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.7236067977499789`, 0.5257311121191336`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.16245984811645317`, 0.5`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, 0.8090169943749473`,            0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.27639320225002106`, 0.8506508083520399`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.42532540417602`, -0.3090169943749474`,            0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.7236067977499789`, -0.5257311121191336`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.85065080835204`, 0.`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.16245984811645317`, -0.5`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.27639320225002106`, -0.8506508083520399`,            0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.2628655560595668`, -0.8090169943749473`,            0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5257311121191336`, 0.`, 0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.8944271909999159`, 0.`, 0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, -0.5`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.6881909602355868`, 0.5`, 0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.7236067977499789`, -0.5257311121191336`, \     -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.42532540417602`, -0.3090169943749474`, \     -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 0.`, -1.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`, -0.8090169943749473`, \     -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.16245984811645317`, -0.5`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.27639320225002106`, -0.8506508083520399`, \     -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.7236067977499789`,            0.5257311121191336`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.42532540417602`,            0.3090169943749474`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.85065080835204`, 0.`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.27639320225002106`,            0.8506508083520399`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.16245984811645317`, 0.5`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.2628655560595668`,            0.8090169943749473`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.8944271909999159`, 0.`, -0.4472135954999579`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5257311121191336`, 0.`, -0.8506508083520399`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, 0.5`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.6881909602355868`, -0.5`, -0.5257311121191336`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, 1.`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5877852522924731`, 0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.9510565162951535`, 0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.9510565162951535`, -0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {-0.5877852522924731`, -0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0}, 0.0011 {0.`, -1.`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5877852522924731`, -0.8090169943749473`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.9510565162951535`, -0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.9510565162951535`, 0.3090169943749474`, 0.`}}, .1],        Cylinder[{{0, 0, 0},          0.0011 {0.5877852522924731`, 0.8090169943749473`, 0.`}}, .1]}]


nested numerical integration: not valid limits?

I encountered an error when I was hoping for some Mathematica (8.0.4) magic sparing me to code up numerical integration, function approximation and root- finding myself. The broader context and the reference functions here come from a previous question:               k=10/3;     H = ParetoDistribution[1.18709*10^6, 0.938482];     Hstar = H;     u[c_,l_]=Log[c]-Log[1+l^(1+k)/(1+k)];     T[z_]=(1-0.84/1.3) * z;     lType[n_]=ArgMax[{u[n l-T[n l],l],l>=0},l];     zType[n_] = n lType[n];      where `u` is the utility function as in Saez 2001 allowing for income effects, `T` the actual tax schedule (approximate). Note that `lType` and `zType` only makes sense numerically. The original problem with               Type=InverseFunction[zType]      was solved with not `SetDelayed` but `Set` everywhere. But the following nested (numerical) integration does not work (for any H distribution you give it). Have I defined it wrong?               g[z_]:=NSolve[T'[z]/(1-T'[z])-(k SurvivalFunction[H,z]/(z PDF[Hstar,z]))              Integrate[(1-g)Exp[Integrate[1-\[Xi]u[zzz]/\[Xi]c[zzz],{zzz,z,zz}]]             PDF[H,zz]/SurvivalFunction[H,z],{zz,z,\[Infinity]}],g,Reals];     N[g[2000000], 10]      Error: > NIntegrate::nlim: zzz = zz is not a valid limit of integration. **EDIT** : More interestingly, when I simply specify numeric arguments for the inner integral, the computation starts, though does not finish in an hour:                 tmp[z_?NumericQ, zz_?NumericQ] := NIntegrate[1 - \[Xi]u[zzz]/\[Xi]c[zzz], {zzz, z, zz}]       g[z_] := NSolve[T'[z]/(1 - T'[z]) - (k SurvivalFunction[H,z]/(z PDF[Hstar, z]))          NIntegrate[(1 - g) Exp[tmp[z, zz]] PDF[H, zz]/SurvivalFunction[H, z], {zz,z,          \[Infinity]}], g, Reals]      But the same gives me an error if I compile first. Why? Because the limit at infinity? How should I proceed?                   tmp = Compile[{{z, _Real}, {zz, _Real}},NIntegrate[1 - \[Xi]u[zzz]/\[Xi]c[zzz],          {zzz, z, zz}],Parallelization -> True, CompilationTarget -> "C"]      Then I run g[2000000] and get the error: > CompiledFunction::cfsa: "Argument zz at position 2 should be a !(\"machine- > size real number\")."


Plotting Piecewise function, ExclusionsStyle not shown completely

Suppose I define               f[x] := Piecewise[{{1.7*10^-6, 150 <= x <= 200}}, 0]      and then plot               Plot[Evaluate[f[x]], {x, 0, 1000}, PlotStyle -> {Red, Thick},          ExclusionsStyle -> {Dashed, Red}]      I get an interrupted dashed vertical line on left ![Plot of Piecewise function with Exclusion dashed line missing](http://i.stack.imgur.com/B7SlY.png) Anyone know why this happens and how to draw the entire dashed line?


More efficient Omnibus number determination?

Amusing myself with concepts from "Omnibus Sequences, Coupon Collection, and Missing Word Counts", in particular the sequences. To paraphrase the concept, a string is _k-Omni_ over some alphabet _a_ if any string of length _k_ (or less) from the alphabet can be found as a sequence of the string. e.g.,               string={5, 4, 0, 5, 3, 3, 1, 4, 0, 2, 4, 0, 2, 3, 5, 0, 0, 0, 5, 4, 2, 3, 3, 5, 5, 4, 1, 5, 5, 4, 4, 5, 3, 2, 1, 3, 1, 2, 2, 4}      is 2-Omni over the alphabet of the string, and 4-Omni over a restricted alphabet of `{1,2,3}`. I'm using               kOmni = Block[{f = Total@BitSet[0, DeleteDuplicates@#1], z, cnt = 0},        Fold[If[(z = BitAnd[f, BitSet[#, #2]]) == f, cnt++; 0, z] &, 0, #2];cnt] &      which takes the alphabet and string as arguments, to determine the _k_ for various conditions, e.g. `kOmni[{1, 2, 3}, string]` returns the desired 4 result. Might there be a more efficient way to do this? You can assume strings (and alphabets) are limited to non-negative integers, and alphabets are almost always under 200 distinct values, but the strings can be quite large (>10^5 elements). Update: An optimization I came up with nodding off...               kOmniO = Block[{f, z, cnt = 0, s = #2, a = DeleteDuplicates@#1},        s = Join[a, s];        s = s[[Sort@(Join @@               GatherBy[Range@Length@s, s[[#]] &][[;; Length@a, 2 ;;]])]];        f = Total@BitSet[0, a];        Fold[If[(z = BitSet[#, #2]) == f, cnt++; 0, z] &, 0, s];        cnt] &      About 50% faster for full alphabet, and with alphabet that is a subset of string alphabet, can be over an order of magnitude faster. I still have a gut feeling there's a faster/smarter way to do this... c'mon wizards ;-)


How to plot imaginary part of a function

I need to plot the cube root of x in mathematica, but the plot shows me only the real part. I want it to look like wolframalpha plot with both real and imaginary parts of the function. Is it possible to do it? EDIT: This is what I want the plot to look like


Find the solution of A^2+AB+B^2 = f(a,b,c)

I wanted to ask the following question: I need to find the solutions (a particular one is enough!) A and B of the equation > $A^2 + AB + B^2 = (a^2+ab+b^2)(c^2+cd+c^2)$ How can I do it? Thank you very much!


Leveling peaks in list

Consider the following:               data={2,2,2,5,3,3,3,6,1,1,1,0};     In[1]:=result=MyFunction@data     Out[1]:={2,2,3.5,3.5,3,3,4.5,4.5,1,1,1,0}      `data[[{4,8}]]` represent the peaks which I want to level via `MyFunction` as follows:               {a___,PrePeakValue1_,peak1_,b___,PrePeakValue2_,peak2_,c___}:>{a,Mean1,Mean1,b,Mean2,Mean2,c}      whereas `Mean1=Mean@{PrePeakValue1,peak1}` (i.e. `Mean@{2,5}`) and `Mean2=Mean@{PrePeakValue2,peak2}` (i.e. `Mean@{3,6}`). I posted this question  already some time ago, but Heike's approach has one disadvantage: neither it identifies and therefor nor levels the second peak. I think using `LengthWhile` migth be one reason why it won't work. EDIT: `data` is just an example. I have other lists which may contain no, one or more than two peaks.


How to detect crosses and circles in 60x60 raster images?

I have hand-written 60 pixel times 60 pixel squares. I need to detect whether they are empty, x or circle. TextRecognize function fails. Is there some other function to process this kind of raster images with text? ![enter image description here](http://i.stack.imgur.com/NWXCe.png) **Harder example** > **Circles:** (0,0..9), (0..5,0), (0..5,9), (5,0..9) > > **Crosses:** (2,3..6), (4,4..5) > > **Empty:** (1,1..8), (2,1..2), (3,1..8), (4,1..3), (4,6..8) * * * I try to summarize and help people to solve the harder puzzle. Work in progress. Have fun! > I. **Preprocessing** (example) > >> 1.1. thread about getting grid from raster image >> >> 1.2. convexity fix >> >> 1.3. rotation > > II. **Testing** > >> 2.1. Further info about mathematical morphology and Mathematica's intro.


How do I evaluate a double or triple integral over a region?

Say I need to evaluate the integral $\iiint_W f(x,y,z) dx dy dz$ and $W$ is a region given to me like $W = \\{ (x,y,z) : 1 \leq x^2 + y^2 \leq 4, 1 \leq z \leq 5\\}$. I don't how to do this with a triple integral in _Mathematica_ code.


How to create a numerically "equal" function?

A simple example about what I need to do. For example, I have three functions:               t1[x,t]     t2[x,t]     t3[x,t]      and,               t3[x_,t_]:=t1[x,t]+t2[x,t]       What is the best way to create a function t4[x,t] that is numerically "equal" to t3[x,t] but is not function of t1[x,t] and t2[x,t] in order to avoid a circular reference in a While loop program? Regards!


Checking if a point is in a convex 3D polyhedron

Extending from these questions How to check if a 3D point is in a planar polygon? and How to check if a 2D point is in a polygon?. I'm trying to do this to render specific shapes made up of spheres. For a sphere it is easy:               (* generate a grid of points*)     d = 20;     points = Table[{x, y, z}, {x, -d, d}, {y, -d, d}, {z, -d, d}]~Flatten~2;          (*check if they are inside a spherical shell*)     points2 = Select[points, 8.5 < Norm[#] < 10 &];          (*render the spheres that are inside the spherical shell*)     Graphics3D[{Sphere[#, 0.75]} & /@ points2, Boxed -> False]      ![Mathematica graphics](http://i.stack.imgur.com/vsbtV.png) However, I want to try and do the same rendering for other shapes, for example a pentagonal dipyramid               Graphics3D[{Lighter@Lighter@Blue, Opacity[.8], EdgeForm[Thickness[ 0.005]], PolyhedronData["PentagonalDipyramid", "Faces"]}, Boxed -> False]      ![Mathematica graphics](http://i.stack.imgur.com/K69AH.png) However, I'm not sure how to check if the points on the grid are with in the polyhedron. I can access the faces... `PolyhedronData["PentagonalDipyramid", "Faces"]`


System of ODEs specified by large coefficient matrices

What is the best way to call `NDSolve` for solving a system of differential equations of the form               Am.y'[x] + Bm.y[x]/x + Cm.y[x] == Dv       with `y[0] == Ev` in the interval x from 0 to 1. where y is an n-vector, Am, Bm, and Cm are n x n coefficient matrices, and Dv and Ev are n vectors. Say with               n=100;     Am = RandomReal[1,{n,n}];     Bm = RandomReal[1,{n,n}];     Cm = RandomReal[1,{n,n}];     Dv = RandomReal[1,{n}];     Ev = RandomReal[1,{n}];


Retrieving Data from Excel Using NETLink / Pulling data using RTD Link

Reference: I've looked at the posting Open excel file with _Mathematica_. My intention is to be able to use Excel's RTD capability in order to pull market data into _Mathematica_. To my knowledge, this can be done, at the least, by having Excel use the RTD link, then using NETLINK to grab the value from Excel. At some point, it would be nice to have _Mathematica_ pulling real time data from an Excel RTD link, but for now the RTD link value is only updated once per day.               Needs["NETLink`"]     PullValue[file_String] :=       Module[{excel, workbook, worksheet, RTDvalue},        NetBlock[InstallNET[];         excel = CreateCOMObject["Excel.Application"];         If[! NETObjectQ[excel], Return[$Failed], excel[Visible] = True;          workbook = excel@Workbooks@Add[];          worksheet = workbook@Worksheets@Item[1];          worksheet@Range["A1"]@Value =            "=ProphetX|QUOTE!'@CT@A?SettlementPrice'";          RTDvalue = worksheet@Range["A1"]@Value;          workbook@SaveAs[file];          workbook@Close[False];          excel@Quit[];]];        LoadNETType["System.GC"];       GC`Collect[]         RTDvalue];          outputfile = "C:\\Temp\\demo.xlsx";     Quiet[DeleteFile[outputfile]];     PullValue[outputfile];      The `=ProphetX|QUOTE!'@CT@A?SettlementPrice'` is the RTD portion, which at this point is putting a value into the saved Excel file, which should be correct. Sometimes when dealing with RTD links, I've noticed that I need to use `FormulaArray`, but `@value` seems to be working fine here. `Print[RTDvalue]` is outputting -2146826246, instead of the correct value of ~ 81.26 So, I am wondering how I can get those values RTD values, which have gone into an Excel cell, into _Mathematica_ , like they did in the posted link. Also, any direction or thought on how I could eventually have the data coming into *Mathematica*in real time.


Use a custom3D graphic for points in ListPointPlot3D

I would like to make a plot where the points of ListPointPlot3D are themselves a Graphics3D object created using SphericalPlot3D, and each one depends on the position of the point. So basically, you have a list of points, {x, y, z}, and at each point there is a graphic which is determined by a function f(xi, yi, zi). I have been searching for about a day now to try and find a solution to this with no luck. Any help is greatly appreciated. Also, I don't have to use ListPointPlot3D, and if there is a better method I would certainly welcome it.


To what extent can NonlinearModelFit be sped up?

Can `NonlinearModelFit` be parallelized or compiled to allow one to achieve a scalable speedup for a fitting procedure? Attempting to use this function to fit a bivariate Gaussian (with a decent guess for initial conditions) can take upwards of a second.


Plots using TextAlignment with SwatchLegend to left align multi-line items

I have Legends that stretch over multi-lines and the only way I can get them left aligned is by adding white space to the end of the legend item. Does anyone know if there is a way to use TextAlignment with SwatchLegend?               gJ = Plot[Sin[x], {x, 1, 12},        PlotLegends -> {Placed[          SwatchLegend[{RGBColor[1, 0.5, 0], RGBColor[0., 0.329412, 0.],             RGBColor[0.619608, 0.25098, 1.],             RGBColor[0, 1, 1]}, {"it ends up centred", "but ",             "fox jumped over two lines that I want to \nalign to the left",             "A quick brown"},            LegendMarkers -> {Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}],              Graphics[{EdgeForm[], Rectangle[]}]},            LegendLayout -> "ReversedColumn", LegendMarkerSize -> 16,            LabelStyle -> {FontFamily -> "Arial", 18},            Spacings -> {0.5, 0.25}], {0.4167, 0.7701}]}]      ![enter image description here](http://i.stack.imgur.com/MFBdF.png)


AstronomicalData and Planetary Heliocentric (x,y,z) Velocity Components

I'm trying to find data on the heliocentric velocities of planets in our solar system and was directed to _Mathematica_ 's `AstronomicalData` in a previous topic. Unfortunately I cannot find any x,y and z velocity components and was hoping someone might be able to point me in the right direction.


Forecasting future Stock Prices II

I intend to do the following: I want to forecast future stock price under the following assumptions: The stock price is governed by the stochastic differential equation: dS = μSdt + σSdWt whereas dW_t~N(0,√dt) In the first step I want to define the Brownian Motion for one path and for multiple paths, which is done by: **1Path:**               BrownianMotion[period_, steps_Integer: 1000, init_: 0] := Accumulate[        Prepend[RandomVariate[NormalDistribution[0, Sqrt[period/steps]],        steps], init]]          ListLinePlot[BrownianMotion[1,1000], AxesLabel->{"Time",B_t},        PlotLabel -> Style["Stochastic Brownian Motion",Bold]]       **Multiple Paths:**               BrownianMotionPaths[period_, steps_Integer: 1000, paths_Integer, init_List]      /; (Length[init] == paths) := Transpose[       Accumulate[        Prepend[RandomVariate[NormalDistribution[0, Sqrt[period/ steps ]],      {steps, paths}], init]]]          ListLinePlot[BrownianMotionPaths[1, 1000, 50,         ConstantArray[0.5, 50]],         AxesLabel->{"Time",B_t},         PlotLabel -> Style["Stochastic Brownian Motion",Bold]]      So I get the following, which works perfectly for one path:               μ2 = 0.01; σ2 = 0.3; S2 = 100;          ListLinePlot[S2*(1+μ2ConstantArray[1,251] + BrownianMotion[1, 250]*σ2),       AxesLabel→{"Time","St"},        PlotLabel -> Style["Price by proxy data"],        PlotRange -> All]      NOW I want to manipulate S2,μ2, and σ2. In order to do so, I entered the following code:               Manipulate[       ListLinePlot[S1*(1 + μ1 ConstantArray[1, 251] + BrownianMotion[1, 250] * σ2),        AxesLabel -> {"Time", "St"},        PlotLabel -> Style["Price by proxy data"],        PlotRange -> All],        {S1, 100, 500, Appearance -> "Labeled"},        {μ1, 0, 1, Appearance -> "Labeled"},        {σ1, 0, 1, Appearance -> "Labeled"}]      It works, but the results must be wrong, because when I choose Sigma to be small and increase Mu drastically, I should get something which looks like an exponentially increasing function, because the function is driven heavily by the drift. However, according to my code this is not the case. So something must be wrong. Does anybody have a solution when I want to manipulate the start value (S1), Sigma, and Mu, for one and for multiple paths?


How to calculate the volume of a convex hull?

Given a spatial curve represented by a parametric equation, is it possible in _Mathematica_ 9 to calculate symbolically (or at least numerically) the volume of its convex hull?


How to fix a PDF line rendering problem in V9

If I run this in V8               Export["test.pdf", Grid[       Table[x, {10}, {7}],       Alignment -> {{Left, {Right}}, Center},       Background -> {None, White},       BaseStyle -> Directive[FontFamily -> "Times", 12],       Dividers -> {{1 -> White, -1 -> White}, {3 -> True,           6 -> True, -1 -> True}},       Frame -> False,       FrameStyle -> Directive[AbsoluteThickness[0.5], Black],       ItemSize -> {{35, {9}}, 1.5},       ItemStyle -> {Automatic, {Bold}},       Spacings -> {{1, 1, {0.5}, 2}, {0.5}}]]      I get divider lines of the correct thickness. If I run it in V9 the divider line thickness is screwed up. With not only the lines being different to the specification but the line thicknesses vary from each other despite all being specified to have the same thickness. Coincidentally I have noticed this the same day as this question was posted. It appears something became broken in V9. I am wondering if anyone has any suggestions for fixes? I am using Mac 10.9.2 and V9.0.1 and V8.0.4


How do I find the all valid pairings between two sets?

I have a pretty hard problem to solve here, and I have no idea how to start. I have X kind of fruits and 5 colors (let's say Red, Green, Yellow, Blue and Purple). Each fruit can be available in several colors (but in at least 1). How can I find each combination, when I need exactly 1 fruit of each color but no fruit twice (so there will always be bought exaclty 5 fruits in exactly 5 different colors)? For example:   1. Pears are available in [Red, Green, Yellow]   2. Apples are available in [Red, Green]   3. Plums are available in [Purple]   4. Grapes are available in [Red, Green, Purple]   5. Bananas are available in [Blue, Yellow] Since bananas are the only fruit available in blue, it's already sure, that bananas will be bought in blue, and not in yellow. These would be the solution for this list:   1. Yellow Pear, Red Apple, Purple Plum, Green Grapes, Blue Banana   2. Yellow Pear, Green Apple, Purple Plum, Red Grapes, Blue Banana No other combination is possible here. Is there any algorithm to do this with a dynamic list, which may also have more than 5 fruits? I know, it's a pretty hard problem, but maybe someone has a simple solution for it.


intersection between function and plane

I try to solve a ODE system of equations and i want to plot the intersection of the 3D solutions with a costant plane. To do this i use the follow code:               Clear["Global`*"]     tfin = 500;     T = p1^2/2 + p2^2/2;     V = x^2/2 + y^2/2 + x^2 y - y^3/3;     H = T + V;     eq1 = x'[t] == D[H, p1] /. p1 -> p1[t];     eq2 = y'[t] == D[H, p2] /. p2 -> p2[t];     eq3 = p1'[t] == -D[H, x] /. {x -> x[t], y -> y[t]};     eq4 = p2'[t] == -D[H, y] /. {x -> x[t], y -> y[t]};     energy = (H /. {x -> -.1, y -> -.2, p2 -> -.05}) == 0.06;     sol = Solve[energy, p1];     p10 = p1 /. sol[[2]];     sol2 = NDSolve[{eq1, eq2, eq3, eq4,         x[0] == -.1,         y[0] == -.2,         p1[0] == p10,         p2[0] == -.05},        {x[t], y[t], p1[t], p2[t]}, {t, 0, tfin}, MaxSteps -> 5000];     a = ParametricPlot[Evaluate[{x[t], y[t]} /. sol2], {t, 0, 20}];     b = ParametricPlot[Evaluate[{x[t], p1[t]} /. sol2], {t, 0, 20}];     c = ParametricPlot[Evaluate[{y[t], p2[t]} /. sol2], {t, 0, 20}];               gr1 = ParametricPlot3D[Evaluate[{x[t], y[t], p2[t]} /. sol2],        {t, 0, tfin},         PlotPoints -> 4000, BoxRatios -> {1, 1, 1}, ViewPoint -> {1, 0, -2},        DisplayFunction -> Identity];      This is the 'plane' of intersection. Maybe I must use something like `PLot3D[0.,{y,ymin,ymax},{z,zmin,zmax}]` because i want a plane that intersect the orbit in the plane x=0.               gr2 = Graphics3D[{Green, Opacity[0.9],          Polygon[{{0, -.31, -.31}, {0, -.35, .35}, {0, .35, .35}, {0, .35, \     -.31}}]}, DisplayFunction -> Identity];      This is the 'intersection' i only plot the solutions with a very thin x-axis but this is not a plot of the points of intersection between the solutions and the plane (pl1):               ParametricPlot3D[Evaluate[{x[t], y[t], p2[t]} /. sol2], {t, 0, tfin},      PlotPoints -> 4000, PlotStyle -> Directive[Red, Thick],       PlotRange -> {{0, 0.002}, {-.4, .4}, {-.4, .4}},      ViewPoint -> {1, 0, 0}, AxesLabel -> {"", "y", "p2"},       ImageSize -> {500, 500}]          Show[gr1, gr2, DisplayFunction -> $DisplayFunction,       ImageSize -> {500, 500}]      Can someone help me please?


PDF of binomial distribution and mixed binomial distribution

I want to plot the PDF of binomial distributed function and a mixed binomial distributed function, therefore I entered for the binomial distribution function the following:               Remove["Global`*"];     m = 45; (*number of banks*)     n = 5;(*number of defaults*)     AssetV = 100;(*asset value at T*)     DebtV = 80;(*debt value at T*)     μ = 0.2;(*annual drift*)     σ = 0.3;(*annual volatility*)     T = 5;(*years*)     ρ = 0.8; (*asset correlation*)          (*calculation of the individual default probabiltiy p^*, which is \     determined based on the Merton model*)                P* = (CDF[            NormalDistribution[], -(Log[                 AssetV/DebtV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[               T])])     (*generating data table, which captures the probabilities that the \     number of defaults will be greater than n1, whereas n1 encompasses \     the range from 0 to m by the step of 1 (integer)*)          dataBD = Table[       Probability[x >= n1,         x \[Distributed] BinomialDistribution[m,  P*]], {n1, 0, m,         1}]      now I want to plot everything:               pdfBD = DiscretePlot[       PDF[BinomialDistribution[m, P*], n1], {n1, 0, m},        PlotRange -> All, AxesLabel -> {"# of Defaults", "PD"},        Joined -> True, ImageSize -> 500]      so I get this plot ![enter image description here](http://i.stack.imgur.com/dxe9p.jpg) now I want to consider the mixed binomial distribution, determiend by the following code:               dataMBD =       Table[1 -         CDF[NormalDistribution[], ((1/             Sqrt[ρ])*(((Sqrt[                1 - ρ])*(InverseCDF[                 NormalDistribution[], (n1/m)]) + (InverseCDF[                NormalDistribution[], (CDF[                  NormalDistribution[], -(Log[                       AssetV/DebtV] + (μ - 0.5*σ^2)*                       T)/(σ*Sqrt[T])])]))))], {n1, 0, m, 1}]      However, if I want to see its PDF and if I therefore enter this command it does not work:               DiscretePlot[PDF[dataMBD, n1], {n1, 0, m, 1}]      Is the error within the command above, or is there a fundamental problem based on wrong understanding? hope somebody can help me. thanks.


ListPlot InterpolationOrder->0 datapoint centered

it is possible to get a histogram style in `ListPlot` using `InterpolationOrder->0`               testdata = {{1, 3}, {3, 4}, {4, 3}, {5, 8}, {7, 6}, {9, 4}};     ListPlot[testdata, Joined -> True, InterpolationOrder -> 0,      Epilog -> {PointSize[Large], Point[testdata]}]      ![enter image description here](http://i.stack.imgur.com/kfem4.jpg) Note that the data points are sitting at the corner of the histograms at the left end of the horizontal lines. My question is: How could I plot the same data set with the data points being centered on the horizontal line segments? For equidistant data points this is of course a simple shift. But how to do this for irregularly gridded data? Edit 1: To clarify: Of course this is possibly not very meaningfull in irregularly spaced cases, and centered is the wrong term, however, in the example case the data point connection I was looking for could look like the following: ![enter image description here](http://i.stack.imgur.com/8UtCJ.jpg)


How to evaluate sums that have 0^0 = 1

In my code:               summand[k_, x_] := (0.25*x*mu)^k/(k!*Pochhammer[(m + 1)/2, k])*                        Hypergeometric1F1[(m + 1)/2, (m + 1)/2 + k, eta];          cumdistfunc[x_] := 1 - 0.5^(m (m + 1)) Exp[-eta] Exp[Tr[kappa x]] Sum[summand[k, x], {k, 0, 20}]      I have that the summand function ought to be able to be evaluated at `0` so that the value of my cumulative distribution function at `0` is actually `0`. Do you know how I could do that? Thank you so much!


NMaxmize with a list of variables

I want to use NMaximize to find the maximum value of a function with multiple variables. The problem is I would like to set this up so the number of variables is only decided when the function sees the data. So I have:               NMaximize[{F[data,a1,a2],a1>0,a2>0},{a1,a2}]      when there are data from two genes. But would like the function to be               NMaximize[{F[data,a1,a2,a3],a1>0,a2>0,a3>0},{a1,a2,a3}]      if there are 3 genes...etc Any way to set this?


Is there a fast way to trilaterate a point?

I have a point in 2D or 3D space at an unknown coordinate, $p_0$, and I'd like to determine its position using distances from known coordinates $(p_1, p_2, p_3)$. Beyond using `Reduce`, what is a fast method of doing this in _Mathematica_ , particularly for the two-dimensional case? Is there some built-in function for this? Also, how can I get an output in coordinate form without any string processing? For example, to parse the output from `Reduce`, I need to convert the output to a string, infer where the actual coordinate values are, and extract them, which is an awful way to go about doing things. Here's an implementation with `Solve`:               PostOne = {10, 10};     PostTwo = {10, 0};     PostThree = {0, 0};          PointToLocalize = {x0, y0};          D1 = 0;     D2 = 10;     D3 = 200^(1/2);          Solve[EuclideanDistance[PointToLocalize, PostOne] == D1 &&            EuclideanDistance[PointToLocalize, PostTwo] == D2 &&            EuclideanDistance[PointToLocalize, PostThree] == D3, {x0, y0}]      Now that the string processing issues have been resolved, is `Solve` or `Reduce` really the most efficient way to do this for $10^6$ or $10^7$ or so points?


Kramers-Kronig Mathematica code

I'm trying to write Mathematica code to use Kramers-Kronig on a csv file with 2 columns. Column 1 is h(eV). It goes from 0 to 6, in increments of 0.1. Column 2 is alpha (cm^-1). For some reason, my code just outputs a blank graph. Can someone please tell me what's wrong with it? This is the equation I'm trying to implement (thanks J.M. for doing the latex) $$n_r(\hbar\omega)-1=\frac{c\cdot h}{2\pi^2}P\int_0^\infty \frac{\alpha(\hbar\omega^\prime)}{(\hbar\omega^\prime)^2-(\hbar\omega)^2}d(\hbar\omega^\prime)$$ The reason I posted on this forum is that my code is based on the code from another topic on this site (Update: wrong link, see comments below)               c = 300000000;     data = Import["kk.csv", "CSV"];     column1 = data[[All, 1]];     column2 = data[[All, 2]];     Delete[column1, 1];     Delete[column2, 1];          output :=        1 + (c PlanckConstant)/(2 pi^2)          NIntegrate[column2/(column1^2 - omega^2), {omega, (column1)^2, 0, infinity},            Method -> "PrincipalValue", Exclusions -> Automatic]          Plot[output, {column1, 0, 6}, AxesOrigin -> {0, 0}]


How do I display a histogram with normalized counts?

I have some data corresponding to real number distances: `{200.04053, 200.232123, 156.3242,...}`, and I would like to bin these values and display them as a histogram where the heights of each bar in the histogram are normalized so that the sum of all the bin heights is equal to one. The objective here is for me to be able to use `FindDistributionParameters` to determine, well, appropriate distribution parameters, and then to overlay the PDF of this suggested distribution on my actual data. Is there an easy way to do this?


Why is CityData[All, "Coordinates"] failing?

When I evaluate               CityData[All, "Coordinates"]      _Mathematica_ returns > >     {Missing["NotAvailable"], Missing["NotAvailable"]} >   but when I evaluate `CityData[All]` or `CityData[{All, "USA"}]`, it behaves as expected, and returns a gigantic list of cities. I'm curious to modify the neat example for `FindShortestTour`, to use coordinates from `CityData` \-- _yes it may take a very long time, but I'm curious to see for myself_ :) My guess is that it is because not every city in the database has coordinates mapped thereto - but why is _Mathematica_ failing this way? **How can I programmatically eliminate the cities with 'bad' coordinates? Or programmatically build a list of all cities that do have coordinates?**


Symbolic evaluation fails because it exceeds $RecursionLimit

I am trying to perform a simple arithmetic in complex algebra.                      a := Subscript[a, 1] + I*Subscript[a, 2];            b := Subscript[b, 1] + I*Subscript[b, 2];            r[z_] := a/(b - z) + a\[Conjugate]/(b\[Conjugate] - z);      when I try to evaluate r[0], mathematica gives me the following message                      $RecursionLimit::reclim: Recursion depth of 256 exceeded.      I was expecting something like the following                      2*Re[a/b] = 2 (a_1 * b_1 + a_2 * b_2)/(b_1 ^2 + b_2 ^2)      Could someone please point out where I did mess up?


Is there a better way to add a "key" for the list of GatherBy?

In ruby ,               1.upto(10).to_a.group_by{|x| x%3}      gives               {1=>[1, 4, 7, 10], 2=>[2, 5, 8], 0=>[3, 6, 9]}      I would like use patten replace as a hash table in _Mathematica_. For example:               {1 -> {1, 4, 7, 10}, 2 -> {2, 5, 8}, 0 -> {3, 6, 9}}      I know I can use `GatherBy`, but it only contains the value. I tried to solve and I feel it isn't efficient for a large list.               fun = Mod[#, 3] &;     Thread[fun /@ #[[All, 1]] -> #] &@GatherBy[Range[10], fun]


Find the derivatives of arbitrary order of a function found using NDSolve

For the following initial value problem               BC[b_]:=x[0]==b;     eq[b_]:=NDSolve[{equation==0, BC[b]}, x, {t,0,1000}];     body[t_,b_]:= x[t]/.eq[b];      one could define the derivative of `body` with regard to `t` as               Dbody[t_,b_]:=x'[t]/.eq[b];      However I'm trying to find a way to define this for derivatives of arbitrary order with regard to `t`, and make the definition of `Dbody` redundant. Simple invocations of `'`, `D` and `Derivative` failed; for example:               Derivative[1][body][1,1]      returns               body'[1,1]


How to convert a transfer function model to a zero-pole-gain model?

Mathematica has a function to convert TransferFunctionModels to StateSpaceModels:               mytf=TransferFunctionModel[(2 s + 3)/(s^3 + 4 s^2 + 5), s]     StateSpaceModel[mytf]      Is there a corresponding function that will convert to a zero-pole-gain model?


Local variables

I'm trying to use `Modules` together with functions.               tmp2 = x^2 + 1; f[y_] := Module[{x = 1}, Evaluate[y tmp2]]      This works when I just have               tmp2 = x^2 + 1; Module[{x = 1}, Evaluate[tmp2]]      But `f[1]` outputs $1 + x^2$. **Edit:** After seeing the answers I wonder how I can get something like this to work:               ClearAll[withRules]     SetAttributes[withRules, HoldAll]     withRules[rules_, expr_] :=       Internal`InheritedBlock[{Rule, RuleDelayed},        SetAttributes[{Rule, RuleDelayed}, HoldFirst];       Unevaluated[expr] /. rules]     ClearAll[f, tmp2]     tmp2[y_] = y (x^2 + 1)     withRules[{expr -> tmp2}, f[y_] := Module[{x = 1}, expr[y]]]      **Edit 2:** Maybe it is better if I explain what I'd like to do. I have a lot of calculations in terms of $k_x$, $k_y$ and $k_z$. So, those are outputted in terms of these three variables. However, sometimes I need to integrate such expressions but to do this I need to use spherical coordinates. So I set $k_x = k \sin(a) \cos(b)$ and so on and then integrate. I don't want the transformations always set because I want the other calculations to have $k_x$, $k_y$ and $k_z$ as variables, not $a$ en $b$.


Question about number theory

Let `S[p]` denote the sum of digits of `p`. A prime `p` is said to be stubborn if none of `S[n] + 1`, `S[n]`, `S[n] - 1`, `S[n] - 2` , or `S[n] - 3` is a prime. Write a mathematica code that finds the smallest stubborn prime and tell which prime is it?


How to solve the recursion equation that include the uncertain value i in it?

I write the following code of a recursion equation, but it can not work correctly.               RSolve[{        a[0]==(1-p)a[n],        For[i=1,i<=n-1,i++,a[i]==p a[n-i+1]+(1-p)a[n-i]],        a[n]==a[0]+p a[1],        Sum[a[k],{k,0,n}]==1},     a[n],n]


How can I defer the loading of a PopupView control until it is used?

Background: I have several `PopupView`s of which the loadtime adds to the startup time of a program. To improve the perceived performance I want to defer the loading of the `PopupView` to the moment that they are actually used. I thought about this:                 Clear[filelist];       Clear[obj];       filelist = {};       Dynamic@PopupView[filelist, Dynamic[obj, (obj = #;) &],          Button["Edit", filelist = {1, 2, 3}, ImageSize -> 80]]      The idea works but not as expected, the popupview is not displayed correctly until filelist is loaded. I want to correct this or find an alternative way to set this up. **Question: How can I defer the loading of a`PopupView` control until it is used ?**


From a list of dates get a list of the last date available in a each month

I wondered if anyone has another or even a more direct way of finding the last dates of each month available from a list of successive dates? I currently do the following (note: nothing special about WeatherData[] here, I just used it to generate a list of dates):               WeatherData["KMDZ", "MeanTemperature", {{2007, 1, 1}, {2007, 12, 31}, "Day"}][[All, 1]];     Last[#] & /@ SplitBy[%, DateList[#][[2]] &]          {{2007, 1, 31}, {2007, 2, 28}, {2007, 3, 31}, {2007, 4, 30}, {2007, 5, 31}, {2007, 6, 30}, {2007, 7, 31}, {2007, 8, 31}, {2007, 9,30}, {2007, 10, 31}, {2007, 11, 30}, {2007, 12, 31}}      This works fine. I just wondered if I could think about this problem in a different way. * * * It seems the question needs a clarification. The starting list of dates may not include every date in a given month as such, it also may not include the actual last date of any given month. I need to find the last date in any month available in the list.


Calculating a limit with a result that is discontinuous in the parameters

The following limit is left unevaluated ( _Edit:_ added the assumption that $\epsilon$ is real thanks to the comment below):               Limit[ 1/(1 + Exp[ϵ/T]), T->0, Direction->-1, Assumptions->ϵ ∈ Reals]      However, the limit is easy to calculate (it is the Fermi-Dirac distribution), and it gives $\theta(-\epsilon)$. It seems that MMA has a hard time when the result is discontinuous in the parameters.   Nevertheless, MMA can actually calculate the limit, if we help it by explicitly splitting up the parameter space:               In[2]:= Limit[1/(1 + Exp[ϵ/T]), T->0, Direction->-1, Assumptions->#] & /@ {ϵ > 0, ϵ < 0}     Out[2]= {0, 1}      **Is there a way to make MMA automatically calculate such limits, without explicitly splitting up the parameter space?**


Measure the length and width of the image

I obtained the images from a Magneto Optic Kerr Effect system from which I have to do some calculations. I cannot calculate the desired information from the images. The details are as follows: ![The image I obtain from the system looks like this:](http://i.stack.imgur.com/eYXlo.jpg) From the image I have to calculate the length and width of the black part of the image (which can be assumed to be a rectangle). So, I first use the command for finding the radius and threshold of the image and then convert it into a binary image. The command I use is               Manipulate[EdgeDetect[image, r, t], {{r, 2, "radius"}, 1, 10},          {{t, 0.1, "threshold"}, 0, 0.5}]      And then I get this result after detecting the edges of the black rectangle.![The result after manipulate and edgedetection](http://i.stack.imgur.com/0gU4F.jpg) Now I have to calculate the width and the length at several different positions in the black box and then take the average to get the mean result. As I know that I will definitely get the result in pixels which I can then convert to real world measurements using the scale bar, but I am unable to calculate the length and the width. Since I am new to _Mathematica_ as well as image processing, help will be highly appreciated.


RSolve with assumptions

I want to solve the following non-linear first order difference equation: $$ k_{t+1} = (1-a) k_t^{a} $$ with $0 < a < 1$, and $k_0 = \text{const.}$ . Of course, the solution is easily found, but I want _Mathematica_ to solve it. Using               RSolve[{ k[t + 1] == (1-a) k[t]^a, k[0] == k0}, k[t], t ]      gives               {{k[t] -> E^(((-1 + a^t) (I π + Log[-1 + a]))/(-1 + a)) k0^a^t}}      The solution is much simpler when considering the restriction on $a$. How can I tell _Mathematica_ that $a$ is between $0$ and $1$ when applying the `RSolve` command? P.S. I've played around with the `Reduce` command, using assumptions, but that did not help.


Can I use Table without the appropriate bounds?

I´d like to use the `Table` command without defining `n`, so that I can have a list of `n` arguments. It is possible for the `Sum` command, but I guess not for the Table command, or is it? Something like               n = 5; eSO = Table[e[i], {i, 1, n}]; ebar[1] = EBAU - Sum[ebar[i], {i, 2, n}];      a[1] = A - Sum[a[i], {i, 2, n}]; b[1] = B - Sum[b[i], {i, 2, n}];          Cost = Table[1/2/a[i]*(ebar[i] - e[i])^2 + b[i]*(Sum[e[i], {i, n}])^2 /2, {i, 1, n}];          FOC = Table[D[Sum[Cost[[i]], {i, n}] == 0, e[i]], {i, 1, n}];          solsSO = eSO /. Solve[FOC, eSO];          solsSO = Flatten[solsSO];          ESO = Simplify[Sum[solsSO[[i]], {i, n}]]      but a bit more complicated in the end.


Writing Fold in terms of Map or MapThread?

Consider               Fold[f,z,{a,b,c}]     ==> f[f[f[z,a],b,c]]      I'm looking for a way to write this (in general) using `Map` or `MapThread` (and perhaps `Flatten[#,1]&`, thinking of monadic `bind` a-la Haskell), and not using mutable variables. In other words, the following is too easy:               Module[{result = z},       Map[v \[Function]         result = f[result, v],        {a, b, c}]] // Last      and the following is not even wrong:               MapThread[f, {{z, f[z, a], f[f[z, a], b]}, {a, b, c}}] // Last      and the following is even more not even wrong (invoking Haskell's state monad); although it could be written recursively to be more general, the recursive form would just be a simulacrum of `Fold` with more functional garbage around the binding functions:               return[v_] := s \[Function] {v, s};     bind[m_, fv2m_] := s \[Function]       With[{vs0 = m[s]},         With[{          v0 = vs0[[1]],          s0 = vs0[[2]]},         fv2m[v0][s0]]]          bind[       bind[         bind[          return[z],          v \[Function] return[f[v, a]]],         v \[Function] return[f[v, b]]],        v \[Function] return[f[v, c]]][z] // First      I'm beginning to think that `Fold` is its own critter, kind of a state-monad- in-disguise, inherently recursive, and not representable by `Map` and friends, which are inherently iterative. But I haven't yet been able to prove that it's not possible, even though I haven't found a solution. Anyone happen to know? EDIT: the reason I'm looking for this is so I can build a reactive version around the Observable/Observer pattern, which is formally dual to the Iterable/Iterator pattern, and replaces `Map` with `Subscribe`, sort-of. I do not know a reactive partner to `Fold`, and that's the ultimate objective.


An easier way to find the properties of an ellipse from its equation?

In this Q&A about fitting an ellipse to a set of points, there are multiple answers that generated general equations of the ellipse, like this one by @ubpdqn: ![enter image description here](http://i.stack.imgur.com/MTLL1.png) However, the steps to find out the properties of the ellipse (namely, major axis, minor axis, center, and rotation) from its given equation seems pretty complicated. Therefore, my goal is to try finding these properties in a more intuitive way (if possible). Let's say I start with this general equation of a particular ellipse:               ellipse = -1.43328 - 0.281261 x + 0.00228797 x^2 - 0.832702 y +         0.00138781 x y + 0.00209387 y^2;     ContourPlot[ellipse == 0, {x, -500, 500}, {y, -500, 500}]      ![Mathematica graphics](http://i.stack.imgur.com/Ttgky.png) A way to find its properties is to start with a simple centered, axis-aligned ellipse with the general formula, where a and b represents the half-lengths of the ellipse' axes: $$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$$ The second step is to subtract the expression by 1 to convert our equation to the form expr=1 to expr=0, which is the way our general formula is written (see top of question). Then, this ellipse is rotated a certain degree, which means that each x and y in the equation is corrected with the rotation angle alpha [Ref], like so: $$x\to x \cos (\alpha )-y \sin (\alpha ),y\to x \sin (\alpha )+y \cos (\alpha )$$ This tilted ellipse is then brought off-center to make our original ellipse, which will transform x and y like so: $$x\to x-h,y\to y-k$$ where (h,k) represents the coordinate of the ellipse' center. This is the final formula as done via MMA: ellipseTransform =                Collect[#, {x,           y}] &@(x^2/a^2 + y^2/b^2 -            1 /. {x -> x Cos[\[Alpha]] - y Sin[\[Alpha]],            y -> x Sin[\[Alpha]] + y Cos[\[Alpha]]} /. {x -> x - h,           y -> y - k})      , which gives ![Mathematica graphics](http://i.stack.imgur.com/vfPPO.png) A plot of this formula confirms that this is indeed an ellipse               ContourPlot[(ellipseTransform /. {a -> 300, b -> 200, h -> 100,           k -> 50, \[Alpha] -> 30 \[Degree]}) == 0, {x, -500,        500}, {y, -500, 500}, Axes -> True]      ![Mathematica graphics](http://i.stack.imgur.com/LZLdB.png) As you can see the transformed equation of the simple ellipse now resembles the form of our given ellipse, which includes a constant term, an x term, y term, xy term, x^2 term, and y^2 term (6 terms) in total. My goal now is to somehow solve for a, b, h, k and alpha using the fact that these 2 expressions are basically equivalent. Now this is when I got stuck, as I've tried a few ways to equate these 2 expressions to look for what I want but to no avail: ![Mathematica graphics](http://i.stack.imgur.com/tKKKV.png) Another (perhaps related) problem is that there are 5 unknowns (a,b,h,k,apha) but 6 equations i.e. the 6 coefficients in my ellipse equation. I suppose this problem is more a mathematics one than of Mathematica but I'm wondering if there's any way to solve (or at least optimize) an overdefined set of equations.


Problem with boundary values for a partial differential equation

I have a PDE problem that I can't solve. and I wonder if you could help me with it. I have a Terzaghi Consolidation equation (similar to the heat equation) that is written as follows: $\frac{du}{dt}=c\frac{d^2u}{dt^2}$ $u$ is pore water pressure $z$ is depth $t$ is time $c$ is a constant pore water pressure is equal at all depth at $t = 0$, but it becomes $0$ at top and bottom directly after that. `u = u[z,t]` ($z$ is depth and $t$ is time) with boundary conditions as follows: `u[z, 0] = 100` ($u$ at all depth when $t = 0$) `u[2, t] = 0` ($u$ at top of the layer; in this case, $2$ is the height of the top layer) `u[0, t] = 0` ($u$ at bottom of the layer) I have solved this kind of problem before using a finite difference technique in a spread sheet, I wanted to find out whether _Mathematica_ can solve this problem directly, but unfortunately I failed. This is what I entered into _Mathematica_ :               NDSolve[{Derivative[0, 1][u][z ,t] == Derivative[2, 0][u][z, t],      u[0, t > 0] == 0, u[2,t > 0] == 0, u[2 > z > 0, 0] == 100}, u, {z, 0, 2},{t, 0, 100}]      Unfortunately, evaluating this expression leads gives the error: > DSolve::litarg: > > "To avoid possible ambiguity, the arguments of the dependent variable in > u[0,t>0]==0; should literally match the independent variables" I dont understand why I'm getting this message. I found a heat problem similar to this. I tried to use the that equation but changed the boundary problem, but that did not work. Can you help me detect which part of equation is wrong, and how I can fix the boundary values?


Any built-in function to generate successive sublists from a list?

Given               lst = {a, b, c, d}      I'd like to generate               {{a}, {a, b}, {a, b, c}, {a, b, c, d}}      but using built-in functions only, such as `Subsets`, `Partitions`, `Tuples`, `Permutations` or any other such command you can choose. But it has to be done only using built-in commands. You can use a pure function, if inside a built- in command, i.e. part of the command arguments. That is OK. It is of course trivial to do this by direct coding. One way can be               lst[[1 ;; #]] & /@ Range[Length[lst]]     (* {{a}, {a, b}, {a, b, c}, {a, b, c, d}}  *)      or even               LowerTriangularize[Table[lst, {i, Length[lst]}]] /. 0 -> Sequence @@ {}     (* {{a}, {a, b}, {a, b, c}, {a, b, c, d}}  *)      But I have the feeling there is a command to do this more directly as it looks like a common operation, but my limited search could not find one so far. Sorry in advance if this was asked before. Searching is hard for such general questions.


HorizontalGauge causes problem with ScalingFunctions -> "Log"

I am trying to use `HorizontalGauge[Dynamic[expt], {0.1, 100}, ScalingFunctions -> "Log"]`, i.e. a gauge with a logarithmic scale. This creates an error, a graph with a pink background. Monitoring the output with `Dynamic[expt]` and a second gauge `HorizontalGauge[Dynamic[expt], {0.1, 100}, ScalingFunctions -> None]` indicates that the logarithmic `HorizontalGauge` actually generates the expected output. Unless, somebody realizes a mistake in this rather simple code, I must assume this is a bug in Mathematica 9. **EDIT** Unluckily, this error has not been corrected in version 9.0.1               ... , ScalingFunctions -> {Exp, Log}      sort of works, but the locations of the tick marks are of course wrong. In the other order `{Log, Exp}` the error from above is reproduced. I reported this as an error.


ControlsRendering and operating systems

Controls, such as those appearing in `Manipulate` constructs, are by default rendered depending on the operating system. Wrapping everything in `Style[..., ControlsRendering->"Generic"]` makes sure that the controls' appearance is independent of the operating system (right?). My question now is split into three parts:   1. Does the rendering depend on the version of Mathematica es well? Specifically, is there a difference between versions 7, 8 and 9?   2. Is there a way to estimate how the controls will be rendered for another operating system? I.e. can I get a rough idea (I'm using Windows 7) how my `Manipulate` will look like on a machine with, e.g., Mac OS X 10.7? It would be enough for me to find out if any of the sizes of things like `Slider2D` or `SetterBar` objects change drastically. Does the `ImageSize` option for `Slider2D` ensure a consistent size even on different operating systems?   3. Can one define a function that makes sure that the default rendering is used on machines with windows, and the `"Generic"` style is used for non-Windows computers?


Can I use what "headerlines" removes from a CSV as TableHeadings for the table I create from that File?

I am reading in some data from a CSV file that has a line which gives titles to each "column". **Here is an example:**               Entry No,Val1,Val2,Val3,Val4     0,1.01,1.345,5.234,345.45     1,2.456,1.256,250.56,45.027      In reality this file has 20 or so values on each line, and therefore 20 column titles on the first line. I want to display this data in a table, so I first import the file and then display it like so:               dataSet1 = Take[Import["data_set_1.csv","CSV","HeaderLines"->1]]      TableForm[dataSet1]      I want to be able to manipulate and plot my data later so I am pretty sure I have to remove the line containing the labels using the "Headerlines->1" option. I would like the table to display the column titles that were on he first line of the CSV file. I know that I _could_ specify them manually, but I think there should be someway to do this because I deleted them the set using "HeaderLines"


Find the coefficients of a set of expressions in partial-derivatives

Is there a way to find the coefficients of these (terms within the square brackets) expressions using mathematica? \begin{align} \hat{l}^2=&\sum\limits_{a=1}^{4}\left[\left(\frac{\partial \chi_a}{\partial \theta_1}\right)^2+\frac{1}{sin^2\theta_1}\left(\frac{\partial \chi_a}{\partial \phi_1}\right)^2\right]\frac{\partial^2}{\partial \chi_a^2}+\\\ &\sum\limits_{a=1}^{4}\left[\frac{\partial^2 \chi_a}{\partial \theta^2_1}+\frac{1}{sin^2\theta_1}\frac{\partial^2 \chi_a}{\partial \phi_1^2}+cot\theta_1\frac{\partial \chi_a}{\partial \theta_1}\right]\frac{\partial}{\partial \chi_a}+\\\ & 2\mathop{\sum\sum}_{a>b=1}\left[\frac{\partial \chi_a}{\partial \theta_1}\frac{\partial \chi_b}{\partial \theta_1}+\frac{1}{sin^2\theta_1}\frac{\partial \chi_a}{\partial \phi_1}\frac{\partial \chi_b}{\partial \phi_1}\right]\frac{\partial^2}{\partial \chi_a\partial \chi_b} \end{align} where for $a=1,2,3,4\quad \chi_a$, refers to $\alpha,\beta,\gamma,\Theta_{12}$ and considering the following relations between $\alpha$, $\beta$, $\gamma$, $\Theta_{12}$ and $\theta_1$, $\theta_2$, $\phi_1$, $\phi_2$: $sin\Theta_{12}cos\beta=sin\theta_1sin\theta_2sin(\phi_2-\phi_1)$, $sin\Theta_{12}sin\beta sin\alpha= sin\theta_1sin\phi_1cos\theta_2- cos\theta_1sin\theta_2sin\phi_2$, $sin\Theta_{12}sin\beta cos\alpha= sin\theta_1cos\phi_1cos\theta_2- cos\theta_1sin\theta_2cos\phi_2$, $2sin\frac{\Theta_{12}}{2}cos\gamma= sin\theta_2cos(\phi_2-\alpha)-sin\theta_1cos(\phi_1-\alpha)$, $2sin\frac{\Theta_{12}}{2}sin\gamma= (cos\theta_2-cos\theta_1)sin\beta + [sin\theta_2 sin(\phi_2-\alpha)-sin\theta_1sin(\phi_1-\alpha)cos\beta$, $cos\Theta_{12}= cos\theta_1cos\theta_2+sin\theta_1sin\theta_2cos(\phi_1-\phi_2)$ As well as the relations between $\theta_1$, $\theta_2$, $\phi_1$, $\phi_2$\, and $\alpha$, $\beta$, $\gamma$ and $\Theta_{12}$: $cos\theta_1= -sin\beta cos(\gamma-\frac{\Theta_{12}}{2}),\\\ cos\theta_2= -sin\beta cos(\gamma+\frac{\Theta_{12}}{2}),$ $sin\theta_1cos\phi_1=cos\alpha sin(\gamma-\frac{\Theta_{12}}{2})+cos\beta sin\alpha cos(\gamma-\frac{\Theta_{12}}{2})$, $sin\theta_2cos\phi_2=cos\alpha sin(\gamma+\frac{\Theta_{12}}{2})+cos\beta sin\alpha cos(\gamma+\frac{\Theta_{12}}{2})$, $sin\theta_1sin\phi_1=sin\alpha sin(\gamma-\frac{\Theta_{12}}{2})-cos\beta cos\alpha cos(\gamma-\frac{\Theta_{12}}{2})$, $sin\theta_2sin\phi_2=sin\alpha sin(\gamma+\frac{\Theta_{12}}{2})-cos\beta cos\alpha cos(\gamma+\frac{\Theta_{12}}{2})$ For example, I know that the first coefficient is for $a=1$ $\frac{sin^2(\gamma+\frac{\Theta_{12}}{2})}{sin^2\Theta_{12}}$ for $\frac{\partial^2}{\partial\Theta^2}$ However, I don't exactly know how to obtain it, and of course the rest coefficients. If you can give me some hints for the first coefficient i'll find the other 13 for shure.


Quickly differentiate and evaluate a function of several variables

How can I differentiate a function with respect to several variables and evaluate it at the same time ? I want to specify also the variable index that I want to differentiate and the number of times I do it for each one.


How to control dependent PopupMenus?

I created three interdependent `PopupMenu`s with names `demographic`, `region` and `custom`:               DynamicModule[{demographic = "Demographic", region = "Region", custom = "Custom"},      Dynamic@Grid@{{          PopupMenu[Dynamic[demographic], {"Demo1", "Demo2", "Demo3"}, "Demographic"],          PopupMenu[Dynamic[region], {"Region1", "Region2", "Region3"}, "Region"],          PopupMenu[Dynamic[custom], {"Custom1", "Custom2", "Custom3"}, "Custom"]          }}]      ![enter image description here](http://i.stack.imgur.com/RtMnx.png) These controls should depend on each others' values. I want the followings:   1. `region` and `demographic` should be reset to `"Region"` and `"Demographic"` if any from `custom` is selected   2. `custom` should be reset to `"Custom"` if either `demographic` or `region` is changed I tried it with `If` and `Which` but it still won't work. How can I control these three `PopupMenu`s?


Option to change cursor/caret shape

While editing on a Mathematica notebook, I often find myself needing to do something else outside of Mathematica for a few hours. After finishing such outside tasks, I resume to work on the notebook. However, it is often difficult to find where the cursor/caret (text insertion point) is because blinking vertical bar is not visually prominent enough. Of course, I can set the cursor at an arbitrary location in the notebook by using mouse and clicking somewhere. The downside of this approach is that I lose context of my previous edits. After several hours, I still remember what I was editing generically, but I can't recall specific edits that I was making. Finding the cursor at the last position helps me to recall details of such specific edits. I want to make the cursor easier to find by making it visually more prominent such as blinking box or using different color. Is there such option? If the answer is yes, how can I set the option globally? Alternatively, can I highlight the current (physical) line? This would also make a point of last edit easy to locate.


How to get updates for Mathematica V10

As you know, _Mathematica_ V10 has just been released and I think a lot of updates will be released. However, I don't see any command in the help menu to update (which is present in most other software). How would we know if an update is available or not? I am using trial version of V10. ![enter image description here](http://i.stack.imgur.com/dTwd2.jpg)


What's the most "functional" way to do Cholesky decomposition?

I can do Cholesky in a procedural style, such as:               ProceduralCholesky[matrin_List?PositiveDefiniteMatrixQ] :=       Module[{dimens,        ll},       dimens = Length@matrin;       ll = ConstantArray[0, {dimens, dimens}];       Do[        Do[          If[i == j,            ll[[i, i]] =               Sqrt[matrin[[i, i]] -                 Sum[Conjugate[#]*# &@ll[[i, k]], {k, 1, i - 1}]];,            ll[[i,                j]] = (matrin[[i, j]] -                  Sum[ll[[i, k]]*Conjugate[ll[[j, k]]], {k, 1, j - 1}])/               Conjugate[ll[[j, j]]];];,          {i, j, dimens}];,        {j, dimens}];       ll       ]      Moreover, I've seen a "half-functional" implementation, which, however, features a `Table` function and an outer `For` loop. So far I have managed to address the need for the Table function by writing:               HalfFunctionalCholesky[matrin_List?PositiveDefiniteMatrixQ] :=       Module[{dimens,        uu},       dimens = Length@matrin;       uu = ConstantArray[0, {dimens, dimens}];       Do[uu[[i]] = makerow[matrin, i, uu, dimens], {i, dimens}];       uu       ]          makerow[matrin_List, rowindex_Integer, uu_, dimens_Integer] :=       PadLeft[       (Join[           {#},           offdiagonalelements[matrin, uu, rowindex, dimens, #]]) &@        diagonalelement[matrin, uu, rowindex],       dimens]          diagonalelement[matrin_, uu_, rowindex_] :=       Sqrt[matrin[[rowindex, rowindex]] - Conjugate[#].# &@        uu[[;; (rowindex- 1), rowindex]]]          offdiagonalelements[matrin_, uu_, rowindex_, dimens_,        diag_] := (matrin[[rowindex, (rowindex+ 1) ;; dimens]] -         Conjugate[           uu[[;; (rowindex - 1),             rowindex]]].uu[[;; (rowindex - 1), (rowindex + 1) ;;             dimens]])/diag      I am not satisfied yet. Can I avoid using the outer `Do` loop by turning it into a `Fold` or a `Nest`? The only idea I was able to come up with involved a `Nest`ed `ReplacePart` function, but I think it would be just some pretentious sweeping under the rug. Am I mistaken? Thank you in advance!


Extract a list of all built-in functions used in a notebook

I am writing my code documentation and need to list all the _Mathematica_ built in functions I have used - explicitly written functions only. Is there a way to extract a list of all built in functions that I have used in my code? For example               Insert[{a, b, c}, x, 3]     a=1     Style["this text",Bold]     Range[1,20]     b=3     a*b      I would require a list containing `Insert`, `Style` and `Range`.


How to get a solution involving logs in the right form?

How do I get               Solve[(1/9)^(r/2) == 1/n , r]       to give me                Log[n]/Log[3]      and not `-Log[1/n]/Log[3]`?


Change Style of Points

I was wondering if it's possible to change the style of a`Point` with another symbol e.g.: cross, x etc... It may sound weird-it is a Point after all, but I would like to have crosses instead of points in the following code                 Manipulate[Module[{data, inside, insidepts}, SeedRandom[n];       data = RandomReal[{-1, 1}, {m, 2}];       insidepts = Cases[data, {x_, y_} /; x^2 + y^2 < 1];       inside = Length[insidepts];       Text@        Style[         Column[          {Graphics[{PointSize[0.0001], Red, Disk[{0, 0}, 1], Blue,             Point[data]}, ImageSize -> If[format, 500, 350]],           Row[{"inside: ", inside, "\toutside: ", m - inside, "\ttotal: ",              m}],           Row[{"π=4 x ", inside, "/", m, " = ", 4. inside/m}]}], "Label"]],      {{n, 1, "random seed"}, 1, 1000, 1, Appearance -> "Labeled"},      {{m, 1, "sample size"}, 1, 100000, 1, Appearance -> "Labeled"},      {{format, False, "large format"}, {True, False}},      AutorunSequencing -> {1, 2}]


how to extract some terms out from an expression

I have an expression as below： > $-\frac{1}{2} A[a,v] A[b,h] A[c,v] A[d,h] \text{Cos}[\theta ]^2+\frac{1}{2} > A[a,h] A[b,v] A[c,v] A[d,h] \text{Cos}[\theta ]^2+\frac{1}{2} A[a,v] A[b,h] > A[c,h] A[d,v] \text{Cos}[\theta ]^2-\frac{1}{2} A[a,h] A[b,v] A[c,h] A[d,v] > \text{Cos}[\theta ]^2+\frac{1}{2} A[a,v]^2 A[b,h] A[d,h] \text{Cos}[\theta ] > \text{Sin}[\theta ]-\frac{1}{2} A[a,h] A[a,v] A[b,v] A[d,h] > \text{Cos}[\theta ] \text{Sin}[\theta ]+\frac{1}{2} A[b,v] A[c,h] A[c,v] > A[d,h] \text{Cos}[\theta ] \text{Sin}[\theta ]-\frac{1}{2} A[b,h] A[c,v]^2 > A[d,h] \text{Cos}[\theta ] \text{Sin}[\theta ]-\frac{1}{2} A[a,h] A[a,v] > A[b,h] A[d,v] \text{Cos}[\theta ] \text{Sin}[\theta ]+\frac{1}{2} A[a,h]^2 > A[b,v] A[d,v] \text{Cos}[\theta ] \text{Sin}[\theta ]-\frac{1}{2} A[b,v] > A[c,h]^2 A[d,v] \text{Cos}[\theta ] \text{Sin}[\theta ]+\frac{1}{2} A[b,h] > A[c,h] A[c,v] A[d,v] \text{Cos}[\theta ] \text{Sin}[\theta ]-\frac{1}{2} > A[a,v] A[b,v] A[c,h] A[d,h] \text{Sin}[\theta ]^2+\frac{1}{2} A[a,v] A[b,h] > A[c,v] A[d,h] \text{Sin}[\theta ]^2+\frac{1}{2} A[a,h] A[b,v] A[c,h] A[d,v] > \text{Sin}[\theta ]^2-\frac{1}{2} A[a,h] A[b,h] A[c,v] A[d,v] > \text{Sin}[\theta ]^2$ There are 16 terms here and every term has for function $A$. In some terms the first parameter of four function $A$ are different from each other( a,b,c,d), in the other terms the four first paramenter are partial overlap(a,a,b,d;...). how can I get the first kind. (the result is as below:) > $-\frac{1}{2} A[a,v] A[b,h] A[c,v] A[d,h] \text{Cos}[\theta ]^2+\frac{1}{2} > A[a,h] A[b,v] A[c,v] A[d,h] \text{Cos}[\theta ]^2+\frac{1}{2} A[a,v] A[b,h] > A[c,h] A[d,v] \text{Cos}[\theta ]^2-\frac{1}{2} A[a,h] A[b,v] A[c,h] A[d,v] > \text{Cos}[\theta ]^2-\frac{1}{2} A[a,v] A[b,v] A[c,h] A[d,h] > \text{Sin}[\theta ]^2+\frac{1}{2} A[a,v] A[b,h] A[c,v] A[d,h] > \text{Sin}[\theta ]^2+\frac{1}{2} A[a,h] A[b,v] A[c,h] A[d,v] > \text{Sin}[\theta ]^2-\frac{1}{2} A[a,h] A[b,h] A[c,v] A[d,v] > \text{Sin}[\theta ]^2$ this is the input form for our mma:                -(1/2) A[a, v] A[b, h] A[c, v] A[d, h] Cos[\[Theta]]^2 +       1/2 A[a, h] A[b, v] A[c, v] A[d, h] Cos[\[Theta]]^2 +       1/2 A[a, v] A[b, h] A[c, h] A[d, v] Cos[\[Theta]]^2 -       1/2 A[a, h] A[b, v] A[c, h] A[d, v] Cos[\[Theta]]^2 +       1/2 A[a, v]^2 A[b, h] A[d, h] Cos[\[Theta]] Sin[\[Theta]] -       1/2 A[a, h] A[a, v] A[b, v] A[d, h] Cos[\[Theta]] Sin[\[Theta]] +       1/2 A[b, v] A[c, h] A[c, v] A[d, h] Cos[\[Theta]] Sin[\[Theta]] -       1/2 A[b, h] A[c, v]^2 A[d, h] Cos[\[Theta]] Sin[\[Theta]] -       1/2 A[a, h] A[a, v] A[b, h] A[d, v] Cos[\[Theta]] Sin[\[Theta]] +       1/2 A[a, h]^2 A[b, v] A[d, v] Cos[\[Theta]] Sin[\[Theta]] -       1/2 A[b, v] A[c, h]^2 A[d, v] Cos[\[Theta]] Sin[\[Theta]] +       1/2 A[b, h] A[c, h] A[c, v] A[d, v] Cos[\[Theta]] Sin[\[Theta]] -       1/2 A[a, v] A[b, v] A[c, h] A[d, h] Sin[\[Theta]]^2 +       1/2 A[a, v] A[b, h] A[c, v] A[d, h] Sin[\[Theta]]^2 +       1/2 A[a, h] A[b, v] A[c, h] A[d, v] Sin[\[Theta]]^2 -       1/2 A[a, h] A[b, h] A[c, v] A[d, v] Sin[\[Theta]]^2


FeynRules vs FeynCalc (or anything else?)

I was looking for a Mathematica package that can take Lagrangians and calculate Feynman diagrams for any given n-point function. (..like if a software can draw and calculate arbitrary loop corrections to the Fermion correlation function in a theory..) Is FeynRules or FeynCalc capable of such?   If yes how? Which is easier to use? If no, then are there other softwares?


Why does $Failed have attribute HoldAll?

Why does `$Failed` have attribute `HoldAll`? Are there typical situations where `$Failed` is returned as a head that must not evaluate further, or is this just a relic from Mathematica's early times?               In[1]:= Attributes[$Failed]     Out[1]= {HoldAll, Protected}


How can I solve a difference-differential equation?

How do I ask _Mathematica_ to try to solve a recursive relation that defines a sequence of functions? For example, suppose I know that $g_n(x) = g_{n-1}'(x)$ for $n > 0$ and that $g_0(x) = e^{2x}$. How can I ask _Mathematica_ to find a closed form for $g_n(x)$? (This is just a placeholder equation to highlight my question; I know the answer of $g_n(x) = 2^n e^{2x}$, $n\geq 0$.) A less trivial instance of the problem would be the Hermite polynomial recursion, $$H_{n+1}(x) = 2xH_n(x) - H_n'(x)$$ I don't see how to convince either `DSolve` or `RSolve` to solve it for me. `DSolve` is unhappy because $n-1$ is used on the RHS:               DSolve[{g[n, x] == 2*D[g[n - 1, x], x]}, g, {n, x}]      `RSolve` just echoes my input:               RSolve[{g[n, x] == 2*D[g[n - 1, x], x], g[0, x] == Exp[2*x]}, g, {n, x}]      I know finding a closed-form solution is going to be hopeless in most instances, but it seems like some cases like the above $g_n(x)$ should be doable. I have been unable to find any examples in the _Mathematica_ documentation addressing this type of problem.


Is there a function that, given a fraction, will return the general term of its infinite series expansion?

Is here some way to expand a fraction to an infinite sum in mathematica, i.e., a series? I want the general term of the series. For example, $\frac{2}{3(x-1)^3}$


Problem with WordBoundary in string patterns

I am trying to extract from a string all words that end with "-man", but the problem is that `WordBoundary` does not seem to work as it returns whole string ignoring actual word boundaries. Here is the code:               mystring = "I am a big fan of Superman, Spiderman and Batman.";     StringCases[mystring, WordBoundary ~~ __ ~~ "man"];


Same Mathematica 9.1 Student License on both Ubuntu and Windows 7

Is it possible to install Mathematica 9.1 on both Ubuntu 12.04.3 LTS and Windows 7 Home Premium on the same machine. I want to be able to use Mathematica on Ubuntu since I wrote some numerical codes there. I would like to know if this is possible and a GUI is present in UNIX operating systems. Thanks


Solution of Non-Linear Equations using Simulation

How I can solve these five non-liner equations where `n=3`, `x=1,3,8` (e.g), and `a,b,c, Alpha` and `Beta` should be estimated.               x = {1, 3, 8}; n = Length[x]; eqn1 = n*D[Beta[a, b], a]/Beta[a, b] -      alpha*c*Sum[x[[i]]^(-beta), {i, 1, n}] == 0;  eqn2 = Sum[Log[1 - Exp[-alpha*c*x[[i]]^(-beta)]], {i, 1, n}] - n*D[Beta[a, b], b]/Beta[a, b] == 0; eqn3 = n/c - alpha*a*Sum[x[[i]]^(-beta), {i, 1, n}] + alpha*(b - 1)*Sum[(x[[i]]^(-beta)*Exp[alpha*c*x[[i]]^(-beta)])/(1 - Exp[-alpha*c*x[[i]]^(-beta)]), {i, 1, n}] == 0; eqn4 = n/alpha - c*a*Sum[x[[i]]^(-beta), {i, 1, n}] + c*(b - 1)*Sum[(x[[i]]^(-beta)*Exp[-alpha*c*x[[i]]^(-beta)])/(1 - Exp[-alpha*c*x[[i]]^(-beta)]), {i, 1, n}] == 0; eqn5 = n/beta - Sum[Log[x[[i]]], {i, 1, n}] + alpha*a*c*Sum[Log[x]*x[[i]]^(-beta), {i, 1, n}] + alpha*beta*c*(b - 1)*Sum[(x[[i]]^(-beta)*Exp[-alpha*c*x[[i]]^(-beta)])/(1 - Exp[-alpha*c*x[[i]]^(-beta)]), {i, 1, n}] == 0; FindRoot[{eqn1, eqn2, eqn3, eqn4, eqn5}, {{a, 0.1}, {b, 0.1}, {c, 0.1}, {alpha, 0.1}, {beta, 0.1}}]      This is not working, and not sure {a,0.1} etc 0.1 is the initial value.


Implementation of the Vector Autoregressive Model

I need to code/write a Vector Autoregressive Model VAR(p) as a function of the parameters. There is no estimation, nor Data involved, this is a "population" exercise: Assume X and Y are univariate, scalar random variables. I need to write the two following time-series models: [Model 1] $\quad X_{t} = \sum_{j=1}^{p}a_{j}X_{t-j} + u1_{t,}, \quad\quad\quad\quad\quad\quad$ where $\;\mathbb{E}[u1_{t}]=0, \; Var[u1_{t}]=\Sigma1$ [Model 2] $\quad X_{t} = \sum_{j=1}^{p}b_{j}X_{t-j} + \sum_{j=1}^{p}c_{j}Y_{t-j} + u2_{t}, \quad$ where $\; \mathbb{E}[u2_{t}]=0, \; Var[u2_{t}]=\Sigma2$ In the first model, X only depends only on it's own past, while in the second model X depends on both the past of X and the past of Y. EXAMPLE: if $p=2$ these models become [Model 1] $\quad X_{t} = a_{1}X_{t-1} + a_{2}X_{t-2}+ u1_{t,}$ [Model 2] $\quad X_{t} = b_{1}X_{t-1} + b_{2}X_{t-2} + c_{1}Y_{t-1} + c_{2}Y_{t-2} + u2_{t}$ I need to do this in symbolic terms so that I can compute a population measure of Granger Causality: $C_{Y \to X} = \frac{1}{2}\; \log\frac{\det \Sigma_{1}}{\det \Sigma_{2}}$ $\quad\quad\;\, = \frac{1}{2}\; \log\frac{Var(X_{t}) - Cov(X_{t},Z_{t})Var(Z_{t})^{-1}Cov(Z_{t},X_{t})}{Var(X_{t}) - Cov(X_{t},\tilde{Z}_{t})Var(\tilde{Z}_{t})^{-1}Cov(\tilde{Z}_{t},X_{t})}$ where $\;\;Z_{t} := [X_{t-1},..., X_{t-p}]'$ (vector that has the past X's) and $\quad\quad\quad\tilde{Z}_{t}:= [X_{t-1},..., X_{t-p}, Y_{t-1},..., Y_{t-p} ]'$ (vector that has the past X's and Y's) MY OBJECTIVE: code $C_{Y \to X}$ as a function of the parameters $p$ and $a,b,c$ so that I can show how it changes for different values of the parameters. (There is no data, no simulation of data either) NOTE: for people familiar with OLS (Ordinary Least Squares), this is a similar idea to doing population OLS: $\beta = \frac{Cov(X,Y)}{Var(X)}$ where $Y = \alpha + \beta X + \epsilon $, no estimation involved. Do you have ideas how to start ?


String pattern matching & replacement

I would like to find all occurrences of a full stop "." followed by a capital letter in a string and have these replaced with a "; ". How do I do this in Mathematica? e.g. `string="this is a test.A new sentence here"` -> output               "this is a test; A new sentence here"      Edit: and also one other pattern matching question - in a string I would like to have every other line occuring before a next line (\n) being deleted - how do I do that one? e.g.               string="this line should be deleted\nthis one not\nbut this one should be deleted too\nthis one not"      -> output               "this one not\nthis one not"


How to Normalise / Normalize eigenvectors?

I have a matrix and am trying to find the normalised eigenvectors of it. I am using the Eigensystem command and am getting a result. There is a normalize command, but as far as I can see this involves applying it to each vector individually. Is there by any chance an option that anyone has come across so that Mathematica does this automatically? Many thanks!


Connection between Mathematica Connector/J and XAMPP MySQL Database

I have been fiddling around with a problem for a while now, and hope you can help me. Have searched for previous solutions, but nothing seems to work. My problem is as follows: I have _XAMPP_ installed on my _Mac_ , as I use it as a localhost for some webpages. One day I got the idea that I wanted to connect _Mathematica_ to the _MySQL_ database, such that I could pull some data from the database, and work with it. I have tried, following the documentation, and write:               Needs["DatabaseLink`"];     JDBCDrivers["MySQL(Connector/J)"]      > > >>     JDBCDriver["Name" -> "MySQL(Connector/J)", >>      "Driver" -> "com.mysql.jdbc.Driver", "Protocol" -> "jdbc:mysql://", "Version" -> 2., >>      "Description" -> "MySQL using Connector/J - Version 5.1.13 - This supports all known >>          MySQL server versions.", "Location" -> "/Applications/Mathematica.app/ >>          SystemFiles/Links/DatabaseLink/DatabaseResources/mysql.m"] >>                 OpenSQLConnection[ JDBC["MySQL(Connector/J)", "localhost:3306/kbm"],                         "Username" -> "username", "Password" -> "*******"]      > > >>     During evaluation of In[6]:= JDBC::error: Communications link failure >>   >>     The last packet sent successfully to the server was 0 milliseconds ago. >>     The driver has not received any packets from the server. >> >>   >>     $Failed >>   I am certain that _MySQL_ listens on pot `3306`, I am certain that the database `"kbm"` exists, and I am certain that username and password is correct. So why doesn't it connect? I have with success connected to the _MySQL_ database through Terminal, and can conclude that it works. I have also read somewhere that sometimes replacing `"localhost"` by `127.0.0.1` works, but having tried that out, it still didn't work. Hope someone can help. **Edit** The config.inc.php file looks as follows:               /* Authentication type */     # commented out by xampp security     #$cfg['Servers'][$i]['auth_type'] = 'config';     $cfg['Servers'][$i]['auth_type'] = 'cookie';     $cfg['Servers'][$i]['user'] = 'root';     $cfg['Servers'][$i]['password'] = '';     /* Server parameters */     //$cfg['Servers'][$i]['host'] = 'localhost';     //$cfg['Servers'][$i]['connect_type'] = 'tcp';     $cfg['Servers'][$i]['compress'] = false;     /* Select mysql if your server does not have mysqli */     $cfg['Servers'][$i]['extension'] = 'mysqli';     $cfg['Servers'][$i]['AllowNoPassword'] = true;          /*     * phpMyAdmin configuration storage settings.     */          /* User used to manipulate with storage */     // $cfg['Servers'][$i]['controlhost'] = '';     $cfg['Servers'][$i]['controluser'] = 'pma';     # commented out by xampp security     #$cfg['Servers'][$i]['controlpass'] = '';     $cfg['Servers'][$i]['controlpass'] = '*******';      The rest is commented out.


Table of Variables

I use a list of variables `{x1, x2, x3}` to `Solve` a particular set of equations. I am now trying to generalise this depending on the number of equations. I need something along the lines of `Table[{"x" i}, {i,1,Length[equations]}]` which prints `{x1, x2, x3, x4,...}` etc. However, `"x" i` obviously does not work. Nor does `x[[i]]` as `{x[[1]], x[[2]], x[[3]]}` won't work in `Solve`. Any quick thoughts? Thank you.


Details of automatic cell-grouping w.r.t. cell-style

What determines how a specific cell-style influences grouping of cells? For example `"Text"` following `"Subtitle"` is grouped but not following `"Text"`               nbtitle = CreateDocument[];     NotebookWrite[nbtitle, Cell["subtitle", "Subtitle"]]     NotebookWrite[nbtitle, Cell["this text gets grouped", "Text"]]          nbtext = CreateDocument[];     NotebookWrite[nbtext, Cell["some text", "Text"]];     NotebookWrite[nbtext, Cell["this text is not grouped", "Text"]];      ![title](http://i.stack.imgur.com/j9Rid.png) * * * ![text](http://i.stack.imgur.com/Orxmu.png) All I can find in the documentation is: > Within a given notebook, there is always a collection of styles that can be > used to determine the appearance and behavior of cells. Typically the styles > are named so as to reflect what role cells which have them will play in the > notebook.