3D plot of a solid of revolution

I'm trying to rotate the area between the graphs of $y=3$ and $y=x^2$ around $y=1$. I'm not attempting to just find the area as that would just be `π Integral[9 - x^4]`, but rather I'm trying to create a 3D plot that I can print with a 3D printer.


Maximize over permutations

I have a set $S=\\{s_1,\ldots,s_k\\}$ and would like to maximize a fixed expression over permutations of $S$: $\max f(x_1,\ldots,x_k)$ with $x_i\in S$ and $x_i=x_j\Rightarrow i=j$. Is there a convenient way to do this? As an example, with $S=\\{1,2,3,4\\}$ I can write               Maximize[      {f[a,b,c,d],       a != b && a != c && a != d && b != c && b != d && c != d &&       0 < a < 5 && 0 < b < 5 && 0 < c < 5 && 0 < d < 5},     {a, b, c, d}, Integers]      but obvious this scales poorly. You can assume $S\subset\mathbb{Z}$ if it helps. Most of the time I'm just using initial segments of the positive integers, as in my example.


Giving value to a constant so that Mathematica simplifies the answer without having to do the whole operation again

I am doing some nasty integrals trying to fill in a matrix, and to save computation time, I set my hbar to be a constant of undefined value, so the answer it spits out consists of a real number plus some number times the square of hbar, which means I should be able to ignore it and chop it off since hbar squared is very small. Essentially I want to tell mathematica to apply to the answer the value of hbar. To clarify, I don't want to define hbar and have it do the integration again because that would make the computation time too long. I want the value of hbar to be defined only on the answer I get from the integration, not during the integration. Thank you!


NumericQ prevents evaluation at a numerical value sometimes

I set up a symbolic integral, to be evaluated only when some of the symbols have been replaced by numbers. The evaluation after assigning numbers to the symbols is still symbolic for some reason. The code is (after clearing all)               $Assumptions=0 < r < 1 && 0 < ah < al && 0 < s && t \[Element] Reals && llow < lhi     rev[t_] := Exp[t]/(1 + Exp[t])     yh1[t_] := \[ExponentialE]^(1/2 t (-1 - Sqrt[1 + 8 r s^2]))     yh2[t_] := \[ExponentialE]^(1/2 t (-1 + Sqrt[1 + 8 r s^2]))     (* Wronskians *)     wrh[t_] := yh1[t]*yh2'[t] - yh1'[t]*yh2[t]     (* Particular solutions of the inhomogeneous equations *)     uh[t_] := rev[t] - ah     inth1[t_, llow_?NumericQ, r_?NumericQ, s_?NumericQ, ah_?NumericQ] :=       Integrate[yh2[z]*uh[z]/wrh[z], {z, llow, t}]     inth2[t_, llow_?NumericQ, r_?NumericQ, s_?NumericQ, ah_?NumericQ] :=       Integrate[yh1[z]*uh[z]/wrh[z], {z, llow, t}]     yhp[t_, llow_, r_, s_, ah_] := -yh1[t]*inth1[t, llow, r, s, ah] +       yh2[t]*inth2[t, llow, r, s, ah]      yhp[t, llow, r, s, ah]     % /. {llow -> -2, lhi -> 2, ah -> 0.1, r -> 1, s -> 1}      The output of `yhp[t, llow, r, s, ah]` is               -\[ExponentialE]^(1/2 t (-1 - Sqrt[1 + 8 r s^2])) inth1[t, llow, r, s,ah] +       \[ExponentialE]^(1/2 t (-1 + Sqrt[1 + 8 r s^2]))   inth2[t, llow, r, s, ah]       like it's supposed to be. But the output of `% /. {llow -> -2, lhi -> 2, ah -> 0.1, r -> 1, s -> 1} ` has `r`,`s` etc still in it. I tried to reproduce the problem in a simple example, but the example works fine. It is               Clear[x, k, int, f]     $Assumptions = {x, k} \[Element] Reals     int[x_, k_?NumericQ] :=       Integrate[Exp[z]/((1 + Exp[z])*Exp[k*z]), {z, 0, x}]     f[x_, k_] := x*int[x, k]     f[x, k]     % /. {k -> 2}      and the final output is               x (1 - \[ExponentialE]^-x - Log[2] + Log[1 + \[ExponentialE]^-x])       as it's supposed to be.


Reversing axes to get Poiseuille profile

