title: Revolving an axisymmetric image for volumetric rendering

text: I have a series of axisymmetric images of a jellyfish swimming in fluid. Overlaid on these images are plots of the Lagrangian coherent structures associated with swimming, which highlight the fluid transport and mixing: ![A plot of the jellyfish bell kinematics and the Lagrangian coherent structures](http://i.stack.imgur.com/W76CQ.jpg) Since these images are axisymmetric, I was wondering: is there a way that I can revolve a single two-dimensional image about its x axis, so as to create a three-dimensional surface, and then visualize this as a volumetric render? If possible, I'd like to retain the same colors as in the two-dimensional image, as they are significant. As well, I'd like to create a cut-away that removes a fourth of the volume, like in the following image: ![A three-dimensional plot of the jellyfish bell kinematics and the Lagrangian coherent structures](http://i.stack.imgur.com/7DP4F.jpg) I'm aware of the following posts: How to show solid bodies using volumetric rendering? and How to create blurred Graphics3D objects?. However, they don't cover a crucial step: how to do the x-axis revolution.


title: Mathematica File Organization

text: Last year I asked how to integrate notebooks to the documentation center in stackoverflow. Back then I was only interested in seeing those notebook and being able to search for them. Unfortunately, it has been painful to write the documentation because of the lack of a good organized stylesheet (Still working on a simple one that does the job). In any case, I would like to revisit part of this question by looking at complete tree of the file organization of a package. In the answers I posted I showed mainly the part for the documentation. ![example](http://i.stack.imgur.com/ogsPR.png) In the picture above I show the folder `SOPackage` which is supposed to be located either in `$UserBaseDirectory` or `$BaseDirectory`. Now that I know a little bit more of stylesheets, palettes and mathlink programs I would like to be able to incorporate them to applications. The question is, can anyone show a a complete tree of an application located in either `$UserBaseDirectory` or `$BaseDirectory` with the folders necessary to make everything work? (By everything I mean, documentation, mathlink/NETlink/LibraryLink programs, stylesheets, palettes and any other thing that you can think of). A place to start is at: http://reference.wolfram.com/mathematica/tutorial/MathematicaFileOrganization.html But it doesn't seem to have everything. The reason I found out about how to create the structure in the picture above was because of a link acl showed in one of his answers. To clarify again, the question at hand is: Can we show the complete structure of an application in `$UserBaseDirectory` that contains the directories where we put:   1. Documentation   2. Source Code for Mathlink/NETLink/LibraryLink (any other link)   3. Stylesheets   4. Palettes If you can think of anything else that would make the application more complete please add it. At some point I wanted to just ask if it was possible to put stylesheets in an application instead of               $UserBaseDirectory <> "/SystemFiles/FrontEnd/StyleSheets/";      but instead I decided to make a question that can bring all of us the complete file organization for a complete application in _Mathematica_.


title: How to minimize a list of data points?

text: I have a list called diff1:               axis = Table[i, {i, 1, 20}];     data1 = Table[Sin[i/(2*Pi)], {i, 1, 20}];     model1[t_] := a*Sin[b*t];     model1points = Map[model1, axis];     diff1 = (model1points - data1)^2;      One example of the entry of diff1: (a Sin[3 b] - Sin[3/(2*Pi)])^2 I want to minimize the elements of this list with respect to `a` and `b`. How can I do that?


title: Reducing the memory footprint of lists of machine numbers

text: I have a large 1D dataset of double precision numbers that are stored in many external database files. In order to load the whole dataset into Mathematica 8 I iterate over the files `AppendingTo` a `List`. The problem is that my computer keeps running out of memory even though the memory available should be more than enough to store the whole set. When researching the issue I discovered a strange behaviour (see the code below). The list produced by `AppendTo` consumes much more memory than would correspond to the size of an integer. I presume that, in the latter `List`, Mathematica uses some different kind of objects to store the data. Any suggestions on how to reduce the memory usage?               In[78]:= ByteCount[Range[1, 10000]]     Out[78]= 40168          In[79]:= data = List[];     For[i = 0, i &lt 10000, ++i,       AppendTo[data, i];     ];          In[81]:= ByteCount[data]     Out[81]= 320040


title: Exporting BSplineSurface to STL

text: I have encountered some difficulties getting `BSplineSurface` to export to STL. The following code works and generates a triangulated polygon mesh from the NURBS spline (adapted from a `BSplineSurface` example):               cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, 4}, {j, 4}];     b = Graphics3D[BSplineSurface[cpts]]     Export["surface.stl", b, "STL"]      However, decreasing the number of control points in each dimension from **4** to **3**               cpts = Table[{i, j, RandomReal[{-1, 1}]}, {i, 3}, {j, 3}];     b = Graphics3D[BSplineSurface[cpts]]     Export["surface.stl", b, "STL"]      results in               GeometricFunctions`BSplineSurface::deglen: -- Message text not found -- (3)     Export::nodta: Graphics3D contains no data that can be exported to the STL format. >>     $Failed      (Mathematica version 10).    Why is the success of exporting a `BSplineSurface` to STL dependent on the number of control points? Is there a reliable way to get arbitrary spline surfaces to export to STL? Convert Graphics3D containing BSpline to polygon primitives for export to 3DS? seems somewhat related though not identical. I am aware that Mathematica cannot actually export NURBS surfaces, so a triangulation will suffice, just as it happens already for the surface with 16 control points.


title: Possible Bug in ProbitModelFit when used in a Dataset

text: Since upgrading to _Mathematica 10_ on Mac OSX I have come across a number of instances of this error, which occurs using Probit and Logit model fit. ![enter image description here](http://i.stack.imgur.com/1gD6T.png) A bit of googling show this is something to do with the estimation algorithm. But the issue is more complex. When I estimate the model straight from this dataset I get the error, but when I first take the values of the data, then fit the model, I get the expected result. Here's an example               var = {age, gender, photo6};          mTest = SemanticImport[        "https://dl.dropboxusercontent.com/u/3997716/test.csv"];          testFit =       mTest[ProbitModelFit[#, var,          var] &, {#age, #gender, #photo6, #rawM} &]          testFit2 =       ProbitModelFit[#, var,          var] &@(mTest[All, {"age", "gender", "photo6", "rawM"}] //           Normal // Values)      Output of this is ![enter image description here](http://i.stack.imgur.com/WeBRA.png) Why the two different results for the same calculation? Is there a workaround that allows the estimation to proceed when directly using the dataset?


title: Imaginary term in Integration procedure

text: How do you remove the imaginary term in the integrated output? Compare the outcome from the operations below. The first operation yields an imaginary term, while the second one has none.               Clear[a, c];     Integrate[q^2 ((4 (c π))/((a q^2 - c) (c + a q^2))), {q, 0, ∞}]     Integrate[q^2 ((4 (c π))/((a q^2 - c) (c + a q^2))), q]     Limit[(Sqrt[c] π (2 ArcTan[(Sqrt[a] q)/Sqrt[c]] +            Log[Sqrt[c] - Sqrt[a] q] - Log[Sqrt[c] + Sqrt[a] q]))/a^(3/2), q -> ∞]


title: Find a word's linguistic pronunciation

text: Is there a way to get a word's linguistic pronunciation given the word as a string? I would like a function `LingusticPronunciation` such that, for example, `LingusticPronunciation["Dog"]` would return `"Dawg"` or maybe even `"dȯg"` or `"däg"`, depending on what type of pronunciation dictionary is used. Ultimately I am trying to search for all homophones in a document and would prefer not having to use the internet to check for different homophone/pronunciation information.


title: Defining a function with global parameters

text: What I would like to do in Mathematica is something like               f[x_] := a x     g[a_] := NIntegrate[f[x], {x, 0, 1}]      But then of course I get               g[1]         NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>     Out= NIntegrate[f[x], {x, 0, 1}]      But I found that I can circumvent the problem with               g[a_] := Hold[NIntegrate][f[x], {x, 0, 1}] // Evaluate // ReleaseHold // Evaluate         NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>     g[1]     Out= 0.5      I don't really understand why this works nor why the definition of `g` throws an error. As I haven't found any other solution to my problem, I would really like to understand why my "solution" works which should also provide an answer to whether there is a simpler solution. (I understand I can solve this simple problem with `f[x_, a_]` but I have in fact a more complex environment in hand where this approach becomes inconvenient.)


title: Combine multiple outputs into a pane

text: **Probably unnecessary detail:** So here's what I'm envisioning. I have several outputs from different calculations (perhaps several ListAnimated tables of GraphicsGrids of plots). In one, I did all the calculations with x=0.13 and everything is a function of y. In a second output, I set y=0.36 and everything is a function of x. Now I want to produce a single box with perhaps tabs at the top that lets me switch between the different outputs. In the limited case above, I could accomplish the whole thing with another nesting of ListAnimate, but what I'm really going for here is something more general. What I would like to be able to do is something like "OutputTabbedPane[{%487, %488, %496}]" and have it produce a single box or whatever that combined the (already computed, possibly long-time computations) outputs and let me click and cycle through them. Pipe dream? Anyone know how to move in this direction?


title: How to use Compile for accelerating matrix multiplications?

text: I am trying to find the inverse of the matrix $A$                m = n = 500;      SeedRandom[123456];      A = RandomReal[10, {m, n}];      iteratively using the following matrix iterative method $$X_{k+1}=X_k(2I-AX_k)$$ when $X_0=\frac{2}{\sigma_1^2+\sigma_r^2}A^*$, with $\sigma_1$ and $\sigma_r$ as the largest and the smallest singular values of $A$, and $I$ is the identity matrix. This iterative methods can simply be coded in what follows:                Schulz[X_] := With[{XX = A.X,Id = SparseArray[{{i_, i_} -> 1.}, {m, m}]}, X.(2 Id - XX)];      The whole of this iteration to reach the prescribed tolerance can then be given by the following two-argument function               inverse[A_, tolerance_] := Module[{smax = SingularValueList[A, 1][[1]],         smin = SingularValueList[A, -1][[1]]},        X0 = (2./(smax^2 + smin^2))*ConjugateTranspose[A];        Schulz[X_] := With[{XX = A.X,           Id = SparseArray[{{i_, i_} -> 1.}, {m, m}]}, X.(2 Id - XX)];        FixedPoint[(Schulz[#] &), X0,          SameTest -> (Norm[#1 - #2, Infinity] <= tolerance &)]];      This function could converge to the inverse $A^{-1}$. For example,               tolerance = 10^-6;     B = inverse[A, tolerance]; // AbsoluteTiming     B.A // Chop // MatrixPlot      My main question is here: the running time of finding the inverse using the above piece of code is too much in contrast to the built-in function `Inverse[A]`. In fact, the above implementation takes 6.2 seconds in my machine while `Inverse[A]` takes around 0.2 seconds. So, is there anyway to accelerate the above code by using `Compile` on the matrix iterations? I think the most time consuming parts are the two matrix-matrix multiplications per step, but is there anyway to use `RunTimeAttribute` or `Parallelization -> True`, to become it faster than it is? I will be thankful if anyone could revise the above implementation.


title: Importing a ragged array while ignoring rows that start with "#"

text: I am new to _Mathematica_ , and I find that there may be a lot of ways of doing this. I was wondering which one might be the most general. I am importing data from `.txt` files, resulting in a ragged array due to many lines containing parameters and other comments which I want to ignore. I just want to import the numbers, and ignore the comments. I am using this:               Import["filename.txt", "TSV", "HeaderLines" -> 15]      I have no TrailerLines that I need to skip, however, there are many rows halfway through the data which I would like to remove. These lines all start with `#`, which makes me think that there is a way to just specify that any line starting with `#` be skipped. Thanks a lot in advance to anyone who might be able to help me with this.


