Object separation from a 2.5D surface

I'm trying to identify the shape and the boundaries of objects. The data was generated with a laser scanner and represent the surface of an area in which many boulders lay on the ground and making up heaps. the data is available here ![enter image description here](http://i.stack.imgur.com/mdats.jpg) In the center of the plot you can see a bigger boulder an i want to seperate it from the other stuff around. For this goal I tried different methods which I want to present you and hope that you could enhance these idea(s) But at first i will reduce the number of samples in the data, because for the most ways the data is to big and need enormous computation time:               data3D = Import["data-a.dat"];     data3Ds = Round[data3D, 0.05] // DeleteDuplicates;      My first intention was to work with ImageProcessing like in this question: Image segmentation and object separation in 3D using Mathematica, because i worked a lot with 2D image processing. At first sight it was a nice idea to create an 3D image out of the data and worked more or less. But the result was not satisfying. The main problem is that all filters and transformations detect the edges between the data points and the NULL-values and doesn't (what i want to do) segment between the data. The presented DistanceTransfrom was created for volumetric data, in my example it is a surface in a three dimensional space. I would like to show some examples and the results, but the .nb-script crashed and I have no access to the results anymore... As second try I used the idea of the documentation of VertexNormals. The idea was to get the orientation of smaller parts of the surface. For this an interpolation of the data is needed. The documentation suggest to use _ListSurfacePlot3D_.               g = ListSurfacePlot3D[data3Ds, Mesh -> None, MaxPlotPoints -> 50]      ![enter image description here](http://i.stack.imgur.com/eUMPc.jpg)               {pl, vl} =        First@Cases[g,          GraphicsComplex[pl_, prims_, VertexNormals -> vl_,            opts___?OptionQ] :> {pl, vl}, Infinity];     vl1 = Table[Norm[vl[[i]] - {0, 0, 1}], {i, Length[vl]}];     nf = Nearest[pl -> vl1];     vl2 = ParallelMap[StandardDeviation[nf[pl[[#]], 50]] &,        Range[Length[pl]]]     ListPointPlot3D[List /@ pl,       PlotStyle -> ({PointSize[Medium],            Blend[{{.1, Darker[Green]}, {0.45, Yellow}, {0.7,               Red}}, #1]} & /@ vl2)]      _vl_ is a list of vectors representing the orientation of a point _pts_ and with the length of 1. _vl1_ is the difference of the orientation between all _vl_ and the vertical. At the end _vl2_ represent the deviation of the orientation of 50 surrounding data points at one point. ![enter image description here](http://i.stack.imgur.com/3VytF.jpg) The result is not that bad, but at the one hand I have no idea how to seperate the different parts. At the other hand this version is very slow and only for the reduced data points. Additionally the ListSurfacePlot3D creates some artefacts like in this question. At the end I tried another interpolation method and worked with tetrahedral meshs of the _TetGenLink_ Package. The simple interpolation function doesn't work good because the data is mainly unstructured (see this link and the related questions) and have more than on z-value for some x-y-pairs. Maybe you have better ideas for this segmentation problem or could give me some advice to think into other directions. I would apppreciate no solution for MMA version 10 because I'm just working with version 9. Thank you! **Edit 1 (Delaunay)** I've tried already the _TetGenLink_ -Package with the this help.               << TetGenLink`     {pts, tetrahedra} = TetGenDelaunay[data3Ds];     csr[{aa_, bb_, cc_, dd_}] :=       With[{a = aa - dd, b = bb - dd, c = cc - dd},        Norm[a.a Cross[b, c] + b.b Cross[c, a] +           c.c Cross[a, b]]/(2 Norm[a.Cross[b, c]])]     radii = csr[pts[[#]]] & /@ tetrahedra;     alphashape[rmax_] := Pick[tetrahedra, radii, r_ /; r < rmax]     faces[tetras_] :=       Flatten[tetras /. {a_, b_, c_,           d_} :> {{a, b, c}, {a, b, d}, {a, c, d}, {b, c, d}}, 1]     externalfaces[faces_] :=       Cases[Tally[Sort /@ faces], {face_, 1} :> face]     polys = externalfaces@faces@alphashape[0.1];     Graphics3D[GraphicsComplex[pts, Polygon@polys], Boxed -> False]      ![enter image description here](http://i.stack.imgur.com/kZkQR.jpg) The result is not that bad and works quite good with version 9. Just I don't have any idea to work further with this Graphic.


Is there any way to obtain an approximate inverse for very large sparse matrices?

I have a very large sparse matrix and I need to obtain its approximate inverse and save it as an sparse matrix too. Any of my efforts as could be seen in what follows fail for large n               ClearAll[n, s, f, aInv]     n = 100000;     s = SparseArray[{Band[{1, 120}] -> -2., Band[{950, 1}] -> -1.,          Band[{1, 1}] -> 20., Band[{1, 100}] -> 2.,          Band[{6, 800}] -> 1.1}, {n, n}, 0.];     f = LinearSolve[s];     aInv = f[SparseArray[{Band[{1, 1}] -> 1.}, {n, n},           0.]]; // AbsoluteTiming      The accuracy of the approximate inverse is not that important to me for the time being, if it could be obtained and saved in the sparse form then I can improve it by the existing iteration methods. Maybe the built-in pre- conditioners for large sparse matrices in _Mathematica_ 8 could be good. I would be grateful if someone give me some hints to obtain an approximate inverse for such large sparse matrices.


Adding Math to Plots

I have several formulas I would like to place at specific coordinates in a `Graphics` object I have already created. I need to be able to choose bold or not as well as how large to make it. I am unsure how to control the size of the text as well as why _Mathematica_ will not place it. Specifically, it continues to try to evaluate my text. One of the objects I wish to place on the plot is (since it won't let me post a picture) $$M^\mu = \oplus_{\lambda \ge \mu} \,m \, \lambda_\mu \, S^\mu$$ However, _Mathematica_ continues to try to evaluate the direct sum rather than just place it at say the point (0,0). Here is the code I am trying at the moment:               Graphics[{Style[HoldForm[M^μ == \!\(*UnderscriptBox[(StandardForm[⊕]), (λ ≥ μ)]\) m Subscript[λ, μ] S^μ], Medium], FormatType -> StandardForm}]      Any ideas?


How to normalise a line in mathematica

I'm working on creating a line plot from a histogram, as in the following:               {g, {binCounts}} =        Reap[Histogram[RandomVariate[NormalDistribution[0, 1], 100],               {-2,2,0.25},               Function[{bins, counts}, Sow[counts]]]];          {g, ListLinePlot[binCounts]}      What I'd like to know is, how can I normalised this line so the area under the curve is 1? (So I can compare the shapes of these histograms independent of the number of counts)


Fitting Function with 3 parameters

I am trying to fit a function with 3 parameters however the result strongly depend on the initial values of parameters:                data = ToExpression@Import["http://pastebin.com/raw.php?i=eSXQuV62"];           FindFit[data,           G/(2/3*x)*(1 - (4.13/G*(Log[k/(x*r)] + G/4.13))^(2/3)),           {{k, 0.0001}, {x, 0.2}, {G, 80}}, r]      the result are > >     {k -> -0.000803039, x -> 0.613938, G -> 47.9489} >   for different set of initial values of parameters                 FindFit[data,            G/(2/3*x)*(1 - (4.13/G*(Log[k/(x*r)] + G/4.13))^(2/3)),             {{k, 0.0001}, {x, 0.2}, {G, 100}}, r]      > >     {k -> -0.00247546, x -> 1.04233, G -> -341.32} >   I also get following message > FindFit::nrlnum: "The function value {31.8606 -11.8829\ I,32.8832 -11.8583\ > I,26.5785 -11.8548\ I,36.1803 -11.852\ I,27.6782 -11.8511\ I,<<42>>,20.6663 > -11.7998\ I,17.8617 -11.7998\ I,7.70671 -11.7992\ I,<<56>>} is not a list of > real numbers with dimensions {106} at {k,x,G} = > {-0.00247546,1.04233,-341.32}. Do you know how to solve this issue?


Export notebook to HTML produces low resolution GIF

I have equations written in my notebooks as text (the cells set as Format -> Style -> Text). When exporting the notebook to HTML (File -> Save As.. -> HTML) with the GIF option (the default) an HTML file is produced along with folders: HTMLFiles and HTMLLinks. The HTMLFiles folder contains GIF images of the equations in the text, but they are very low resolution / quality. Is there a way to make Export set them to a higher resolution? motivation: to write equations in Mathematica (it is nice to write in) and output the equations as images to use in a presentation. I have tried: SetOptions[Image, ImageSize -> 5000]; SetOptions[Image, ImageResolution -> 5000]; SetOptions[Graphics, ImageSize -> 5000]; SetOptions[Rasterize, RasterSize -> 1000]; With no luck. Thanks,


Using a different version of R with RLink on Windows 7

I'd like to run the R version installed in my Windows 7 system from within Mathematica 9 but when I execute the following command:               InstallR["RHomeLocation" -> "C:\\Program Files\\R\\R-2.14.2\\bin\\x64"]      I get the following error message: > InstallR::fail: Failed to install R. The following error was encountered: > Unable to load dynamic libraries Does anybody know how to fix this issue? Many thanks in advance


f[arg1, arg2,...,argN] vs. f[{arg1, arg2,...,argN}]

I am trying to reproduce the API of a function (written in R) that accepts an arbitrary number of arguments and handles it the same way as it would handle a single argument that is a list of different data sets. Is there a Mathematica idiom that allows a function to be defined so that:               f[ arg1, arg2, ..., argN ]      behaves the same as               f[ {arg1, arg2, ..., argN} ]      ?


How to load data into a Manipulate expression

I have data showing truncated octahedron geometry changing with time. How can I read those data into a `Manipulate` expression? To be specific, I want to manipulate time and have other parameters change correspondingly as in my data. Those parameter value should show simultaneously. Now I have geometry that I can change by varying the parameters. My `Manipulate` code is               Manipulate[      Grid[{{RegionPlot3D[          x + y + z < 0.866 A && x + y - z < 0.866 A &&            x - y + z < 0.866 A && -x + y + z < 0.866 A &&            x + y + z > -0.866 A && x + y - z > -0.866 A &&            x - y + z > -0.866 A && -x + y + z > -0.866 A, {x, -0.5*r*A,            0.5*r*A}, {y, -0.5*r*A, 0.5*r*A}, {z, -0.5*r*A, 0.5*r*A},           ImageSize -> 300, Mesh -> 1, PlotRange -> {-16, 16}],          SpanFromLeft, SpanFromLeft}, {"volume(nm^3)",          ScientificForm[          NIntegrate[           Boole[void =              x + y + z < 0.866 A && x + y - z < 0.866 A &&               x - y + z < 0.866 A && -x + y + z < 0.866 A &&               x + y + z > -0.866 A && x + y - z > -0.866 A &&               x - y + z > -0.866 A && -x + y + z > -0.866 A], {x, -0.5*r*A,             0.5*r*A}, {y, -0.5*r*A, 0.5*r*A}, {z, -0.5*r*A, 0.5*r*A}],           3] }, {"{002}Facets area(nm^2)",          ScientificForm[12*(0.866 A - 0.5*r*A)^2,           3]}, {"{111}Facets area(nm^2)",          ScientificForm[          4*(3)^(0.5)*((0.866 A)^2 - 3*(0.866 A - 0.5*r*A)^2), 3]}}],        {{A, 20, "Distance between {111} facets (nm)"}, 1, 20, Slider, Appearance -> "Labeled"},        {{r, 1.4, "Aspect ratio"}, 1.04, 1.4, Slider, Appearance -> "Labeled"},        ControlPlacement -> Top]      And a small subset of my data is               Time  A      r      200   16.09  1.084524549     210   15.74  1.062261753     220   15.02  1.053262317     225   14.59  1.067169294     235   14.21  1.073187896


Combining Newtonian 3D N-Body Simulation Output and Earth Sphere

I'm trying to figure out how to make a simulation whereby two satellites orbit Earth, but have run into a little bit of a snag. I have a solution to the system of ODEs for the n-body output, and I found a brilliant thread explaining how to create an Earth sphere here (How to make a 3D globe?) but I'm struggling to combine the output of the two. This is my attempt: (Note that "soln" is the output of the n-body NDSolve computations, which I didn't put in here as I thought combining the two entities would be a trivial syntactic edit. If the full code is needed I'll be happy to supply it as well)               Earth = Import["Desktop/earthtruecolor_nasa_big.jpg"];     EarthSphere =      ParametricPlot3D[{Cos[u] Sin[v], Sin[u] Sin[v], Cos[v]}, {u, 0,      2 Pi}, {v, 0, Pi}, Mesh -> None, PlotPoints -> 100,      TextureCoordinateFunction -> ({#4, 1 - #5} &), Boxed -> False,      PlotStyle -> Texture[Show[Earth, ImageSize -> 1000]],      Lighting -> "Neutral", Axes -> False, RotationAction -> "Clip",      ViewPoint -> {-2.026774, 2.07922, 1.73753418}, ImageSize -> 800];          Show[ParametricPlot3D[     Evaluate[{{x[1][t], y[1][t], z[1][t]}, {x[2][t], y[2][t],      z[2][t]}} /. soln], {t, 0, 20000}, AxesLabel -> {x, y, z},      AspectRatio -> 1, BoxRatios -> 1, PlotStyle -> Automatic,      ImageSize -> Large,      PlotRange -> {{-10000000, 10000000}, {-10000000,        10000000}, {-10000000, 10000000}}] {EarthSphere, {0, 0, 0}}]      This is my output so far: ![enter image description here](http://i.stack.imgur.com/eDRyi.png) EDIT: I added in the n-body code as I thought it would cause confusion if I did not:               G = 6.672*10^-11     m[0] = AstronomicalData["Earth", "Mass"];     tmax = 20000;     r[0] = AstronomicalData["Earth", "Radius"];     rx[1] = (r[0] + 300000 ) Cos[45 Degree];     ry[1] = (r[0] + 300000 ) Sin[45 Degree];     rz[1] = 0;     rx[2] = (r[0] + 600000 ) Cos[90 Degree];     ry[2] = (r[0] + 600000 ) Sin[90 Degree];     rz[2] = 0;     vx[1] = Sqrt[(G  m[0])/(r[0] + 300000)] Sin[45 \[Degree]]      vy[1] = Sqrt[(G  m[0])/(r[0] + 300000)] Cos[45 \[Degree]]     vz[1] = 0     vx[2] = Sqrt[(G  m[0])/(r[0] + 600000)] Sin[90 \[Degree]]     vy[2] = Sqrt[(G  m[0])/(r[0] + 600000)] Cos[90 \[Degree]]     vz[2] = 0     soln = NDSolve[{        x[1]''[t] == -((          G m[0] x[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        y[1]''[t] == -((          G m[0] y[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        z[1]''[t] == -((          G m[0] z[1][t])/(x[1][t]^2 + y[1][t]^2 + z[1][t]^2)^(3/2)),        x[2]''[t] == -((          G m[0] x[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),        y[2]''[t] == -((          G m[0] y[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),        z[2]''[t] == -((          G m[0] z[2][t])/(x[2][t]^2 + y[2][t]^2 + z[2][t]^2)^(3/2)),             x[1][0] == rx[1], y[1][0] == ry[1], z[1][0] == rz[1],         x[2][0] == rx[2], y[2][0] == ry[2], z[2][0] == rz[2],         x[1]'[0] == -vx[1], y[1]'[0] == vy[1], z[1]'[0] == 0,         x[2]'[0] == -vx[2], y[2]'[0] == vy[2], z[2]'[0] == 0}, {x[1][t],         y[1][t], z[1][t], x[2][t], y[2][t], z[2][t]}, {t, 0, tmax} ,        MaxSteps -> 1000000, Method -> "StiffnessSwitching"]


Choosing among different function definitions without sacrificing speed

I'm working on some code that numerically integrates a function, let's call it `G`, which calls another function, `F`, that can be defined according to any of several models. In one model, there is an analytic expression for `F`. In the other models, `F` needs to be defined by loading data from a file and interpolating it. There is a different data file for each model (other than the analytic one). One way I tried to do this was to have a `Switch` statement in `F`, and get it to choose whether to use the analytic expression or to take data from a file each time it's called based on the options provided.               (* load data from a file and Interpolate it *)     FFromFile[filename_] := FFromFile[filename] = Module[{...}, ...]     FAnalytic[a_,b_,c_] := a^2+b^2+c^2     F[a_,b_,c_,OptionsPattern[]] :=  Switch[OptionValue[Model],        "File",FFromFile[OptionValue[Source]][a,b,c],        "Expr",FAnalytic[a,b,c]     ]     G[d_,e_,f_,phi_,opts:OptionsPattern[]] := Block[{g,h,i},        (* do a bunch of calculations to figure out g and h *)        i = F[g, h, 5, opts];        (* do more calculations involving i *)     ]     GenerateData[phi_,opts:OptionsPattern[]] := NIntegrate[G[x,y,z,phi,opts],        {x,2,10}, {y,0,x}, {z,0,3}, Method->"QuasiMonteCarlo", PrecisionGoal->3]      Unsurprisingly, that turned out to be too slow. So, another method I tried was to predefine `F`, since the same model is used throughout an integration.               (* load data from a file and Interpolate it *)     FFromFile[a_,b_,c_] = Module[{v,...}, v=ReadList[filename, ...]; ...];     FAnalytic[a_,b_,c_] = a^2+b^2+c^2;     Switch[TheModel,        "File",F=FFromFile,        "Expr",F=FAnalytic     ]     G[d_,e_,f_,phi_] := Block[{g,h,i},        (* do a bunch of calculations to figure out g and h *)        i = F[g, h, 5];        (* do more calculations involving i *)     ]     GenerateData[phi_] := NIntegrate[G[x,y,z,phi],        {x,2,10}, {y,0,x}, {z,0,3}, Method->"QuasiMonteCarlo", PrecisionGoal->3]      `filename` and `TheModel` would be defined prior to running this code snippet. This way is faster, though it turns out to be kind of inconvenient because sometimes I want to run calculations that compare two different models (for example, from two different files), which requires me to run one, save the data to a file, quit the kernel to ensure that all the definitions are cleared, start it up again and run the other. Plus, this method of passing information to the function by defining variables in advance (`filename` and `TheModel`) makes me kind of queasy ;-) Is there some way I can get the best of both worlds, namely be able to **specify the model by passing options to`GenerateData`, while still retaining the speed benefits of predefining `F`?**


dropping a row with at least one value larger than a particular value

So for instance I have M X N table. I want to drop any row which has an element larger than, say, one in the second or the third column. I guess I have to do some sort of pattern matching. But not exactly sure how to do it. I can use a table to search for a value and then find its Position and then drop the corresponding row. There must be a easier way to do this without traversing through each element using the Table function. help please :)


Export notebook to pdf in landscape orientation

Assuming the following is a notebook with a linebreak: ![enter image description here](http://i.stack.imgur.com/AunnN.png) How might I export a landscape pdf (preferred although other formats could work) such that **~~each cell content~~ each group of cells** above and below the page break are stretched to take up half of the landscape page. ![enter image description here](http://i.stack.imgur.com/JVLOZ.png) The colors are simply there to act as placeholders. I certainly could copy and paste such data into a word document, but ideally something like this could be automated.


Creating custom notation

How does one generate custom symbols? For example, the physicist notation for the rotation is "nabla cross function". In this case however, Mathematica complains that the `[esc]del[esc]` symbol evaluates to the unary operator `Del[]`, which of course cannot take a cross (`[esc]*[esc]`) after it, since a bracket is expected. Although a correctly looking output is generated by               Prefix[f[a], "\[Del]\[Times]"]      ![](http://i.stack.imgur.com/2vco3.png) the result cannot simply be assigned to an operation (`Prefix[...] := ...`) you can type in using the nicely readable [esc] commands I mentioned above. Is there some way of doing this, i.e. invoking completely custom functionality to (combinations of) existing symbols?


How can I break through Function's HoldAll attribute to force evaluation of a body element?

The question concerns creating a function. Let consider the following code               With[{f = Function[t, Cos[t]]},      {First[#], f'[#]} &     ]      which returns               (* ==> {First[#1], Function[t, Cos[t]]'[#1]} & *)      How to can I force it to return the derivative evaluated (only second part of the returned list); i.e., how to can I get               (* ==> {First[#1], -Sin[#1]} & *)


The clearest way to represent Mathematica's evaluation sequence

WReach has presented here a nice way to represent the _Mathematica_ 's evaluation sequence using `OpenerView`. It is **much more** clear way to go than using the standard `Trace` or `TracePrint` commands. But it could be improved further. I need straightforward way to represent the real sequence of (sub)evaluations inside _Mathematica_ 's main loop for beginners. In particular, it should be obvious when new evaluation subsequence begins and from which expression (it is better to have each subsequence exactly in one `Opener`). The evaluation (sub)sequence should be identified as easily as possible with the standard evaluation sequence. I mean that the reader should be able to map real evaluation step to one described in the Documentation for the standard evaluation sequence. Is it possible?


Data Table Manipulation in Mathematica: Step 2

In this previous post (Data Table Manipulation in Mathematica) we find the brilliant suggestion proposed by Leonid Shifrin that allows to select specific rows identified by the header name. I'm now looking for a way to then also select the data of a specific column (or more columns) of the subset of data generated by Leonid's select function. Suppose we have this data:               table = List[     {"ID", "Variable 1", "Variable 2"},      {"Alpha", 1, 0},      {"Beta", 1, 1},      {"Alpha", 0, 0}]      which when formatted as a grid looks like this:               ID     Variable 1 Variable 2     Alpha       1          0     Beta        1          1     Alpha       0          0      Using Leonid's function we can obtain this:               subset = select[table, where["Variable 1" == 1]]          (* {{"Alpha", 1, 0}, {"Beta", 1, 1}} *)      Suppose that we now want to sum all the values that are in the column named 'Variable 2'. We could just do this:               Total[subset[[All,3]]]      However, in this way we loose the advantage of using Leonid's function that can work directly with header names. Ideally, I would like to find a way to get those data by using the header name. Something like:               Total[subset[[All,"Variable 2"]]]      or, even better:               select[table, where["Variable 1" == 1], columns["Variable 2"]]      Any hints would be highly appreciated.


Overlaying location pointer on to a png file

So I have started off with importing a png image of size $512\times 1024$ px. I have then created two locators as demonstrated on the Wolfram tutorials:               length = DynamicModule[{p1 = {0, 0},         p2 = {1, 1}}, {Dynamic@         Graphics[{Arrow[{p1, p2}], Locator[Dynamic[p1]],            Locator[Dynamic[p2]]}, PlotRange -> 1024],         Dynamic[Grid[{{"Length:", EuclideanDistance[p1, p2]}, {"Slope:",             1/Divide @@ (p2 - p1)}}]]}]      I would like to be able to overlay these locators on to my png image and move them around, in order to measure the distance between two points on the image. I'm sure this should be possible but I really can't see how! Thanks for looking :)


Numbered equations/formulas

How do you number equations in _Mathematica_ notebooks so that they are exported correctly into latex? In case you don't know how to put numbered equations here is quick review.   1. Open a new notebook and create a new cell with an equation.    2. Select the cell, on the menu go to `Format -> Style -> DisplayFormulaNumbered` or change this by pressing the shorcut command+0 on mac or alt+0 on windows and enter `DisplayFormulaNumbered`. At this step you should have something like this: ![Output 2](http://reference.wolfram.com/mathematica/ref/format/TeX.html#1511511812)   3. Select the cell again in case you deselected like I did. Go to `Cell -> Cell Tags -> Add/Remove Cell Tags` or use the shorcut command+J on the mac (don't know about windows). A panel should appear, enter the name of how you would like to refer to the equation and click Add. I entered `simpleParabola`.   4. To see that you successfully added the tag go to `Cell -> Cell Tags -> Show Cell Tags`. You can use this options to show and hide the cell tags. I suggest to keep them on while you are editing and hiding them when you are done. This is what I see so far.  ![Output 4](http://i.stack.imgur.com/7aDbB.png) You can repeat these steps to enter your equations and labeling them. Now, to refer to them by the tag you have given them you have to write some text. Say you write something like:               This is my text and now I refer to XXX because it is important to refer to it.      What we want is to let `XXX` to refer to the label `simpleParabola`. What you do is select that part of the text. Then go to `Insert -> Automatic Numbering ...`. On `Counter` you need to select `DisplayFormulaNumbered` because that's the type of cell you want to refer to. Then select `simpleParabola`, click ok and you are done. The `XXX` should change to `1`. The good thing about this is that if in the future your numbers change then your number will automatically change. To test this, just go above the cell where you have numbered formula and create a new `DisplayFormulaNumbered` cell, Now this new one should have the label 1 and the cell with the tag `simpleParabola` should have label number 2. But guess what? You don't have to worry about changing the numbers in your text because you already linked it to the label. Here is a screenshot: ![Output](http://i.stack.imgur.com/kURZx.png) Ok, so we can create documents with numbered equations. Now lets assume that you are collaborating in some document and this document is required to be typed in latex. As the awesome _Mathematica_ user that you are you type the document faster in _Mathematica_ thanks to all the shortcuts that it offers. Finally, after you are done you save it in Latex format. Here is a what we obtain:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         g(x)=x^3         \end{equation}          \begin{equation}         f(x)=x^2         \end{equation}          This is my text and now I refer to 2 because it is important to refer to it.          \end{document}      Not bad. Unfortunately, our cell tags are gone. Now, laTeX users, please correct me if I'm wrong. Will the next modification work?                 %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         g(x)=x^3         \end{equation}          \begin{equation} \label{simpleParabola}         f(x)=x^2         \end{equation}          This is my text and now I refer to ~\ref{simpleParabola} because it is important to refer to it.          \end{document}      All I've done is add `\label{simpleParabola}` and `~\ref{simpleParabola}`. After running LaTeX on it twice I obtain this pdf ![pdf](http://i.stack.imgur.com/25x9Y.png) _Mathematica_ did a pretty good job at giving the latex version but it gave me the job to add the labels and references. Now here is something that is very interesting. If you have the modifed version of the latex document that I showed I want you to open a new notebook and enter:               NotebookPut[Import["Path_To_Latex_Document"]]      You will end up with a new document with the latex content in there. But what happened to the numbers? and why is the reference messed up? If you show the cell tags again it will reveal that the label that you put in latex was converted to a cell tag. And if you see the expression on the text you will see that it added the automatic numbering for you. The reason it isn't working is because it placed the wrong counter. ![Output](http://i.stack.imgur.com/Mzd0e.png) So now that you have an idea of what I am doing here are the questions:   * Is there any way to write in latex the style that the _Mathematica_ cells should use? Notice how _Mathematica_ uses `NumberedEquation` instead of the `DisplayFormulaNumbered` style.   * How do you specify the counter so that _Mathematica_ knows what counter to use. Notice that in this case it is using `Section` instead of `DisplayFormulaNumbered`.   * How do you make it so that when you export the notebook file to a latex file it places the `\labels` and `\~ref` in the latex file?  Any ideas? * * * I will post some new stuff I've found here. I still haven't found an answer. If you go to this link you will find an example. This is what I've been working with               ExportString[      Cell[       BoxData[{         "This is a reference to an equation: ",         CounterBox["NumberedEquation", "eq:myEq1"],         ". This is another one: ",         CounterBox["NumberedEquation", "eq:myEq2"],         ". And this is yet another one: (",         CounterBox["NumberedEquation", "eq:myEq3"],         ")."         }        ], "Text"       ]      , "TeX",      "ConversionRules" -> {        "Text" -> {          # &          }        } ]      The output I obtain is:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          This is a reference to an equation: CounterBox[NumberedEquation, eq:myEq1]. This is another one: CounterBox[NumberedEquation, eq:myEq2]. And this     is yet another one: (CounterBox[NumberedEquation, eq:myEq3]).          \end{document}      I can tell _Mathematica_ to let the the contents go as they are. One problem though, I want to replace say `CounterBox[NumberedEquation, eq:myEq1]` with `~\ref{eq:myEq1}`. How do you use the replacement rules here? ## EDIT: The `ConversionRule` for text should be               "Text" -> {         If[MatchQ[#, _CounterBox], "~\\ref{" <> #[[2]] <> "}", #] &      }      Here is the remaining problem I can't figure out:               ExportString[      Cell[       BoxData[        FormBox[RowBox[{RowBox[{"f", "(", "x", ")"}], " ", "=", " ", "x"}],          TraditionalForm]        ],       "NumberedEquation",       CellTags -> "eq:myEq"       ]      , "TeX",      "ConversionRules" -> {        "NumberedEquation" -> {          "\\begin{equation}\n", Convert`TeX`BoxesToTeX[#] &,           "\n\\end{equation}"          }        } ]      We get:               %% AMS-LaTeX Created by Wolfram Mathematica 8.0 : www.wolfram.com          \documentclass{article}     \usepackage{amsmath, amssymb, graphics, setspace}          \newcommand{\mathsym}[1]{{}}     \newcommand{\unicode}[1]{{}}          \newcounter{mathematicapage}     \begin{document}          \begin{equation}         f(x) = x         \end{equation}          \end{document}      We need to get               \begin{equation}\label{eq:myEq}         f(x) = x         \end{equation}      How do we obtain the `CellTag`?


Manipulating differential equations

I would be very grateful if anyone could help with manipulating the solution to the system of differential equations below. I've tried just about everything I can think of all to no avail. The code doesn't seem to be working (i.e. the parameters I'm trying to adjust have no effect on the dynamics of the graphs which can't be right-I computed other values myself and it gave a different plot). I have had a look at some similar topics like Manipulate a Differential Equation result but its quite specific for single differential equations rather than a system of equations. The variables I'd like to vary are mhigh, s0, p0 and z0. My code is given below:               Needs["PlotLegends`"];          De = 2.1;      B = 2.3;     B2 = 0.001;      mhigh = 0.001, mlow = 0.0004;     fr = 0.77, fs = 1, fp = 1.4;      s0 = 1000;      z0 = 1000;      p0 = 0;      r0 = 0;           solutionN2 =        NDSolve[{         Z'[t] == De*(S[t] + P[t] + R[t]) - B*Z[t]*((fs*S[t]) + (fp*P[t]) + (fr*R[t])),          S'[t] == fs*B* S[t]*Z[t] - (mlow + mhigh)*S[t] - De *S[t],          P'[t] == fp* B* P[t]*Z[t] + mlow *S[t] - B2* P[t] - De* P[t],          R'[t] == fr *B* R[t]*Z[t] + mhigh* S[t] + B2 *P[t] - De *R[t],          S[0] == s0, P[0] == p0,          R[0] == r0, Z[0] == z0},          {S, P, R, Z}, {t, 0, 200}];           Manipulate[        Plot[{Z[t] /. solutionN2, S[t] /. solutionN2, P[t] /. solutionN2, R[t] /. solutionN2},           {t, 0, 200},           ImageSize -> {700},           PlotStyle -> {Brown, Red, Blue, Darker[Green]},           PlotLegend -> {"Z", "S", "P", "R"}, LegendPosition -> {0.2, -0.2},           FrameLabel -> {Style["time (in days)", Medium]}],        {{s0, 1000, s0:initial sus pop"}, 0, 5000,          ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{z0, 0, z0:initial resources"}, 0, 5000,          ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{p0, 0, p0:initial p. sus. pop"}, 0, 1000,         ImageSize -> {Tiny}, Appearance -> "Labeled"},        {{mhigh, (0.001), "mut. rate"}, 0, 0.01,          ImageSize -> {Tiny}, Appearance -> "Labeled"}]      Please bear with me as I'm a beginner with _Mathematica_. As stated, any useful help would be so much appreciated as Ive spent nearly the whole day trying to sort this out.


Efficient evaluation of functions defined by NIntegrate

I have a complicated function $f$ and I want to plot the function $F(x)$ defined by the definite integral of $f$ from $0$ to $x$: $$ F(x) = \int_0^x f(y)\mathrm dy. $$ Apparently $f$ cannot be integrated in closed-form, and I use `NIntegrate[]` instead               F[x_] := NIntegrate[f[y], {y, 0, x}];     Plot[F[x], {x, 0, 100}]      I would like to improve the efficiency of this computation by telling _Mathematica_ that `F[s + t]` is simply `F[s] + NIntegrate[f[y], {y, s, t}]` so that (for example) _Mathematica_ can save the value of `F[1]` and whenever `F[2]` or `F[3.2]` is needed, _Mathematica_ can substitute the value of `F[1]` and compute only the integral of the remaining interval. Essentially I am looking for the continuous version of the trick one uses to compute the Fibonacci sequence:               f[n_] := f[n] = f[n-1] + f[n-2]      Is there a simple way to implement this? Any help is much appreciated.


How do I find the degree of a multivariable polynomial automatically?

I have a very simple question which appears not to have already been answered on this forum. Is there built-in functionality that returns the degree of a multivariable polynomial? For example if the polynomial is               s1 + s2^2 s3 + s3^2 s4^7      I want _Mathematica_ to return 9. If there is no automatic solution, could somebody please suggest a simple (and fast) implementation? EDIT: I removed my "solution" because it actually only works for simple examples. I tested out the four solutions presented so far on a degree 20 polynomial in 6 variables (`ByteCount[poly] = 2006352`). I used `AbsoluteTiming` to determine that the answer I chose is the fastest, with a run-time of 53.06 s for 1000 evaluations. This is quite a bit faster than the closest competitor's run-time of 283.76 s for 1000 evaluations. UPDATE: I tested the improved version of the solution (the one with random reals) and found that the run-time is now slightly worse but still far better than the competition at 90.52 s for 1000 evaluations.


Parallel linear algebra with arbitrary precision

Is it possible to do parallel linear algebra with arbitrary precision within Mathematica (in a simple manner, as is done for the machine precision)?


Why does Assuming for Integrate not work as expected?

I'm trying to perform the following integral with Mathematica 7:               Assuming[{t>0},       Integrate[(-s^2 + 4*s*t + 2*alpha*s)^(-(1/2)*D),{s, 0, t}, {alpha, 0, Infinity}]]      If I perform the integration with just the t>0 assumption, Mathematica gives:               (1/(-2 + D))If[Re[D] < 2,       ( 2^-D t^(2 - D) (       -8 (-4 + D) Gamma[1 + D/2] Hypergeometric2F1[1 - D/2, D/2, 2 - D/2, 1/4]       + (-2 + D) D Gamma[D/2] Hypergeometric2F1[2 - D/2, D/2, 3 - D/2, 1/4]       ))/((-4 + D) (-2 + D) Gamma[1 + D/2]),       Integrate[(-s (s - 4 t))^(1 - D/2)/s, {s, 0, t}, Assumptions -> Re[D] >= 2 && t > 0]]      which indicates that D must be less than 2. If I now use the additional assumption `D<2` with `Assuming[{t>0,D<2},` Mathematica says that the integral no longer converges. (Also with exchanged places for the integration variables, the integral can no longer be calculated). Can anyone solve the mystery? Thanks, Tobias


Optimize inner loops

I'm Mathematica newbie so please be gentle :) I have this, heavily non- optimized part of code, which I would like to speed up. I have put all matrices to be RandomReal, but in my code they take specific values. Also, matrices mat3, mat4, mat6 and mat7 consist of random simple trigonometric functions. Any kind of help is much appreciated. I have read about Map, Table, Do, Functional Programming... but I don't know how to apply it. Code is part of Finite element-Finite strip calculation. I don't mind losing computing time during "real" calculation, but this part of code is just placing elements of matrices into other places with just few calculations. Matrices mat2, mat5, mat9, mat10 and mat11 need to be stored for later data processing. Bonus question: is it possible to Compile this part of code? Hope I gave optimal amount of data about my problem All the best, Aleksandar               limit1 = 10;     limit2 = 20;     limit3 = 10;     limit4 = 15;     mat1 = RandomReal[{-100, 100}, {limit3, 2}];     mat2 = RandomReal[{-100, 100}, {limit1, limit2, limit3, 2}];     mat3 = Table[Sin[m*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat4 = Table[Sin[m*s*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat5 = RandomReal[{-100, 100}, {limit1, limit2, limit3, 6}];     mat6 = Table[Sin[m*m*\[Pi]*y] + Cos[s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat7 = Table[Sin[m*\[Pi]*y] + Cos[s*s*\[Pi]*y], {m, limit2}, {s, limit3}];     mat8 = RandomReal[{-100, 100}, {limit2, limit3, limit4, 2}];     mat9 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];     mat10 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];     mat11 = RandomReal[{-100, 100}, {limit1, limit2, limit3, limit4}];          For[n = 1, n < limit1 + 1, n++,     For[i = 1, i < limit2 + 1, i++,          For[j = 1, j < limit3 + 1, j++,          y = (mat1[[j, 1]] + mat1[[j, 2]])/2;          mat2[[n, i, j, 1]] = mat3[[i, j]];          mat2[[n, i, j, 2]] = mat4[[i, j]];          mat5[[n, i, j, All]] = 1/2 (mat6[[i, j]] + mat7[[i, j]]);          Clear[y];          For[k = 1, k < limit4 + 1, k++,          zz = 1/2 (mat8[[i, j, k, 1]] + mat8[[i, j, k, 2]]);          mat9[[n, i, j, k]] = {mat5[[n, i, j, 1]] + zz*mat5[[n, i, j, 4]],                            mat5[[n, i, j, 2]] + zz*mat5[[n, i, j, 5]],                            mat5[[n, i, j, 3]] + zz*mat5[[n, i, j, 6]]};     mat10[[n, i, j, k]] = mat11[[n, i, j, k]].mat9[[n, i, j, k]];          Clear[zz]     ]          ]]     ]


Plot 3D image of function

I'm (very!) new to _Mathematica_ , and trying to use it plot a set in $\mathbb{R}^3$. In particular, I want to plot the set $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{R}^3\setminus\\{0\\} \big\\}. $$ This is just the image of function from $\mathbb{R}^3\setminus\\{0\\} \to \mathbb{R}^3$. I haven't been able to make any of the plot functions display this. Any advice would be greatly appreciated. If it makes it easier, the set above is also $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{u^2+v^2+w^2}(vw,uw,uv) \text{ for some } (u,v,w) \in \mathbb{S}^2 \big\\}. $$ Alternatively, one could plot the three sets $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1+v^2+w^2}(vw,w,v) \text{ for some } (v,w) \in \mathbb{R}^2 \big\\}, $$ $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1 +u^2+w^2}(w,uw,u) \text{ for some } (u,w) \in \mathbb{R}^2 \big\\}, $$ $$ \big\\{ (x,y,z) : (x,y,z) = \frac{1}{1+u^2+v^2}(v,u,uv) \text{ for some } (u,v) \in \mathbb{R}^2 \big\\}. $$


What is PointForm?

I stumbled across a function called `PointForm` but the only documentation I can find is the pop-up line offered by autocomplete, which contains the same information as `Information[PointForm]`: ![enter image description here](http://i.stack.imgur.com/QFBDM.png) What does this mean and how does it work?


How to efficiently find multimap k-itemset frequency

I am doing this to learn association rules. The data `d` is in format `{id, value}`, for example:               {{0, 29}, {1, 30}, {1, 31}, {1, 32}, {2, 33}, {2, 34}, {2, 35}, {3, 36}, {3, 37}, {3, 38},      {3, 39}, {3, 40}, {3, 41}, {3, 42}, {3, 43}, {3, 44}, {3, 45}, {3, 46}, {4, 38}, {4, 39},      {4, 47}, {4, 48}, {5, 38}, {5, 39}, {5, 48}}      Bigger data example (task I am using it for has x100 amount data) I want to find number of id's that contain values `{x, y}` and `P(x|y)`. Something like:               Contains[d_, x_] := Take[Transpose[Select[d, #[[2]] == x &]], 1][[1]]     ContainsBoth[d_, x_, y_] := Length[Intersection[Contains[d, x], Contains[d, y]]]     ProbabilityOfXGivenY[d_, x_, y_] := ContainsBoth[d, x, y]/Length[Contains[d, y]]      I would like to print out a table or export into a file ![enter image description here](http://i.stack.imgur.com/lr3Ov.png) As my effort, I can write a brute force solution, that works well for input size of 100 instances.               GetRow[d_, {x_, y_}] := {x, y, ContainsBoth[d, x, y],        100 ProbabilityOfXGivenY[d, x, y] // N,        100 ProbabilityOfXGivenY[d, y, x] // N}     Select[GetRow[d, #] & /@        Select[Tuples[DeleteDuplicates[Transpose[d][[2]]], 2],          (#[[1]] < #[[2]]) &], #[[3]] > 1 &];     TableForm[%, TableHeadings -> {Automatic, {"x", "y", "\[Exists]{x,y}", "P(x|y)", "P(y|x)"}}]      **edit** : I slightly improved my bruteforce solution:               d = Import["https://raw.github.com/gist/4040530/       fb175e2134559351354572a4aa0554d462cae31b/gistfile1.txt", "Package"];     data = Take[d, 100000];          MultiSet[hm_, key_, value_] := hm[key] = value;     ContainsBoth[hm_, x_, y_] := Length[Intersection[MS[x], MS[y]]]     P[hm_, x_, y_] := 100 (ContainsBoth[hm, x, y]/Length[hm[y]])     GetRow[d_, {x_, y_}] := {x, y, ContainsBoth[d, x, y], P[d, x, y] // N, P[d, y, x] // N}          Timing[      Clear[MS];      MultiSet[MS, #[[1, 2]], #[[All, 1]]] & /@ SplitBy[SortBy[data, Last], Last];      parsedData = {#[[1, 1]], #[[All, 2]]} & /@ SplitBy[SortBy[data, First], First];      nrnodes = Length[pairs = DeleteDuplicates[Flatten[Subsets[#, {2}] & /@         parsedData[[All, 2]], 1]]];      result = GetRow[MS, #] & /@ pairs;      nrnodes]      This completes in 41.091 s on my computer.               Export[FileNameJoin[{NotebookDirectory[], "datax.csv"}], Reverse[SortBy[result, #[[3]] &]]]


Gaps at curve that represents the solution of system of equations as a function of parameter

Manipulate[{       Quiet[sol =           Solve[{K1*P*L == PL, K2*P*L == LP, K3*PL*L == LPL,             P0 == P + PL + LP + LPL, r*P0 == L + PL + LP + 2*LPL}, {P, L,             LP, PL, LPL}]][[2]];       complex[x_] := LPL /. sol[[2]] /. r -> x;       Plot[{complex[r]}, {r, 0.1, 6}]       },           {K1, 1001, 10000},      {K2, 1000, 10000},      {K3, 1000, 10000},      {P0, 0.1, 1}      ]      If `K1 == K2 == K3` we have nice curve otherwise there are gaps at curve. what's wrong?


Using Map with If

I have an If statement I need to carry out where the result should be a single number for each time the if is executed. What I have at the moment returns a list for each time the If is executed. I specifically do not want to use a Do loop so is there a way to use Map to do this?               x = {0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`};     y = {0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`, 0.897409001634915`,         0.897409001634915`, 0.897409001634915`};     z = {0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};          TimeModelSelection[41]     {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}      The first few lines of the result are               Map[If[# == 0, x*y, z] &, TimeModelSelection[41], {1}]     {{0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162}, {0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162, 0.8053429162, 0.8053429162, 0.8053429162,        0.8053429162},...      I have also tried thefollowing without luck               Map[If[# == 0, x[[#]]*y[[#]], z[[#]]] &, TimeModelSelection[41], {1}]


Bug when using Plot3D over an ImplicitRegion?

Evaluating this expression seems to cause Mathematica to beep and quit the kernel:               Plot3D[Exp[Sqrt[x^2]] - Exp[-Sqrt[x^2]], {x, y} \[Element] ImplicitRegion[-5 <= x <= 5 && -5 <= y <= 5 , {x, y}]]      I am running Mathematica 10.0.0 on MacOS 10.9.4. Is this a known issue? Interestingly, plotting only one of the exponentials rather than their difference does not produce any problems.


Forget past outputs to free memory

While tinkering with a notebook that loads a large chunk of data in memory, I noticed that if I run it multiple times, the past chunks reside in memory. I understand that the reason (or one of) for which this happens is that the past output mechanism (`%`) keeps a reference to them, so they cannot be garbage collected. Is there a way to explicitly make _Mathematica_ forget some data?


Sparse convolution of sparse arrays

The documentation for `ListConvolve` mentions that "ListConvolve works with sparse arrays", which is true. The result, however is never sparse, eg:               a = SparseArray[50 -> x, 1000];     b = SparseArray[40 -> 2, 50];     ListConvolve[b, a]      Is there a way to do "sparse convolution"? (The background is multiplication of high-degree many variables polynomials.)


Any ideas on how GeneralMiniMaxApproximation is implemented?

`GeneralMiniMaxApproximation` is used to construct minimax approximations of parametrically defined functions. I am curious about how `GeneralMiniMaxApproximation` is implemented (just a general overview). Any ideas? Or is this a _Mathematica_ trade secret?! The document states that `MiniMaxApproximation` uses Remez's second algorithm, but does this algorithm extend to parametrically defined functions? I can't seem to locate any references.


How to correctly call a Module within another Module?

How to embed and call the correct embedded modules inside another `Module`? Say:               importNames:=Module[{},           CWC=FinancialData["CWC.L","Jan. 1, 2007"];           KON=FinancialData["AH.MI","Jan. 1, 2007"];           IFX=FinancialData["IFX.DE","Jan. 1, 2007"];           ISYS=FinancialData["ISYS.L","Jan. 1, 2007"];           LAD=FinancialData["LAD.L","Jan. 1, 2007"];       ]            checkLength:=Module[{},           LCWC=Length[CWC];           LKON=Length[KON];           LIFX=Length[IFX];           LISYS=Length[ISYS];           LLAD=Length[LAD];       ]            plotNames:=Module[{},           plotCWC=DateListPlot[CWC];           plotKON=DateListPlot[KON];           plotIFX=DateListPlot[IFX];           plotISYS=DateListPlot[ISYS];           plotLAD=DateListPlot[LAD];       ]          Remove[corrMat];       Remove[importNames];       Remove[checkLength];       Remove[plotNames];             corrMat:=Module[{},             importNames;           checkLength;           plotNames;       ]            corrMat       plotNames       plotKON        When doing `plotKON`, how do I know it is calling from within the base definition of `plotNames`, or it is called from `corrMat.plotName.plotKON` (using java syntax)?


Creating a cross referencing shortcut

I believe I have gather all the pieces of information I need to create what I want but yet I cannot make the connection. Let me start with the goal. # Simple Cross referencing Let us start by creating a new notebook. Here we create a `"DisplayFormulaNumbered"` cell. Enter whatever contents you want here. Then press `command`+`J` or `control`+`J` in windows and enter the tag that you want to give your equation. Here is a screenshot of what I have so far: ![enter image description here](http://i.stack.imgur.com/P1INB.png) To be able to see the tag go to `Cell > Cell Tags > Show Cell Tags`. What we want now is to refer to eq1. Here is a text cell: ![enter image description here](http://i.stack.imgur.com/CdpRs.png) Notice here that I'm using the exact $\LaTeX$ notation. What I want to do now, is to be able to select the text cell, press some button in a palette and obtain this: ![enter image description here](http://i.stack.imgur.com/yWq6F.png) # Tools gathered so far jVincent showed me here how to create the a button that executes a function to replace a selected part of the text. Notice here that I do not want to be selecting parts of text manually, I want to apply the function to the whole cell and replace the part containing ref with `CounterBox["DisplayFormulaNumbered", "eq1"]`. In other words, the ref parts will tell it to put "DisplayFormulaNumbered" and the text in between the brackets next to ref is the tag. To find the cases where I have ref we can use something like this:               StringCases["Reference \\ref{tag1} goes here. Reference \\ref{tag2} \here.", "\\ref{" ~~ __ ~~ "}"]          {"\\ref{tag1} goes here. Reference \\ref{tag2}"}      Unfortunately, I'm not quite making a good use of it. But the idea is to maybe use something like this to obtain the tag. Next we have to check if this is a valid tag in the notebook (given that we were able to locate the tag in the whole string):               MemberQ[NotebookTools`NotebookCellTags[EvaluationNotebook[]], "tagName"]      This is thanks to Rojo's answer. I feel a little ashamed that I cannot combine the tools that you guys have provided me yet but I'd rather get this out of the way so that I can be more efficient when doing cross referencing. What do you guys think? Is this worth the trouble of creating a palette button that does this? # EDIT: The idea I was suggesting for making the shortcut is by no means what I wanted to see. I guess I should have clarified that really all I wanted to see was an easy and fast method of dealing with cross referencing. Albert Retey has shown two methods in his answer and makes a good point that if you were to keep typing large chunks of text and evaluate everything in one go then my suggestion would be justified. In any case, I'm satisfied with Retey's method but other neat ideas are still welcomed.


IntegerDigits has Listable attributes, but not fast

See this example, a function has `Listable` attributes often more efficient than `Map`,but why is this one is an exception?               With[{n = 6},        IntegerDigits[Range[10^(n - 1), 10^n - 1]]        ] // Hash // AbsoluteTiming     (*{1.573090, 756716557}*)          With[{n = 6},        IntegerDigits /@ Range[10^(n - 1), 10^n - 1]        ] // Hash // AbsoluteTiming     (*{0.202012, 756716557}*)


Implementing Central Symmetry

I'm interested in implementing symmetry groups. So it would be useful to have central symmetry (isometry transformation). There are built-in functions: `RotationTransform`, `TranslationTransform` and `ReflectionTransform`, but I was not able to find something like central symmetry. The goal is to translate one object of any kind (image or built-in graphical primitives) into the symmetric analog to it. If anyone has any thoughts, please write!


How to compute values only if input fields are filled?

In the following code how can I keep the DynamicModule from computing values if the input values are not all filled? If I don't specify default values it will show the code used to compute the values instead of blank values. Thanks.               backingAgreementValue[w_, \[Sigma]_,        a_] := \[Sigma] /Sqrt[2 \[Pi]] Exp[ -(w - a)^2/(2 \[Sigma]^2)] +        w CDF[NormalDistribution[0, 1], (w - a)/\[Sigma]]          DynamicModule[{w = 40, \[Sigma] = 600, a = 0, n = 100, horseCut = 0.5,        backingValue, expectation, backerValue, horseValue,        horseExpectationPercentage, values},       Deploy[Style[        Panel[Grid[          Transpose[{{Style["Mean", Blue],              Style["Standard Deviation", Blue], Style["Threshold", Blue],              Style["N", Blue], Style["Player Cut", Blue],              Style["Backing Agreement Value", Orange],              Style["Expectation", Orange], Style["Player Value", Orange],              Style["Player Expectation Percentage", Orange],              Style["Backer Value", Darker[Magenta]]}, {InputField[              Dynamic[w], Number], InputField[Dynamic[\[Sigma]], Number],              InputField[Dynamic[a], Number],              InputField[Dynamic[n], Number],              InputField[Dynamic[horseCut], Number],             Dynamic[              Style[backingValue =                 backingAgreementValue[expectation, \[Sigma] Sqrt[n], a] //                  N, If[backingValue >= 0, Darker[Green], Red]]],             Dynamic[              Style[expectation = w n // N,                If[expectation >= 0, Darker[Green], Red]]],             Dynamic[              Style[horseValue = horseCut  backingValue // N,                If[horseValue >= 0, Darker[Green], Red]]],             Dynamic[              Style[horseExpectationPercentage =                 horseCut backingValue/expectation // N,                If[horseExpectationPercentage >= 0.5, Darker[Green], Red]]],             Dynamic[              Style[backerValue = (expectation -                     backingValue + (1 - horseCut) backingValue) // N,                If[backerValue >= 0, Darker[Green], Red]]]}}],           Alignment -> Left], ImageMargins -> 10],         DefaultOptions -> {InputField -> {ContinuousAction -> True,             FieldSize -> {{5, 30}, {1, Infinity}}}}]],       SaveDefinitions -> True]


SplineDegree->1 does not work with BezierFunction?

This works (`SplineDegree -> 2`)               ParametricPlot[BezierFunction[{{0, 0}, {1, 0.5}, {2, 2}}, SplineDegree -> 2][u], {u, 0, 1}]      ![BezierFunction SplineDegree 2](http://i.stack.imgur.com/8fZhz.png) but this does not (`SplineDegree -> 1`)               ParametricPlot[BezierFunction[{{0, 0}, {1, 0.5}, {2, 2}}, SplineDegree -> 1][u], {u, 0, 1}]      > BezierFunction::invdeg: Value of option SplineDegree -> 1 should be a > positive integer, or a list of positive integers I found no reference to a possible issue in the documentation for `BezierFunction`. `SplineDegree -> 1` works fine with `BSplineFunction` and `BezierCurve`; shouldn't it also work with `BezierFunction`? (Mma 8.0.4 Mac OSX)


Is there a way to use functions like Prime[n] within Solve[]?

I'm trying to see if a number can be written as the sum of two prime numbers. Ideally, I would like to use               Solve[ Prime[n] + Prime[m] == 100, {n, m}]      But that simply doesn't work in _Mathematica_. So is there another way to implement this?


How and when to use Evaluate?

A month ago, I used Mathematica to solve my experiment of the Test Technology of Mechanics Engineering. The exeriment is mainly about the Fourier Transform and verify the validity of the theory of Fourier. My code is below:                originwave[t_] :=        If[-5 <= t <= 5, t, If[t > 0, originwave[t - 10], originwave[t + 10]]];     (*the definition of SawtoothWave function*)      **four periodic originwave**               Column[           {Plot[originwave[t], {t, -20, 20}, PlotRange -> {-5, 5},                 AspectRatio -> 1, ImageSize -> 300, AxesStyle -> Arrowheads[0.03],                 AxesLabel -> {"t", "four periodic originwave"}           ]},           Center]      ![four periodic originwave](http://i.stack.imgur.com/ty9AL.png) **The seven order Fourier series expansion**               Column[           {Plot[Evaluate[FourierTrigSeries[originwave[t], t, 7]], {t, -20, 20},                PlotRange -> {-5, 5}, AspectRatio -> 1, ImageSize -> 300,                 AxesStyle -> Arrowheads[0.03],                 AxesLabel -> {"t", "The seven order Fourier series expansion"}]},           Center]      ![The seven order Fourier series expansion](http://i.stack.imgur.com/TAmCy.png) Furthermore,I encounter a problem about Taylor Series that we can use the approximate value of Maclaurin Series to replace a function. I can see the degree of closeness between them by changing the variable n. That's my trial:               Manipulate[               Show[                   Plot[E^x, {x, 0, 5}, PlotStyle -> Pink],                   Plot[Evaluate@Normal@Series[E^x, {x, 0, n}], {x, 0, 5},                         PlotRange -> {0, 150}]],              {{n, 6}, 0, 10, 1, Appearance -> "Labeled"}]      ![enter image description here](http://i.stack.imgur.com/nfGeM.png) Lastly ,the problem of plotting 2-D graph of `|x|+|2x+y|=1`, below is the solution:               Plot[y /. Solve[Abs@x + Abs@(x + y) == 1, y, Reals] //           Evaluate, {x, -2, 2}, AspectRatio -> Automatic]      ![enter image description here](http://i.stack.imgur.com/Yc75g.png) **Summary and my confusion:** In three tasks, I am alway using the `Evaluate` command. Firstly,I know this command and I will remember it when the MMA cannot give the result that I want. However, it is confusing to me that I don't know when to use it or not use it. Can someone help me?


Finding a Concave Hull

I have a 3d clustered data: Is there any other way to get concavehull of 3D data points?


Exporting extremely large images; arrays generated via TensorProduct use 5 times as much RAM as expected?

I am generating plots of the roots of certain classes of polynomials, in the spirit of the multicolored visuals on the Wiki page on algebraic numbers. I've thus far been able to make some extremely spectacular plots, such as this 3600 x 3600 image of the roots of the monic quadratics and cubics (very low-res preview below) ![enter image description here](http://i.stack.imgur.com/KZYZa.jpg) and this 4600 x 4600 image of the roots of the cubics with lead coefficient 5 (low-res preview below) ![enter image description here](http://i.stack.imgur.com/G37MC.jpg) and this 4600 x 4600 image of the roots of the cubics with lead coefficient 1 or 5 (low-res preview below). ![enter image description here](http://i.stack.imgur.com/yBjIW.jpg) I have been running into a RAM usage bottleneck during the `Export` step as I try to make more detailed visuals. To make the images, I essentially execute               Export["Imagename.PNG",Image[A]]      where $A$ is roughly a $4600\times 4600\times 3$ rank-3 array specifying the RGB color channels. I was having issues with the MathKernel swallowing many gigabytes of RAM and initially thought it was from the Image `Export` step, but it turns out it's due to the `TensorProduct` I used to generate $A$. I've begun to observe that arrays generated via `TensorProduct` occupy 5 times as much RAM as I would naively expect. For example,               $HistoryLength = 0;     L = 2000;     a = RandomReal[{-10^6, 10^6}, {L, L}];     b = RandomReal[{-10^6, 10^6}, 3];     c = TensorProduct[a, b];     d = RandomReal[{-10^6, 10^6}, {L, L, 3}];     ByteCount[a]     ByteCount[b]     ByteCount[c]     ByteCount[d]     Quit[]      indicates that $c$ occupies 480 MB RAM, while $d$ occupies 96MB RAM. Choosing $L=4600$ shows that $c$ occupies 2.6 GB RAM, while $d$ occupies 500 MB RAM. Changing the ranges of `RandomReal` from $10^6$ to other numbers does not significantly alter the result. This is a bit unexpected, since both $c$ and $d$ are of the same dimension and same MachinePrecision entry type, and yet the manner of array generation seems to strongly impact the space it occupies in RAM. Question: _Does anyone know why using`TensorProduct` to generate an array creates an array object which occupies 5 times the normal RAM amount as comparable arrays generated via other means?_ EDIT: After applying the packed array fixes, things work well. Here are links to the two notebooks that can be used to generate the images I used. _Root Generator_ is used to compute and export the polynomial roots of one's choice to sparse matrix formats, and _Root Visualizer_ imports the sparse matrices and exports the images. I use packed arrays in the RAM-intensive parts, and `Compile` the convolution kernel used to blur the image. If anyone sees any obvious improvements that could be made, I'd love to hear it.


Permutation count for sets with multiplicities

I am able to do a permutation counr for the set `{a, a, b}` which gives me 3 groups. I am happy with that result. However, if the set is `{a, a, b, c, c, d}`, _Mathematica_ gives me all the possible groups, but it is difficult to count the number of groups. Can _Mathematica_ find the total number of groups? If so, which function to do I use?


Pattern evaluation in nested function call

I'll put the question right here, but will add some context below in case someone wonders why the heck I'm trying to do this. Why is it that I have to do two passes to get the value of the arguments in the call to f1 below?               In[24]:= s = { 10 Cos[-Pi t], -4 Sin[0.23 t]};          In[25]:= f2[a1_, a2_, a3_] := Module[                {a = a1, phi = a3},                Function[                   a a2[phi #1]                ] (* #1 is the time *)               ]                   f1 := Function[                      f2[#1, #2, #3]              ]          In[27]:= l = Cases[s, amp_ trig_ [afreq_ t] -> f1[amp, trig, afreq]]              %[[1]][.33]          Out[27]= {a$1667 Cos[phi$1667 #1] &, a$1667 Sin[phi$1667 #1] &}              (* I expected amp and afreq to have been replaced by                 their matched values, and a numerical value here *)     Out[28]= amp Cos[0.33 afreq]                   (* It works as I (naïvely) expected when I introduce this temporary symbol, func *)     In[29]:= l = Cases[s, amp_ trig_ [afreq_ t] -> func[amp, trig, afreq]]              % /. func -> f1              %[[1]][.33]          Out[29]= {func[10, Cos, \[Pi]], func[-4, Sin, 0.23]}          Out[30]= {a$1668 Cos[phi$1668 #1] &, a$1669 Sin[phi$1669 #1] &}          Out[31]= 5.09041      **Context:** I'm a total noob to Mathematica, but I do ok with plenty of other progamming languages. This issue came up in a structural dynamics course I'm teaching, using Mathematica as a support tool. Not that it should matter here, but I'm using it to compute the dynamic response of a SDOF system to a periodic excitation. I compute the Fourier series expansion of the forcing function, then apply a function that I've written to all terms of the expansion and then sum it all up. I have removed all of the details of this to concentrate on the essence of the problem, but I'd be more than happy to post the entire functions in case it helps. I come from a hpc background, where we tend to overcomplicate things in search of "efficiency", bear that in mind :) The general ideal is that the response is a function of many physical parameters, and the time, but for a single term of the expansion, only the time varies and the physical parameters are fixed. I wrote a function that takes all the physical constants and forcing terms, computes some constants _as local variables inside a module_ , and returns a function of time using these constants. For all terms of the expansion, however, the physical parameters are the same, just the forcing terms are different, so I wrote another function that takes the physical constants, and returns a function that takes only the forcing terms, combines them with the physical parameters and calls the function above, returning a function that depends only on time, and has all that is constant precomputed. It's worth noticing that the variable that is not local to the module always gets substituted. Even though the original question has been answered, I'm adding the original functions here as a justification for my roundaboutery...               fresp[F0_, w_, m_, c_, k_, trig_] :=       Module[{phi = ArcTan[k - m w^2, c w], A = F0/Sqrt[(k - m w^2)^2 + (c w)^2]},       Function[ t, A trig[w t - phi]]]     ]          tresp[ m_, c_, k_] := Function[        fresp[#1 (*F0*), #2(*w*), m, c, k, #3(*trig*)]     ]          mck1 = tresp[2., 2., 3.]     mck2 = tresp[1., 1., 2.]      The idea being that each mck function would represent the response of a different physical system. I apologize if my mind has been poisoned by object orientation :)


How can I make a ContourPlot3D with inequality constraints?

I need to plot a function in implicit form as below:               ContourPlot3D[{73.04 z*y^2 - 293.04 z*x^2 ==         2605.68 y^2 - 2605.68 x^2}, {x, 0, 3}, {y, 0, 6}, {z, 0, 15}]      but with the constraint `x > y`. How can I do this with _Mathematica_?


Set of integers not divisible by smaller set of primes

Let $p_n$ be the sequence of prime numbers, and $s(x,n)=$ the set of integers less or equal than $x$ that are _not_ divisible by $p_1,\dots,p_n.$ I can define it as follows:               s[x_,n_]:=DeleteCases[Map[If[Total[Table[Map[If[CoprimeQ[Prime[Range[n]],a][[#]]==True,1,0]&,Range[n]],{a,1,x}],{2}][[#]]==n,Range[x][[#]],0]&,Range[x]],0]      But it is inefficient. I am sure there is a more efficient way of doing this.


How to make this particular replacement involving exp

I apologize if similar questions have already been asked, but I have some difficulties with replacements in Mathematica and I would like to make a substitution like               Exp[I m phiA] --> f[m,phiA]     Exp[I m phiB] --> f[m,phiB]      where m is a number and `phiA`,`phiB` are variables, in expressions that contain sums in the exponent, e.g.               2 + Exp[-2 I (phiA + phiB)] + Exp[2 I phiA + 2 I phiB]      which should give               1/4 + f[-2,phiA] f[-2,phiB] + f[2,phiA] f[2,phiB]      Is this possible? How can it be done?


A Box for the integral or partial derivative d

I am looking for the name of the box in the Box Language of Mma making integrals, such as those shown in the image below ![enter image description here](http://i.stack.imgur.com/5t7Nx.jpg) as well as of the sign of the partial derivative. I understand that I can get it through MakeBoxes trick, but it would be nicer to have special operator for such a purpose. The code with such an operator will be more concise.


Can ReplacePart be sped up?

Test case:               data = RandomReal[1, {1000, 1000}];     pos = RandomInteger[{1, 1000}, {5*10^5, 2}];     r1 = ReplacePart[data, pos -> 0]; // AbsoluteTiming     (data[[##]] = 0) & @@@ pos; // AbsoluteTiming     data == r1          (*     {3.433196, Null}     {1.892108, Null}     True     *)      The similar matlab code only takes about 0.16 second:               tic;     A=rand(1000,1000);     pos= randperm(5e5);     A(pos)=0;     toc;     (*Elapsed time is 0.166717 seconds.*)      I am looking for a more efficient way.


How can I get $(r^{1/x})^x$ to simplify to $r$?

`Simplify` and `FullSimplify` do not simplify this kind of expression: $(r^\frac{1}{x})^x$. Consider               FullSimplify[r^2+(r^(2/x))^x+(r^(2/(x+y)))^(x+y)]      _Mathematica_ 's output is the same as my input, instead of `3 r^2`. Is there a way to simplify $(r^\frac{1}{x})^x$ to $r$?


Domain restrictions for NMaximize

I am trying to solve a maximization problem, where my variable can only take a limited number of values. (Probably) the easiest example would be               dom = {0, 1/2}; NMaximize[{x^2, Element[x, dom]}, {x}]      While the `Element[x,dom]` syntax works just fine for `dom = Integers`, I keep getting error messages for any other domain. (edit: this seems to be because my chosen domain is invalid to use with ∈) edit: I also tried the `MemberQ` syntax as stated below:               dom = {0, 1/2}; NMaximize[{x^2, MemberQ[dom, x]}, {x}]      This seems to be an acceptable constraint, but for some reason _Mathematica_ seems unable to find a value that meets the constraint, as I get the following message: > NMaximize::nsol: There are no points that satisfy the constraints {False}. Any other ideas? edit: just to clarify. I need to restrict the variable(s) to a finite set of real numbers, hence I cannot use ">=/<=" constraints to get the job done. The above is just the simplest application I could think of.


Log is not being evaluated inside Grid

My command is:               Grid[{{N, logN!, N log N - N}, {10, Log[10!], 10 Log[10] - 10}}, Frame -> All]      In the second row of the grid, the function `Log[]` is not being evaluated. Please let me know what is going wrong.


How to render a 3D ellipsoid with Graphics3D?

With `Graphics3D[Sphere[{0,0,0},1]]` I can render a uniform 3D sphere, but how can I render an ellipsoid? I would need to specify the rotation of the ellipsoid and the length of the main axes. And the method should be reasonable fast to display around 100 at once.


Help on evaluation control?

I want to plot series of slopes: x, 2x, 3x, 4x, 5x, 6x... I'm trying to do this:               a = Range[10]; c = 0; Clear[b]     f := ToExpression[ToString[b] <> ToString[a[[c = c + 1]]]]      So everytime I input `f`, it gives me:               b1     b2     b3     b4     ...      Now I want to assign every bn to one of the plots:               b1=Plot[x,{x,1,10}]     b2=Plot[2x,{x,1,10}]     b3=Plot[3x,{x,1,10}]     b4=Plot[4x,{x,1,10}]     ...      I've tried to do this:               f=Plot[x,{x,1,10}]      But It will only switch the variable from the first fuction to the Plot function. How can I do to the `f`become `b1` first and then the `b1` be assigned to the Plot function? I guess it has something to do with evaluation control, something like that. NOTE:. The ? in the title means that I'm not very sure If it's about evaluation control.


How to get the quantity of Physical constants?

I need to get the quantity of gravitational constant: `QuantityMagnitude[GravitationalConstant]` why this is not work? Already load the `PhysicalConstants` package.


Interpreting a certain result of Minimize

I am given a certain function $f(k_1)$ that I would like to minimize. Asking Mathematica to do it (and supplying the given bounds of other parameters in the expression) I get the following result:               f[k1,k2] = (k2 * r + k1)/(r + (k2*r + k1 -1)*d) + (k1 * r + k2)/(r + (k1*r + k2 -1)*d)     k2 = 2*n/(r+1)-k1       Minimize[f, {k1 >= 0, r >= 2, n >= 2,k1 <= 2*n/(1+r),  d >= 2, d <= r}, {k1}]      > >      {Piecewise[{{f, d >= 2 && r >= d && n >= 2}}, Infinity], >          {k1 -> Piecewise[{{n/(r+1), d >= 2 && r >= d && n >= 2}}, > Indeterminate]}} >   My question now is: What is this result supposed to mean? Somehow I am not able to understand what the output tells me about the minimum of the function I am trying to minimize.


How to get the distance of Jupiter from the sun?

I am aware of the command `AstronomicalData["Jupiter", "Distance"]` from which I can get the distance between the earth and Jupiter. Is there any way to use `AstronomicalData` to get the distance between the sun and Jupiter?


Solve Laplace equation using NDSolve

I am new to Mathematica, a friend recommended this software and started using it, in fact download the trial version to know. I recently did a program in C to calculate numerically the solution to the Laplace equation in two dimensions for a set of points as in the figure. ![enter image description here](http://i.stack.imgur.com/ustcO.png) The result was very good, finding the image below. ![enter image description here](http://i.stack.imgur.com/6OKmy.png) This program took me about 100 lines in C, my friend told me that Mathematica could do it in a couple of lines, which seemed quite interesting. I studied a bit and found that Mathematica can solve the Laplace and Poisson equations using NDSolve command. However, this command requires to be given to the specific boundary conditions. The boundary condition in which $\phi = 0$, it is quite easy to introduce. But on the inside border, where $\phi = 100$, I failed to get the condition. My idea is to make this problem as follows:                           uval = NDSolveValue[{D[u[x, y], x, x] + D[u[x, y], y, y] ==                  0,                  u[x, 0] == u[x, 100] == u[0, y] == u[100, y] == 0,                  u[40, y] == u[60, y] == u[x, 40] == u[x, 60] == 100},                  u, {x, 0, 100}, {y, 0, 100}]      But this does not work, and I could not give the boundary conditions on the inner square. Any help would be the most grateful.


Find the point that holds a given property

I have a normal distribution with mean 106, and a standard deviation of 8. I'm being asked to find the point that has the property that 25% of these values have this value or lower. What I've concluded on my own (I'm just learning _Mathematica_ ) is that the value I'm looking for would be `y` in the following:               NProbability[x <= y, x \[Distributed] NormalDistribution[106,8]] = 0.25      Since I'm not very well versed in the language, I'm hoping someone can lead me in the right direction here.


Find file names in directory

I am trying to find the list of any file in any directory of a given name (by in the directory, I mean directly in the directory, so in a directory which is in the directory would not count). For the sake of example. Let's suppose I want to find all files in each folder called "Preferences", and let's restrict our search to the folder ~/.Mathematica. If I wanted to do this from the terminal, I could just do `find ~/.Mathematica -regex ~/.Mathematica.*Preferences/[^/]*`. This works and I see there is a single file matching my criteon, `~/.Mathematica/ApplicationData/Parallel/Preferences/Preferences.m` But I want to try to do it conveniently in mathematica. I am thinking the `Filenames` function should do it. I will first run `SetDirectory["~/.Mathematica"]` Then I would run               fileAndDirectoryNames =       FileNames["*",RegularExpression[".*Preferences"], 1]      followed by               fileNames = Select[fileAndDirectoryNames, ! DirectoryQ[#] &]      However, this gives incorrect results for me: `fileAndDirectoryNames` is an empty list. If I instead run               fileAndDirectoryNames =       FileNames["*", RegularExpression[".*/.*/Preferences"], 1]      and recompute `fileNames` as before, then I get correct output. I am confused because it seems to me that the regular expression in my second attempt is stronger (allows for fewer matches) than the one in my first attempt. The fileNames function should have a monotonicity property in the second argument that if you weaken the pattern, then the new output ought to be a superset of the original output. Yet this doesn't seem to happen. Why is this? I am not sure if I am having a problem with mathematica or my understanding of regular expressions.


Visualization of iteration procedure in NMinimize

I have this optimization code:               vars1 = Array[Subscript[x, #] &, {4}];     ka = {35, 10, 20, 25};     objectiveFunction = Total[ka.vars1^5];     NMinimize[{objectiveFunction/100,      Apply[And, Thread[GreaterEqual[vars1, 0]]] && Total[vars1] == 100 &&     Element[vars1, Integers]}, Flatten[vars1], MaxIterations -> 200]      How is it possible in MMA to capture the values of variables and also objective function in each iteration and plot them versus iteration number??(Separate plots or all in one plot?)


Strange behaviour of Internal`InheritedBlock

I was going to post an answer for fast way to replace all zeros in the matrix. I was even quite happy because timings were the same order of magnitude as others. The idea was to overwrite `Identity`:               Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;              Map[Identity, {{2, 0}, {Pi, 9}}, {2}]]      > >     {{2, 1}, {Pi, 9}} >   But I've checked that for bigger matrices the result is not even close to the expected one:               Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;              m = RandomInteger[1, {100, 2}];         Map[Identity, m, {2}] ~ Shallow ~ {5, 2}]      > >     {{0, 1}, {1, 0}, <<98>>} >   * * * It seem it breaks at **size** of the array of about $90$ positions:                test = Internal`InheritedBlock[{Identity}, Unprotect[Identity]; Identity[0] = 1;                   Apply[               Boole[Map[Identity, RandomInteger[1, {##}], {2}] == ConstantArray[1, {##}]                    ]&,                                    Array[List, {35, 35}],               {2}]];          Show[MatrixPlot[test, DataReversed -> True, Mesh -> All],          ContourPlot[x y == 90, {x, 1, 35}, {y, 1, 35}]          , BaseStyle -> {Thickness@.01, 18}]      ![enter image description here](http://i.stack.imgur.com/XLFUA.png) * * * I hope I haven't missed anything obvious. Any ideas?


how to take some parts of String with certain pattern

I have the large number of files in which the file's names follow certain pattern. for example here are names of two files               name1="event_No. 2_20140311_910_914.jpg"     name2="event_No. 403_20140311_230727_230731.jpg"      I need to extract the last two numbers of the names to get something like this (String or Expression, it does not matter):               {"910","914"}     {"230727","230731"}      I tried StringTake but it is not supporting Rules and patterns. can any one suggest some way to do this? Thanks


How to determine BLAS/LAPACK implementation used internally for numerical matrix operations?

Is there a command which reveals which implementation of BLAS and LAPACK are used in Mathematica's matrix operations such as `Eigensystem`? I asked a related question on StackOverflow and one user mentioned that in Julia, the BLAS/LAPACK implementation can be found by executing `versioninfo()`. Several users who tried my code there had varying results, with some observing Mathematica to execute faster, and others observing Julia executing faster. In my case, my Julia installation appears to make use of the OpenBLAS implementation, and it runs between 3 to 6 times slower than Mathematica's `Eigensystem` for randomly-generated arrays of size $1000\times1000$ to $2000\times2000$. In the Mathematica documentation's tutorial/SomeNotesOnInternalImplementation, it mentions "For dense arrays, LAPACK algorithms extended for arbitrary precision are used when appropriate" and "BLAS technology is used to optimize for particular machine architectures", but nothing more. EDIT: So in response to Kuba's comment, apparently one of the Julia devs noted that there is anomalous behavior in Julia with regards to eigenvector computation speed as a function of BLAS thread number. In short, using more threads in Julia's use of OpenBLAS appears to slow things down considerably. For reference, in Mathematica:               SetSystemOptions["MKLThreads" -> 1];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 2];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 3];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     SetSystemOptions["MKLThreads" -> 4];     First@Timing@Eigensystem[RandomReal[{-500, 500}, {1000, 1000}]]     (*Out:*)     1.747211     1.466409     1.341609     1.357209      So I guess there's nothing wrong with Mathematica's implementation.


MathLink linking error after OS X 10.9 (Mavericks) upgrade

After macosx 10.9 mavericks upgrade i have a compilation problem, you can see below. Even the examples given in /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples are not compiling anymore. It throws an error about the architecture. I also followed the solution given by MathLink compile errors, reinstalling the Xcode and command line tools. It didnt work. I also checked the _libMLi3.a_ for architecture and seems like it is ok *libMLi3.a: Mach-O universal binary with 2 architectures libMLi3.a (for architecture i386): current ar archive random library libMLi3.a (for architecture x86_64): current ar archive random library* and clang/gcc as well > Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) Target: > x86_64-apple-darwin13.0.0 Thread model: posix > > gcc -v Configured with: > \--prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include- > dir=/usr/include/c++/4.2.1 Apple LLVM version 5.0 (clang-500.2.79) (based on > LLVM 3.3svn) Target: x86_64-apple-darwin13.0.0 Thread model: posix which are the latest. **I wonder if anyone manages to compile the MathLink examples after the 10.9 upgrade?** Here is the error message:               /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples]:>      g++  -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples/../CompilerAdditions \     addtwotm.o addtwo.o -L/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MacOSX-x86-64/MathLinkExamples/../CompilerAdditions \     -lMLi3 -lstdc++ -framework Foundation -o addtwo     Undefined symbols for architecture x86_64:       "std::string::find_last_of(char const*, unsigned long, unsigned long) const", referenced from:           MLThreads::DestroyName(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)       "std::string::find_first_of(char const*, unsigned long, unsigned long) const", referenced from:           MLThreads::NameValidQ(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)           MLThreads::DestroyName(std::string&) in libMLi3.a(mlplatformthreads.cpp.o)       "std::string::find(char const*, unsigned long, unsigned long) const", referenced from:           _mlipinterfacecontainer_get_domain_names in libMLi3.a(mlipinterface.c.o)           MLNetwork::MLIPAddress::LoadDomainName(bool) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::IPV4NameQ(std::string) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::IPV6NameQ(std::string) in libMLi3.a(mlipaddress.cpp.o)           MLNetwork::MLIPAddress::AutoconfiguredQ() const in libMLi3.a(mlipaddress.cpp.o)           _pipe_make in libMLi3.a(_pipe.c.o)           MLDevices::MLTCPIPDevice::OldConnectServer() in libMLi3.a(mltcpip.cpp.o)        .        .        .        .        .        .           ...       NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.     ld: symbol(s) not found for architecture x86_64     clang: error: linker command failed with exit code 1 (use -v to see invocation)


How do I save/export a list so that it can later be easily imported as a list again?

I have a couple of big lists (each of them contains elements that are themselves lists of two elements, i.e. an element of each list that I have is of the form {x, y}) that I want to save/export. Their generation namely takes hours, and I don't want to do this every single day. I looked at the Mathematica help section on this (http://reference.wolfram.com/mathematica/tutorial/ImportingAndExportingData.html), but found that if I follow the example, I can't just import the data back into a list as it was before. It just ends up being something really messy. So given such a list, say, list = {{1,2}, {1,3}, ... , {500, 500}}, what do I do, so that the next day I can just write list = Import[...]?


How to create an adjustable Bézier curve?

I tried to create an adjustable `Bézier curve` with the following simple code. However the curve didn't show up. What is the problem? Please help.               pts = {{0, 0}, {1, 2}, {2, 0}, {3, 3}};     bez = BezierFunction[pts ];          Manipulate[      Show[Graphics[{Red, Point[lo], Green, Line[lo]}, Axes -> True],        ParametricPlot[bez[lo ], {t, 0, 1}], ImageSize -> { 200, 200 }],      {{lo, pts}, Locator}      ]      ![enter image description here](http://i.stack.imgur.com/YOKLG.gif)


Compute coefficient of Generating function

Given a generating function $F(z)$, is there any way to compute the coefficient $a_k$ of $z^k$ by Mathematica? One method is to calculate by the equation $\frac{F^{(k)}(0)}{k!}$. However, this approach is not feasible for $k$ large.


displaying Laurent polynomials nicely

I have some 2-variable Laurent polynomials in $q$ and $t$, and I'd like to collect powers of $q$ and display them without using fractions, and to sort the terms by the power of $q$. For example, I'd like to display $(t-t^{-1})q^{-1} + (t^{-1})q$, instead of $(t-\frac 1 t)\frac 1 q + \frac q t$ which is what Mathematica wants to output. Is there a nice way to do this? Right now I'm applying the function > StandardForm[# /. Power[expr_, r_?Negative] :> Superscript[expr, r]] & to the polynomials I'd like to display, which makes negative powers display as exponents. But the problem is that Mathematica then doesn't sort the terms correctly, since it doesn't recognize the "Superscript" as a power.


How to convert an output to a graphic that can be selected like a plot?

EDIT: István Zachar informed me of the **Rasterize[]** command, which does exactly what I need. Danke! I have a self-built function that uses Grid[] to create a table that is more presentation-friendly than TableForm. Example output is: ![Example output of dougTable](http://i.stack.imgur.com/tbBLt.png) What I usually do to copy this into a presentation is take a screenshot with the Snipping Tool. For plots, I can just select the plot in Mathematica and then select Edit -> Copy As -> Bitmap. I want to be able to do the same with this table. Right now, if I try selecting the table, I get a cursor and can start typing in the figure. I was hoping there was a Mathematica function that just puts a selectable bounding box around the entire output of a function, but I've been unable to find one yet. Does anyone have any ideas on how to make this entire table selectable? Source code for my function can be found below, although you shouldn't need to use it to find a solution to the problem: any function with a non-graphic default output should work fine.               Clear[dougTable]     dougTable[data_List, cols_List: {}, rows_List: {}] :=      Module[       {genOpts, none, colHead, rowHead, both, font},       genOpts = {Frame -> All, Background -> RGBColor[1, .9, 0],          FrameStyle -> Thickness[1]};       font = {FontFamily -> "Arial", FontSize -> 12, FontWeight -> "Bold"};       none = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2]}, {1 ->              Thickness[2], -1 -> Thickness[2]}}};       both = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}, {1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}},          ItemStyle -> {{Directive[font], Automatic}, {Directive[font],             Automatic}}};       colHead = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2]}, {1 ->              Thickness[2], -1 -> Thickness[2], 2 -> Thickness[2]}},          ItemStyle -> {Automatic, {Directive[font], Automatic}}};       rowHead = {genOpts,          Dividers -> {{1 -> Thickness[2], -1 -> Thickness[2],             2 -> Thickness[2]}, {1 -> Thickness[2], -1 -> Thickness[2]}},          ItemStyle -> {{Directive[font], Automatic}, Automatic}};            Which[Length[cols] == 0 && Length[rows] == 0, Grid[data, none],        Length[cols] != 0 && Length[rows] == 0,         Grid[Prepend[data, cols], colHead],        Length[cols] == 0 && Length[rows] != 0,         Grid[MapThread[Prepend[#1, #2] &, {data, rows}], rowHead],        Length[cols] != 0 && Length[rows] != 0,         Grid[Prepend[MapThread[Prepend[#1, #2] &, {data, rows}], cols],          both]]       ]


Plotting in the "Manipulate" function - simple coding

Hello Mathematica community, my name is Preston! I have a real quick question that should be easy to answer. Alright, so for a research project that I'm involved it at my university, I need to illustrate the outline of a Cassini Oval using something I've been calling "concentric circles" - but that doesn't really matter. I've decided to use Mathematica in my research. I used the "Manipulate" function in order to illustrate what these "concentric circles" would do as their radii varied over a specific interval. Here's the code for that:                   Manipulate[         Graphics[{Circle[{-1, 0}, H], Circle[{1, 0}, 1.2/H]},          Axes -> True], {H, Sqrt[1.2 + 1] - 1, Sqrt[1.2 + 1] + 1}]        That is all fine and good, and it does exactly what I want. However, I really need to somehow plot the curve of the following function in the Manipulate:                   [(x+1)^2+y^2]*[(x-1)^2+y^2]=(1.2)^2      So, basically, as the manipulator runs, I want the "concentric circles" to do what they do, but I want the function I just listed to just sit still. The idea is that as the "concentric circles" change over the interval defined for $H$, their intersection will outline a Cassini Oval (the equation above). I would greatly appreciate any help. Thanks! Also, what I'm trying to do may be illustrated in the following code:                    x = Table[{(-1 + H^4)/(4 H^2), Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H}, {H, 1, 1 + Sqrt[2], 0.01}];              x1 = Table[{(-1 + H^4)/(4 H^2), -(Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2((-1 + H^4)/(4 H^2))^2]/H)}, {H, 1, 1 + Sqrt[2], 0.01}];              x2 = Table[{-((-1 + H^4)/(4 H^2)), Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H}, {H, 1, 1 + Sqrt[2], 0.01}];              x3 = Table[{-((-1 + H^4)/(4 H^2)), -(Sqrt[1 - H^2 + (2 H^2 (-1 + H^4))/(4 H^2) -               H^2 ((-1 + H^4)/(4 H^2))^2]/H)}, {H, 1, 1 + Sqrt[2], 0.01}];               m =              Manipulate[                  Graphics[{Green, Circle[{1, 0}, 1/H], Blue, Circle[{-1, 0}, H],                   Black, {BezierCurve[x]}, {BezierCurve[x1]},                   {BezierCurve[x2]}, {BezierCurve[x3]}}, Axes -> True], {H, 1/(Sqrt[2] + 1),                   Sqrt[2] + 1}]      This is something I did for a trivial Cassini Oval with constant product equal to 1. It sort of does what I want, but it's way to complicated and glitchy. I want to know if a more evolved code is possible.


ParametricPlot with plot markers

I have a parametric plot, and would like to fit a line to it with "■" `PlotMarkers` on it, but am unable to do so.               ParametricPlot[{f(x), g(x)}, {x, 0, 1}, AxesLabel -> {"x", "y"}, PlotMarkers->{"■", 10.9}]


Numerically Solving two dependent Transcendental Equations

I need to solve a system similar to the following (Except it is quite large. Solving this ought to do the job): $$ \tan[2f(t)] = 1+ t^2\ $$ and $ f(t) $ is $ k $, such that$$ \tan[2kt]-(1+k^2) = 0\ $$ I have used `RootSearch` for both equations as I also know the range in which $k$ and $T$ lie. The sample of my code is below.               f[T_] := k /. Extract[Flatten[Quiet[RootSearch[Tan[2*k*T] - (1 + k^2) == 0, {k, 0, 1}],              $MinPrecision::precset]], -1];          Extract[Flatten[Quiet[RootSearch[Tan[2*f[T]] - (1 + T^2) == 0, {T, 0, 1}],             $MinPrecision::precset]], -1]      and I end up getting the following error               ReplaceAll::reps: {k,0,1} is neither a list of replacement rules nor a valid dispatch table,     and so cannot be used for replacing. >>      Please suggest a solution. It would be preferable to use something as powerful as `RootSearch` because my other equations seem to be unsolvable via `FindRoot` or `NSolve`.


Fill circle layers with colors according to read values from a plotted curve

I want to read (temperature) values from plotted (cooling) curves and visualize them in layered circles. I have an example made manually for clarification: 3 plotted curves, at certain time steps the value of all plotted curves are read out -> I made a scale assigning (temperature) values to colors. These colors are used further to color the inner circle ( _value from curve "center"_ ), the mid-layer ( _value from curve "half radius"_ ) and the outer layer ( _value from curve "radius"_ ). Data can be found here (csv-file) Thank you for helping me! ![enter image description here](http://i.stack.imgur.com/Pb4IH.jpg)


False Color SEM image with Mathematica

I have a question regarding colouring and binary image filtering, but unfortunately, the system doesn't permit the inclusion of images for first- timers. If anyone would like to see the images described below, please email me directly. I have an image of gold electrodes on a flat substrate obtained with a scanning electron microscope. I would like to colour in all the gold electrodes and particles that appear in the centre of the image, leaving the colour of the background as it is for now. I perform straightforward routines by implementing the following code: Firstly, I rename the image q: `q=Image`; Then I apply the PeronaMalik Filter to enhance the edges and diffuse the background:               pq = PeronaMalikFilter[q, 20, 0.02, 2]      The background in the image thus obtained looks more diffused and uniform, while the edges of the gold electrodes and particles appear sharp, in contrast to the background. Then I give the following command to colour in the gold               goldq = ImageApply[# {1., 0.843104, 0.} &, q,        Masking -> SelectComponents[Binarize[pq, 0.36], "Area", # > -300 &]]      The result is an image in which the gold electrodes are almost entirely coloured in gold, but there are also large regions that are coloured by gold, which shouldn't be; for instance, the left side of the image, and the top right and bottom right. It seems that these areas receive colour due to the fact that they have the same binary level as the actual gold electrodes, which is an artefact of the scanning, and should definitely have the same zero level as the rest of the background. Is there any way to correct this gaffe digitally using Mathematica's built-in functions? Is it possible, additionally, to give the background a different colour? * * * As suggested, here are all three images: Original image: ![original image](http://i.stack.imgur.com/Lns0F.jpg) After filter: ![After filter](http://i.stack.imgur.com/kcHJ6.jpg) After gold: ![After gold](http://i.stack.imgur.com/qqcBa.jpg)


Prevent interdependence of controls

My question is probably best illustrated with this small sample code:               Manipulate[      Plot[{eqn1, eqn2, eqn1-eqn2}, {x,-5,5}],      {{eqn1,r-x,"y1="}},{{eqn2,E^-x,"y2="}},      {r,-2,2}     ]      I would like to be able to have the user input two equations which including a variable `r`, and then use the slider to manipulate this variable. The issue is that `Manipulate` changes `r` within the input field, and then doesn't update the graphs. Is there a way of allowing the user to input an equation which contains one of `Manipulate`'s variables without having it change that variable within the input field?


Convolution with interpolated function

I have some problems to calculate in reasonable speed the convolution of an interpolated function with a Gauss function. I have here (ExampleData.txt, alternate Pastebin link) data which I interpolate linearly:               data = Import["ExampleData.txt", "Table"];     interPolFunc = Interpolation[data, InterpolationOrder -> 1]      First, I tried to work with following function (I have to add a Dirac delta function to my interpolated function):               firstTry[y_] := Integrate[        PDF[NormalDistribution[0, 0.008],x-y]*(interPolFunc[x] + 4 DiracDelta[1-x]), {x, 0, 1.1}];      If I calculate some values with               firstTryTable = ParallelTable[{u, firstTry[u]}, {u, 0, 1.1, 0.005}];      I only get back the contribution of the Dirac delta function. If I use this function                secondTry[y_] :=           Integrate[PDF[NormalDistribution[0, 0.008], x - y]*4*DiracDelta[1 - x],{x, 0, 1.1}]  +           Integrate[PDF[NormalDistribution[0, 0.008], x - y]*interPolFunc[x],{x, 0, 1.1}];      and calculate values with                secondTryTable = ParallelTable[{u, N[secondTry[u]]}, {u, 0, 1.1, 0.005}];      then the result seems to be reasonable. So, my first question (not so important) is:   Why do I get back two different results? The second is:   Is there any way to decrease the calculation time? It is really slow. I would be happy about some help.


How can a big table be treated as a database?

I often work with big tables that I want to treat kind of like a database. Here's an example table.               theTable = {      {"id","color","size","flavor"},      {1,"blue",5,"cherry"},      {2,"green",5,"piquant"},      {3,"blue",20,"peppermint"}     }      In a database I would ask               SELECT * FROM `theTable` WHERE `color` = 'blue' AND `size` > 10      and get effectively               {{3, "blue", 20, "peppermint"}}      in response. In _Mathematica_ , I need to determine the "column number" for `color` and `size`, then use `Cases` with `And` to do the same thing.               Cases[theTable[[2 ;;]], a_ /; And[a[[2]] == "blue", a[[3]] > 10]]      This is operationally much clumsier than the database way. Unfortunately setting up a database for every such table is too much extra work, particularly since I want the data to end up in mma anyway. How can this approach be improved? Specifically, how can I more easily use the column names directly, instead of their part numbers? And how can I avoid the ugly `a_/;f[a]` pattern?