I am trying to plot my velocity profile, similar to this plot (not the arrows, just the shape) ![enter image description here](http://i.stack.imgur.com/lmzSd.jpg) Here is my function               Diam = 2;     Uavg = 200;     SL = 40;     R = Diam/2;     theta[r_] := ArcCos[SL*Diam^2/(8*Uavg*(R^2 - r^2))];     Plot[Piecewise[{{SL/Cos[theta[r]], r >= 0}, {8*R^2*Uavg/Diam^2,      r = 0}}], {r, 0, 0.99}]


Transform 3D data into 2D color map like Matlab's surf/imagesc

I have a bunch of 3D data (x, y coordinates and values) which is generated in Matlab and I need to render them in a 2D color map with certain axis ranges. Here are the Matlab code and the generated figure.               rho = linspace(0, 80, 100);     phi = linspace(0, 2*pi, 100);     [PHI,RHO] = meshgrid(phi, rho);     dat = rand(size(PHI)); % data was generated in cylindrical coordinate     [x, y] = pol2cart(PHI, RHO);     surf(x, y, data,'edgecolor','none'); shading interp;     view(0, 90);     axis equal; axis off;     xlim([-50, 50]); ylim([-50, 50])     save('data.mat', 'x', 'y', 'dat')      ![render 3d data into a 2d colormap](http://i.stack.imgur.com/6LerO.png) In **_Mathematica_** , I imported these data by evaluating               {x, y, dat} = Import["data.mat", "MAT"]      but I have no idea how to render them as shown above. I tried               ListPlot3D[{x, y, dat}]      It gave a 3D pattern but was extremely slow because I have a lot of data. Could anyone give me a hint to tackle this problem?


Manipulate keeps replaying the animation non-stop

I made a notebook with the following code, but for some reason when I evaluate it it keeps replaying repeatedly. What is causing this? Thanks.               RandomWalk[n_, roi_, bi_,        rake_] := (pwin = bi (1 + roi)/(2 (bi - rake));        NestWhileList[# +           RandomChoice[{pwin, 1 - pwin} -> {1 - 2 rake/bi, -1}] &,         0, True &, 0, n])          Manipulate[(data = RandomWalk[nrTournaments, roi, bi, rake];        dollarWon = biWon bi; biWon = Last[data];        ListPlot[data, Joined -> True]), {{nrTournaments, 10000,         "tournaments"}, 0, 100000, 100}, {{roi, 0.015, "ROI"}, 0, 20,        0.001}, {{bi, 60, "BI ($)"}, 0, 10000,            1}, {{rake, 1.26, "rake ($)"}, 0, 500, 0.01},           Panel[Grid[{{Dynamic[               Row[{"BI won: ", ToString[biWon], " (",                  Style["$" <> ToString[dollarWon],               If[dollarWon >= 0, Darker[Green], Red]], ")"}]]}},         Alignment -> Left]], SaveDefinitions -> True]


Using SetDelayed wih SQLExecute

I want to create a reusable line of code that I can send a column, table name and criteria to match using the WHERE clause.               colCount[x_, y_, z_] :=  Length[SQLExecute[conn,      "SELECT " && x && " FROM " && y && " WHERE " && x && " = " && y &&       ""]];      When I try to pass a column name to the SELECT statement using the variable x and pass the table name to y, using               colCount[col1,db1,40]      MM doesn't seem to understand. I tried the column and database name in quotes too. Cheers!


Derivative from the left and right

I am currently trying to write a script that takes a curve $C$, a starting point $p$ and a direction vector $\vec{v}$ and calculates the path of a beam starting at $p$ in direction $\vec{v}$ when it is reflected on $C$. The idea is basically: (Numerically) find the (first) crossing point of beam and $C$, calculate tangent in that point, calculate new beam direction, repeat. Now, if my curve is point-wise not differentiable (in my case: $C$ has "kinks"), I would like to treat it as a limit case where both smooth curves around the kinks are considered, so the calculation forks and I get 2 possible beam pathes. For this, I need the left and the right side derivative of this point. How do I get those in Mathematica? Also, if somebody knows a better way or this has already been written and is public, I appreciate any clues, of course.


How do I make Mathematica understand roots of unity?

Try the following:               z = Exp[2 \[Pi] I / 5]          Z = { { z, 1 }, { 0, 1/z } }          Simplify[MatrixPower[Z, 5]] //MatrixForm      Of course, this should return a 2 x 2 identity matrix. Instead, we get:               {{1, 1 - (-1)^(1/5) + (-1)^(2/5) - (-1)^(3/5) + (-1)^(4/5)}, {0, 1}}      That is, _Mathematica_ doesn't seem to understand that summing these roots of unity gives zero. Is there some way to make it realize this?


Declaring a positive variable

Why I have this behaviour?               R /: Greater[R, 0] = True     R > 0       => True     Simplify[Sqrt[R^2]]       => Sqrt[R^2]      I expect `R` as last result.


Assumption for all the notebook

I would like to know how to fix an assumption over a variable that will be fixed for all notebook. For example a>0 in all the notebook.


Does Eigenvalues evaluate in a parallelized way?

I use mathematica on a computer with linux operating system. The computer has 2 cpus and each cpu has 4 cores, so there are totally 8 cores available. Now I got confused with whether the evaluation of `Eigenvalues` is parallelized or not. I present two kinds of codes below one use `ParallelDo`               ParallelDo[         Eigenvalues[# +              ConjugateTranspose[#] &[Table[RandomReal[], {i, 5000}, {j,5000}]]         ];     ,{4}]//AbsoluteTiming      the time it takes is 135.12254 second. And use `Top` command in linux during the evaluation, it shows like below: ![enter image description here](http://i.stack.imgur.com/2BKyH.png) It show that 4 cores are trying their best, that's quite reasonable. the other use `Do` only               Do[Eigenvalues[# + ConjugateTranspose[#] &[Table[RandomReal[], {i, 5000}, {j,5000}]]];,{4}]//AbsoluteTiming      this time it takes 109.004395 second. It evaluates even faster!!. And use `Top`, It shows like below: ![enter image description here](http://i.stack.imgur.com/cdVSm.png) Almost 800%, it means that this time, the evaluation uses all the cores? **I don't know why it shows one 800% instead of eight 100%s. What is the difference?** If `Eigenvalues` really evaluates in a parallelized way automatically, why `Parallelize[Eigenvalues[matrix]]` gives error message saying that " **`Eigenvalues` can't be parallized;proceeding with sequential evaluation**"??


Key to get help about current function

I know you can hit `F1` to pop up the documentation center, and then type the name of a function and search for it. I'd like to know if there's a key that just pops up the help page of the function the cursor is in right now. For instance, when writing `Integrate[`, sometimes I forget the right syntax for it, so I just want to immediately see the help page for it without having to manually search for it.


How to find the position of non consecutive numbers?

Given a sorted table, how can I find the position of non consecutive numbers in the first column of the table?               list = {{1, 3, 5}, {3, 3, 5}, {4, 3, 5}, {5, 3, 5}, {7, 3, 5}}//MatrixForm      ![enter image description here](http://i.stack.imgur.com/ZkcuC.gif) How to do I find the row position of the **first** non-consecutive number in column one?   How to do I find the row position of the **last** non-consecutive number in column one?


Nesting Parallel processes

I just attempted to run code that had nested ParallelMap[] functions. It generates the error message: > ParallelMap::subpar: Parallel computations cannot be nested; proceeding with > sequential evaluation. I can represent a simplified version of the code's structure with the following:               f[list_] := ParallelMap[# + 0.1 &, list]     dataLists = RandomReal[{0, 1}, {5, 100, 3}];     Dimensions[dataLists]     ParallelMap[f[#] &, dataLists];      When `ParallelMap` calls `f[datLists]` I have extra kernels available for use, but it appears that whatever manages the distribution of processing jobs can't reach them. I can appreciate that nesting parallel computations presents some complications, but not having the ability to nest them doesn't seem very Mathematica like. As my code has many functions at the same (2nd) level in the hierarchy as `f[list_]`, this constrains my possible solutions quite a bit and makes optimizing performance by using parallel computation time consuming. I think I can either parallelize at the top level or parallelize all the functions at the second level, but obviously not both. Also, this 2nd level of functions tend to greater complexity than the simple example above. They look more like:               If[#[[1]] == 0, 0, 1 - NProbability[x < #[[1]], x \[Distributed] #[[2]]]] &,          Transpose[{listOfReals, myDistributions}]      Just speculative brainstorming, but maybe (probably) I haven't thought of all the possible ways to attack a problem like this.   * Rather than mapping or parallel mapping, could I recast this problem in other ways better suited to the single available level of parallelization?   * Could one flatten the computations then cull out the answers afterwards?   * Could one turn this into a matrix operation of some kind? As CUDA and OpenCL don't look like a ready or easy solution for me (see: CUDA and GPU hardware and compatibility questions) I'd hoped to get everything I could out of Mathematica's parallel powers.


Poor rendering of fractals

Could someone explain why I get those ugly graphics .. ![enter image description here](http://i.stack.imgur.com/7Hm75.jpg) ..trying to use fractals in mathematica 8 ? I'd also like to know if it is possible to draw 2D fractals in Mathematica * * * My configuration is:   * Windows 7 64 bits    * Intel Pentium P600    * RAM 4Go    * ATI Mobility Radeon HD5470


Segmentation of sunspots

I recently went for a walk with my camera and snapped a few pictures of the sun. The pictures didn't turn out too well, but this was to be expected without a telescope. I thought it might be a nice exercise to segment out the sunspots and see how my results compare to the data of SOHO. Here is what I came up with:               img = Import["http://i.imgur.com/4lDwE33.jpg"];     soho = Import["http://i.imgur.com/XNmroTf.jpg"];          (*determine center and radius of the sun in the the image*)     {center, radius} =        ComponentMeasurements[         MorphologicalComponents[img, 0.2], {"Centroid",           "EquivalentDiskRadius"}][[1, 2]];          (*segment the sun from background, polar transformp, post process *)     ImageTransformation[img,        center + {Cos[#[[1]]], Sin[#[[1]]]}*#[[2]] &, {2 Pi radius, radius},        DataRange -> Full, PlotRange -> {{0, 360 °}, {1, radius}}];     polar = ColorConvert[%, "LUV"];     mean = Mean@ImageData[polar][[All, All, 1]][[#]] & /@         Range[Round[radius]];     normalPolar =        Image@Rescale[         ImageData[polar][[All, All, 1]][[#]] - mean[[#]] & /@           Range[Round[radius]]];          (*transform back to cartesien coordinates*)     normalCart =        ImageTransformation[        normalPolar, {ArcTan @@ (radius - #),           Norm[# - radius]} &, {2 radius, 2 radius},         DataRange -> {{-180 °, 180 °}, {0, radius}},         PlotRange -> {{0, 2 radius}, {0, 2 radius}}];     (*segmentation of sun spots*)     segmentation =        ColorNegate@        ImageAdd[         Dilation[          Binarize[ImageCorrelate[%, GaussianMatrix[6], CosineDistance],            0.253], 2.29], Graphics[Disk[center, radius]]];     (*generate spot labels*)     centroids =        ComponentMeasurements[        SelectComponents[MorphologicalComponents[ColorNegate@segmentation],          "Count", 10], {"Centroid", "EquivalentDiskRadius", "Label"}];     labeled = Show[normalCart,        Graphics[{Red, Circle @@ # & /@ centroids[[All, 2, 1 ;; 2]],          MapThread[           Text, {centroids[[All, 2, 3]] - 1, {0, 6 + #[[2]]} + #[[1]] & /@              centroids[[All, 2, 1 ;; 2]]}]}]        ];          (* plot:     "original image", "post processed image"     "segmented sun spots", "labeled post processed image"     "image from Solar and Heliospheric Observatory (SOHO)"     *)     GraphicsGrid[{{ImageCrop[img], normalCart}, {segmentation,         labeled}, {soho}}, Frame -> All, ImageSize -> 900]      ![enter image description here](http://i.stack.imgur.com/1TrbS.png) ![enter image description here](http://i.stack.imgur.com/9eJ8r.png) While I'm quite happy with the result, I thought some of you guys might come up with some clever ideas to make the approach more robust and the results even better. I'm also very thankful for a review of my code. You never stop learning!


How to convert equations to piecewise form

equations={{2 u,2,1+t,1}=={a c,a b+c,a+b,1},{u,t,0,1}=={c d,c+b d,b+d,1}};     Thread/@equations//TraditionalForm      equations was typed to do some `Solve` How to get the following TraditionalForm I typed(I hate typing directly too much) the following equations by hand to show the result expected. Saving equations to `.tex` also could get beautiful appearance. I'd like the equations become beautiful in _Mathematica_ or _Tex_ ( Row/Column seems will not preserve the effect after converting to _Tex_ ). So how to convert equations to (1) or (2) both in Notebook and `TeXForm`? ![enter image description here](http://i.stack.imgur.com/wCu2K.png)(1) ![enter image description here](http://i.stack.imgur.com/TXiIZ.png)(2) as @chris mentioned in the comment, this is one good look, so problem is to convert equations to `Piecewise` in this way.               f[x_] = Piecewise@{{Sin[x], x < 0}, {x, x >= 0 && x < 1}, {x^2, x >= 1}}           f[x]//TeXForm      \begin{cases} \sin (x) & x<0 \\\ x & x\geq 0\land x<1 \\\ x^2 & x\geq 1 \end{cases}


Solving this system of equations produces an error message about badly conditioned matrix

I want to determine a balance distribution.               Ü = {{0.4, 0.2, 0.3}, {0.3, 0.5, 0.2}, {0.3, 0.3, 0.5}};       and               X = {{x1}, {x2}, {x3}};       so that               Ü.X == X      But when I want to solve               Solve[{0.4 x1 + 0.2 x2 + 0.3 x3 == x1,0.3 x1 + 0.5 x2 + 0.2 x3 == x2, 0.3 x1 + 0.3 x2 + 0.5 x3 == x3,        x1 + x2 + x3 == 240000}, {x1, x2, x3}]      I get the error > RowReduce::luc: Result for RowReduce of badly conditioned matrix {{0.3, 0.2, > -0.6, 0.}, {0.2, -0.5, 0.3,0.}, {-0.5, 0.3, 0.3, 0.}, {1., 1., 1., > -240000.}} may contain significant numerical errors. >>   >  {} How can I solve this system?


List of atomic expressions

I was surprised to see `Graph` objects are atomic. Is there a way (through documentation or programmatically) to find all atomic heads? The ones I know of are:               Integer     Rational     Real     Complex     Symbol     String     SparseArray     StructuredArray     Image (* since v9 *)     Image3D     Graph     ColorProfileData     Association     MeshRegion     BoundaryMeshRegion      Are there any others? ## Others mentioned in the comments               Internal`Bag     System`Utilities`HashTable     System`RawArray     BooleanFunction     Dispatch (* since v10 *)     Dataset


Download a notebook (or any type of file) from the cloud

Let us say that I have a Notebook in the Wolfram Programming Cloud called `foo.nb`. If I try `CloudGet["foo.nb"]`, what I get back is a CloudObject (or the link to it), which in any case does not allow me to download the notebook itself. Is there a way/function/trick to obtain a link to download `foo.nb` to the Desktop?


Showing the progression of a Jarvis march algorithm

I am trying to use `Manipulate` to show the process of creating a convex hull using the Jarvis march algorithm. My code currently computes the convex hull using locators when you input points on the pane. I've shown it below. What I would like to do is use the `Manipulate` to plot the progress of each addition of a side, one step at a time. In particular, I'd like for the user to be able to click on an "Autorun" button, and have the graph update after each computation of `find$next$point`, showing the addition of the next side. How could I go about doing this?               l = Graphics[{Black, Disk[{0, 0}, .1]}, ImageSize -> 10];          find$next$point[u_, p1_, p2_] :=      Module[{v1, v2, angles, maxIndex, i},        v1 = p1 - p2;        v2 = Inner[List, u[[All, 1]] - p2[[1]], u[[All, 2]] - p2[[2]], List];        angles = {};        Do [        If[v2[[i]] == {0, 0},          angles = Append[angles, 0];,          angles  = Append[angles, VectorAngle[v1, v2[[i]]]];        ];        , {i, 1, Length[u]}      ];      maxIndex = Position[angles, Max[angles]][[1, 1]];      u[[maxIndex]]     ];           convexHull[u_] :=       Module[{hull, p1, p2, temp},      If[u == {},      hull = u;      ,      hull  = {};      p2 = u[[Position[u[[All, 1]], Min[u[[All, 1]]]][[1, 1]]]];      p1 = {p2[[1]], -10000};      hull = Append[hull, p2];      temp = find$next$point[u, p1, p2];      p1 = p2;      p2 = temp;      hull = Append[hull, p2];      While [p2 != hull[[1]],       temp = find$next$point[u, p1, p2];       p1 = p2;       p2 = temp;       hull = Append[hull, p2];       ];      ];     hull     ];          Manipulate[       Graphics[Line[convexHull[u]], PlotRange -> 3],        {{u, {}}, Locator, LocatorAutoCreate -> True, Appearance -> l}]


NMaximize not satisfying binary constraint

I'm solving an optimization problem in Mathematica with binary integer constraints. It works alright with other constraints. But the only problem is that both NMaximize and NArgMax are not treating the variable with binary integer correctly. When it's done finding a solution, some of the numbers are actually 0.4881, 1, 0, and 0.00154, and so on. This is how I've currently set the variable with the binary constraints:               binconst = Table[Subscript[\[Beta], v], {v, 5}]     Join[Thread[0 <= binconst <= 1], {binconst \[Element] Integers}]      this gives: $$\left\\{0\leq \beta _1\leq 1,0\leq \beta _2\leq 1,0\leq \beta _3\leq 1,0\leq \beta _4\leq 1,0\leq \beta _5\leq 1,\left(\beta _1\left|\beta _2\right|\beta _3|\beta _4|\beta _5\right)\in \mathbb{Z}\right\\}$$ I could approximate, but this is not good for my model. So how do I make the function recognize the binary constraints.


Faster code for solving an equation with parameters

I am new to _Mathematica_ and wanted to solve an equation that depends on parameters. The code is below                   theta = 0.3;         v = 0.05;         alpha = 1;              q := InverseCDF[ GammaDistribution[ alpha, 1], (1 - theta)]         rk[k_, r_] := r k         rkplus1[k_, r_] := r k + 1              Lfun[k_, r_] :=            (1/rkplus1[k, r])^alpha Exp[ rk[k,r] q] CDF[ GammaDistribution[ alpha,                                                                           1/(rk[k, r] +1)],                                                        q]              Lplustheta[k_, r_] := theta + Lfun[k, r]         logLplustheta[k_, r_] := Log[ Lplustheta[k, r]]         LHS[k_, r_] := rk[k, r] q Lfun[k, r]/Lplustheta[k, r] - logLplustheta[k, r  ]         RHS[r_] := r v         r := 1;             While[ r < 100,              { While[ LHS[ k 0.00001, r 0.05] < RHS[r 0.05], a = k 0.00001; k++],                 Print[ r 0.05, " ", v, " ", theta, " ",                       Lfun[k 0.00001, r 0.05], " ", a, " ",                        a/Lplustheta[ k 0.00001, r 0.05], " ",                        a - (a/Lplustheta[k 0.00001, r 0.05])]; k := 1}; r++]      The code works but is extremely slow. Is there a faster way to accomplish what I trying to do?   Essentially solve `RHS - LHS == 0` for `k`, for a range of `r`, and print?


Replacing a specific pattern of values at level 2 in a list

I've a list of lists,               tl = {{True, False, m12}, {False, m22, m33}, {m32, False, True}}      and each nested list has the same length, What is the proper way to replace the occurances of all `m*` values, i.e., `m12`, `m22`, etc., with a particular value say `x`. All I want is this result > >     tl = {{True, False, x}, {False, x, x}, {x, False, True}}` >   Any help will be appreciated.


Create custom mappings of Mathematica Expressions => Java Objects?

I would like to call a JLink-based java function from Mathematica with a Mathematica Span[] object as shorthand, like so...               << JLink`     MyJavaPackage`myStaticMethod[ variable1, variable2, 1 ;; 10 ]      I would like to convert the `Span[1, 10]` object into a Java object automatically (actually, a `scala.range` object) I know you can specify the mapping of complex values in Mathematica using ` SetComplexClass["classname"]`. Is there any general equivalent, so I can do the above conversion automatically? I am thinking I need something like the inverse of `MakeJavaExpr[]`... The alternative would be, I guess, to specify in Mathematica, in the MyJavaPackage` scope, something like...                MyJavaPackage`myStaticMethod[ variable1, variable2, span_Span ]:=           myStaticMethod[ variable1, variable2, JavaNew["scala.Range", span[[1]], span[[2]]]      ... that would preclude doing this for non-static Java functions though, I guess. Thank you for your help!


Adding an unused column creates an error in JoinAcross

I'd been having trouble using `JoinAcross` on two datasets. After going through the answers to my original question and fixing my code, I find I'm now having a problem that I think is being caused by my data. I'm adding a column to an Excel sheet, but not using it in my dataset. I'm reading in two Excel sheets, "Reported" and "Estimated". Below are screens shot of "Reported" followed by "Estimated": ![Reported](http://i.stack.imgur.com/sgG2u.png) ![Estimated](http://i.stack.imgur.com/ILPHf.png) Next is my code and its output:               repFile = Import[NotebookDirectory[] <> "test.xlsx", {"Sheets", "Reported"}];     repHeader = repFile[[1]];     repData = repFile[[2 ;;]];          estFile = Import[NotebookDirectory[] <> "test.xlsx", {"Sheets", "Estimated"}];     estHeader = estFile[[1]];     estData = estFile[[2 ;;]];          repDS = Dataset@Map[AssociationThread[repHeader, #] &]@repData;     estDS = Dataset@Map[AssociationThread[estHeader, #] &]@estData;          rep1 = repDS[All, {"a", "z1"}];     est1 = estDS[All, {"a", "z2"}];          rep1     est1     rep1 // Normal     est1 // Normal     JoinAcross[rep1, est1, "a"]      ![Output1](http://i.stack.imgur.com/Nl6cP.png) Now I add one column to "Estimated" to get: ![Estimated2](http://i.stack.imgur.com/xxufd.png) My output now looks like: ![Output2](http://i.stack.imgur.com/ufteh.png) Since I'm not actually bringing in that additional column to the dataset I don't understand what's happening. Is this a bug or am I doing something wrong?


What are the best practices / most common / idiomatic ways to report errors in Mathematica?

In particular, what are the best ways to report errors about incorrect arguments to a function? Checking for the correct arguments is relatively easy using patterns, but how to report an informative error message specific to the situation is not obvious. Most built-in functions will return unevaluated when the arguments are incorrect, while printing an informative error message. Points to consider:   * easy to add to an already implemented function without changing much, easy to keep the error reporting separate from what the function actually does   * robust and maintainable   * plays well with functions that take options _Note:_ I can come up with several ways to achieve this behaviour. But instead of starting from scratch and learning from mistakes I'd like to draw on the experience and knowledge of the community to learn about some time tested methods.


Integrating a BesselJ integrand to obtain the same result as Maple 16

I would like to check the following integration:               Integrate[y*Integrate[1/x*BesselJ[1,x*Exp[I*π/4]]*BesselJ[1,x*Exp[-I*π/4]],{x,0,y}],{y,0,r}]      _Mathematica_ 9.0 is not able to evaluate the integral. However, Maple 16 gives the following result:               r^4/32 * hypergeometric([1/2],[3/2,3/2,2,2],r^4/64)       Is this result correct ?


Combining separate CHColorStructureDiagrams to form one molecular structure

I am trying to attach a fructose molecule to a sucrose molecule by using information obtained from the following               ChemicalData["Sucrose", "CHColorStructureDiagram"]     ChemicalData["Fructose", "CHColorStructureDiagram"]      My question is how do you combine each separate structure diagram to form a single one shown here which is a combined structure arising from the two structures (description at http://en.wikipedia.org/wiki/Fructan) ![enter image description here](http://i.stack.imgur.com/t3FXg.png)


Ito process estimating in Mathematica

How can I estimate parameters of Ito process in _Mathematica_? I have some time-process data (for example assets) and want it to be described Heston model - vector Ito process.


MixtureDistribution in Mathematica 7

Is it possible to use a mixture of several distributions in _Mathematica_ 7.0? Consider for example the following code :               arms = Table[              NestWhileList[                 {#[[1]] + RandomInteger[{-2, 1}], # + RandomReal[{-1, 1}] & /@ #[[2]]} &,                  {RandomInteger[{25, 30}], {0, 0, 0}}, #[[1]] > 15 &],                 {10}            ];          points = Table[# + RandomReal[                         MixtureDistribution[                            {1, 1},                             {NormalDistribution[-0.1, 0.3], NormalDistribution[0.1,0.3]}                         ]] & /@ #[[2]], {#[[1]]}] &/@Flatten[arms, 1];          ListPointPlot3D[points, BoxRatios -> {1, 1, 1}, ImageSize -> 800,                      PlotStyle -> {Blue, PointSize[Small]}]      The command "MixtureDistribution" isn't recognized in Mathematica 7.0. The question is : **Is there a way to mix distributions in Mathematica 7 ?** I never found any documentation on this, so I suspect that the answer is simply "No. Upgrade to v8". Sometimes, in the software world, there are options and commands that aren't well documented. So this is why I'm asking the question anyway.


Multiple assumptions in integral

I want to add two assumptions, so I can get this probability density function to equal 1, though I can't get a solution.               Integrate[(L r x^(r - 2))/(r - 1)! e^(-L x), {x, 0, Infinity},       Assumptions -> r > 0, Assumptions -> L > 0]      My equation. With the assumptions `r > 0` and `L > 0`


How to choose three points on the circle so that the triangle is not a right triangle?

I want to choose three points $A$, $B$, $C$ has integer coordinates on the circle $$(x+2)^2 + (y+1)^2 = 25$$ so that the triangle is not a right triangle. But I can not. I tried               ClearAll[a, b, r];     a = -2;     b = -1;     r = 5;     Solve[{(x - a)^2 + (y - b)^2 == r^2, x != a, y != b}, {x, y}, Integers]


Need help in making a fit to my experimental data

This is what I have done so far. The points are of angles-of-deviation and wavelengths from my physics lab experiment.               V = ListPlot[       {{589.3, 53.50}, {435.8, 56.02}, {535.4, 54.52}, {546.1,          53.57}, {577.0, 53.13}, {690.9, 52.10}, {402.6, 55.72}, {447.2,          55.02}, {492.2, 54.53}, {501.6, 54.83}, {587.6, 53.03}, {667.8,          52.83}, {706.5, 52.05}        }, PlotRange -> {{400, 710}, {50, 60}},        AxesLabel -> { wavelength, deviation}, PlotStyle -> Red,        GridLines -> Automatic]      ![this is what i have done so far. ](http://i.stack.imgur.com/v8Q2y.jpg) I am trying to find the best fit line of these points. I know it is some type of exponential function. But I can not figure out how to do it. Please help me out.


BoundedDiagram Error

Although `BoundedDiagram` function worked well for a small data set, I got errors in a specific case that I cannot explain. I am sorry I am pasting here a large list but you could not verify it otherwise:               Needs["ComputationalGeometry`"];          data2D = {{0., 0.1846}, {-0.1846, 0.}, {0., -0.1846}, {0.1846, 0.}, {0.4189,0.2418},                {0.2418, 0.4189}, {0., 0.4837}, {-0.2418, 0.4189}, {-0.4189, 0.2418},                {-0.4837, 0.},{-0.4189, -0.2418}, {-0.2418, -0.4189}, {0., -0.4837},               {0.2418, -0.4189}, {0.4189, -0.2418}, {0.4837, 0.}, {0.8455, 0.},                {0.8041, 0.2613}, {0.684, 0.497}, {0.497, 0.684}, {0.2613, 0.8041},               {0., 0.8455}, {-0.2613, 0.8041}, {-0.497, 0.684}, {-0.684, 0.497},               {-0.8041, 0.2613}, {-0.8455, 0.}, {-0.8041, -0.2613}, {-0.684, -0.497},                {-0.497, -0.684}, {-0.2613, -0.8041}, {0., -0.8455}, {0.2613, -0.8041},                {0.497, -0.684}, {0.684, -0.497}, {0.8041, -0.2613}, {1.2923, 0.},                {1.2599, 0.2876}, {1.1643, 0.5607}, {1.0103, 0.8057}, {0.8057, 1.0103},               {0.5607, 1.1643}, {0.2876, 1.2599}, {0., 1.2923}, {-0.2876, 1.2599},                {-0.5607, 1.1643}, {-0.8057, 1.0103}, {-1.0103, 0.8057}, {-1.1643, 0.5607},               {-1.2599, 0.2876}, {-1.2923, 0.}, {-1.2599, -0.2876}, {-1.1643, -0.5607},                {-1.0103, -0.8057}, {-0.8057, -1.0103}, {-0.5607, -1.1643}, {-0.2876, -1.2599},                {0., -1.2923}, {0.2876, -1.2599}, {0.5607, -1.1643}, {0.8057, -1.0103},                {1.0103, -0.8057}, {1.1643, -0.5607}, {1.2599, -0.2876}};      You can see in               ListPlot[data2D, AspectRatio -> 1, PlotStyle -> PointSize[Large]]      and in               DiagramPlot[data2D]       that the `Voronoi` Areas appear clear. But when using               BoundedDiagram[{{-4, -4}, {4, -4}, {4, 4}, {-4, 4}}, data2D]      I get errors like : > Solve::svars: Equations may not give solutions for all "solve" variables. > > BoundedDiagram::nobd: Bounded diagram failed. If I limit the data set I get correct results (but not always):               BoundedDiagram[{{-4, -4}, {4, -4}, {4, 4}, {-4, 4}}, data2D[[1 ;; 10]]]      Notice that `VoronoiDiagram[data2D]` produces the correct `Voronoi` data. Can anybody explain why this is happening or is it a _Mathematica_ bug ? **Solution** Following Belisarius' advice, I am rolling my own algorithm. Actually I used `VoronoiDiagram` function (why invent the wheel?). I used a circular bound (of radius 1.5) that seems more appropriate for my application.               v = VoronoiDiagram[data2D];          intersection[ray_, radius_] :=       Module[{start = ray[[1]], end = ray[[2]], sx, sy, ex, ey, l},         {sx, sy} = start; {ex, ey} = end;         l =            (sx*ex + sy*ey + Sqrt[(sx*ex + sy*ey)^2 - (ex^2 + ey^2) (sx^2 + sy^2 - radius^2)])/             (ex^2 + ey^2);         start + l*(end - start)];          {vorvert, vorval} =       {Table[          If[Head[v[[1, i]]] === Ray,             intersection[v[[1, i]], radius = 1.5],             v[[1, i]]],           {i, 1, Length[v[[1]]]}],        v[[2]]};          DiagramPlot[data2D, vorvert, vorval]      ![enter image description here](http://i.stack.imgur.com/WOrTt.jpg) I welcome any improvement - addition.


Social Network Analysis - Get the List of InBoundEdges for Directed Graph

I wish to get the list of inwards edges for a node. `IncidenceList` provides both inwards and outwards list. I can of course filter with `Cases` using the following way. But is there any better way or built-in function for the same?               InBoundEdges[graph_, x_] := Cases[IncidenceList[graph, x], _ \[DirectedEdge] x]      When I use the `InBoundEdges` function in one of my simulation functions I am getting _MaxFormatDepthExceeded exception_ , even for a smaller number of nested operations. I need around _10000 number of iterations_. Lets take an Example,               g = Graph[{1 -> 2, 3 -> 2, 2 -> 5, 4 -> 2, 2 -> 6, 1 -> 4, 3 -> 5, 6 -> 4}];     IncidenceList[g, 2]     IncidenceList[g, 2][[All, 1]]     InBoundEdges[g, 2]      Now `IncidenceList[g, 2]` gives               {1 -> 2, 3 -> 2, 2 -> 5, 4 -> 2, 2 -> 6}      but I only need `{1 -> 2, 3 -> 2, 4 -> 2}` which I can get with `InBoundEdges` written above. However it is not an efficient solution.


Result of Reduce contains duplicate terms

On my system, the result of this:               f[x_] := 2 Sin[x] + Sin[x]^2;     Reduce[f'[x] == 0, x]      contains the following expression twice:               x == -(Pi/2) + 2*Pi*C[1]      This is the entire result:               Element[C[1], Integers] &&           (x == -(Pi/2) + 2*Pi*C[1] || x == Pi/2 + 2*Pi*C[1] ||            x == -(Pi/2) + 2*Pi*C[1] || x == (3*Pi)/2 + 2*Pi*C[1])      Is there a reason the expression appears twice? Is this a bug?


Coefficient of function different than polynomial

My question arise from the problem that Mathematica can't solve the equation $$ \text{Solve}\left[e^{a-x} (0.0299584 a+0.1 b-0.0299584 x-0.152913)-0.9 a+0.9 b+0.9 x+0.18=0.0498614 e^{-x} \left(e^a ((0.09 a-0.378) a+b (0.600833 x+0.660917)-0.54075 x-0.107925)+5.4075 \left(3.00417 e^x (-1. a+b+x+0.2)+a-b+0.8\right)\right)\land (0.1 b-0.09) e^{a-x}+0.9 (-a+b+x+0.1)=\frac{1}{2} e^{-x-2.2} \left(0.9 e^a \left(0.09 \left(a^2-4.2 a+5.41\right)-6.00833 (-0.1 (a-1) b+0.09 a-0.19)\right)+5.4075 \left(e^{x+1.1} (-a+b+x+0.1)+0.9 (a-b+0.8)\right)\right),\\{a,b\\}\right] $$ I was thinking about extracting coefficients of $\exp{x}$ of the LHS of the first equation and then compare it with the same coefficient on the RHS. Then perform the same operation, but with the coefficient of $x\exp{x}$ and so on? How to do it?


Convert GraphPlot[]s with many nodes into something that's human-understandable

This is more of an abstract/creative problem. I think everyone who has played around with `GraphPlot`, ended up with an image that looks like this, at least once in their life: ![messy GraphPlot output](http://i.stack.imgur.com/ynzmam.png) I am looking for general solutions to convert _many connections_ -> _many connections_ into something that's human understandable. Here's my code above:               d = DictionaryLookup[RegularExpression["[a-z]{1,5}"]];     d = Take[d, 1000];     g = {};     Do[Do[If[Abs[StringLength[d[[i]]] - StringLength[d[[j]]]] > 1,         Continue[]];       If[EditDistance[d[[i]], d[[j]]] == 1,         AppendTo[g, d[[i]] -> d[[j]]];        AppendTo[g, d[[j]] -> d[[i]]]], {j, i + 1, Length[d]}], {i, 1,        Length[d]}]          Needs["GraphUtilities`"]     s = StrongComponents[g];     sc = Last[SortBy[s, Length]];     gc = Select[g, MemberQ[sc, #[[1]]] &];     GraphPlot[gc,       EdgeRenderingFunction -> ({Orange, Arrowheads[Small],           Arrow[#1, .07]} &)]      I would love something like this, where strongly connected nodes are grouped into single pie-chart vertices which represent the # of node connections over total connections.


Symbolic manipulation of the moments of an unknown distribution

I'm curious as to whether it's possible to get _Mathematica_ to simplify/manipulate/expand basic expectations, conditional expectations, sums of random variables, etc. A simple example might be: $$Var(X+Y)=E[(X+Y)^2]-(E[X]+E[Y])^2$$ It's trivial to show this can be expanded to: $$Var(X+Y)=E[X^2]+2E[XY]+E[Y^2] - E[X]^2-2E[X]E[Y]-E[Y]^2$$ and then simplified to $$Var(X+Y)=Var(X)+Var(Y)+2Cov(X,Y)$$ These sorts of manipulations are easy enough by hand, but when I'm exploring lots of different possibilities, it's easy to get bogged down, make mistakes, etc. It would be nice to get mathematica to do the manipulations for me. However, I haven't been able to figure out how to get _Mathematica_ to perform these sorts of operations _without_ defining an actual distribution. Thoughts?


adding labels to points in ListPlot

Table[{Re[5 Exp[I 5/2 t]], Im[5 Exp[I 5/2 t]]}, {t, 0, 6}]     ListPlot[%]      This code plots 6 points in the complex plane. To each point I would like to add a label in the plot that lists the value of `t`. How can I do that? Please note: I want to print this plot, so the labels should all be visible.


Smoothing ListContourPlot contours

I have some data of type `{{x1, y1, f1}, {x2, y2, f2}, ...}` and want to do `ListContourPlot`. However, there is a problem that the data `f` is not smooth enough and has small errors. Here is a toy example illustrating the problem:               data = Flatten[         Table[{i (1 + RandomReal[0.1]), j (1 + RandomReal[0.1]),           i + j}, {i, 0, 100}, {j, 0, 100}], 1];     ListContourPlot[data, Contours -> {80, 120}, ContourShading -> None]      ![enter image description here](http://i.stack.imgur.com/g4ndv.png) I would need to smooth the lines in the above curve, to get something like ![enter image description here](http://i.stack.imgur.com/ueqyd.png) Any ideas to get this kind of smoothed plot? Thanks! And here is the figure from real data (which is too large to paste here), which I need to smooth: ![enter image description here](http://i.stack.imgur.com/zSztT.png) I find this thread InterpolationOrder for ContourPlot related. But I was unable to get the method work in my case because of (I guess) different input. **Note added:** Thanks a lot for the answers! Those answers works great for the toy example, but for the real data I still cannot get smooth lines so far (edit: so far means before the great guys update their answers ^_^. Now it worked great). Here is my data and plotting function, just in case you would like to give a try. I will also investigate why those interesting methods fail to work when I apply it to data... https://www.dropbox.com/s/2pgobgrhbo42f4v/contourData.dat               data = << "contourData.dat";     ListContourPlot[data, Contours -> {2.30, 6.18},       ContourShading -> None]


How change order of items added to the Palettes menu?

After installing an add-on package (Spin) in `$UserBaseDirectory/Applications`, there is now a new palette for that package listed on the `Palettes` menu. But it's in an awkward place in the list, between the `Classroom Assistant` and `Writing Assistant` provided by installation of Mathematica itself. How does one change the order in which palettes appear on the menu?


JSON problem? MMA10, Windows 7 or Linux Mint

I want to test Mathematica 10 to import various data format. In this case, I have a JSON file with the following data and structure:               { "_id" : "ac3", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone", "price" : 200, "warranty_years" : 1, "available" : true }     { "_id" : "ac7", "name" : "AC7 Phone", "brand" : "ACME", "type" : "phone", "price" : 320, "warranty_years" : 1, "available" : false }     { "_id" : { "$oid" : "507d95d5719dbef170f15bf9" }, "name" : "AC3 Series Charger", "type" : [ "accessory", "charger" ], "price" : 19, "warranty_years" : 0.25, "for" : [ "ac3", "ac7", "ac9" ] }         { "_id" : { "$oid" : "507d95d5719dbef170f15bfa" }, "name" : "AC3 Case Green", "type" : [ "accessory", "case" ], "color" : "green", "price" : 12, "warranty_years" : 0 }         { "_id" : { "$oid" : "507d95d5719dbef170f15bfb" }, "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38, "warranty_years" : 2, "for" : [ "ac3", "ac7", "ac9", "qp7", "qp8", "qp9" ] }         { "_id" : { "$oid" : "507d95d5719dbef170f15bfc" }, "name" : "AC3 Case Black", "type" : [ "accessory", "case" ], "color" : "black", "price" : 12.5, "warranty_years" : 0.25, "available" : false, "for" : "ac3" }         { "_id" : { "$oid" : "507d95d5719dbef170f15bfd" }, "name" : "AC3 Case Red", "type" : [ "accessory", "case" ], "color" : "red", "price" : 12, "warranty_years" : 0.25, "available" : true, "for" : "ac3" }         { "_id" : { "$oid" : "507d95d5719dbef170f15bfe" }, "name" : "Phone Service Basic Plan", "type" : "service", "monthly_price" : 40, "limits" : { "voice" : { "units" : "minutes", "n" : 400, "over_rate" : 0.05 }, "data" : { "units" : "gigabytes", "n" : 20, "over_rate" : 1 }, "sms" : { "units" : "texts sent", "n" : 100, "over_rate" : 0.001 } }, "term_years" : 2 }         { "_id" : { "$oid" : "507d95d5719dbef170f15bff" }, "name" : "Phone Service Core Plan", "type" : "service", "monthly_price" : 60, "limits" : { "voice" : { "units" : "minutes", "n" : 1000, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "term_years" : 1 }         { "_id" : { "$oid" : "507d95d5719dbef170f15c00" }, "name" : "Phone Service Family Plan", "type" : "service", "monthly_price" : 90, "limits" : { "voice" : { "units" : "minutes", "n" : 1200, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "sales_tax" : true, "term_years" : 2 }         { "_id" : { "$oid" : "507d95d5719dbef170f15c01" }, "name" : "Cable TV Basic Service Package", "type" : "tv", "monthly_price" : 50, "term_years" : 2, "cancel_penalty" : 25, "sales_tax" : true, "additional_tarriffs" : [ { "kind" : "federal tarriff", "amount" : { "percent_of_service" : 0.06 } }, { "kind" : "misc tarriff", "amount" : 2.25 } ] }      When I try to import this file in Mathematica, it's an error:               Import["C:\\Users\\Steeve Brechmann\\Desktop\\products.json", "JSON"]     Import::fmterr: Cannot import data as JSON format. >>      I've imported successfully this file in a MongoDB database so I guess the file is ok. Any ideas? Steeve


How do I find the elements in a list that return the highest value for a function?

Suppose we have a list of values and a function `f`. I want to find which of the elements maximizes the return value of the function in Mathematica. Let call the function `ListMaxArg`. On the following example,               ListMaxArg[Total, {{1, 2, 3}, {10}}]      it should return `{10}`. Is there any such function in Mathematica's library? If not, what is the simplest way to write it? I can for sure write the function using a loop, but I am looking for something more functional style.


Make a button that evaluates a function over and over

I would like to have a command "RedoButton" which would make a button (or whatever control is suitable) that when clicked would print the value of a certain function over and over _in the same place_. So for example `RedoButton["do it", RandomInteger[{1, 10}]` would produce a button that, when clicked, would produce a random integer of the sort required, clicking it again would produce a possibly different random integer where the old one was, and so on. I have tried `Toggle`, `Button`, and numerous other commands but can't make any of them work correctly.


Result about Context is inconsistent with the description of “Power Programming with Mathematica”

x = 5;     temp`x = 6;     Begin["temp`"]     {x, Global`x, temp`x}      The result in my Mathematica session is `{5,5,6}`, but it's `{6,5,6}` in "Power Programming with Mathematica". (Page 231)


Why can't I use Show with BoxWhiskerChart?

![Broken Plot](http://i.stack.imgur.com/hqChN.jpg) As you can see in the example image above, I am frequently (but not always) seeing broken line plots when I try to overlay them on top of another plot using `Show`. This is especially common when plotting on top of a `BoxWhiskerChart`, like above, but I have seen similar artifacts with other combinations of graphics. It seems like this is probably a bug, but is there a way to work around it? EDIT: As requested, here is example data and code that reproduces the plot:               d1 = {{380.85484658712056, 286.8907758484098,          277.5346417980861, -260.9698886255429, -212.00464593127498}, \         {110.64430107319674, 144.47675987473627,          99.93373512263015, -56.177881856948964,          29.868418465268505}, {43.12802057882277, -68.16017567325775,          14.084311318612794, -36.20880886565394, -81.87985320930875}, \         {106.99911157544254, -31.663203349930104, -27.570575917736175,          61.25746244652189,          0.07927149668211417}, {22.786524517448473, -40.71909598294233, \         -5.457645151349941, -43.881578084779825, -56.53761318830431}, \         {-23.848477320370613, 6.595731836165279, 49.84565391704327,          14.463305228579669,          1.7165492496714267}, {-24.233241726829753, -34.41986971239141,          71.77402199374153,          6.240151571212979, -9.893448889735769}, {27.530209189665232, \         -39.16537688719902, 7.934274688868037, 21.450252634259602,          22.436356176565518}, {5.815740478111099, -19.121655982833524,          6.276548184966871, -6.191562514728518,          8.163468204721694}, {-1.1095960641474583, -1.8024030708469272,          0.5884529855628465, 6.78776508911811,          3.2052724335758094}, {1.9945820939801755, -4.961791563938944,          0.7207552625366906, -23.034734413964447,          23.31037162230476}, {7.791172424307904*^-14, \         -2.810291307094996*^-14, 5.16543833023678*^-14,          1.6887681396769957*^-14, -6.281861164741391*^-14}};     d2 = {{-179.0813322830084, 168.63728065982806,          7.613650128893625, -52.78046442802247,          4.762591758605045, -5.301920135661192, -20.832115595725575, \         -4.066331598432242, 14.421498996215757, 2.7434661239850864,          4.4509223705660865, 6.406095853462969*^-14}};     Show[BoxWhiskerChart[d1, "Outliers"], ListLinePlot[d2]]


Unexpected differences with various uses of NormFunction

I would expect all of the following to give the same answer (`2.12467`) but only half of them give this answer. The others seem to be using the default `NormFunction:>(Norm[#,2]&)`. Can anyone explain this?               α = 3;     n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> ((Null; Norm[#, α]) &)]     n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> ((Norm[#, α]) &)]     n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> (Norm[#, 3] &)]          Block[{α = 3},  n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> (Norm[#, α] &)]]     With[{α = 3}, n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> (Norm[#, α] &)]]     Module[{α = 3}, n /. FindFit[{1, 3, 9, 20}, x^n, n, x, NormFunction :> (Norm[#, α] &)]]          (* Outputs: 2.12467, 2.13284, 2.12467, 2.13284, 2.12467, 2.13284 *)


Getting Integrate to perform numerical integration

I am trying to calculate the mutual impedance of two antennas which is just a big integral. I defined my function in terms of my variable, but when I execute it, Mathematica runs for a while and then just gives back my original equation, just a little bit expanded. It does not show any errors, just runs for a while and spits out my unintegrated equation. My exact code is below:               (* this part is just setting up the equations I will be using in my integral *)     Sza[s_, θ_]            := s*Cos[θ]     Sya[s_, θ_, φ_]        := s*Sin[θ]*Sin[φ]     Sxa[s_, θ_, φ_]        := s*Sin[θ]*Cos[φ]     ρa[Sx_, y0_, Sy_]      := Sqrt[Sx^2 + (y0 + Sy)^2]     ra[ρ_, z0_, Sz_]       := Sqrt[ρ^2 + (z0 + Sz)^2]     r1a[ρ_, z0_, Sz_, L1_] := Sqrt[ρ^2 + (z0 + Sz + L1/2)^2]     r2a[ρ_, z0_, Sz_, L1_] := Sqrt[ρ^2 + (z0 + Sz - L1/2)^2]          (* Defining the integral equation *)     R21[ρ_, r1_, Sz_, z0_, L1_, r2_, r_, Sx_, y0_, Sy_, L2_] := -30*     Integrate[         (((1/ρ^2)*(Sin[2*Pi*r1]*((Sz + z0 + L1/2)/r1) +              Sin[2*Pi*r2]*((Sz + z0 - L1/2)/r2) -              2*Cos[Pi*L1]*Sin[2*Pi*r]*((Sz + z0)/r))*(Sx^2 + y0*Sy +              Sy^2)) + ((2*Sin[2*Pi*r]*Cos[Pi*L1]/r - Sin[2*Pi*r1]/r1 -              Sin[2*Pi*r2]/r2)*Sz))*(Sin[2*Pi*(L2/2 - Abs[s])]/s),         {s, -L2/2, L2/2}]          (*Calculating constants *)     Sz = Sza[s, 1/4*Pi]     Sy = Sya[s, 1/4*Pi, 1/4*Pi]     Sx = Sxa[s, 1/4*Pi, 1/4*Pi]     ρ  = ρa[Sx, .6175, Sy]     r  = ra[ρ, .103, Sz]     r1 = r1a[ρ, .103, Sz, .395]     r2 = r2a[ρ, .103, Sz, .395]          (*Executing the integration equation, with constants plugged in *)     R21[ρ, r1, Sz, .103, .395, r2, r, Sx, .6175, Sy, 1.63]      After that, it ran for about 2 hours, and then just spit out `R21` in its integration form. What I am doing wrong?


Rewriting For loop to FoldList or similar

In CrossValidated, the answer to a question on prediction of number of viewers of Gangnam Style is given in R. I have mapped the answer directly to _Mathematica_ :               S0 = 10000000; a = 0.00000005; b = 0.01; k = 1.2;     views = {{0, 0}}; S = S0; inf = 1;     For[t = 1, t < 365, t++, dS = -a*inf*S;       dinf = a*inf*S - b*inf;       S = S + dS;       inf = inf + dinf;       noviews = Last[Last[views]] + k inf;        views = Append[views, {t, noviews}]];     ListPlot[views]      ![Result from function](http://i.stack.imgur.com/SOsyb.jpg) However, this doesn't really feel or look like good _Mathematica_ code. I tried to follow the advice in Alternatives to procedural loops and iterating over lists in Mathematica. But I get stuck in trying to create the function that the `FoldList` should use. It seems like the solution would be to have `FoldList` create a number of lists, one for each "state" variable. So my question is: how do I rewrite the `For` loop that has a number of "state" variables and where the output depends on both these variables and earlier values of the output?


Replacing graph nodes with matrices

I would like to label a graph with matrices. Suppose the graph is simple: * * * ![GraphPlot](http://i.stack.imgur.com/qLA4M.png) * * * And I have an array **mats** that contains the labels for vertices 1,2,3,4 (these are just random 0-1 matrices; ignore the entries): * * * ![mats](http://i.stack.imgur.com/05V6s.png) * * * What is the appropriate syntax to employ `VertexRenderingFunction` to achieve having each vertex `i` replaced by (an image of) the `MatrixForm` of `mats[[i]]`? Or perhaps I am looking in the wrong direction entirely...? I know this is elementary; thanks for your patience & advice!


Name of current Notebook

I've searched the documentation, this forum and with google, but I was not able to find how to ask _Mathematica_ to give back the name of the current notebook file one is working on. Perhaps something with `EvaluationNotebook[]`, but that gives a `NotebookObject`. How is it possible to use this information to retain just the filename?


Adding headers to sublists

I would like to transform the following list:               data = {{0, A1, 1}, {1, C1, 2}, {1, C2, 3}, {3, C4, 1}, {0, A2, 1}, {1, C2, 1},             {0, A1, 4}, {1, C1, 1}, {2, C2, 1}}      into another list like this:               output = {{A1, 1, 0, A1, 1}, {A1, 1, 1, C1, 2}, {A1, 1, 1, C2, 3}, {A1, 1, 3, C4, 1},               {A2, 1, 0, A2, 1}, {A2, 1, 1, C2, 1}, {A1, 4, 0, A1, 4}, {A1, 4, 1, C1, 1},               {A1, 4, 2, C2, 1}}      Basically, the first column indicates the level, 0 being the head level of a bill of material and would like to put the header item and header quantity as columns besides the components for easier computation further along. Thanks.


How to create bar or pie chart from sql query where legend automatically uses list [[2]] element

This is my query:               totalCntLByCnty =    {#[[1]], #[[2]] } & /@ SQLExecute[conn, "     SELECT  COUNT(*), c.description     FROM name_loc f     INNER JOIN countries       c ON f.fk_cnty_id  = c.id     INNER JOIN identifiers     i ON f.fk_ident_id = i.id       GROUP BY f.fk_cnty_id     LIMIT 5     "]      I get this: I got: `{{2, "ANDORRA"}, {33, "UNITED ARAB EMIRATES"}, {14, "ANGUILLA"}, {1, "ARMENIA"}, {78, "ARGENTINA"}}` Normally I would not use 'limit 5' I'm using it now to limit the return for this question. I need to build a barchart where the name of the country returned is automatically used as a legend at the bottom of the chart, and count (vertical axis) is just 'Total's'. I do not or can not use something like:               ChartLegends -> Placed[{"ANDORRA", "UNITED ARAB EMIRATES", "ANGUILLA",      "ARMENIA", "ARGENTINA"}, Bottom]      Because the name of the countries will change depending upon certain search criteria. I will be using either a bar chart or a pie chart to display the data. My question is: 1) How can I generate the chart so the legend uses the name returned from the "#[[2]] list? 2) Is there a better chart or way of displaying this data? I am using Mathematica 8 Thank you for any help.


Error loading shared library libML64i3.so

I'm trying to call Mathematica from C. I'm following the example http://mathematica.stackexchange.com/a/32864/14301 with http://reference.wolfram.com/mathematica/tutorial/MathLinkDeveloperGuide- Unix.html#725481284 The code I have is: mlcall.c (identical to what i linked)               #include <mathlink.h>     #include <stdio.h>          int main(int argc, char *argv[]) {         MLENV env;         MLINK link;         int errno;         int packet;              env = MLInitialize(0);              /* consider using MLOpenString instead here: */                  link = MLOpenArgcArgv(env, argc, argv, &errno);              MLActivate(link);              /* send 42+137 using the full form Plus[42, 137] */         MLPutFunction(link, "Plus", 2);         MLPutInteger(link, 42);         MLPutInteger(link, 137);         MLEndPacket(link);              /* get packets until we find a ReturnPacket or error */         while ((packet = MLNextPacket(link)) && packet != RETURNPKT)             MLNewPacket(link);              if (MLError(link))             printf("error.\n");         else {             int result;             MLGetInteger(link, &result); /* we know that the result is an integer in this case */             printf("result: %d\n", result);         }              return 0;     }      and makefile:               MLINKDIR = /opt/Mathematica-9.0/SystemFiles/Links/MathLink/DeveloperKit     SYS=Linux-x86-64     CADDSDIR = ${MLINKDIR}/${SYS}/CompilerAdditions          INCDIR = ${CADDSDIR}         LIBDIR = ${CADDSDIR}          MLLIB = ML64i3          EXTRALIBS = -lm -lpthread -lrt -lstdc++ # Set these with appropriate libs for your system.          mlcall: mlcall.c         $(CC) -O mlcall.c -I$(INCDIR) -L$(LIBDIR) -l${MLLIB} ${EXTRALIBS} -o $@          clean:         rm mlcall      Output of make is:               cc -O mlcall.c -I/opt/Mathematica-9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux-x86-64/CompilerAdditions -L/opt/Mathematica-9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux-x86-64/CompilerAdditions -lML64i3 -lm -lpthread -lrt -lstdc++  -o mlcall      So no errors, but when I try to run mlcall with either `./mlcall` or `./mlcall -linkmode launch -linkname "/usr/bin/MathKernel"` I get the following error:               ./mlcall: error while loading shared libraries: libML64i3.so: cannot open shared object file: No such file or directory      I do have `libML64i3.so` in the directory `/opt/Mathematica-9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux-x86-64/CompilerAdditions -L/opt/Mathematica-9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux-x86-64/CompilerAdditions` and I also tried to copy it to the directory I was running `mlcall` in. What should I do?


Block attributes of Equal

I answered “Equating matrices (or higher order tensors) element-wise” with:               {A, B} = RandomInteger[3, {2, 4, 3, 2}];          Block[{Equal},       SetAttributes[Equal, Listable];       A == B     ]      > >     {{{False, False}, {False, True},  {False, False}}, >      {{False, True},  {False, False}, {True, False}}, >      {{False, True},  {False, False}, {False, False}}, >      {{False, False}, {False, False}, {True, False}}} >   But it fails if `A` and `B` are packed arrays:               {A, B} = Developer`ToPackedArray /@ {A, B};          Block[{Equal},       SetAttributes[Equal, Listable];       A == B     ]      > >     False >   One may observe that setting `SetAttributes[Equal, Listable]` outside of `Block` also fails to effect the `Listable` behavior. This also applies to `Unequal` and `SameQ`. This is of interest to me, but my prime concern is that despite the `Block`, `Equal` is being recognized and receiving special treatment. I expected symbols localized with `Block` to behave generically. * * *   * How does this fit into the main evaluation loop?   * How can I get get _true_ "blocking" of a symbol such that it behaves generically within a scoping construct?   * What other symbols besides `Equal`, `Unequal`, and `SameQ` are handled differently?


ordering of functional eigenvalues

Is there any order to the symbolic eigenvalues of a matrix returned by the command `Eigenvalues[...]`? While numerical eigenvalues are listed in descending order (i.e., $\lambda_1 \ge \lambda_2 \ge \cdots \ge \lambda_N $), this is not the case for functional eigenvalues (see two examples below). The examples suggest that the ordering may be the reverse, although this cannot be positively inferred from two examples. Do functional eigenvalues have the order $\lambda_1 \le \lambda_2 \le \cdots \lambda_N$, another ordering (based on eigenvectors, for instance), or no ordering at all? * * * Examples showing that functional eigenvalues are not sorted in descending order. (1) As a trivial example,               Eigenvalues[{{Exp[x], Exp[x]}, {Exp[x], Exp[x]}}]      returns $\left\\{0,2 e^x\right\\}$. For real inputs, the latter is always greater than or equal to the former. (2) As another example, consider               Eigenvalues[{{Exp[x], Exp[x]}, {Exp[x], Exp[x/2]}}]      which returns $$\left\\{\frac{1}{2} \left(e^{x/2}+e^x-e^{x/2} \sqrt{1-2 e^{x/2}+5 e^x}\right),\frac{1}{2} \left(e^{x/2}+e^x+e^{x/2} \sqrt{1-2 e^{x/2}+5 e^x}\right)\right\\}.$$ Again, for real inputs, the latter is always greater than or equal to the former:               Plot[%, {x, -10, 10}]      ![enter image description here](http://i.stack.imgur.com/ZBwqn.png)


Random data generator

Inspired by Quality of random numbers I would like to set up a true random data generator in _Mathematica_. My idea is to use the static from an open microphone. I recall reading about extracting the "most random" data from such a source but I do not remember the specifics. Presumably all recognizable patterns and frequencies would need to be filtered out, and the remaining data "balanced" (for lack of a better term) to get a uniform distribution. I would like to know how this may be accomplished and what quality and quantity of random data I could expect to to gather. If the mic static idea is not valid, I would like to know what other options exist.


Fluid mechanics problem concerning flow over a wedge

Below is the code I am using to generate a velocity profile and temperature profile for flow over a wedge.               sol[ξ_] :=        NDSolve[{        D[f[η], {η, 3}] + (m + 1)/2 f[η] f''[η] + m* (1 - (f'[η])^2) == 0,        D[θ[η], {η, 2}] + f[η] θ'[η]*(m + 1)*0.5*0.7 == 0,        θ[0] ==  1, θ[5] == 0, f[0] == -2/(m + 1)*bsp,         f'[0] == 0,         f''[0] == ξ},         {f[η], θ[η], θ'[η]}, {η, 0, 9}]           m = β/(2 π - β);     m = 0;     DFEnd[ξ_?NumericQ] := D[f[η] /. sol[ξ], {η, 1}] /. η -> 9     SOL1[bsp_] := FindRoot[DFEnd[ξ] == 1, {ξ, 0.5}]          plt1 =        Plot[Evaluate[             Flatten[Table[D[f[η] /. sol[ξ /. SOL1[bsp]], {η, 1}], {bsp, 0, -1, -0.25}]] /.                η -> x],          {x, 0, 9},           PlotLegends -> Range[BSP = 0, BSP = -1, BSP = -0.25],          PlotRange -> All]     plt2 =        Plot[Evaluate[              Flatten[Table[D[θ[η] /. sol[ξ /. SOL1[bsp]], {η,  1}], {bsp, 0, -1, -0.25}]] /.                 η -> x],          {x, 0, 5},          PlotLegends -> Range[0, 1, .25],          PlotRange -> All]      Here is how I am generating values of `f''[0]`, varying the `bsp` parameter for various values of `m`. I wish to generate a table having values of `η` for which `f'[η]` is equal to 0.99 for different values of `bsp` for a given `m`, and then I wish to vary `m` as well. Let's say, for example, I first want a table for `m = 0`, where `bsp` ranges over `{-2.5,2.5,0.5}`; then `m = 1`, etc. Is there a way to generate such a table for `f'[η] == 0.99` and similarly `θ'[0]` for different values of `m` and `bsp`.


GUI of a Karnaugh Map (2)

Adopting kguler's answer to my previous question, I managed to get the simplified map by using _Mathematica_ 's build-in function `BooleanMinimize`. The tough job left is to produce the circles showing the grouping of the related terms as seen from most textbooks. Insight on how to accomplish this? Any help would be much appreciated.               labels = {"00", "01", "11", "10"};     lab = {"0", "1"};     Clear[a, b, c, x, y];     elem = {{! a && ! b && ! c, ! a && ! b && c }, {! a && b && ! c, ! a &&           b && c }, { a && b && ! c, a && b && c }, { a && ! b && ! c,          a && ! b && c } };     res = {};     RES = {};     frame = Graphics[{         Line@Table[{{i, 0}, {i, 4}}, {i, 0, 2, 1}],         Line@Table[{{0, i}, {2, i}}, {i, 0, 4, 1}],          Table[Text[           labels[[3 - i + 1]], {-0.3, i + 0.3}], {i, {0, 1, 3, 2}}],          Table[Text[lab [[i + 1]], {i + 0.75, 4.25}], {i, {0, 1, 0, 1}}],          Line[{{0, 4}, {-0.75, 4.75}}],          Text[Style[ "A B" , 12], {-0.5, 4.}],          Text[Style["C", 12], {0., 4.5}]}, ImageSize -> {100, 200}];          Row[{Manipulate[        arrX = ConstantArray[0, {2, 4}];             EventHandler[Dynamic[mat = Reverse[Transpose[arrX]];          Show[           frame,           MatrixPlot[            mat,            Mesh -> All,            ImageSize -> {100, 200},            PlotRangePadding -> 0,            FrameTicks -> None,            ColorRules -> {1 -> None, 0 -> None}],            Epilog -> {MapIndexed[              If[#1 == 1, Text[Style[#1, Bold, 20, Red], #2 - {.5, .5}],                 Text[""]] &, arrX, {2}              ]}           ](* Show *)          ],  (* Dynamic *)         {"MouseClicked" :> (            pos = Ceiling[MousePosition["Graphics"]];            arrX = ReplacePart[arrX, pos -> 1 - arrX[[Sequence @@ pos]]];            arrY = Reverse[Transpose[arrX]];            res = Flatten[Pick[elem, arrY, 1]];            RES = BooleanMinimize[ Or @@ res ];            map = RES /. {! a -> "\!\(\*OverscriptBox[\(A\), \(_\)]\)",                 a -> "A", ! b -> "\!\(\*OverscriptBox[\(B\), \(_\)]\)", b -> "B",                ! c -> "\!\(\*OverscriptBox[\(C\), \(_\)]\)", c -> "C" };            map = map /. { x__ && y__ -> x y  };            map = map /. { x__ || y__ -> x + y };            )          }         ],        Paneled -> False,        AppearanceElements -> None,        FrameMargins -> 0        ] ,       Dynamic@map}  ]      ![enter image description here](http://i.stack.imgur.com/T2011.gif) This page details the rules for the grouping together adjacent cells containing ones.


Checking if first derivative is zero at a given point

I have a function               V[a_, h_, tau_] := (Sqrt[3]/2) h (Sqrt[3] a + h/3 tau)^2      now I want to check, whether its first derivative is zero in a given point. Say for the solution               {a -> 8.47344, h -> 1.67718, tau -> 12.9438}      I tried               Dt[V[a, h, t], a, h, tau] /. {a -> 8.47344, h -> 1.67718, tau -> 12.9438}       Is this the proper way to show that? I use `V` in a system of equations, which I am trying to solve with Newton's method.


How do I treat elements in a list as variables inside a module?

I want to be able to assign values to a list element inside a module. For example if I have:               testscan[listin_] :=       Module[{zz},        Do[listin[[1]] = zz; Print[{zz, listin[[1]]}], {zz, 1, 2, 1}]]      Given:               testscan[{a, 1, 3, 1}]      Returns:               {1,a}          {2,a}      What I want it to return:               {1,1}          {2,2}      So its not just the output I care about, I want 'a' in this case to be able to reassigned to anything. Any ideas? Thanks a lot for your time. LH- it is indeed a that I want to modify. The page you linked to is on the right track, but doesn't quite give me what I need yet. For example using your setPart function: in:               foo = {a, 1, 3, 1};     setPart[foo, 1, xxx];     foo                                out:               {xxx, 1, 3, 1}                                                    But then for: IN:               Clear[listin];     testscan[listin_] :=       Module[{}, setPart[listin, 1, \[Pi]]; Print[{listin[[1]], listin}]]                                                                  testscan[{a, 1}]                                                            out:               {a,{a,1}}      So setPart doesn't seem to work inside modules as the way I have it. Can you offer my any further assistance? Again, thank you so much for your time. Leonid - I am fairly new to Mathematica so I wasn't sure about these subtleties, but now its pretty clear that indeed I am just trying to find workarounds instead of a proper solution. The 'true' problem I am working on is trying to scan a parameter space of varying numbers of parameters subject to some constraints (I am interested in any number of constraints just out of curiosity, but in reality no more than 2 constraints in the actual). So it would look something like : TestScan[c1,...,cm,{list1,....listn}] Where the ci are constraints and the list_i's take the form {x_i,x_i_initial, x_i_final, x_i_increment} that will be fed to a Do loop. For example I might have a constraint like x^2+y^2+z^2=1, I want to scan over values of y and z, solve for the corresponding values of x, then store all the possible solutions in a list. By putting the variables I want to scan over in an array it seems easier since then I can have Mathematica see the size of the array, and run the proper number of Do loops. Obviously if I just put the variables in a function like TestScan[c1,...,cm,x_i,x_i_initial, x_i_final, x_i_increment,....] it works, but I would have to change the code every time I change the number of variables in the constraints. So this to me boils down to my earlier question of how to make Mathematica see a part of a list as a variable that I can then increment in a Do loop inside a Module.Do you have any advice how I could achieve this without such work-arounds, and hopefully without bothering you any more? Thanks a ton for your time. DB


Specifying optional arguments with variables

Perhaps this is poor programming on my part, but I would like to create a function that uses a variable as an optional parameter:               var = 2;     f[a_:var] := {a}      The desired output would be:               f[]     (* {2} *)     var = 5;     f[]     (* {5} *)      However the optional `a` maintains the value of `var` when `f` was defined:               var = 2;     f[a_:var] := {a}     var = 5;     f[]     (* {2} *)     f[5]     (* {5} *)      I can work around this somewhat by making the optional value dynamic:               var = 2;     f[a_:Dynamic[var]] := {a}     f[];     (* {2} *)     var = 5;     (* Above output updates to 5 *)      I can imagine having some fun with this type of behavior, but it is not what I want at the moment. Is it possible to set an optional parameter that can be updated? I'll also happily accept an answer that tells me why this would be a bad idea.


Get the neighboring vertices and incident edges from a vertex in a graph

I need to get the neighboring vertices and incident edges from a vertex in a graph. I assume `NeighborhoodVertices` can be used for the former. Anything better? Or given something like `{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 3 \[UndirectedEdge] 1}`, how to directly get these information? Can I do list matching to some pattern?


How to write a function to add edges or vertex to a graph

I need to add either a vertex or an edge to a graph, and also sometimes, vertices or edges, or a mixture of the two. How to write a function for this?


How to plot a curve with border around the line?

This can be useful if the curve is passing over both dark and light backgrounds (like well-done subtitles in movies).


Plotting an function defined by an integral

How can I plot a function defined by an integral. More specific, I have the following equation: $$ T = \frac{1}{\pi}\int\sqrt{\sin^2\;\arccos\left(-\frac{E}{2}\right)-\sin^2\frac{ϕ}{2}}^{-1}\mathrm{d}ϕ $$ Translating to Mathematica input:               T[E_]:=(1/Pi)*NIntegrate[(Sin[ArcCos[-E]/2]^2 - Sin[ϕ/2]^2)^(-0.5), {ϕ, 0, ArcCos[E]/2}]      Now I need to plot TxE. How do I do it?


Mathematica Bifurcation

Continuing with the same question I have posted earlier I would like to find the equation of the stable fixed point curve using my graph, i.e. from the curve somehow find the equation for $x=f(x)$. I have been trying using Solve but I keep getting errors. I would also like to find the value of $a$ where bifurcation begins, i.e. it becomes unstable. It looks like about $-1.5$.               f[c_][x_] := x^2 + c;          [c_] := Take[NestList[f[c], 0., 1500], -1]     plotdata = Table[Flatten[{i, d[i]}], {i, -2, 0.1, 0.0011}];     ListPlot[plotdata, PlotRange -> All, Frame -> True, Axes -> True]


Change Default Font Color of Commands

I encountered to two problems with _Mathematica_ : one: How can I change the default font color of commands and functions in _Mathematica_ (which is black) to another color, so that whenever I wanted to write that command, the color of that, changes automatically? Actually, how can I set all define commands or functions with a specified color? Second: I want to copy a command from _Mathematica_ into _Microsoft Word_ For example the bellow one:               Plot[x^2 + 1, {x, 1, 5}]      I have colored `Plot` with Red and `x` is shown Green by default in _Mathematica_. But when I copy this command to _Word_ , all of those will be black; and if I want them colored I have to color them in the _Word_ again.


Lists not being recognized correctly within manipulate

I've created a keyboard-free panning system within Mathematica. The code does the job, but I continually get errors in relation to it, and I cannot seem to get it to perform within a CDF because of it. The main line of code that seems to be problematic is               ViewCenter -> {{1/2, 1/2, 1/2},                     {Dynamic[x = CurrentPosition[[1]] + panvalue[[1]]],                      Dynamic[y = CurrentPosition[[2]] - panvalue[[2]]]}}      It may look messy, but basically it maps the center of a graphic, `(1/2,1/2,1/2)`, to a new two-dimensional point based on the click and drag of the mouse. This seems fairly logical to me, but some may notice the seemingly unnecessary use of `Dynamic` in the above. These are created because the code only works until I manually interact with the craft through the use of `Shift` or `Ctrl`. Meaning, I can freely pan with my right-click and drag function until I decide to use the built in Mathematica interactons. I think I may have discovered part of the error, in that the errors that I mentioned before say that I am calling `ListQ` with 0 arguments, but this function appears nowhere in my code. Furthermore, I was originally getting errors saying that `CurrentPosition[[2]]` and the other references to list elements were longer than the depth of their objects. However, with these all being references to points, shouldn't they have as many elements as I'm referencing? Any ideas on what could be the source of my issue? I did my best to simplify the code, but it's still quite extensive. Feel free to ask for clarification and I will do my best. Looking at the Initialization should help a little. Without the `Dynamic` around the Position updating,               Manipulate[     EventHandler[     Dynamic[Show[graphic,      ViewCenter -> {{1/2, 1/2,         1/2}, {x = CurrentPosition[[1]] + panvalue[[1]],         y = CurrentPosition[[2]] - panvalue[[2]]}}]],     If[CurrentValue["AltKey"],     {{"MouseDown",        1} :> (a = CurrentValue[MousePosition]), {"MouseDragged",        1} :> {b = CurrentValue[MousePosition], drag = b - a,        panvalue = {drag[[1]]/(pt[[1]]),          drag[[2]]/(pt[[2]])}}, {"MouseUp", 1} :> {drag = {0, 0},        panvalue = {0, 0}, CurrentPosition[[1]] = x,        CurrentPosition[[2]] = y}}]], SynchronousUpdating -> True,      Initialization :> (CurrentPosition = {1/2, 1/2}; panvalue = {0, 0};      pt = CurrentValue[ImageSize]; drag = {0, 0}; a = {0, 0};      b = {0, 0})]      Feel free to try this, but it will likely allow you to pan by clicking and dragging when the `Alt` key is depressed, but only until you manually interact with the graphic. Adding `Dynamic` around the `ViewCenter` argument fixes the problem, but gives errors.


How to compile Heike's winding number function?

Heike gave the following function for winding number:               winding[poly_, pt_] :=       Round[(Total@Mod[(# - RotateRight[#]) &@(ArcTan @@ (pt - #) & /@ poly),         2 Pi, -Pi]/2./Pi)]      I attempted to compile it as follows:               winding2 := Compile[{{poly, _Real, 2}, {pt, _Real, 1}},        Round[(Total@Mod[(# - RotateRight[#]) &@(ArcTan @@ (pt - #) & /@ poly),          2 Pi, -Pi]/2./Pi)]]      Applied to the following simple problem, the compiled version gives error messages:               poly = {{0., 0.}, {10., 0.}, {10., 6.}, {0, 6}, {0., 0.}};     pt = {5., 3.};      winding2[poly, pt]      The error messages include:               Compile::cpapot: Compilation of ArcTan@@(ptCompile`GetElement[poly,System`Private`CompileSymbol[0]])      is not supported for the function argument ArcTan. The only function arguments supported are      Times, Plus, or List. Evaluation will use the uncompiled function. >>     CompiledFunction::cfse: Compiled expression 6.283185307179586` should be a machine-size integer. >>     CompiledFunction::cfex: Could not complete external evaluation at instruction 1;     proceeding with uncompiled evaluation. >>      Where am I going wrong?


Changing some stuff to Kruskal's Algorithm

I'm trying to modify this algorithm: http://demonstrations.wolfram.com/ConnectingTownsUsingKruskalsAlgorithm/ The thing is that I want to receive a Graph (declared outside, with all its vertex, edges and weights) in the Kruskal's function and start from there, using maybe a WeightedAdjacencyMatrix[G] and sort the weights and returning them. It's just a practice I want to do, because I'm learning Mathematica, so I'm still a noob with this. To be more specific with my question, I just want to know where and how I can replace parts from the code, with the things I mentioned above. This is my idea, of course without the Kruskal's implementation:               G = Graph[{a \[UndirectedEdge] b, a \[UndirectedEdge] d,      a \[UndirectedEdge] f, b \[UndirectedEdge] c,      b \[UndirectedEdge] d, b \[UndirectedEdge] e,      c \[UndirectedEdge] e, c \[UndirectedEdge] g,      d \[UndirectedEdge] e, d \[UndirectedEdge] f,      d \[UndirectedEdge] g, e \[UndirectedEdge] g,      f \[UndirectedEdge] g},      EdgeWeight -> {5, 6, 7, 5, 5, 4, 3, 3, 2, 2, 3, 1, 2},      VertexLabels -> "Name", ImagePadding -> 10]      Kruskal[G]


Simultaneously running the same .m file with different inputs

I have my _Mathematica_ code in a `.m` file and I run it from the command line with some parameters. I was wondering, if there is no overlap in input and output files, can I run the same `.m` file simultaneously with different inputs? Will this create any problems? My code is pretty huge, so I don't want to try that unless I am sure. I use the following command on the unix/linux commandline:               for i in $var     do     math -noprompt -script "scriptname.m" "parameter1" "parameter2"     done      I would like to run something like:               for i in $var     do     math -noprompt -script "scriptname.m" "parameter1" "parameter2" &     done      So that they would run in parallel. Is this possible?


Why does Rescale performance vary significantly based on the real number values in a list?

I have a list of the form:               testList = Table[{Flatten[RandomReal[{-200, 200}, {1, 2}], 1], RandomReal[{-200, 200}, {69, 2}]}, {i, 1, 100}];      And I would like to perform the following rescaling operation very quickly:               Rescale[testList, {-160 Sqrt[5], 160 Sqrt[2]}] // AbsoluteTiming      And indeed we see that this takes about $\approx 1$ millisecond. However, if we manually specify testList:               riggedTestList = {{72.0003, 254.632}, {{0., 0.}, {164.523, -1.48019}, {-36.4013, -1.6529}, {-30.6006, -9.68836}, {79.1769, -9.38496}, {127.414, -13.3351}, {26.2267, -14.9839}, {101.471, -17.2131}, {112.759, -20.2044}, {140.786, -20.3125}, {152.117, -23.4485}, {171.028, -28.6424}, {128.855, -34.8548}, {67.2216, -48.2581}, {-58.5145, -53.227}, {147.275, -52.8399}, {-2.11577, -54.7374}, {160.367, -57.3066}, {-43.8697, -59.9146}, {50.3993, -63.4993}, {105.478, -64.6626}, {-38.5779, -73.1765}, {167.692, -74.2231}, {38.1779, -75.0274}, {182.719, -75.3023}, {101.273, -76.3709}, {91.2674, -78.7477}, {140.126, -83.058}, {167.292, -83.068}, {-30.6985, -90.7144}, {73.0603, -91.5605}, {15.3827, -93.4644}, {168.049, -97.4066}, {101.349, -97.9227}, {148.875, -105.038}, {-27.7536, -106.1}, {119.991, -110.415}, {170.865, -110.703}, {-1.03466, -111.89}, {96.2519, -121.383}, {179.463, -127.087}, {-62.9256, -127.913}, {172.077, -131.731}, {-41.8538, -137.851}, {171.768, -143.748}, {28.4562, -146.02}, {71.0586, -145.51}, {149.767, -146.569}, {37.6894, -150.356}, {-26.1955, -159.44}, {-41.9501, -163.069}, {135.019, -164.213}, {-62.5847, -172.048}, {7.02217, -174.589}, {133.175, -175.744}, {0.392205, -184.99}, {56.418, -189.734}, {83.9584, -196.068}, {-9.36728, -198.523}, {141.564, -197.764}, {43.6112, -200.002}, {133.577, -201.431}, {16.5308, -203.89}, {79.8118, -207.938}, {178.305, -210.113}, {-45.2895, -216.227}, {-4.60035, -234.998}, {3.16025, -240.952}, {78.6896, -248.948}}};          riggedTestList = Table[riggedTestList, {i, 1, 100}];      And then attempt the same rescale on this array with the same dimensions as testList:               Rescale[riggedTestList, {-160 Sqrt[5], 160 Sqrt[2]}] // AbsoluteTiming      The `Rescale` operation takes $\approx 33$ milliseconds, a difference of over an order of magnitude. How could this be the case? Both `Developer`PackedArrayQ[testList]` and `Developer`PackedArrayQ[riggedTestList]` return `False`, so I don't think it's a list packing issue?


Is there a reason why some specific arrangement of scattered grid points would yield bad RBF (Obtuse package) interpolation results?

I have an arrangement of grid points given by the figure below (the datagrid data is posted below at the end of the post): ![Scattered Grid Point Positions](http://i.stack.imgur.com/AZhZK.gif) They correspond to electrode positions of an EEG signal. I am interpolating the field of points using the RBF method in the Obtuse package (the data in data3dznobp is copied at the end of the post).               fun = Interpolation[data3dznobp, Method -> "RBF",        DistanceFunction -> EuclideanDistance,        RadialBasisFunction -> Automatic]      Running a contour plot of the data yields strange results:               Show[ContourPlot[       fun[x, y], {x, Min[Transpose[datagrid[[Range[63]]]][[1]]],        Max[Transpose[datagrid[[Range[63]]]][[1]]]}, {y,         Min[Transpose[datagrid[[Range[63]]]][[2]]],        Max[Transpose[datagrid[[Range[63]]]][[2]]]},        ColorFunction -> "PigeonTones"],       ListPlot[datagrid, PlotMarkers -> {\[FilledCircle], 7},        PlotStyle -> {Black}]]      ![RBF interpolation: visibly wrong](http://i.stack.imgur.com/oaSBS.gif) A simple ListContourPlot gives an idea of what the data should look like:               ListContourPlot[Transpose[Partition[Flatten[data3dznobp], 3]],       ColorFunction -> "PigeonTones"]      ![List Contour Plot](http://i.stack.imgur.com/TEklJ.gif) The data is as follows:               datagrid={{-18, 255.55}, {0, 127.8}, {-39, 166.665}, {-54, 255.555}, {-72,        319.445}, {-69, 197.22}, {-45, 88.89}, {-90, 127.78}, {-90,        255.555}, {-108, 319.445}, {-111, 197.22}, {-135, 88.89}, {180,        127.78}, {-141, 166.665}, {-126, 255.555}, {-162, 255.555}, {180,        255.555}, {162, 255.555}, {141, 166.665}, {126, 255.555}, {108,        319.445}, {111, 197.22}, {135, 88.89}, {90, 127.78}, {90,        255.555}, {72, 319.445}, {69, 197.22}, {45, 88.89}, {39,        166.665}, {54, 255.555}, {18, 255.555}, {-38, 255.555}, {-23,        205.555}, {0, 191.665}, {-22, 138.89}, {-49, 208.335}, {-72,        255.555}, {-62, 138.89}, {0, 63.89}, {-90, 63.89}, {-90,        191.666}, {-108, 255.555}, {-118, 138.89}, {-158, 138.89}, {-131,        208.335}, {-144, 255.555}, {-157, 205.555}, {180, 191.665}, {157,        205.555}, {144, 255.555}, {131, 208.335}, {158, 138.89}, {180,        63.89}, {118, 138.89}, {108, 255.555}, {90, 191.665}, {90,        63.89}, {62, 138.89}, {72, 255.555}, {49, 208.335}, {22,        138.89}, {23, 205.555}, {38, 255.555}}          data3dznobp = {{{-18, 255.55}, -6.5739}, {{0, 127.8}, -6.2363}, {{-39,         166.665}, -3.5378}, {{-54, 255.555}, -5.0099}, {{-72,         319.445}, -0.0989}, {{-69, 197.22},        1.7936}, {{-45, 88.89}, -5.4844}, {{-90, 127.78}, -8.0216}, {{-90,         255.555}, -1.4105}, {{-108, 319.445}, -14.113}, {{-111,         197.22}, -1.6699}, {{-135, 88.89},        32.775}, {{180, 127.78}, -11.329}, {{-141,         166.665}, -2.9397}, {{-126, 255.555}, -15.252}, {{-162,         255.555}, -27.238}, {{180, 255.555}, -20.285}, {{162,         255.555}, -15.96}, {{141, 166.665}, -5.817}, {{126,         255.555}, -7.7154}, {{108, 319.445}, -6.8306}, {{111,         197.22}, -6.4974}, {{135, 88.89}, -5.9639}, {{90,         127.78}, -1.4527}, {{90, 255.555}, 0.0393}, {{72, 319.445},        2.0624}, {{69, 197.22}, -1.3429}, {{45, 88.89}, -2.615}, {{39,         166.665}, -2.3825}, {{54, 255.555}, -0.5267}, {{18,         255.555}, -8.0669}, {{-38, 255.555}, -6.5788}, {{-23,         205.555}, -0.8235}, {{0, 191.665}, -0.0289}, {{-22,         138.89}, -7.5299}, {{-49, 208.335}, -4.4647}, {{-72, 255.555},        0.4955}, {{-62, 138.89}, -5.9479}, {{0, 63.89},        0.9733}, {{-90, 63.89}, -0.3306}, {{-90, 191.666}, -5.5189}, {{-108,         255.555}, 6.2573}, {{-118, 138.89},        0.2364}, {{-158, 138.89}, -1.4894}, {{-131,         208.335}, -2.488}, {{-144, 255.555}, -31.974}, {{-157,         205.555}, -19.144}, {{180, 191.665}, -11.368}, {{157,         205.555}, -15.279}, {{144, 255.555}, -14.626}, {{131,         208.335}, -7.4315}, {{158, 138.89},        0.4834}, {{180, 63.89}, -5.1433}, {{118, 138.89}, -11.177}, {{108,         255.555}, -6.7141}, {{90, 191.665}, -3.6082}, {{90,         63.89}, -0.5016}, {{62, 138.89}, -2.5683}, {{72,         255.555}, -1.4882}, {{49, 208.335}, -2.9735}, {{22,         138.89}, -5.4577}, {{23, 205.555}, -7.9206}, {{38,         255.555}, -1.2869}}


How can I use "Save as (html)" and still render code as text?

I use notebook "Save as ... (html)" to convert my .nb to web. Formulas and plots get converted to images, which is fine. But code (input cells) get converted too into images. I would like people to be able to copy and paste my code, what can I do? Not sure how to use (in a generic scenario) what is mentioned in here. **edit** Got something very close working:                 Export[NotebookDirectory[] <> "/test.html",          EvaluationNotebook[], "HTML",         "ConvertReverseClosed" -> True,         "ConversionRules" -> {"Input" -> {"", DisplayForm[#] &,           ""}}]      if someone can improve on this it will be awesome. **second edit** This is the code I now have in a Palette. The context of the question is here. The code above is now in the proper place to export to HTML, including the CDFs, in (* 1 *).               PaletteNotebook[      Button[Style["Blog it", 12, FontFamily -> "Times"],       Module[{         nb = InputNotebook[],         fpath = NotebookDirectory[InputNotebook[]],         htmlName =           StringDrop[NotebookFileName[InputNotebook[]], -3] <> ".html",         generateCDF,         generateCDFs,         exportHTML         },        generateCDF[nb_, name_] := Module[{sel},          sel = SelectionMove[nb, Next, Cell];          Message[generateCDF::info, name];          Export[           FileNameJoin[{fpath, name}],           Notebook[{NotebookRead[nb]}],           "CDF"];          SelectionMove[nb, "Input", Next, CellStyle]          ];        generateCDF::info = "Generating CDF `1`";        generateCDFs[nb_] := Module[{sel, curID},          SelectionMove[nb, Before, Notebook];          sel = NotebookFind[nb, "Input", Next, CellStyle];          While[ MatchQ[sel, _NotebookSelection],           curID = CurrentValue[sel, CellID];           sel = Switch[CurrentValue[sel, CellTags],             _String, generateCDF[nb, CurrentValue[sel, CellTags]],             _, NotebookFind[nb, "Input", Next, CellStyle]             ];           ];          ];        exportHTML[nb_] := Module[{           rules = {             "Input" -> {               "\n
\n",               DisplayForm[#] &,               "\n
\n"               } (* 1 *)             }           },          Message[exportHTML::info, FileNameTake[htmlName]];          Export[           htmlName,           nb,           "HTML",           "CSS" -> None,           "MathOutput" -> "GIF",           "ConvertReverseClosed" -> True,           "ConversionRules" -> rules           ];          Message[exportHTML::done];          ];             exportHTML::info = "Generating HTML `1`";        exportHTML::done = "Export to HTML done";        generateCDFs[nb];        exportHTML[nb];        ],       Appearance -> "Palette"]      ]      The problem I have is that it generates funny characters in the HTML. I have tried several "encoding" options without luck. This is an example of what I get: ![web page screenshot](http://i.stack.imgur.com/ErA7x.png) I am not worried about the tags or formatting as I know how to deal with those in my Rails app or in CSS. But the "wrongly encoded" characters are my issue. I committed the sample.nb and sample palette code to github if any one wants to test it.


How to retrieve the parameters calculated and used by ImageAdjust?

When `ImageAdjust` is called with an image, i.e. with one parameter, it returns an automatically adjusted `Image`. I would like to retrieve the `{contrast, brightness, gamma}` values `ImageAdjust` has calculated and use them as starting points for a following interactive manipulation of these value using `ImageAdjust[img, {contrast, brightness, gamma}]`, i.e. with four parameters. An obvious solution is to perform an image histogram equalization and calculate `{contrast, brightness, gamma}`. However, since **_Mathematica_** provides the solution somewhere in its code and I intend to continue using `ImageAdjust` I would rather conform with the already implemented algorithm. Hence, my questions is: How do I retrieve the parameters calculated and used by `ImageAdjust` when it runs automatically?


How can I simplify $\log(512)$ to $9\log(2)$?

Can you explain me about the result of `Integrate`.               \!\(\*SubsuperscriptBox[\(\[Integral]\), \(1\), \(3\)]\(\*SubsuperscriptBox[\(\[Integral]\),          \(1\), \(3\)]\*FractionBox[\(9  v\), \(v + u\ v\)] \[DifferentialD]u \[DifferentialD]v\)\)     (*         2 log(512)     *)          % // Simplify     (*         2 log(512)     *)          % // FullSimplify     (*         18 log(2)     *)      However, I cannot FullSimplify this result               FullSimplify[Log[512]]     (*         log(512)     *)          Log[512] // N     (*         6.23832     *)          FullSimplify[2 Log[512]] // N     (*         12.4766     *)      So question $1$ is how to simplify `Log[512]` and why it doesn't simplify to `9Log[2]` by default.               9 Log[2] // N     (*         6.23832     *)      When I'm integrating by hand, I collect `9` or `18` easily, so I like the result `18 log(2)` , not `2 log(512)`, so I wonder why _Mathematica_ gives this result?


Generate PrimePower counting function

Is there a way to generate a counting function for prime powers - i.e. to create a similar function to `PrimePi`, but including prime powers. The following will, of course, generate a list of these numbers:               Select[ Range[1000000], PrimePowerQ]


"Evaluating" polynomials of functions (Symbols)

I want to implement the following type evaluation symbolically $$(f^2g + fg + g)(x) \to f(x)^2 g(x) + f(x) g(x) + g(x)$$ In general, on left hand side there is a polynomial in an arbitrary number of functions (e.g. $f, g^3 h, (f_1 + f_2 + f_3)^3, \dots$ and on the right hand side all the functions have been evaluated at the same element $x$. I would to define a function `eval` or a rule such that               In[1]:= (f^2g + fg + g)[x] // eval     In[2]:= f[x]^2 g[x]+ f[x] g[x] + g[x]      What is a good way of accomplishing this?


Cannot calculate with Dynamic variables in a grid

This is a prototype of a grading scheme. In reality it is bigger. The 10 pts in `initPtsPartA` comes from the school. The output cell should be deployed as a CDF file for the teacher. The teacher enters the points of the students and get a final mark. I have two questions. 1) How can I limit the `InputField` to allow for integer numbers between 0 and 10? If I enter anything else, say a negative number or a symbol, it should be cleared automatically. 2) In the Code Snippet section "Why don't the calculations work?" you see expressions with `Dynamic` variables which I need to work with. What is wrong? What is the solution?               DynamicModule[{       mark4 = 1/3, mark3 = 0.51, mark2 = 0.68, mark1 = 0.80,       initPtsPartA = {{10, 8, 10, 6}, {10, 5, 10, 5}, {10, 7, 10, 1}},       initPtsStudent, initPtsSchool, initPtsPartSum, numTable,        SchoolAPts, StudentAPts, StudentMinAchieved       },            numTable[x_, y_ /; OddQ[y]] := initPtsPartA[[x, y]];      numTable[x_, y_ /; EvenQ[y]] := InputField[Dynamic@initPtsPartA[[x, y]],        Number, ContinuousAction -> True, FieldSize -> 1];           initPtsPartSum[x_, y_, col_] := Dynamic@Total[initPtsPartA[[x ;; y, col]]];           SchoolAPts = (Total[initPtsPartA[[1 ;; 3, #]]] &) /@ {1, 3};      StudentAPts = (initPtsPartSum[1, 3, #] &) /@ {2, 4};          (* CODE SNIPPET, part of a longer program with `Graphics` involved. *)          Column[{Grid[         Append[ Array[numTable, {3, 4}], (initPtsPartSum[1, 3, #] &) /@            Range[4]]],             {"Just Testing Values:", initPtsPartSum[1, 3, 1],          initPtsPartSum[1, 3, 2], initPtsPartSum[1, 3, 3],          initPtsPartSum[1, 3, 4], "Student Pts only:", StudentAPts},             {"Why don't the calculations work?",          Dynamic[5*initPtsPartSum[1, 3, 2] + 10],            Dynamic[initPtsPartSum[1, 3, 4] > 30],          Dynamic[ Total[(initPtsPartSum[1, 3, #] &) /@ Range[4]]  ],          Dynamic[(Total@StudentAPts)]/(Total@SchoolAPts)},             {"Why don't the calculations work?",          StudentMinAchieved =           Dynamic[(StudentAPts[[1]]/SchoolAPts[[1]] >               mark4) && (StudentAPts[[2]]/SchoolAPts[[2]] > mark4)]}        }]      ]


Check whether a function of two variables is a probabilty distribution function

I have a function like this $f(x,y)=c\,y\,(y-x),\ \text{for}\ 0<x<2,\;-x<y<x$ and I need to find the value of $c$ such that $f(x,y)$ is a PDF. How can I do that? I know that the condition is double integral $f(x,y)=1$, but how can I impose that condition with _Mathematica_?


Incorrect means of order statistics for the standard normal distribution

Table[Mean[OrderDistribution[{NormalDistribution[], 4}, i]], {i, 1, 4}] // N     (* {-1.02938, -6.47326, 0.297011, 1.02938} *)      Above are the means of order statistics from a random sample of size $n=4$ from a standard normal distribution. Now, the problem is that the second element in the output is wrong; it should be `-0.2970111` because of symmetry. Also, the first and last elements of this array are equal in magnitude, but opposite in sign, due to symmetry. I'm using _Mathematica_ 8.0.


How to get string representation (like repr in Python)

I have a string variable. I want to obtain another string which contains the representation of the string variable content itself.               s = "a \n b"      I need to get a string containing the exact characters from above, including the escape character `\` and the `"`:               r = "\"a \\n b\""      Is there a function that can do that? The output should be similar to `repr("a \n b")` from Python: _This function makes an attempt to return a string that would yield an object with the same value when passed to`eval()`_


Random sample with gap sizes

Lets say I have 101 instances of `data` with multiple attributes. In particular case, one attribute has 7 unique values. I want to get `7<=n<=101` element positions from `data`, in a way that it contains at least 1 of each unique attribute case. First I get the example data and gather it by particular attribute:               data = Import["https://raw.github.com/BioGeek/aima/master/aima-data-read-only/zoo.csv"];     g = GatherBy[data, #[[18]] &];      List `g` of lists with element sizes `h`               h = Length[#] & /@ g (*{41,13,20,10,8,4,5}*)      Following works in the best case scenario               n = RandomInteger[{Length[g], Length[data]}]     l = RandomSample[RandomSample[#] & /@ IntegerPartitions[n, {Length[g]}], 1][[1]]     s = Table[RandomSample[g[[i]], l[[i]]], {i, 1, Length[g]}]     p = Sort[Position[data, #][[1]][[1]] & /@ #] & /@ s      Example result:               {{30,33},{8,62},{57,72,96,101},{14,73,78,82,86},{25,40,43,89},{26,27,53,90},{77,81,91,92}}      I can bruteforce, but I do not like the idea.               While[MemberQ[Table[h[[i]] >= l[[i]], {i, 1, Length[h]}], False],       l = RandomSample[RandomSample[#] & /@ IntegerPartitions[n, {Length[g]}], 1][[1]]]      How do I find random sample `l` so it is less then gap sizes `h`? **edit:** > If n = 7 ![enter image description here](http://i.stack.imgur.com/F9RG4.png) > If n = 21 ![enter image description here](http://i.stack.imgur.com/YFlzK.png) Problem is that `h = {41,13,20,10,8,4,5}` and even if `n = 11` then `l = {1,1,1,1,1,5,1}` that is invalid as there are not enough elements in that sublist. **edit 2**               f[data_List, n_Integer] := Module[{data1 = data, h, k},       k = RandomSample[DeleteCases[data1, Alternatives @@           (h = RandomChoice /@ GatherBy[data1, #[[18]] &])], n - 7];       h~Union~k]


Interpolating 2D data

> **Possible Duplicate:**   >  Interpolating 2D data with missing values I am trying to interpolate a 21x21 array of values. The 21x21 array sometimes has zero values and with the help of interpolation, I am replacing the zero with an appropriate value to get a reasonable output. My code is as follows:               binmeans     dataInt = Flatten[binmeans]               int = Interpolation[Select[Transpose[{Range[Length[dataInt]], dataInt}],         Last[#] != 0 &], InterpolationOrder -> 1]          l = 1;     gTable1 = Table[0, {binSize}, {binSize}];      For[x = 1, x <= binSize, x++,      For [y = 1, y <= binSize, y++,         gTable1[[x, y]] = int[l];       l++]      ]      I flatten the binmeans list, selected the values which are not zero, made an interpolation function, create another 21x21 table and populate it with the output of the interpolation function. The final output is as follows:![Interpolated output](http://i.stack.imgur.com/o6Pbq.png) And the expected output is this : ![Expected output](http://i.stack.imgur.com/Hpnwa.png) The Interpolation function works by interpolating values on the x-axis only. I am wondering how can I interpolate by considering all the points in the surrounding (x and y axis interpolation). Thank you