title: 3D plot of a solid of revolution

text: 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.


title: Maximize over permutations

text: 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.


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

text: 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!


title: NumericQ prevents evaluation at a numerical value sometimes

text: 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.


title: Reversing axes to get Poiseuille profile

text: 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}]


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

text: 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?


title: Manipulate keeps replaying the animation non-stop

text: 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]


title: Using SetDelayed wih SQLExecute

text: 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!


title: Derivative from the left and right

text: 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.


title: How do I make Mathematica understand roots of unity?

text: 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?


title: Declaring a positive variable

text: 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.


title: Assumption for all the notebook

text: 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.


title: Does Eigenvalues evaluate in a parallelized way?

text: 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**"??


title: Key to get help about current function

text: 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.


title: How to find the position of non consecutive numbers?

text: 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?


title: Nesting Parallel processes

text: 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.


title: Poor rendering of fractals

text: 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


title: Segmentation of sunspots

text: 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!


title: How to convert equations to piecewise form

text: 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}


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

text: 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?


title: List of atomic expressions

text: 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


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

text: 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?


title: Showing the progression of a Jarvis march algorithm

text: 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}]


title: NMaximize not satisfying binary constraint

text: 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.


title: Faster code for solving an equation with parameters

text: 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?


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

text: 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.


title: Create custom mappings of Mathematica Expressions => Java Objects?

