Wavelet expansion of given function (as opposed to DWT of given data)

To illustrate, say I take the following function (the reason for the square root will be apparent soon)               dist = NormalDistribution[0.5,0.1];     f[x_] := Sqrt[PDF[dist,x]];      Then I can grab the Haar wavelet to calculate coefficients like               data = Table[Evaluate@f[x], {x,0,1,1/31}]; (* 32 equally spaced points *)     dwt = DiscreteWaveletTransform[data, HaarWavelet[], 5];      If I then take squares of coefficients, because of $$ \sum _{j=J_o}^{J_1} \sum _{k\in \mathbb{Z}} \psi _{j,k}^2+\sum _{z\in \mathbb{Z}} \varphi _{J_0,k}^2\simeq \int f^2 (x) \, dx = \left\| f\right\| ^2 $$ I should get $\simeq 1.0$ as $f$ is, in this case, the square root of a probability density function. And it kind-of works; to wit:               Total[Flatten[Last[#] & /@ dwt[Automatic]]^2]/31      returns 1.0 (`dwt[Automatic]` gives you the coefficients for the inverse transform only; see here). This should be very close to `NIntegrate[Evaluate@f[x]^2, {x, 0, 1}]`, which is _0.999999_. However, note that "/31"! Where did that come from? This is: that `1/31` does not appear in the Parseval's identity but it is needed for the calculation to work (!) And if I change `HaarWavelet[]` by `DaubechiesWavelet[]`, say, then this _data sampling_ no longer works. I am even taking care of the fact that the Daubechies family has bigger support and for that I am using the following function to determine the number of points required as:               dataSize[wave_, 1] :=       Length[WaveletFilterCoefficients[wave, "PrimalLowpass"]];     dataSize[wave_, n_Integer /; n > 1] :=       2 dataSize[wave, n - 1] -        Length[WaveletFilterCoefficients[wave, "PrimalLowpass"]] + 2;      What I am doing wrong? ( _Why this?_ You may ask. For example, one could use wavelet expansions to calculate the norm (in Hilbert space) between two functions, or a function and some other approximation; instead of attempting `NIntegrate`. By the way, I am actually interested in dimensions greater than 1) **Note:** I am only interested in _orthogonal_ wavelets; Parseval's formula should be just ok as far as I know. **UPDATE** I modified `dist` to `NormalDistribution[0.5,0.5]`. In this case, one needs a longer interval `{x,-2,3}` to effectively cover $f$. In this case, the squared coefficients are added like **5**`Total[Flatten[Last[#] & /@ dwt[Automatic]]^2]/31` (note the factor 5.) This points me to the fact that the $x_i$ sample points are usually considered as in the `[0,1]` interval (if I remember correctly), therefore the final answer needs to be _rescaled_ by 5. Still... work in progress.


FindRoot on a 2D list of Equations

I have a $n \times k$ Matrix of data that I want to feed into an equation and solve for an unknown variable. I suppose I can always just convert the Matrix into a long Array but I'd like to learn how to do this while keeping the data structure as is. I want to be able to solve $n \times k$ `FindRoots` in one shot and mimicking some code from MMA.SE this is what I have managed.               f = x^(Mod[a, 3]) + b     a = {{2, 5, 8}, {1, 4, 7}};     b = {{-3, -5, -7}, {3, 5, 7}};     eqn = Table[(#[[j]] == 0), {j, 1, Dimensions[f][[2]]}] & /@ (f)     {{-3 + x^2 == 0, -5 + x^2 == 0, -7 + x^2 == 0}, {3 + x == 0, 5 + x == 0, 7 + x == 0}}     Table[FindRoot[#[[i]], {x, 1}] & /@ eqn, {i, 1, Dimensions[f][[2]]}]     {{{x -> 1.73205}, {x -> -3.}}, {{x -> 2.23607}, {x -> -5.}}, {{x -> 2.64575}, {x ->7.}}}      As you can see, this works but is a kind of a mess. I am hoping I can be helped in the direction of a cleaner, better code and learn how to use pure functions on n-dimensional lists. Thanks.


FindFit::nrlnum What am I doing wrong?

I have a model called qobs:               qobs=0.039 ns (T (8.314 + (8.314 - 8.314 m) Hypergeometric2F1[1., 1/m,          1. + 1/m, (ns/ns∞)^m] +        8.314 Log[-1. (A E^((0.120279 ΔE)/T))^(-1./           m) (-1. + 1/(1. - 1. (ns/ns∞)^m))^(-1./           m) (1/(-1. + 1. (ns/ns∞)^m))^1. (ns/           ns∞)^(1. m) Psat[T]]) + 1. λp[T])      I have a set of data with two independent variables (ns and T):               Data = {{0, 85, 0}, {0.131592244, 85, 69.07308925}, {0.230286428, 85,      115.4518887}, {0.255592629, 85, 126.8281889}, {0.382123633, 85,      181.8483799}, {0.426409484, 85, 200.2798617}, {0.516246497, 85,      237.7531003}, {0.60102227, 85, 271.3000332}, {0.642777502, 85,      288.766803}, {0.749063545, 85, 329.4612163}, {0.760451336, 85,      332.9712438}, {0.762981956, 85, 334.6336615}, {0, 100,      0}, {0.074653293, 100, 39.4734225}, {0.111347284, 100,      57.64231052}, {0.127796314, 100, 65.7007577}, {0.212572087, 100,      104.7308741}, {0.269511039, 100, 130.1461666}, {0.29481724, 100,      141.0225864}, {0.408695144, 100, 189.1969421}, {0.523838358, 100,      236.109073}, {0.536491458, 100, 241.0802459}, {0.551675179, 100,      247.1796371}, {0.58710386, 100, 261.1558457}, {0.632655021, 100,      278.7613986}}      Other known values within the model are:               λp[85] = 6540     λp[100] = 6540     Psat[85] = 78896.6     Psat[100] = 323767     R = 8.314      I have tried using FindFit:                FindFit[Data, qobs, {ns∞, m, A, ΔE}, { ns, T}]      And I get the error code:               FindFit::nrlnum: "The function value {0.,-69.0731+0.0051321\ (85.\ (8.314 +8.314\ Log        [<<1>>])+1.\ λp[85.]),<<21>>,-261.156+0.0228971\ (100.\ (8.314 +8.314\ Log     [<<1>>])+1.\ λp[100.]),-278.761+0.0246735\ (100.\ (8.314 +8.314\ Log[<<1>>])+1.     \ λp[100.])} is not a list of real numbers with dimensions {25} at {ns     ∞,m,A,ΔE} = {1.,1.,1.,1.}. "      I found, what I thought was a similar problem here how to avoid inducing complex numbers in FindFit In particular the answer suggested by Oleksandr R. which involves splitting the model into explicitly real and imaginary parts and changing the data to force the imaginary part of the model to go to zero. Hence I changed my model to:               ComplexModel = Inner[#1[qobs] KroneckerDelta[i, #2] &, transformation,      Range@Length[transformation]]      where               transformation = {Re, Im}      and I reformatted my data to:               ComplexData = {{1, 0, 85, 0}, {1, 0.131592244, 85, 69.07308925}, {1,      0.230286428, 85, 115.4518887}, {1, 0.255592629, 85,      126.8281889}, {1, 0.382123633, 85, 181.8483799}, {1, 0.426409484,      85, 200.2798617}, {1, 0.516246497, 85, 237.7531003}, {1,      0.60102227, 85, 271.3000332}, {1, 0.642777502, 85, 288.766803}, {1,     0.749063545, 85, 329.4612163}, {1, 0.760451336, 85,      332.9712438}, {1, 0.762981956, 85, 334.6336615}, {1, 0, 100,      0}, {1, 0.074653293, 100, 39.4734225}, {1, 0.111347284, 100,      57.64231052}, {1, 0.127796314, 100, 65.7007577}, {1, 0.212572087,      100, 104.7308741}, {1, 0.269511039, 100, 130.1461666}, {1,      0.29481724, 100, 141.0225864}, {1, 0.408695144, 100,      189.1969421}, {1, 0.523838358, 100, 236.109073}, {1, 0.536491458,      100, 241.0802459}, {1, 0.551675179, 100, 247.1796371}, {1,      0.58710386, 100,      261.1558457}, {1, 0.632655021, 100, 278.7613986} {2, 0, 85, 0}, {2,     0.131592244, 85, 0}, {2, 0.230286428, 85, 0}, {2, 0.255592629, 85,     0}, {2, 0.382123633, 85, 0}, {2, 0.426409484, 85, 0}, {2,      0.516246497, 85, 0}, {2, 0.60102227, 85, 0}, {2, 0.642777502, 85,      0}, {2, 0.749063545, 85, 0}, {2, 0.760451336, 85, 0}, {2,      0.762981956, 85, 0}, {2, 0, 100, 0}, {2, 0.074653293, 100, 0}, {2,      0.111347284, 100, 0}, {2, 0.127796314, 100, 0}, {2, 0.212572087,      100, 0}, {2, 0.269511039, 100, 0}, {2, 0.29481724, 100, 0}, {2,      0.408695144, 100, 0}, {2, 0.523838358, 100, 0}, {2, 0.536491458,      100, 0}, {2, 0.551675179, 100, 0}, {2, 0.58710386, 100, 0}, {2,      0.632655021, 100, 0}}      I tried to use FindFit again:               FindFit[ComplexData, ComplexModel, {ns∞, m,      A, ΔE}, {i, ns, T}]      however I am still getting an error code:               FindFit::nrlnum: The function value {0.,-69.0731+0.0051321 Re[85. (8.314 +Times     [<<2>>])+1. λp[85.]],<<45>>,0. +0.0228971 (831.4 Im[Log[Times[<<2>>]]]+1. Im     [λp[100.]]),0. +0.0246735 (831.4 Im[Log[Times[<<2>>]]]+1. Im[λp     [100.]])} is not a list of real numbers with dimensions {49} at {ns∞,m,A,     ΔE} = {1.,1.,1.,1.}. >>      Any help would be greatly appreciated.


why mathematica outputs "TRUE" sometimes in outputs that are conditional to mean "in all other cases"?

consider this simple Input:               Probability[g <= m && m <= -g + 1,       {m, g} \[Distributed] UniformDistribution[{{0, 1}, {0, gg}}]]      which generates a piecewise continuous function: $$\begin{cases} 1-gg & gg\le\frac{1}{2}\\\ \frac{1}{4\,gg} & \text{True} \end{cases}$$ My question is: why does mathematica outputs `True` rather that `gg>1/2`?


Using FindFit for step functions

Having used `FindFit` like so:               x = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};     y = {17, 14, 11, 11, 10, 10, 9, 9, 9, 9};     data = Transpose[{x, y}];          model = a Zeta[b n + c]     fit = FindFit[data, model, {a, b, c}, n]     modelf = Function[{n}, Evaluate[model /. fit]]          Plot[modelf[x], {x, 0, 11}, Epilog -> Map[Point, data], PlotRange ->      {{0, 11}, {0, 50}}, AspectRatio -> Automatic]      with a relatively small data set, I took the average a, b & c (which were all very close) (n clearly followed a linear trend) & came up with a step function that plotted the following against the original data points: ![enter image description here](http://i.stack.imgur.com/1yBBj.gif) Plotted with:               x = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};     y = {17, 14, 11, 11, 10, 10, 9, 9, 9, 9};     data = Transpose[{x, y}];     n = 10;     ListLinePlot[Round[Table[     (n - 1) Zeta[(Cos[1/2] + Sin[1/2]) + (Cos[1/2] - Sin[1/2]) (x)], {x, 0, 20}], 1],       InterpolationOrder -> 0, PlotRange -> {{1, 12}, {0, 70}}, Frame -> True,      AspectRatio -> Automatic, Filling -> Bottom, ImageSize -> 100,      Epilog -> {PointSize[Medium], Red, Point[data]}]      Is there any way I can improve the accuracy of these plots? Do I have any hope of finding the _exact_ step function, or am I being a little optimistic? Original data set:               x = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};      where x is the same for all               y = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};     y = {2, 1, 1, 1, 1, 1, 1, 1, 1, 1};     y = {4, 3, 2, 2, 2, 2, 2, 2, 2, 2};     y = {6, 5, 4, 3, 3, 3, 3, 3, 3, 3};     y = {7, 6, 5, 5, 4, 4, 4, 4, 4, 4};     y = {8, 7, 7, 6, 5, 5, 5, 5, 5, 5};     y = {12, 8, 8, 7, 7, 6, 6, 6, 6, 6};     y = {13, 10, 9, 8, 8, 7, 7, 7, 7, 7};     y = {15, 13, 10, 10, 9, 8, 8, 8, 8, 8};     y = {17, 14, 11, 11, 10, 10, 9, 9, 9, 9};     y = {18, 15, 13, 12, 11, 11, 10, 10, 10, 10};     y = {20, 16, 14, 13, 13, 12, 11, 11, 11, 11};     y = {23, 18, 15, 14, 14, 13, 12, 12, 12, 12};


Modify a sub-part of a sub-list only

I have this list:               a = {{{0, 0}, {1, 7}, {2, 0}, {3, 2}, {4, 7}}, {{0, 0}, {1, 0}, {2, 1}, {3, 2}, {4, 7}}}      and I'd like to transform it to this:               a = {{{0, 0}, {1, 7}, {2, Na}, {3, 2}, {4, 7}}, {{0, 0}, {1, Na}, {2, 1}, {3, 2}, {4, 7}}}      ie I'd like to replace every 0 by Na except in the first sub-sub-list of each sub-list. All I can come up with is:               Part[#, 2 ;; All, All] & /@ a  /. 0 -> Na      and it works I get               {{{1, 7}, {2, Na}, {3, 2}, {4, 7}}, {{1, Na}, {2, 1}, {3, 2}, {4, 7}}}      but the modification is not attributed to `a`. How can I do that?


Adjusting placement of control objects in a row within a panel

My minimal example               Panel[Column[{        Row[{"Board size: ", InputField[Dynamic[max], Number, FieldSize -> 3],           Button["Clear Board"]}], "A graphic object which is large enough"}]]      evaluates to ![enter image description here](http://i.stack.imgur.com/Bzkoi.jpg) Since I have a large graphic object underneath the first row, there is some space to the right of the "Clear Board" button. I would like to move the button to the right so that it is flush with the boundary of the panel -- basically the effect of the LaTeX command `\hfill` if I were typesetting. I have been messing with `Alignment` and `ControlPlacement`, but no luck so far.


Changing the Actions in EventHandler

I would like to be able to change which action specified events take depending on some condition. For example, I have established a `SetterBar`               SetterBar[Dynamic[setter], {Zoom, Pan}]      and created a graphic that I would like the left mouse button to cause to either zoom or pan, depending on what the value of `setter` is when the event occurs.               DynamicModule[{frac = 0, zoomval = 7*Pi/36, drag = {0, 0},      pt = CurrentValue[ImageSize], CurrentPosition = {1/2, 1/2},      panvalue = {0, 0}},      EventHandler[     Dynamic[Show[graphics,      ViewCenter -> {{1/2, 1/2,         1/2}, {x = CurrentPosition[[1]] + panvalue[[1]],         y = CurrentPosition[[2]] - panvalue[[2]]}},      ViewAngle -> (Which[drag[[2]] > 0,         zoomval = Min[Pi*0.7, zoomval + frac*(Pi - zoomval)],         drag[[2]] < 0,         zoomval = Max[zoomval - frac*(Pi - zoomval), 0.2],         drag[[2]] == 0, zoomval = zoomval]),      RotationAction -> "Clip"]], {{"MouseDown",       1} :> (a = CurrentValue[MousePosition]), {"MouseDragged",       1} :> {Which[       setter == Zoom, {b = CurrentValue[MousePosition], drag = b - a,         frac = 0.5 Norm[drag]/Norm[pt]},        setter == Pan, {b = CurrentValue[MousePosition], drag = b - a,         panvalue = {drag[[1]]/(pt[[1]]),           drag[[2]]/(pt[[2]])}}]}, {"MouseUp", 1} :> {frac = 0,       drag = {0, 0}, panvalue = {0, 0}, CurrentPosition[[1]] = x,       CurrentPosition[[2]] = y}}]]      This may be a little difficult to follow, but esentially I want the `Which` function to alter the action taken by the event `"MouseDragged"` depending on if setter is set to Zoom or Pan. Currently, everything works when the value is set to Zoom, but no action occurs upon setting the value to Pan. Also, `graphics` is simply a red cylinder created for example.               graphics = Graphics3D[{Red, Cylinder[]}];


Import a file only if it contains a certain pattern

Let's say I have three files containing:               File 1:     x y z     1 4 6           File 2:     x y z     2 5 9           File 3:     x y z     5 4 8      My goal is to import the data from a file only if in this file `y == 4` (so here I would want to import files 1 and 3). Is there a way to do that with functional programming? The only solution I can think of currently is to loop through all the files, check if `data[[2, 2]] == 4`, and append this data to a list if true. Is there a better way to do that? And if I have to loop, is it better to import all the files as lists and then discard the lists that do not match `y == 4`? Or is it better to import only the files matching `y == 4` in the first place?


Mathematica Precision

How can I set the output precision of the following statement to 10 decimal places? I was looking through the documentation, and for some reason, all I could find was `Accuracy[]` or `Precision[]`.               f[x_] := E^Cos[x]     NIntegrate[f[x], {x, 0, 2*Pi}]      Which, by default, evaluates to:               7.95493      Thank you for your time.


Finding all length-n words on an alphabet that have a specified number of each letter

For example, I might want to generate all length `n=6` words on the alphabet `{A, B, C}` that have one `A`, three `B`'s and two `C`'s. An example of such a word is: `'ABBBCC'`. I'd like to generate all such words. I've already tried generating all permutations of a particular string (like `'ABBBCC'`) and deleting all duplicates. This is too slow for my purposes.


Inheriting Stylesheets when using CreateDocument

I build a lot of presentations and custom notebooks with very different stylesheets, and use `Button` and `CreateDocument` quite often to accommodate optional/procedurally generated content. For instance,               Map[Button[Style[ToString[#] <> " random images", "Text"],             CreateDocument[               {Cell["Here are " <> ToString[#] <> " random image(s)", "Title"],                             ExpressionCell[Column@Table[RandomImage[2, {200, 200}], {#}],                "Output"]}]] &,        Range[5]]      What I'd like to do is specify that the notebook generated by `CreateDocument` inherits the StyleSheet from the parent notebook, without having to save the StyleSheet and provide the `StyleSheetPath` Option in the `CreateDocument` function each time I change a style. I imagine there's an undocumented feature, but haven't found it in my brief searches of StackExchange.


Having the derivative be an operator

How do I create an operator which acts like a derivative to everything to the right of it: for example: $ \left( \partial_x + \partial_y + z \right ) x \psi $ How do I make that evaluate to: $x \partial_x \psi + \psi + x \partial_y \psi + z x \psi $ (I want the derivatives to distribute...)


RandomReal closed on left & open on right?

I have a number of algorithms that depend on uniform random reals in half-open intervals such as $[0,1)$. In particular, I need a (pseudo) random-number generator that produces machine-precision numbers in the range $0.0$ to $1-\epsilon$. It can return $0.999...$, but will never return exactly $1.0$. I haven't found in the Mathematica documentation whether Mathematica's `RandomReal` satisfies this requirement. The documentation does state that `RandomInteger[{xMin,xMax}]` produces values in the double-closed interval $[x_{min}, x_{max}]$ inclusive of both ends, but I haven't found an equally clear statement about the real-number generators. The documentation that I've read just says "between 0 and 1." I could read this as double-open, but it really isn't precise enough for me. I would be grateful for an authoritative answer.


How to prove an expression by method of mathematical induction?

I want to prove the expression $$1^2 + 2^2 + 3^2 + \cdots + n^2 = \dfrac{n(n+1)(2n+1)}{6}$$ by method of mathematical induction with Mathematica, but I do not know how to start. How do I tell Mathematica to do that?


MatchQ and patterns for similar lists

I can't seem to find the right set of patterns to independently match two different lists. Simplified versions of the lists are as follows:               list1 = {{2}, {2}, {20}, {2}, {10}}     list2 = {{2}, {2}, {2}, {2}, {2}, {2}}      In general, the second list will always have the same number inside the parentheses. They can have different lengths. Both will have just a single number inside the parentheses. I am trying to find two patterns (`p1`,`p2`):               p1 = {{s_?NumericQ} ..};     p2 = {{_?NumericQ} ..};      Such that               {MatchQ[list1,p1],MatchQ[list1,p2],MatchQ[list2,p1],MatchQ[list2,p2]}      Gives               {True, False, False, True}      My test patterns give `{True, True, False, True}` instead. I'm sure the answer is easy, but I just can't get it right...


Shading in squares crossed by a diagonal

You have a rectangle and it is diagonal. How many squares will be crossed by the diagonal (I guess assuming the side length of the rectangle are nice whole numbers) I've seen an implementation in Geogebra to shade in the squares that are crossed by the diagonal of a rectangle. I'd really be happy to see how to do this using Mathematica, it would help me learn a lot. But it's beyond me right now. Here is my "start"....               Manipulate[ Module[{length, width},              length = Round[p[[1]]];         width = Round[p[[2]]];              Graphics[{              {GrayLevel[0.8],           Line /@ Table[{{i, 0}, {i, 20}}, {i, 0, 20}],          Line /@ Table[{{0, i}, {20, i}}, {i, 0, 20}]},              (*rectangle to mark off area*)         {Line[{{0, 0}, {Round[p[[1]]],              0} , Round[p], {0, Round[p[[2]]]}, {0, 0}}]},              (*point to control rectangle*)         {Blue, AbsolutePointSize[8],           Point[Round[p]]},              (*diagonal*)         Line[{{0, 0}, Round[p]}]              },             PlotRange -> {{-0.1, 20.1}, {-0.1, 20.1}},        ImageSize -> {800, 640}]],      {{p, {1, 1}}, {0, 0}, {20, 20}, Locator, Appearance -> None}     ]      ![Mathematica graphics](http://i.stack.imgur.com/0f1nT.png) Any help would be appreciated.


How to pull scalars out of a function that should act on lists?

Suppose I have               A = a vecA     B = b vecB      where `a` and `b` are supposed to be arbitrary scalars and `vecA={vA1,vA2}` and `vecB={vB1,vB2}` are vectors, i.e. lists (I guess from a mathematica point of view the difference is that a and b have Head `Symbol`, whereas vec1 and vec2 have head `List`?). Now imagine an arbitrary function of two arguments `f[A,B]`. What I would like to do is to pull out the scalars and multiply them:               f[A,B] -> a * b * g[vecA,vecB]      where g[vecA,vecB] is again an arbitrary function that only works on vectors (lists). How can I achieve that? The background is that I would like to process (simplify, rearrange, expand in series, etc.) expressions that mix scalars and vectors and contain inner products of such mixtures without explicitly expanding the inner products into the components of the vectors. Such that I can later on easily replace occurrences of some inner products. See also my (not yet really solved) question: Symbolically associate vectors and their norms My current take on this is to use               Inner[f,A,B]      instead of `Dot[A,B]` such that the inner product is not explicitly expanded into components. However I do need to pull out the scalars somehow..


How do I define the "Coupon" within the function FinancialBond with a time-varying coupon

Is it possible using `FinancialBond` function to calculate the yield of a bond paying a gradual coupon ? An example : > A bond with maturity of 7 years pays 4.125% the first 3 years, then 6% the > next two and finally 7.75% the last two. The actual price of the bond is > 102.35% and it is redeemed at par. I know the answer using `TimeValue` and `Cashflow` functions. It is 5.14601% But I want to know if it is possible to calculate it straight from the `FinancialBond` function.


making a TreeGraph VertexLabel that contains a text label and also a Tooltip?

I am trying to make a TreeGraph[] that has as labels for vertices both text and Tooltip. The text displays all the time, when the `TreeGraph` is plotted, and in addition, when the mouse moves over the vertex, another text shows up using `Tooltip` (may be below the static text, but I'll worry about this later). This Tooltip text will contain more information about the node. Right now, I can do each one of the above separately but can't figure how to combine them. I'll show my attempts below. This is all using V9 ### Tooltip shows up when mouse on vertex               TreeGraph[{1, 2, 3}, {1 -> 2, 1 -> 3},      VertexLabels -> {"Name", 3 -> Placed["equation 1", Tooltip]},       ImagePadding -> 20]      ![enter image description here](http://i.stack.imgur.com/W3WTT.png) ### standard vertex label               TreeGraph[{1, 2, 3}, {1 -> 2, 1 -> 3},      VertexLabels -> {"Name"}, ImagePadding -> 20]      ![Mathematica graphics](http://i.stack.imgur.com/2FHgK.png) # Attempts to combine them I noticed that it says in the help that any expression can be used as label: ![Mathematica graphics](http://i.stack.imgur.com/QiH3i.png) ### attempt 1 Since any expression can be used as label, then I tried `Column`               TreeGraph[{1, 2, 3}, {1 -> 2, 1 -> 3},      VertexLabels -> {"Name",         3 -> Column[{"3", Placed["equation 1", Tooltip]}]},       ImagePadding -> 20]      Which does not work. ![Mathematica graphics](http://i.stack.imgur.com/WOtqH.png) ### attempt 2               TreeGraph[{1, 2, 3}, {1 -> 2, 1 -> 3},      VertexLabels -> {"Name",         3 -> Labeled[Placed["equation 1", Tooltip], "3"]},       ImagePadding -> 20]      ![Mathematica graphics](http://i.stack.imgur.com/RiMbR.png) ### attempt3 The strange thing is that one can add a button that changes the color of the node and speaks when clicked and also add a Tooltip at the same time, but so hard to add a text in addition to Tooltip               TreeGraph[{1, 2, Button[Style[3, Red], Speak["Vertex 3"]]}, {1 -> 2,        1 -> 3}, VertexLabels -> {"Name",         3 -> Placed["equation 1", Tooltip]}, ImagePadding -> 20]      ![Mathematica graphics](http://i.stack.imgur.com/E4hdT.png) Tried maybe another 10 different ways, too boring to show. So I gave up. I am a newbie in using Graphs in Mathematica, only today I started looking at them. **Question** How make a label for Vertex and also show Toolip when mouse is on Vertex?


how can I avoid CPU waste (by master kernel) using WaitNext?

I'm using `WaitNext` in _Mathematica_ for parallel processing on Mac OS X. I have 4 processors on my MacBook and `LaunchKernels[]` has launched 4 kernels in _Mathematica_ , in addition to the master kernel. However, each of these 4 kernels gets approximately 75-80% of a processor, while the master kernel gets 70-75%. It seems to me that the master kernel should be just waiting, instead of using CPU. The relevant code is               While[Length[parallelJobs] > 0,      {result, pJ, parallelJobs} = WaitNext[parallelJobs];      Write[outputstream, result];      setofresults = Join[setofresults, result]     ]      where `parallelJobs` is a list of process IDs of the form `ParallelSubmit[{...},...]`, and each of the jobs should take about an hour. Thus, there is no reason for the master kernel to be running. A similar code with `WaitAll` instead of `WaitNext` leaves the master kernel with 0% CPU and gives 100% to each of the launched parallel kernels. But the reason I want to use `WaitNext` instead is because I want to write the results as they're generated. I'd be grateful for any explanation of what's going on or ideas for getting around this waste of CPU. Thanks. Later: Here's a fix. I bundle more stuff into the `ParallelSubmit[...]` parts, in order to Write there, and then I use `WaitAll` on the list of `ParallelSubmit` items. This seems to result in considerably less overhead CPU used by the master kernel. It now seems to be an academic question: why does `WaitNext` (seem to?) use so much more overhead than `WaitAll`?


Disconnected Frame/Axes in Plots

Is it possible to have "Tufte" style figure axes? That is so that the axes do not need to connect or span the entire data range? For an example of what I mean from the R's default histogram style: ![enter image description here](http://i.stack.imgur.com/4TXsD.png) I know how to get the ticks out etc ... but not how to break the axes at the origin or only draw the axes/frame for a subset of the graphic range.


Adding a label to an expression result

To make my notebook easier to read for non-Mathematica literate colleagues (myself included), I'd like to have the output from an assignment expression look somewhat more obvious. Normally an expression assignment would look something like this:               In[1]= myVariable = 1 + 1          Out[1]= 2      But I'd like to get an output that looks more like:               Out[1]= myVariable = 2      I'm sure there are very convoluted ways to get this as an output but is there some really simple thing I can do so that the input is also still fairly easily readable without a heap of other commands wrapped around it?


How to combine two vectors into a matrix by columns?

I know it may sounds idiot, but I've been looking through the document, and couldn't find a way to combine two vectors say `{a, b}` and `{c, d}` into `{{a, c}, {b, d}}`. Thanks all.


Subscripts to a variable; why a letter shoud come before a digit?

I noticed that I cannot create a variable $f_{2s}$ since Mathematica seems to leave a space between the subscripts `2` and `s` implying that $f_{2s}$ is not recognised in later calculations. But I see that I can create the variable $f_{s2}$ instead without any problem. Is there a way to create the variable $f_{2s}$ in Mathematica? Thank you.


Cleaning mildew from old documents using Mathematica (Image processing)

While visiting family over the holiday period, I managed to have some good mother-daughter bonding over how far back I’ve managed to trace the family tree (Mom is in her 80s and doesn’t do computers). I’ve been using the usual databases like Ancestry.com, familysearch.org and asking the odd question over on genealogy.SE when I get stuck. But I’ve also been lucky that certain old church records for parts of Kent in England have been scanned and the images available online. Unfortunately some of them are in poor condition, and I thought I could use Mathematica’s image processing capabilities to clean them up a bit. Take this example:               raw = ImageRotate[Import["http://goo.gl/er4c5"], 180 Degree];      Cleaning this up with `Sharpen` and some of the filters like `MeanShiftFilter` definitely helps.               sharpened = Sharpen[raw, 3]         s2 = MeanShiftFilter[sharpened, 2, 0.03, MaxIterations -> 20]      ![enter image description here](http://i.stack.imgur.com/drdLx.png) But there are still a lot of mildew blotches on the image. I’d like to fade out the things that look like disks, and darken the things that look like handwriting, but I have not yet found the iteration of things like `MorphologicalComponents` that would do the trick. I keep getting the background of the page as the connected component, so I can’t, for example used the `"Holes"` property to select handwriting and not mildew blotches. Does anyone have any suggestions? I’m quite unfamiliar with the image processing side of Mathematica.


Calculating the density of nearest neighbours

I am trying to plot this ![](http://i.stack.imgur.com/8I0EM.png) which is a numerical simulation of the Montgomery-Odlyzko law for the nontrivial 1st $10^5$ zeros of the Riemann zeta function $ζ(s)$. The solid line is given by `1-(Sin[π x]/(πx))^2`. The following is what I can't seem to interpret: > The blue symbols indicate the pair correlation function of normalized > spacings $δn=(γ_{n+1}-γ_n)\log(γ_n/2π)/2π$ between two consecutive > nontrivial zeros $1/2+iγ_n$ and $1/2+iγ_{n+1},\ n=1\dots10^5)$ of the > Riemann zeta function $ζ(s)$. from this page. I have looked at various ways of calculating the density, using `Histogram`, `NearestFunction`, `FindClusters`, etc. but am getting nothing like the image above. I realise that this is largely due to a conceptual misunderstanding, but I was hoping someone could point me in the right direction. # Update ![](http://i.stack.imgur.com/BNIbu.gif) plotted with               DeleteCases[Flatten[Table[Abs[z1 - z2] Log[z2/(2 π)]/(2 π),      {z1, Take[zz,1000]}, {z2, Take[zz,1000]}]], 0];     Show[ListPlot[HistogramList[%, {0, 3, 0.1}][[2]]/200,      DataRange -> 3], Plot[1 - (Sin[π u]/(π u))^2, {u, 0, 3}]]      using First $10^5$ zeros as `zz`, thanks to Rahul Narain's comments below. Unfortunately, my computer won't calculate for $10^5$ zeros, but link left for those that will. ... I am now beginning to appreciate the computational power that would have to be used to generate an image like this or this!


On generalizing Partition[] (with offsets) to sublists of unequal length

The usual `Partition[]` function is a very handy little thing:               Partition[Range[12], 4]     {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}          Partition[Range[13], 4, 3]     {{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}      One application I'm working on required me to write a particular generalization of `Partition[]`'s functionality, which allowed the generation of sublists of unequal lengths, for as long as the lengths were appropriately commensurate. (Let's assume for the purposes of this question that the list lengths being commensurate is guaranteed, but you're welcome to generalize further to the incommensurate case.) Here's my generalization in action:               multisegment[lst_List, scts_List] := Block[{acc},       acc = Prepend[Accumulate[PadRight[scts, Length[lst]/Mean[scts], scts]], 0];       Inner[Take[lst, {#1, #2}] &, Most[acc] + 1, Rest[acc], List]]          multisegment[CharacterRange["a", "x"], {3, 1, 2}]     {{"a", "b", "c"}, {"d"}, {"e", "f"}, {"g", "h", "i"}, {"j"}, {"k", "l"},      {"m", "n", "o"}, {"p"}, {"q", "r"}, {"s", "t", "u"}, {"v"}, {"w", "x"}}      (Thanks to halirutan for optimization help with `multisegment[]`.) The problem I've hit into is that I wanted `multisegment[]` to also support offsets, just like in `Partition[]`. I want to be able to do something like the following:               multisegment[Range[14], {4, 3}, {3, 1}]     {{1, 2, 3, 4}, {4, 5, 6}, {5, 6, 7, 8},       {8, 9, 10}, {9, 10, 11, 12}, {12, 13, 14}}      How might a version of `multisegment[]` with offsets be accomplished?


How can I create a ColorFunction using Blend?

As shown below, I am trying to find a cool way to show some variance weighted deviation from the mean. There are 10 attributes that I compute the distance for. How can I add a color function such that it is progressively a darker shade of red when its value is negative (towards the left) and green when the value is positive (towards the right of the graphics)?               distance = {0.245, -0.235, 0.053, -0.048, -0.128,                 -0.007, -0.075, -0.067,-0.005, 0.082}          Show[       Function[         attributes,         Graphics[           Rectangle[             {If[distance[[attributes]] < 0, distance[[attributes]]*10, 0],               attributes - 1},             {If[distance[[attributes]] < 0, 0, distance[[attributes]]*10],               attributes}           ],           PlotRange -> {{-5, 5}, {0, 10}},           Epilog -> {White, Line[{{0, 0}, {0, 11}}]}       ]] /@ Range[10],       Frame -> True]      ![enter image description here](http://i.stack.imgur.com/e2Pft.png)


sprintf() or close equivalent, or re-implementation?

Is there a `sprintf()` command (some command that takes a `printf`-style format string and a list of values to insert into the string) or something very much like it (preferably with a similar style of format specifiers)? Or, alternately, how would I implement `sprintf()` in Mathematica?


Labeling triangle edges in Mathematica 10

Mathematica 10 introduced lots of new geometry related functions, and one of these is SSSTriangle which creates a triangle graphic given the three side lengths. Is it possible however to label the side lengths to achieve something like this ![enter image description here](http://i.stack.imgur.com/PzQYP.png)


Export vector images

I am having difficulties exporting vector graphics. Using Kardashev3's code provided here:               images = Image[ListPlot[pdata = Table[Sin[2 \[Pi] x/12.34], {x, #}] +      RandomReal[.1, {#}]]] & /@ Table[i, {i, 100, 200, 10}];      and then exporting them as follows:               Export[NotebookDirectory[] <> "image" <> ToString[#] <> ".eps",      "AllowRasterization" -> False, Image[images[[#]]]] & /@ Range[Length[images]]     Manipulate[images[[n]], {n, 1, Length[images], 1}]      I get the error message:               <<Export::noelem: {...} is not a valid set of export elements for the EPS format.>>      The code works well for rasterized graphics, but appears to run into problems with vector graphics.


How can I create a Distribution from its probability density function?

I have a probability density function. Is there a mechanism to create a `Distribution` object from it, such that normal Mathematica commands that usually work on distributions, such as `Variance`, `RandomVariate`, etc., work on it?


Can ParallelDo speed up a counting problem?

How to make parallelize the following code keeping the same "idea". The example I have in mind is more complicated, but I would like to know if a program of this structure can be parallelized?               c = 0     ParallelDo[If[RandomReal[] > 0.5, c += 1], {i, 100}]


Possible Bug in DiscretizeRegion with Option MaxCellMeasure

Consider the following `ImplicitRegion`:               reg = ImplicitRegion[x^2 + y^2 + z^2 == 16, {x, y, z}];      We can discretize it using `DiscretizeRegion`               dr = DiscretizeRegion[reg]      ![Mathematica graphics](http://i.stack.imgur.com/g0hE2.png) To get finer triangles the option `MaxCellMeasure` is available, only it does nothing when used.               DiscretizeRegion[reg, MaxCellMeasure -> {"Area" -> #}] & /@ {0.1, 0.05}      ![Mathematica graphics](http://i.stack.imgur.com/iEGOh.png) Of course using one of the `Graphics` primitives               DiscretizeRegion[Ball[], MaxCellMeasure -> {"Area" -> #}] & /@ {0.1, 0.05}      ![Mathematica graphics](http://i.stack.imgur.com/DO7W2.png) You can see that it works fine. I'm on **Windows 8.1** , can anyone confirm this on other platforms? Confirmed on **Linux** via the Wolfram Programming Cloud.


Generate a list of values with equal number of each value

I want to create a list of 32 values such that from `{a,b}` I can generate               {{a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b},     {a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b},...,     {b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a}}      (that's exactly 16 a's and 16 b's in each array, with repeats allowed). I have tried `Select[Tuples[{a,b},32],Count[##,a]==16]`, but get an error that `"The length of the output of Tuples[{a,b},32] should be a machine integer."` The problem as I see it is that `Tuples` is generating a lot of unneeded cases for my problem and the computer can't handle such a large number (and it would take a really long time even if it could). I did a study of the timing of running some lower length arrays and assuming that the scaling stays linear (like it did for some of the larger numbers) it would take nearly 7 hours. EDIT: I have the answer, but it won't let me post it, because I am new. So here it goes: Building off of Kuba's suggestion, I came up with an answer that works for my problem. Sorry if I was unclear. I built a list and then made every permutation of the list until all elements were switched. It is easy enough to make sure it goes through the switch and then back to the original (thus generating every possible combination without eliminating repeats).               list = Join @@ (ConstantArray[#, 16] & /@ {a, b});     For[c = 1, c < 17, c++,      For[d = 17, d <= 33 - c, d++,       new = Permute[list, Cycles[{{c, d}}]];      ];      list = new     ];      Hopefully this will help someone else!


ArrayPlot of square matrix: how does ColorFunction -> Automatic work?

Suppose you have the following:               tt = Table[{i, j}, {i, 0, 10}, {j, 0, 10}]      The table `tt` is a matrix of pairs, `{i, j}`. Now you issue               ArrayPlot[tt]      you get a nice image with the top row and the rightmost column white. How does `ArrayPlot` work in this case? I tried to look into the `ColorFunction` documentation but I was not able to actually understand how the system is working. I am curious to find an explanation.


Swapping rows and columns in matrix

If I have an array like the following $\left( \begin{array}{ccc} 1 & 2 & 3 \\\ 4 & 5 & 6 \\\ 7 & 8 & 9 \end{array} \right)$ How can I swap the rows and columns, so it is transformed into this? $\left( \begin{array}{ccc} 1 & 4 & 7 \\\ 2 & 5 & 8 \\\ 3 & 6 & 9 \end{array} \right)$ This question touches upon the subject, but rather than swapping it simply rotates the matrix.


Mathematica averaging a big list of large images

I have a list of several hundred images, and I want to average the list to get a single image. Each image is 12bit TIFF with 2048*2048 pixels, and I am using the following to do the job:               result=Mean[Map[ImageData[Import[#]]&,imagelist]];      The problem is that the data becomes huge. I tried to do the task with about 400 images with 2048*2048 resolution. The computer ran out of ram, created a 25GB of virtual memory, and could not finish the task. Is there any other alternative that I can use to do the task? I would greatly appreciate your help.


Problem with large values in ParametricPlot

I've got a question quite similar to No 18163:Problem with high parameter values in ParametricPlot, but the solution of that problem did not work for me. So I hope you may have another tip. I want to plot an equation similar (just a bit more difficult) then the following, the parameter and data range of concern is also similar: $\omega = 2 c \pi / \lambda$, where $c$ is the speed of light. Now, the other function is a bit more tricky, therefore I want to use `ParametricPlot` and not `Plot`. My problem however is that it does not display the x-axis (or it might be so small I don't see it) when I use the correct value for `c`. It seems to be a problem with the large values, as everything is OK if I set `c = 2` or `c = 10` instead. The code I used is: 1)               ParametricPlot[{(2 π)/λ, (2 π)/λ*1000}, {λ, 300, 1000}]      2)               ParametricPlot[{(2 π)/λ, (2 π])/λ*1000}, {λ, 300, 1000},        PlotRange -> {{0.010, 0.02}, {10^15, 10^16}},        MaxRecursion -> 15,       Evaluated -> True]      I tried to apply a workaround, creating a list to `Map` over the range $\lambda$ = 300 .. 1000 and then using `ListPlot`. This would work; however, it's not so good for my full problem.


Loop through a list and select elements

I am new to _Mathematica_ and I have no idea how to make a basic for loop work. I want to loop through the elements of a list: `Range[45, 200]`. I want to select the elements (i) for which the following conditions holds: if i mod 3 and i mod 8 and i mod 12 == 1 and i mod 5 == 0 I want to print the element. How would I achieve this? I want something like this:               for i in range(45, 201):        if i%3==1 and i%8==1 and i%12==1 and i%5==0:           print i      Of course in _Mathematica_ language. Sorry if this is a dumb question but the _Mathematica_ documentation is pretty hard to understand. Thanks.


Plotting the solutions of a system of differential equations on a simplex

I want to solve and plot the solutions of the following system on the triangle simplex:               x'[t] == x[t]*(2*x[t] - 2)     y'[t] == y[t]*(2*x[t])      z'[t] == z[t]*(2*x[t])      It is assumed that `x[t] + y[t] + z[t] == 1` for all times `t`. I am looking for output similar to this: ![Imgur](http://i.imgur.com/Koz3AP0.png) I;m also interested in plotting the frequency changes of `x[t]`,`y[t]` and `z[t]` over time. That is, given an initial value, I want to find how the frequencies vary over time?


Color plot markers using If statement

I am calculating eigenvlaues. Some are negative, some are positive. I define the index nn and mm (as well as np and mp) of each matrix element by some functions that assign positive, zero and negative integer values for nn (np) and strictly positive integers for mm (mp). My code is much more complex, but a simplified version of it looks like this:               nn = 2; mm = 3; som = 2 (nn + 1) mm; RX = 1; PO = 5;     n[a_] := Floor[(a - 1)/mm] - Floor[(a - 1)/((nn + 1) mm)] - nn;      m[a_] := Mod[a - 1, mm] + 1;     np[b_] := Floor[(b - 1)/mm] - Floor[(b - 1)/((nn + 1) mm)] - nn;      mp[b_] := Mod[b - 1, mm] + 1;     Vnozer[nn1_, np1_, mm1_,         mp1_] := (2 nn1 + 3 np1 + 4 mm1 + 5 mp1) Exp[kx];     Vzer[nn1_, np1_, mm1_,         mp1_] := (-4 nn1 - 3 np1 - 2 mm1 - 1 mp1) Exp[kx];     V[nn1_, np1_, mm1_, mp1_] :=        If[Abs[nn1] > 0 && Abs[np1] > 0, Vnozer[nn1, np1, mm1, mp1],         Vzer[nn1, np1, mm1, mp1]];     EN[nn1_] := Sign[nn1] Sqrt[Abs[nn1]];     c[a_, b_] :=        EN[n[a]] KroneckerDelta[Abs[n[a]], Abs[np[b]]] KroneckerDelta[m[a],           mp[b]] KroneckerDelta[Sign[n[a]], Sign[n[b]]] +         V[n[a], np[b], m[a], mp[b]];     Q = Array[c, {som, som}];     MF = Table[{kx, Eigenvalues[Q]}, {kx, -RX, RX, (2 RX)/(PO - 1)}];     Array[ou, som]; Array[pl, som];     Table[ou[y] = Table[{MF[[x, 1]], MF[[x, 2]][[y]]}, {x, 1, PO}], {y, 1,         som}];     Table[pl[y] = ListPlot[ou[y], PlotRange -> All], {y, 1, som}];     FPL = Table[pl[z], {z, 1, som}];     Show[FPL]      ![Eigenvalue plot looks like this.](http://i.stack.imgur.com/5aFGb.jpg) I would like to get Red PlotMarkers when my eigenvalues are positive and, say, Blue when my eigenvalues are negative. I played around with an If statement, but I was not able to figure out the right syntax. Something along the lines               PlotMarkers->{If[x]>0, {Red, dotsize}, {Blue, dotsize}}


Extract information from function definition returned by DefineDLLFunction

I have an application using `DefineDLLFunction` whose output is: > Function[Null, If[NETLinkDLLPrivatecheckArgCount["DRV_AOVoltageOut", > {##1},2], WolframNETLinkDynamicDLLNamespaceDLLWrapper2DRVUAOVoltageOut[##1], > $Failed], {HoldAll}] How to extract the information “DynamicDLLNamespaceDLLWrapper2” from the output above?


ToExpression and Fortran notation

ToExpression["9.0E-03"]      interprets String as               9*e - 3      instead of what I am expecting               0.009      How can I convert to expression Fortran notation?


Determining the dimension of a probability distribution

Functions like `Mean` and `RandomVariate` clearly infer the dimension of the distribution passed to them. One can also usually determine the dimension of a distribution by calling one of these functions, but this is suboptimal. `RandomVariate` does not work if some of the parameters of the distribution are symbolic and long tailed distributions may not have a well defined mean. Even when this method works it is overkill. Presumably there is some lower level function that just determines the dimension that `Mean` and `RandomVariate` themselves use to determine the dimesion but I have not been able to find it.


Plot a function based on Derivative - Gradient field

I'm trying to plot the gradient field of a function in such a way that is possible to change it easily, only editing the function. Consider the code:               xmin := -2; xmax := -xmin; ymin := -2; ymax := -ymin;     f[x_, y_] := x^2 + y^2     Plot3D[f[x, y], {x, xmin, xmax}, {y, ymin, ymax}]      ![enter image description here](http://i.stack.imgur.com/PoDlW.png) So, the following code produces a very fancy result:               VectorPlot[{2 x, 2 y}, {x, xmin, xmax}, {y, ymin, ymax},       StreamPoints -> Coarse, StreamColorFunction -> Hue]      ![enter image description here](http://i.stack.imgur.com/WGaR7.png) Since `{D[f[x, y], x], D[f[x, y], y]}` produces `{2 x, 2 y}` I tried to define               Gradf := {D[f[x, y], x], D[f[x, y], y]}      and use               VectorPlot[Gradf, {x, xmin, xmax}, {y, ymin, ymax},       StreamPoints -> Coarse, StreamColorFunction -> Hue]      but I got a lot of errors as > General::ivar: -1.99971 is not a valid variable. >> > > General::stop: Further output of General::ivar will be suppressed during > this calculation. >> I really don't understand why it is not working. Any idea how to solve this so I could only change the definition of `f` and plot again?


How do I get a different (random) independent edge set each time I run FindIndependentEdgeSet?

I'd like to use FindIndependentEdgeSet[g] repeatedly to get random maximal matchings of a fixed graph, but each time I call this function it gives me the same answer (i.e. the same list of edges). How do I "randomise" it?


FullSimplify assumptions for function body

I'd like to pass an assumption to `FullSimplify` so whenever it gets a function that is squared and square rooted would return me only the function body, without `Abs[f]` (I've tried assumption `_Symbol ∈ Reals && _Symbol > 0` but it gives `Abs[f]` instead of `f`.               f[x_] := a x^2;     FullSimplify[Sqrt[f[x]^2], _Symbol ∈ Reals && _Symbol > 0]      > >     x^2 Abs[a] >


How do I avoid the gaps introduced by a frame on a plot?

You can see that there are gaps on all sides of the plot between the frame and the extent of the line that I've plotted. How do I get rid of these? I'd like the frame to cover $[0,1]\times[0,1]$ and no more.               Plot[x, {x, 0, 1}, Frame -> True]      > ![enter image description here](http://i.stack.imgur.com/Y5Ck5.png)


Kronecker delta notation

Is there an easier way to enter `KroneckerDelta[n,m]` in Mathematica? When I use the notation $ \delta_{n,m} $, it won't work.


Interpolation of multidimensional data organized logarithmically

The following threads call our attention to the fact that "accuracy of Interpolation will be worse with an unstructured grid", in the context of interpolation of 3d data: interpolation of 3D data Improved interpolation of mostly-structured 3d data I want to know if there is a systematic way to do the interpolation correctly for a 3D data with the points distributed logarithmically along x and y. **Simple example** The xy grid would be built using               grid = Table[ {10^t, 10^u}, {t, 1, 3, 0.05}, {u, 1, 3, 0.1}]     ListPlot[ grid ]      ![Logarithmic grid](http://i.stack.imgur.com/8GxNs.jpg) Of course, in logarithmic scale it looks fine (linear):               ListLogLogPlot[ grid ]      ![enter image description here](http://i.stack.imgur.com/KPGvv.jpg) The 3D data would be built using some 2 variable function `func`:               tabx = Table[10^w, {w, 1, 3, 0.05}]     taby = Table[10^w, {w, 1, 3, 0.1}]     tab = Table[ {{x,y},func[x, y]}, {x, tabx}, {y, taby}]      Then, how to interpolate `tab` properly?


Solving polynomial equations takes infinit time

I need to solve an polynimial equation, but when i try to use Solve or NSolve in mathematica, its cant find the solution in appropriate time (i interrupted calculation after 5 hour left). The equations is:               Remove["Global`*"];     g = 9.8;     C1 = 3.6;     C2 = 0.25;     C3 = 666;     C4 = 2;     c = -36;     e = 0.86;     P0 = 24.44;     h0 = 0.1;          h = h0*(1 + C3*P^C4);     NSolve[{P/P0 == ((1 - e*(1 - h/e))/(1 - e))^((2 + c)/3)/(1 - h/e)^4.65}, {P}]      Maybe my computer is too weak or I'm using the wrong method?


NonLinearFit with "complicated" integral model

I have a set of data $y_i (z_i)$ with errors $\Delta y_i$                data = {{0.015, 34.1114},{0.0277, 35.705},{0.048948, 36.7316},{0.0651, 37.3067},{0.100915, 38.4567},{0.159, 39.4164},{0.248508, 40.2722},{0.455, 42.3239},{0.655, 42.3151},{0.75, 43.243},{0.84, 43.5143},{0.961, 44.2642},{1.188, 44.6076},{1.34, 45.0675},{1.414, 44.8038}}                sigmadata={0.215239,0.118114,0.175773,0.242628,0.121087,0.21481,0.152213,0.306006,0.188809,0.198402,0.471047,}      that I want o fit with a complicated formula $$ Y(z) = 5\log \Bigl((1+z)\int_0^z \frac{dz'}{a+bz'+cz'^2}\Bigr)+25; $$ I used a `NonLinearFit` in the following way               model[a_?NumericQ, b_?NumericQ, c_?NumericQ, z_] := 5*Log[10, (1 + z)*      NIntegrate[1/(a + b*x + c*x^2), {x, 0, z}, PrecisionGoal -> 7,        AccuracyGoal -> 7]] + 25                  fit1 =  NonlinearModelFit[data, model[a,b,c,z], {a, b, c}, z,         Weights -> 1/(sigmadata)^2];       Mathematica was not able to make the fit, and the problem seems to be that the coefficients becomes complex. I decide then to use the analytical form of the Integral and then make the fit (to avoid the integration),               model2=5Log[10,(1+z)*(2ArcTan[(b+2*c*z)/(Sqrt[4*a*c-b^2])])/(Sqrt[\4*a*c-b^2])]+25;       but the same problem appears. There is any way to fix somehow the conditions over $\\{a,b,c\\}$ ??. The full set of data is about 580 points, its a Cosmological fot for Supernovae. I appreciate your help.


Fredholm integral equation of the second kind with kernel containing Bessel and Struve functions

I need to solve this Fredholm integral equation of the second kind:               f[s]+integrate[f[t] K[s,t],{t,0,1}]=s       where `0<=s<=1`. The kernel is:               K[s,t]=(a/2)*(BesselJ[1,a*(s+t)]-BesselJ[1,a*Abs[s-t]]-i*StruveH[1,a*(s+t)]+i*StruveH[1,a*Abs(s-t)])       where a: real, i: imaginary unit. I tried to solve this with the method described here: Integral equation numerical solution with NDSolve, this is the best algorithm for this case I have come across so far but it takes for ages and in the end it doesn't produce any result (due to memory insufficiency). Could anyone please help me solve it?


How can I define a ⊕ operator?

What is wrong with the following code?               CirclePlus := SparseArray[Band[{1, 1}] -> {##}] &     a_ ⊕ b_ := CirclePlus[a, b]      > SetDelayed::write: Tag Function in (SparseArray[Band[{1,1}]->{##1}]&)[a_,b_] > is Protected. >> I want to define the operator ⊕ to work like `+,-,*,/`, so it can be used as `a ⊕ b`.


How do you programatically load data into symbols?

I am trying to convert a list of string names into symbols, which will then be used to store data. I have 24 files (where the name of each file is a member of the list mentioned above) that I need to process, which is why I am trying to accomplish my goal progammatically. The code below results in a Tag warning. I have read the normal documentation sources, and appreciate that you can not inappropriately assign something to a protected symbol, but this doesn't help me solve the problem. Would you have any advice how to accomplish my goal?               Table[(ToExpression[mmsignalnames[[i]]] =         Extract[ToExpression[celfilenames[[i]]], mmammindices[[j]]]), {i,        1, Length[mmsignalnames]}, {j, 1, Length[mmammindices]}]          Set::write: Tag ToExpression in ToExpression[mmsignalGSM356796] is Protected. >>


How to get Symbol["x"]=3 to work

This is probably a really simple one, but I'm stumped. I want `Symbol["x"]=3` to work just like `x=3`. However I can't figure out how to get Mathematica to evaluate the `Symbol`, converting the string to the symbol `x`, but then _not_ evaluate `x`. > x = 2 > > 2 > > Symbol["x"] = 3 > > Set::write: Tag Symbol in Symbol[x] is Protected. >> > > 3 > > Evaluate[Symbol["x"]] = 2 > > Set::setraw: Cannot assign to raw object 3. >> > > 2 I know that I can remove the definition, but I have a ton of these and would like to be able to replace their values that have been already set. `x=3` doesn't require that I remove the definition of `x` to set it. In case it matters, I'm using 10.0.0.


Solving algebraic equations

How may I make `n` and `k` in terms of `x` and `y` in this equation?: $$\frac{1-n-i k}{1+n+i k}=\sqrt{x} e^{i y}$$ I have tried separating the real and imaginary terms on the left hand side using complex expand so that I can have 2 sets of equations now but I have no idea how to continue?               ComplexExpand[((1 - n - I k)/(1 + n + I k))]


Is it possible to do vector calculus in Mathematica?

I am trying to rearrange and manipulate some vector differential equations in _Mathematica_. As far as I understand you have to tell _Mathematica_ that a variable is a vector by specifying the components of the vector. For example               r = {x, y, z};      If I want to define vector fields I have to do it in the following way               v = {vx[r, t], vy[r, t], vz[r, t]};     n = {nx[r, t], ny[r, t], nz[r, t]};      Now I can use the Div operator to express a differential equation, in this case the continuity equation in hydrodynamics.               D[n, t] + Div[n*v, r] == 0      My problem is the output I get from this. It looks absolutely horrible and I can't do anything with it.                  ({0, 0, 0},1)                                    ({0, 0, 1},0)     {nx             [{x, y, z}, t] + vz[{x, y, z}, t] nz             [{x, y, z}, t] +                          ({0, 0, 1},0)                                    ({0, 1, 0},0)      nz[{x, y, z}, t] vz             [{x, y, z}, t] + vy[{x, y, z}, t] ny             [{x, y, z}, t] +                          ({0, 1, 0},0)                                    ({1, 0, 0},0)      ny[{x, y, z}, t] vy             [{x, y, z}, t] + vx[{x, y, z}, t] nx             [{x, y, z}, t] +                          ({1, 0, 0},0)      nx[{x, y, z}, t] vx             [{x, y, z}, t],        ({0, 0, 0},1)                                    ({0, 0, 1},0)     ny             [{x, y, z}, t] + vz[{x, y, z}, t] nz             [{x, y, z}, t] +                          ({0, 0, 1},0)                                    ({0, 1, 0},0)      nz[{x, y, z}, t] vz             [{x, y, z}, t] + vy[{x, y, z}, t] ny             [{x, y, z}, t] +                          ({0, 1, 0},0)                                    ({1, 0, 0},0)      ny[{x, y, z}, t] vy             [{x, y, z}, t] + vx[{x, y, z}, t] nx             [{x, y, z}, t] +                          ({1, 0, 0},0)      nx[{x, y, z}, t] vx             [{x, y, z}, t],        ({0, 0, 0},1)                                    ({0, 0, 1},0)     nz             [{x, y, z}, t] + vz[{x, y, z}, t] nz             [{x, y, z}, t] +                          ({0, 0, 1},0)                                    ({0, 1, 0},0)      nz[{x, y, z}, t] vz             [{x, y, z}, t] + vy[{x, y, z}, t] ny             [{x, y, z}, t] +                          ({0, 1, 0},0)                                    ({1, 0, 0},0)      ny[{x, y, z}, t] vy             [{x, y, z}, t] + vx[{x, y, z}, t] nx             [{x, y, z}, t] +                          ({1, 0, 0},0)      nx[{x, y, z}, t] vx             [{x, y, z}, t]} == 0      I would like _Mathematica_ to write the equation in vectorial form so that I can rearrange it and use vector identities to manipulate it. Is there a way to do this?


How can I do symbolic vector differentiation in mathematica?

I want to do this calculation using Mathematica and I do not know how. I want to finf gradient of a vector function I Have this $$ f:R^n\to R $$ $$ \nabla_xf(x)=\nabla_x(x^tBx) $$ I want to get this using mathematica (I want to differentiate vector function) $$ \frac{1}{2}(B+B^t) $$ $B$ is for example a $n\times n$ matrices and $x$ is a $n\times 1$ vector. does anybody know how am I supposed to do this using mathematica?


Control which frontend session/kernel the Workbench gets attached to

(I am new to Workbench) I have 2 or 3 Mathematica frontend sessions open with a few of them running some long-running codes. When I try to open/edit a code in Workbench, I see that it sometimes it attaches itself to the "busy" frontends. (This is not useful since any new evaluations are queued up)   * How does Workbench interact with Mathematica to decide which frontend to attach to?   * Is there a way in the settings, to force the Workbench to open its "own" new kernel for each session and keep reusing it?   * Is there a way to force the Workbench to open the code (and hence attach to) in a particular frontend session, which is free, so that I can continue coding/debugging?


Calculate the centroid of a group of pixels with the same PixelValuePositions

My question is about how to recognise objects in a image. I would like to recognise objects of the same color. Then I want to calculate the centroid of these objects. I want to apply this calculation on the image below. ![enter image description here](http://i.stack.imgur.com/xNI6h.gif) Based on the centroid it is possibe to calculate the xy-coordinate of the soccer players on this field. The difficulty is that the soccer players can wear a shirt and socks of the same color, but I will be happy if I can get an approximation.


How to combine more locations (GPS coordinates inside one city) with Google map?

I have a list of GPS coordinates.E.g.               GPSList = {{47.680800, 17.626446}, {47.681078, 17.627283}, {47.682759,          17.631810}};      I would like to crate a Google Map of the part of the city (Győr) with some signs. If I could do that, I could change simple red dots to discs or bars showing data.               Show[CountryData["Hungary", {"Shape", "Equirectangular"}],       Axes -> True,       Epilog -> {PointSize[0.01], Red, Point[Reverse /@ GPSList]}]      The resolution of that is not enough.


How do I make Reduce yield all solutions explicitly?

Say I want to do the following:               Reduce[ x+y+z==1, {x,y,z}, Modulus -> 7 ]      then I get a solution with parameters, `C[1]` : > >     x == 1 + 6 C[1] + 6 C[2] && y == C[2] && z == C[1] >   Now, for non-linear equations, such as               Reduce[x + y^2 + z == 1, {x, y, z}, Modulus -> 7]      I get a complete list of solutions, here are the first `5` of them :               %[[ ;; 5]]      > >     (x == 0 && y == 0 && z == 1) || (x == 0 && y == 1 && z == 0) || >     (x == 0 && y == 2 && z == 4) || (x == 0 && y == 3 && z == 6) || >     (x == 0 && y == 4 && z == 6) >   Is there a way to make the system yield this type of output also in the first case ? (Of course, I can just loop over all possibilities of the parameter and get a complete list, but I'd prefer to make _Mathematica_ do it for me if it is possible.)


Am I missing anything? Solving Equations

I want to know what $ a^4+b^4+c^4 $ would be when $ a+b+c=1, a^2+b^2+c^2=2, a^3+b^3+c^3=3. $ I tried               Solve[{a + b + c == 1, a^2 + b^2 + c^2 == 2,      a^3 + b^3 + c^3 == 3}, {a, b, c}]          a^4 + b^4 + c^4 /. {a -> ... }      I copied and pasted one instance from the result of `Solve[]` into `{a -> ...}` The solution and the result of `Simplify[]` of it was not quite what I expected. So as a test, I tried `a+b+c /. {a -> ...}` Still it was strange, it didn't come up with 1 which is obvious correct answer. So am I missing anything here? Is there any better way?


Text with date, how to convert?

I use this script to recognise a date in a textfile and write the result in another file.               For[i = 1, i < 20, i++,       test1 = Import["E:\\data\\MC1 Data\\MC1 Data\\articles\\" <> ToString[i] <>".txt", "Text"];       test2 = {StringCases[test1, DatePattern[{"Year", "Month", "Day"}]],              StringCases[ToLowerCase[test1], RegularExpression["\\w(?<!\\d)[\\w'-]*"]]};     Write[s, test2]];      The result is a file like this: ![example data file](http://i.stack.imgur.com/vIfRf.gif)               test3 = ReadList["E:\\data\\MC1 Data\\MC1 Data\\articles\\testfile3.txt"]      Then I would like to make a selection on the date/first column. In this example, mathematica don't recognise it as a datastring. I tried to convert it like               DateString[test3[[All, 1]]]      but that didnt work. Who has a suggestion?


How do you plot the same function with different options over different intervals?

Here is the motivation for my question. I want to plot `Sin[x]` over the interval `0` to `2 π`, with the part from `π/2` to `2 π` as a dashed curve. I want to plot this with a legend so that it shows the solid part is for acute angles, and the dashed part is for, say, other angles. Perhaps using `Show` and `ShowLegend` will work, but I couldn't figure out how to get the legend boxes to match the curves (solid and dashed curves). It seems `PlotLegend` takes care of this for you, but I couldn't figure out how to use this in `Show`. So I thought using `PlotLegend` in `Plot` will be easiest, except I don't know how to use `Plot` for the same function with different options on different intervals. I tried using the suggestions from Plotting piecewise function with distinct colors in each section, but I think my problem is that the same function is being used for both parts of the piecewise function I defined.


Multiple curves plotted with different colours

I am trying to use `ColorFunction` for 2 functions on the same plot. I only want the cubic equation to change colour.               Plot[{-x^3 + 3.5*x + 0.5, y = 2.9*Tanh[5 x] + 0.3}, {x, -2.5, 2.5},            PlotRange -> {-3, 3.5}, Axes -> False, Frame -> True, FrameTicks -> None,            PlotStyle -> {{Darker[Green], Thick}, {Blue, Thick}},            ColorFunction -> Function[{x, y}, If[x > 1, Red, Black]],            ColorFunctionScaling -> False, PlotStyle -> Thick]      This is what the code above produces: ![enter image description here](http://i.stack.imgur.com/1Q6T6.jpg) This is ideally how i would like it to be displayed. Is this possible in _Mathematica_ without using the drawing tool? ![](http://i.stack.imgur.com/vNC8Y.jpg)


Simple question about AxesLabel

I am plotting a function and for labeling the axes I use:               AxesLabel -> {Style[y, FontSize -> 21], Style[{Subscript[f, i], Subscript[q, i]}, FontSize -> 21]}      here $y$ is for the $x$-axis and $\\{f_i,q_i\\}$ is for the $y$-axis. The problem is that I dont want to have $\\{\\}$. I only want to have $f_i,q_i$ at the $y$-axis. How can I manage this? Thank you very much.


Replacement rules in combination with pure functions to make a change of variables

I have defined my function in this way               w = f[r,Θ] ;      After some calculations i obtained my results with respect to the previous function. For instance:               Set[lapla1, -(1/(2 μ)) (1/r D[w r, {r, 2}] - 1/r^2 (D[w, {Θ, 2}] + Cot[Θ] D[w, {Θ, 1}]))] // ExpandAll      In this moment i don't need to work with the previous function $w$, instead i need to keep my previous result, multiply lapla1 by $r$ and work with a new $w$               w = f[r, Θ]/r ;      I'm trying to use pure functions to accomplish this, however i don't know if i'm proceeding correctly.               Set[lapla11,lapla1*r /. f -> (f[#, #2]/r &) // ExpandAll ]      **EDITED:** When you make this transformation, the term $\frac{1 }{rμ }\frac{\partial f}{\partial r}$ must disappear from lapla1. This is the only way i found to prove it               Set[lapla12, -(r/(2 μ)) (1/r D[w/r r, {r, 2}] - 1/r^2 (D[w/r, {Θ, 2}] + Cot[Θ] D[w/r, {Θ, 1}]))] // ExpandAll


Cancellation of common terms

Can someone explain why the term A in case 2 does not get canceled out when case 1 does? I use "9.0 for Microsoft Windows (64-bit) (January 25, 2013)"               case1 = A*(E^(-λ) + α) == A;     Simplify[case1, A > 0]      gives `1 + E^λ α == E^λ`               case2 = A*(E^(-2*λ) + α) == A;     Simplify[case2, A > 0]      gives `A (E^(-2 λ) + α) == A`


Update a function avoiding infinite recursion

I am quite new to _Mathematica_ and not completely familiar with functional programming. I am currently working with a function (call it foo) and wish to change its behaviour, for example, by adding 1 to its output. Obviously writing               foo = (foo[#]+1)&;      or               foo[x_] := foo[x] + 1;      leads to an infinite recursion as soon as I try to evaluate the function. To be more explicit, if at the beginning `foo[1]` returns 1 and `foo[2]` returns 3, I would like the output to be 2 and 4 respectively after the change. Is there any way to easily obtain this behaviour with _Mathematica_? I apologize if the question is a duplicate, but I did not find anything similar already posted.


Using Mouseover to change the appearance of a button without writing the button specification twice

When I code in _Mathematica_ , I often find myself having to repeat large chunks of code for a function to work. The latest example of this is a color changing button that prints when clicked, code shown below.               Mouseover[      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> Red       ],      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> Green       ]      ]      The only thing that is changing on the mouse over is the button color, but for this to work I need to repeat a whole chunk of code. A simpler way of doing this is to define a button color function, and then use that in the Mouseover function, code shown below.               ButtonColor[color_] :=      Style[       Button[        Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},          ImageSize -> {34, 24}],        Print["Print"],        Appearance -> None        ], Background -> color       ]          Mouseover[      ButtonColor[Red],      ButtonColor[Green]      ]      This is better, but what if i only have to refer to the button color changing function for one mouse over button? Should I really have to define a function to use it for one instance? I think the ideal way to code this would be to use Table or something similar, code shown below.               Mouseover[      Table[       Style[        Button[         Pane["Print", FrameMargins -> {{4, 4}, {4, 4}},           ImageSize -> {34, 24}],         Print["Print"],         Appearance -> None         ], Background -> color        ],       {color, {Red, Green}}       ]      ]      The only problem, Table doesn't work because it creates EXTRA BRACES! Is there a better way of coding this color changing button?


Finding a fixed vector which minimizes the pairwise distance between noisy elements in two unordered arrays

Let $A$ and $B$ be two sets of $d$-dimensional coordinates of comparible (though not necessarily equal length). For example, here we can set $d = 3$ and have normalized values like:               A = {{0.446362, 0.811292, 0.0922594},{0.244159, 0.260142, 0.304582}, {0.122547, 0.269019, 0.0644819},          {0.448114, 0.828661, 0.733406},{0.347111, 0.296056, 0.398861}, {0.219952, 0.653454, 0.09107},          {0.592839, 0.0333978, 0.210341},{0.0970157, 0.132429, 0.366429}, {0.294297, 0.527056, 0.403706},          {0.196355, 0.115887, 0.636247},{0.993047, 0.51482, 0.229379}, {0.251266, 0.135959, 0.178469},          {0.789068, 0.182785, 0.338934}, {0.42705, 0.151849, 0.671407}, {0.796922, 0.229053, 0.946328},          {0.292144, 0.148314, 0.116313}, {0.589524, 0.474425, 0.0958731}, {0.181622, 0.140052, 0.958391},          {0.0376616, 0.614436, 0.394617}};          B = {{0.690322, 1.17215, 0.961834}, {0.271458, 0.942832, 0.745714}, {0.508862, 1.03457, 0.3475},           {0.81515, 0.378891, 0.465227}, {0.6036, 1.34974, 0.426426}, {0.405347, 0.463069, 1.27554},          {1.12031, 0.604772, 1.19204}, {0.373017, 0.343105, 0.595875}, {0.642332, 0.602587, 0.678469},          {0.884344, 0.746337, 0.38915}, {1.22961, 0.47189, 0.712069}, {0.56058, 0.755362, 0.648201},          {0.596699, 0.465542, 0.646428}, {0.48087, 0.522362, 0.315634}, {0.752854, 1.17231, 0.421088},          {0.693156, 0.546617, 0.9851}, {0.507197, 0.426626, 0.847138}, {0.584263, 0.452749, 0.422986},          {0.545495, 0.427736, 0.494085}};      (Note that the order of the elements in $A$ and $B$ are of no consequence.) While a bijection isn't possible, I would like to find the best possible "rigid mapping" between the elements in $A$ and $B$ where we add some fixed real number vector $Q=(q_1,q_2,q_3)$ to each coordinate in $B$ to minimize a weighted distance between pairs of coordinates in $A$ and $B$ according to some axis-specific cost function. Consider that in the above example, I've rigged things to make $Q = (q_1,q_2,q_3) \approx (0.3,0.3,0.3)$ about optimal (the largest error is of magnitude $\approx 0.1$). To specify this cost function, we select array $A$ if it has more points than $B$ and vice versa. For convenience, let's say this array is $A$. Now let $(d_{(1,i)},d_{(2,i)},d_{(3,i)})$ be the shortest distance between a point $b_i \in B$ and $a_j \in A$. I'd like to have a cost function that looks something like: $C = \sum_{i=1}^{||B||} || ((d_{(1,i)})^{z_1},(d_{(2,i)})^{z_2},(d_{(3,i)})^{z_3}) ||$ Where $(z_1,z_2,z_3)$ represents an arbitrary set of exponents. For a single real numbered value cost, we could compute the Norm of the above sum.


How do I obtain an intersection of two or more list of lists conditioned on the first element of each sub-list?

Given two lists like               list1 = {{1, 1}, {2, 4}, {3, 9}, {4, 16}};     list2 = {{2, 6}, {3, 9}, {4, 12}, {5, 15}};      I would like to produce an output like               listout = {{2, {4, 6}}, {3, {9, 9}}, {4, {16, 12}}}


Combining two lists

> **Possible Duplicate:**   >  How do I obtain an intersection of two or more list of lists conditioned on > the first element of each sub-list? I would like to combine two lists.               list1 = {{134, 12}, {136, 14}, {140, 45}}      and               list2 = {{134, "B"}, {135, "A"}, {136, "E"}, {137, "A"}, {138,"I"}, {139, "B"}, {140, "G"}}      the result should be:               result = {{134, 12, "B"}, {136, 14, "E"}, {140, 45, "G"}}      Thank you very much!


Sparse Principal Component Analysis

I'd like to run sparse PCA on some economic data. There appear to be several R functions available including elasticnet and PMA but I wanted to check if anyone had something coded up directly in MMA they might be willing share? Thanks, Peter


How to put some values from a list into a function in a Do loop

I want to program a code in MATHEMATICA in order to calculate some values in different iteration. For example, assume this list: `list={1,2,3,4,5}` Now assume that the function is : `f1=Function[u,3+u][x]` I want to use a `Do` loop to orderly put each integer from the `list` into `f1` function and `Do` loop uses 5 iteration (`{i,1,5}`) and gives 5 answers using the values in the list. For this example, The results will be : `4 5 6 7 8` I wonder if anyone could help me with this problem.


Filling a curve to a vertical axis

I am preparing a figure for an article, and I would like very much to be able to fill a curve, but not under it, but to the vertical axis, i.e. to the left. Due to the meaning of the data I present, I cannot exchange the axes. Here is a minimal example:               Plot[ArcCot[x], {x, 0, 1}, PlotRange -> {{0, 1.1}, {0.5, 2}}, AxesLabel -> {x, y}]      Can anyone think of a way of filling the curve to the`y` axis? I find no mention of this kind of filling in the standard documentation.


Poor results with ImageLines function

I'm trying to get my mind wrapped around _Mathematica's_ image feature recognition functions. I'm intrigued by the `ImageLines` function for a couple future ideas I have but generally get very poor performance from it. ...as I will now demonstrate: Let's import some very basic gridlines, surely this will be easy.               pic = Import[         "http://www.samplewords.com/docthumbs/home-graphpaper-thumb.jpg"]      ![enter image description here](http://i.stack.imgur.com/AVXQh.jpg) Straight out of the box, here's how _Mathematica_ recognizes the lines at different thresholds (parallelized because of my impatience):               Row@ParallelTable[Graphics@Line@ImageLines[pic, i], {i, .1, 1, .1}]      ![enter image description here](http://i.stack.imgur.com/M5jv1.png) Interesting... not what I would've expected. Even if I dilate and binarize the image, I still get pretty bad results: ![enter image description here](http://i.stack.imgur.com/fKWuR.png) Playing with the distictness parameter, it gets a little better but still pretty weird. ![enter image description here](http://i.stack.imgur.com/WkJnj.png) So, Wolfram shows some pretty neat examples, and it seems to work well there. How can I get improved results from the `ImageLines` function?


Marking points of intersection between two curves

I'm trying to illustrate the solutions numerically and graphically for an equation such as `Tan[x] == x`. I think I did everything ok except I wanted to mark each intersection between `Tan[x]` and `x`. Does anyone know how such a thing can be done?


Binomial[-1,-1]

According to various sources e.g. http://www.proofwiki.org/wiki/Definition:Binomial_Coefficient and Wolfram themselves http://functions.wolfram.com/GammaBetaErf/Binomial/02/ , the binomial coefficient ${n\choose k}$ is is defined as 0 whenever $k$ and $n$ are negative integers and $k\le n$. But when I type               Binomial[-1,-1]      Mathematica returns               1      I looked up the documentation for the definition of `Binomial` and it says > In general, ${n\choose m}$ is defined by > $\Gamma(n+1)/\Gamma(m+1)\Gamma(n-m+1)$ or **suitable limits** of this. Apparently, when $n=-1$ or $m=-1$ since $\Gamma(0)$ is not defined the suitable limit case is applied. So, why does Mathematica return 1 for ${-1\choose -1}$? What precisely is the "suitable limits"?


What are the best tips in Michael Trott's beer/whiskey Wolfram Blog post?

Michael Trott posted this incredible tour-de-force on the wolfram blog: http://blog.wolfram.com/2014/08/19/which-is-closer-local-beer-or-local- whiskey/ The length of the post is overwhelming, so I'm trying to crawl through it with a fine toothed comb looking for some Mathematica tricks and techniques that are new to me. I would be very interested to see what others noticed, since I doubt I will find everything in there. Some of the things I noticed were:   * use of TimeSeries, which is a new discovery for me in MMA 10   * {Except["Alaska"], "UnitedStates"} as a pattern for Cases ... I regularly struggle with using Cases, so this is mysterious to me   * the StringReplace / Shortest / StringCases constructs when parsing the distillery information is not something I had seen before and seems powerful


Estimating a distribution using binned data

I have data from which information has been irretrievably lost through binning and I am trying to find a plausible distribution from which it derives. There is an academic paper suggesting that the underlying data is Zipf or Pareto distributed, but I believe that the paper is wrong. Just because one can fit a line to the log-log transform of survival data does not mean that the data is really Zipf or Pareto distributed! The data (which you can see here, table 2b) is in an $n\times 2$ table in which the first column is a discrete range defining a "bin" and the second relevant column is an integer count. It thus states that there are y1 firms that have between min1 and max1 employees, that there are y2 firms that have between min2 and max2 employees, etc. I thus know that there are y1+y2+ ...+ yn firms that have at least min1 employees, that there are y2+y3 + ... + yn firms that have at least min2 employees, etc. I would, of course, love to be able to use `EstimatedDistribution` with various guesses as to functional form and then use `DistributionFitTest` to see if the guess was plausible. But I can not figure out how to get _Mathematica_ to find the best parameters for a distribution where all I have is binned data. I've floundered about with `SurvivalModelFit`, `WeightedData`, all to little avail. All help appreciated.


How to checkpoint computations?

Suppose I do some big experiment, presumably in a `Table[]`, or a `ParallelTable[]`. Experience shows that there is a non-zero probability of Mathematica (or the computer) crashing part-way through (usually through excess of ambition by the user, but whatever), so it would be nice to export the results of the individual computations as soon as they become available. Is there any preferred way of doing that? (`Reap[]` and `Sow[]` seem like they could do the right thing, but it seems likely that they wait for the whole computation to finish). (and, by the way, I have no idea what the right tag for this is, maybe someone can help).


Package for representation of groups (group theory)

I wanted to know if there is a package which allows to compute representations of a group like the definition representation, adjoint and so on (for example the Pauli matrix for $SU(2)$ if I specify that I want the definition representation of $SU(2)$). Which allow also to compute the structure constants of a particular group and, given a set of matrix, to test if these matrix form a representation of a particular group.


Interpolating a sparse list of two-dimensional coordinates

I've run into a problem where I have an ordered array of sets of coordinates, for example:               OrderedArray = {{{70.8938, 216.539},{70.89,216.54}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{71.0656,216.573}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.6546, 220.338}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9211, 216.364}}, {{70.9184, 216.346}}, {{70.9079, 216.349}}, {{70.9046, 216.335}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.951, 216.705}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9621,216.586}}, {{70.918, 216.576}}, {{70.9116, 216.559}}, {{70.9189,216.581}}, {{70.9115, 216.565}}, {{70.9294, 216.552}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.0276, 218.154}}};      Note that some elements (here the first) contain more than a single coordinate. And I need to fill in the blanks, i.e. the {} positions, via some interpolation procedure. What would be the best way to do this? Reading through the instructions for InterpolatingPolynomial (for example), and playing around a bit, it isn't immediately clear how to do this. Ideally I'd like to be able to specify that the "gaps" should be filled in assuming a linear curve, or a polynomial of some order.


Generating a "best fit" curve to a set of noisy data corresponding to a moving object

Please note that this is an extension of a previous question: Interpolating a sparse list of two-dimensional coordinates We have an ordered array of coordinates corresponding to the position of an object in a set of camera frames $(f_1,...,f_N) \in F$, which we're tracking with an imperfect object recognition algorithm. As a result, in any given frame, we sometimes fail to identify the object, and we sometimes identify multiple copies of the object. We're left with noisy data that looks something like this:               OrderedArray = {{{70.8938, 216.539},{70.89,216.54}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{71.0656,216.573}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.6546, 220.338}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9211, 216.364}}, {{70.9184, 216.346}}, {{70.9079, 216.349}}, {{70.9046, 216.335}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {},{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.951, 216.705}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{70.9621,216.586}}, {{70.918, 216.576}}, {{70.9116, 216.559}}, {{70.9189,216.581}}, {{70.9115, 216.565}}, {{70.9294, 216.552}}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {{67.0276, 218.154}}};      Where the position of a coordinate in the array corresponds to a particular image frame. Here's a listplot output for a larger version of my data set: ![enter image description here](http://i.stack.imgur.com/Ub1DT.png) I'd like to generate a "best guess" for the motion of my object from frame to frame provided this noisy data, and with the constraint that the object cannot move more than a Euclidean distance $D$ from frames $f_i$ to $f_{(i+1)}$. How might I best use the intepolation tools in Mathematica 9 to "guess" the shape of the curve followed by the object? I'd ideally like to specify that the object follows a linear trajectory, or, say, a trajectory characterized by a polynomial of bounded degree. * * * Update: In response to Thies Heidecke's comment on filters, here, I'm tracking a moving object that changes direction fairly slowly. The curve fitting the data should be fairly smooth.


Filling between quantile ranges

Following code plots Quantiles for a GBM process.               ranges = {.01, .05, .25, .5, .75, .95, .99};     Manipulate[      Plot[       Quantile[         GeometricBrownianMotionProcess[\[Mu], \[Sigma], 100000][t],ranges],      {t, 1, 30},PlotRange -> {0, 1500000}],      {\[Mu], .07, .1}, {\[Sigma], .07, .20}]      I would like to shade the area between between the ranges .01 to .05 and .95 to .99 say lt. blue .05 to .25 and .75 to .95 say med. blue .25 to .75 say dark blue with the .5 quantile line thick black Plot options seems to allow filling between curves using               Filling->{{1}->2}       syntax but not sure how or if that can be applied here?


Solve-ing with initially unassigned parameters and Solve-ing using their numerical values produces different results

I am trying to solve an equation using the following piece of code:               f[t_] = Aa*t^4 + Bb*t^3 + Cc*t^2 + Dd;          s = Solve[f[t] == 0, t];          t1 = t /. s[[1]];     t2 = t /. s[[2]];     t3 = t /. s[[3]];     t4 = t /. s[[4]];        And it gives me four symbolic formulas. Then, I try to give numbers to the `Aa`, `Bb`, `Cc`, `Dd` parameters:               Aa = 1.2347931365926803*10^30 ;     Bb = 4.6356322739291924*10^23 ;     Cc  = 4.350806821541392*10^16 ;     Dd = -1.2562823055999998*10^6 ;      and the formulas provide the results:               -7.18016*10^-7 - 6.17065*10^-7 I     5.30307*10^-7 + 6.17065*10^-7 I     -7.18016*10^-7 + 6.17065*10^-7 I     5.30307*10^-7 - 6.17065*10^-7 I      But, if I solve using the numerical values of `Aa`, `Bb`, `Cc`, `Dd` from the beginning, I get:               -1.10255*10^-6     -9.38545*10^-8 - 9.99928*10^-7 I     -9.38545*10^-8 + 9.99928*10^-7 I      9.14844*10^-7      I have also noticed that this behavior is sensitive to the values I give to the parameters. Using these instead,               Aa = 2.8262007068794462*10^25;     Bb = -5.389762192271189*10^21;     Cc = 2.5696632603084144*10^17;     Dd = -1.2213607220736102*10^6;      the problem seems to still be there, but not as serious. Any ideas on what might be causing this and maybe a way to avoid it?


A function that accepts a pair or a list of pairs

Probably a duplicate, but it's not easy to search on "lists". I have a function that accepts a list of lists, say `{{a1, b1}, {a2, b2}, {a3, b3}}` and performs some computation on `{ai,bi}` for each `i`. (We may assume that none of the `ai` or `bi` are themselves lists). I would like this function to also accept simply `{a1,b1}` as its argument list and operate on this as if it were the only member of the (nonexistent) outer list. That is, I would like               f[{a1,b1}]      to behave the same way as               f[{{a1,b1}}]      What I have done is the following:               f[list_] := Module[{nlist},        nlist = If [ListQ[list[[1]]], list, {list}];        <do other stuff...>     ]      This works fine, but seems pretty inelegant. Is there a better way?


Find an inverse matrix, regarding a parameter as real

I have the matrix               {{3, 2, 1}, {3, 1, 2}, {2, 3, -1},      {-(3/b), -(3/b^2) - 2/b, -(3/b^3) - 2/b^2 - 1/b},      {-(3/b), -(3/b^2) - 1/b, -(3/b^3) - 1/b^2 - 2/b},      {-(2/b), -(2/b^2) - 3/b, -(2/b^3) - 3/b^2 + 1/b}}      and I want to compute its inverse (or pseudoinverse). The problem is that _Mathematica_ solves this regarding `b` as a complex number. How do I change this to set `b` as real? I tried `Assuming` but that didn't work. Maybe I am writing it wrong. Any ideas? It should be fairly simple, but I am not really good at `Mathematica` and I couldn't find a solution elsewhere. I would be greatful for a general answer, not one specifically for this example; e.g., `Pseudoinverse[a] /. Reals[b] -> ...` (this didn't work). Thanks


Formatting a number with fixed number of significant digits

I need a formatting function (say `format[x_, n_]`) which outputs numbers with fixed `n` _significant_ digits without unnecessary dot. Examples:               format[.02,3] -> "0.0200"     format[.2,3] -> "0.200"     format[1,3] -> "1.00"     format[100,3] -> "100"         format[1000,3] -> "100\[Times]10^1"     format[10000,3] -> "100\[Times]10^2"      Any ideas? The shorter - the simpler!


Finding a subsequence in a list

I have a list and I want to find (in this particular case the first) appearance of a any of some subsequences, of possible different lengths. None of the subsequences is a subsequence of each other. In my particular case I could do this translating the list to a string and using `StringPosition`. But I could do it because all elements on my list were one-character-long. Before realizing this I had implemented a not-nearly-one-liner that did the trick without recurring to Strings. It didn't do any useless comparison but it did lots of useless coping of the list as a whole, and it turned out to be 50 times slower than the `StringPosition` version. It can be improved, avoiding that issue, making it even less one-liner. The task just seems too easy to describe so as to be so not-easy to program well... Is there an efficient way to do it for the general case? "Find the first appearance of one of many subsequences (possible different lengths, perhaps could be patterns, or not) in a list" (Wow, I think I just thought of a good way, I'll give it a shot... If it works I'll auto-answer. But I'd still like your input, I'm afraid I'm missing some options)


Printing Block Matrices

I have a 2D matrix, such as:               d=2;     M=Array[a, {d^2,d^2}];      and I would like to print it in a way which emphasizes its dxd block matrix structure. If `MatrixForm` had a `Dividers` option like `Grid`, then this is what I would use. But it doesn't. The first thing I tried was:               With[         {div={False, Join[Table[False, {n, d - 1}], {Dashed}], False}},         {{Grid[M,Dividers->{div,div}]}}//MatrixForm     ]      where the `{{stuff}}//MatrixForm` is simply to get the parentheses. The problem with this is that if your matrix is big (d>2) and certain entries of your matrix are big expressions, then they do an ugly line wrap thing. To counter this, I call `{{TableForm[#]}}&` on each element of the matrix first:               With[         {div = {False,Join[Table[False, {n, d - 1}], {Dashed}],False}},          {{             Grid[Map[TableForm[{{#}}] &, M, {2}],Dividers -> {div, div}]         }} // MatrixForm     ]      but this is a hack. So I suppose my questions are: What Form do `TableForm` and `MatrixForm` use on each of their elements, and can I use this here? I've tried `StandardForm` but that's not it. Next, is there in general some better way to do what I am trying to do? **Edit:** As requested, here is an example that illustrates the "ugly line wrap thing":               d = 3;     M = Table[Expand[(a + b)^RandomInteger[4]], {i, d^2}, {j, d^2}];


NDSolve::ndsz problem

I'm using NDSolve to solve a set of coupled differential equation which depend on a variable x. I noticed that when I set the range of x from a small value to a large value, I obtain solutions. But when I do the opposite I get a problem! For example when I consider this,               t1 = 3000;     t2 = 4*^16;     f = 1/(16 Pi^2);     NDSolve[{y'[x] == f/x * 16 y[x]^3, y[t1] == 0.37}, y, {x, t1, t2},     Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}];      No errors and I can find:               y[t2] /. %          {0.920385}      Then I use this value of y[t2] as the initial condition for the following case, where I swap the range of x:               t1 = 3000;     t2 = 4*^16;     f = 1/(16 Pi^2);     NDSolve[{y'[x] == f/x * 16 y[x]^3, y[t2] == 0.92}, y, {x, t2, t1},     Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}]      I get the error:               NDSolve::ndsz: At x == 4.`*^16, step size      is effectively zero; singularity  or stiff system suspected.      I tried to switch off the StiffnessTest to see if the problem goes away, which would mean that it's a stiffness problem, but the error message still shows. Also tried to use:               Method -> {StiffnessSwitching, Method -> {ExplicitRungeKutta, Automatic}}      And it didn't work either. Considering that this is a typical differential equation encountered in physics (renormalization group equations) I'm pretty sure that there should be no singularity at x = t2, and I should be able to solve from the high-scale to the low-scale. Any insights on why this is happening and how to deal with it?


Where is the "Insert > Citation> Bibliographical Reference" Command?

I don't have the command for inserting citations described in the documentation: "Insert > Citation> Bibliographical Reference" is not present in my menus: ![enter image description here](http://i.stack.imgur.com/QZg4E.png) That's the entire contents of my "Citation" menu: no "Bibliographical Reference" item anywhere to be seen. How do I restore this item to my menus? What could I have done that would have removed it?


List of supported units in Mathematica 9

Is there a list of supported units in Mathematica 9 documentation? I personal haven't found any; even the physical constants (newly supported as units in 9) can only be found in compatibility information. It is quite strange that Wolfram didn't even compile a list of units for the documentation.


Where to see all Mathematica units

Is there a tutorial page that have all Mathematica units? I sometimes have hard time figuring out the correct unit spelling when using quantities


Interactive Graph Editing with Animation

I want to make a simple interactive user interface like this: ![gui](http://i.stack.imgur.com/cxrvJ.png) Such that when the user clicks on the "Add Edge" button, the edge specified by _from_ and _to_ fiels is added to the graph. The new graph may have a new layout and I want to make an animation between the old and new graphs (see my other question and my answer to the question). Most of the examples I found, change the graph/plot just on change of the inputs without waiting for a click from the user. I know how to add the edge to the graph and generate the frames of the animation, but how can I do the rest?


Why does $\frac{\partial}{\partial x}O\left(\left(\frac{1}{x}\right)^0\right)$ equal $O\left(\left(\frac{1}{x}\right)^0\right)$ in a series expansion?

When taking the derivative of a series expansion around a finite point, the $O(x^n)$ part is differentiated as expected. $O(x^n)$ becomes $O(x^{n-1})$ except $O(x^0)$ which stays $O(x^0)$. When expanding around infinity, things do not work out that nicely. $O\left(\left(\frac{1}{x}\right)^n\right)$ in general becomes $O\left(\left(\frac{1}{x}\right)^{n+1}\right)$. So far so good but $O\left(\left(\frac{1}{x}\right)^0\right)$ stays the same as in the expansion around a point that is finite. This doesn't seem to make sense because the leading constant term should drop out and the second one should be differentiated so we should get $O\left(\left(\frac{1}{x}\right)^2\right)$. Am I missing something? Is this behavior to be expected?               D[O[x, Infinity] x, x]     (* Out[1]= SeriesData[x, DirectedInfinity[1], {}, 0, 0, 1] *)


Solving a single equation with multiple parameters

If I wanted to solve equations like Cos[x]^2 = A Cos[Bx + C] + D what function should I use? The Solve function seems to only solve for as many variables as there are equations. Please note that my given equation is only an example of what I would like to do. I am not asking for the solution to that specific equation. I know I could use TrigReduce, but I would like to know how to do this more generally for expressions that aren't even trigonometric. I also know I could sample Cos[x]^2 and just do a fit with those parameters, but I was looking for a cleaner, non-numeric way of solving this. Is this possible? edit: It now looks like SolveAlways is the right function for the task, but unfortunately it doesn't solve my example equation.


Access pairs of vectors, rather than the matrices, in partitioned data structure at a levelspec

I have some old code to analyze correlation between 2 time series by looking at windows of different lengths shifting across the time series data. The code:   * gets 2 sets of time series data (in this case using `FinancialData[]` for convenience);   * sets a list of windows on which to calculate the correlations;   * partitions the data into matrices by applying each window over time;   * calculates correlations;   * pads the data; and   * plots Code:               data = Transpose[Drop[FinancialData[#, "Aug. 4, 2006"] & /@ {"SPY", "GLD"}, None, None, 1][[All, All, 1]]];     windows = Range[100, Round[Length[data], 100], 100];     partitionedData = Partition[data, #, 1] & /@ windows;     correlations = Map[Correlation, partitionedData, {2}];     plotData = PadLeft[correlations[[All, All, 1, 2]]];     ListPlot3D[      plotData,      ImageSize -> 400,      AxesLabel -> {"Days", "Window", "Correlation"},      PlotRange -> {Automatic, Automatic, {-1, 1}},      BoxRatios -> {1, 1, 0.75},      ViewPoint -> {2, 0, 1}]      Output ![ListPlot3D](http://i.stack.imgur.com/lkAS9.png) Now typically I'd run these correlations on log returns rather than price, but I wanted to keep the example as simple as possible. In this case the windows have lengths of 100, 200, 300, ... 1500 corresponding to the 15 windows in the plot. This all works fine, but now I want to look at other correlation measures:               SpearManRankCorrelation[]     KendallRankCorrelation[]      Neither of these take a matrix as input, they both take 2 vectors: ![enter image description here](http://i.stack.imgur.com/LYK2j.png) ![enter image description here](http://i.stack.imgur.com/DAGPZ.png) So my problem comes down to this single line of code:               correlations = Map[Correlation, partitionedData, {2}];      I need to alter this line of code so that it will map to the pairs of vectors in each of the matrices at level 2 of `partitionedData`. As `Correlation[]` can also use vectors as inputs this will give me a more generalized approach. Some additional background... The structure of `partitionedData` looks like this:               Dimensions[partitionedData]     {15}          Dimensions[#] & /@ partitionedData     {{1410, 100, 2}, {1310, 200, 2}, {1210, 300, 2}, {1110, 400, 2}, {1010, 500, 2}, {910, 600, 2}, {810, 700, 2}, {710, 800, 2}, {610, 900, 2}, {510, 1000, 2}, {410, 1100, 2}, {310, 1200, 2}, {210, 1300, 2}, {110, 1400, 2}, {10, 1500, 2}}      I've fiddled around with this all morning, but keep confusing myself. I don't see a clear way to use the same form of `Map[]` using `levelspec`, so I keep trying variations on pure functions but keep getting into a muddle. I've tried lots of variations of this basic approach:               Correlation[#[[1]], #[[2]]] & /@ partitionedData[[All, 2]];      but I don't get myself anywhere. Thoughts and guidance appreciated.