text: 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!


title: Adding an unused column creates an error in JoinAcross

text: 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?


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

text: 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.


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

text: 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 ?


title: Combining separate CHColorStructureDiagrams to form one molecular structure

text: 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)


title: Ito process estimating in Mathematica

text: 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.


title: MixtureDistribution in Mathematica 7

text: 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.


title: Multiple assumptions in integral

text: 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`


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

text: 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]


title: Need help in making a fit to my experimental data

text: 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.


title: BoundedDiagram Error

text: 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.


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

text: 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.


title: Result of Reduce contains duplicate terms

text: 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?


title: Coefficient of function different than polynomial

text: 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?


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

text: 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.


title: Symbolic manipulation of the moments of an unknown distribution

text: 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?


title: adding labels to points in ListPlot

text: 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.


title: Smoothing ListContourPlot contours

text: 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]


title: How change order of items added to the Palettes menu?

text: 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?


title: JSON problem? MMA10, Windows 7 or Linux Mint

text: 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


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

text: 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.


title: Make a button that evaluates a function over and over

text: 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.


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

text: 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)


title: Why can't I use Show with BoxWhiskerChart?

text: ![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]]


title: Unexpected differences with various uses of NormFunction

text: 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 *)


title: Getting Integrate to perform numerical integration

text: 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?


title: Rewriting For loop to FoldList or similar

text: 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?


title: Replacing graph nodes with matrices

text: 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!


title: Name of current Notebook

text: 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?


title: Adding headers to sublists

text: 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.


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

text: 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.


title: Error loading shared library libML64i3.so

text: 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?


title: Block attributes of Equal

text: 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?


title: ordering of functional eigenvalues

text: 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)


title: Random data generator

text: 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.


title: Fluid mechanics problem concerning flow over a wedge

text: 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`.


title: GUI of a Karnaugh Map (2)

text: 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.


title: Checking if first derivative is zero at a given point

text: 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.


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

text: 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


title: Specifying optional arguments with variables

text: 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.


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

text: 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?


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

text: 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?


title: How to plot a curve with border around the line?

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


title: Plotting an function defined by an integral

text: 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?


title: Mathematica Bifurcation

text: 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]


title: Change Default Font Color of Commands

text: 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.


title: Lists not being recognized correctly within manipulate

text: 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.


title: How to compile Heike's winding number function?

text: 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?


title: Changing some stuff to Kruskal's Algorithm

text: 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]


title: Simultaneously running the same .m file with different inputs

text: 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?


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

text: 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?