Skip to main content

Posts

Showing posts from July, 2015

How to call an old build-in function in a new version of Mathematica?

In order to use the UnitStep of Mathematica 5.2, I have to install two different versions 5.2 and 11.3 at the same time because Unitstep is different in the two versions (UnitStep has different derivatives in the two different verions of Mathematica, I listed the difference here ). Today I suddenly think of that: Can I call the old version UnitStep of MMA 5.2 in the new Mathematica 11.3? How to realize if it's true? Thank you.

Remove static objects from an image sequence

Is it possible to remove static objects/pixels from a sequence of images? Lets say I have a black square in the middle of my white picture (white background) and a black circle is orbiting around it. The result would be that my images will only contain the moving black circle from frame to frame and that the static black square would be colored white and though "removed". My example would be something like this: Manipulate[Graphics[{ Opacity[0], Rectangle[{-1.1, -1.1}, {1.1, 1.1}], Opacity[1], Rectangle[{-.5, -.5}], Disk[{Cos[p], Sin[p]}, .1] }], {p, 0, 2 Pi}] Which gives this image sequence My first thoughts were going to something like that "put a circle around a cell"-thing with which one could identify not moving cells by looking at the static positions of the targeted cells positions. But I don't have enough expertise in that to manage this problem by myself right now. Another thing that I came up now was the possibility to create a table with a

manipulate - Clicking to add/remove a Locator

I would like to add a Locator to a figure displayed by Manipulate when I click inside the figure, at the location where I click, and to have this trigger an update of the figure. I would also like to have clicking on an existing Locator remove it, and dragging a locator reposition it (again, redrawing the figure in response in each case). For (a silly) example, I would like clicking anywhere in the region displayed by With[{locs = {}}, Manipulate[Graphics[Text[locs, {0, 0}], PlotRange -> 2], {{q, {1, 1}}, Locator, Appearance -> Graphics[{Green, Disk[{0, 0}, .1]}, ImageSize -> 10]}, {{p, locs}, Locator, Appearance -> Graphics[{Red, Disk[{0, 0}, .1]}, ImageSize -> 10]}]] to add the corresponding Point to locs , and for clicking on any p Locator to remove it from locs , with the text, updating accordingly in response to additions, deletions or repositionings of a Locator . To make things hard, I have another locator q that needs to coexist with the one to

import - Plotting a large number of data points

I would like to know how to plot when I have a large number of points (arround 600) in a specific format: X Y 1.000E-03 1.251E+01 1.500E-03 1.201E+01 2.000E-03 1.144E+01 2.484E-03 1.088E+01 2.484E-03 1.088E+01 2.534E-03 1.082E+01 2.586E-03 1.076E+01 2.586E-03 1.076E+01 3.000E-03 1.027E+01 3.066E-03 1.019E+01 3.066E-03 1.019E+01 All I need is to draw a line trought those points, but it would be anoying to write points in format (x1,y1), (x2,y2), ... . It would be tedious if I had to insert the commas and braces by hand for every pair of points coordinates. I'm totaly new in Mathematica and I would appreciate help. Answer Here is a complete walkthrough to expand on Zahra's answer a little. I'm assuming that the exact contents of the example in your question is saved in a text (ASCII) file data.dat in your home directory (or the current working directory of your notebook). dataContent = Import["data.dat"] (* ==> {{"X", "Y"}, {0.001

evaluation - Unexpected behavior of Set

Set doesn't work in some conditions. (* Input separately, whithout "()" or ";" *) In[1]:= expr1 = x + y == 0 && x > 0 Out[1]= x + y == 0 && x > 0 In[2]:= expr2 = x + y == a && x > 0 Out[2]= x + y == a && x > 0 In[3]:= {expr1, expr2} Out[3]= {expr1, x + y == a && x > 0} Evaluating again would make the assignments successfully. (* Chinese Edition *) In[4]:= $Version Out[4]= "10.3.1 for Microsoft Windows (64-bit) (December 21, 2015)" I'm wondering if I have done something wrong. However, I found that Mathematica returned to normal behavior when I minimized the Suggestions Bar. Any ideas?

NIntegrate & non-numerical values

I am wondering why I am receiving the message "The integrand ... has evaluated to non-numerical values for all sampling points in the region ..." for a particular calculation I am running. How can I change my code so that this is not an issue? A simple example is copied below. a = 1/20; b = 1/5; FF[y_] := Exp[I a y - 1/2 b^2 y^2]; f[x_] := NIntegrate[E^(-I x y) FF[y], {y, 0.0, 100}]; NIntegrate[f[x], {x, -100, 100}] Thanks... Answer a = 1/20; b = 1/5; FF[y_?NumericQ] := Exp[I a y - 1/2 b^2 y^2]; f[x_?NumericQ] := NIntegrate[E^(-I x y) FF[y], {y, 0.0, 100}]; NIntegrate[f[x], {x, -100, 100}] converges slowly ... to Pi

image processing - Package for symbolic computation of christoffel symbols and parallel transports in Riemannian geometry, given the metric

I've no knowledge in mathematica (but I do in matlab), but I'd really appreciate if someone could mention what is/are the best and easy to learn mathematica package(s) for symbolic and numerical (both, really) computation of Riemannian geometry, specially Christoffel symbols, sectional curvature, and parallel transport along a given curve on M, given the topological type of the manifold M and the Riemannian metric g on M. To explain myself a little more: in order to symbolically compute the Christoffel symbols, I've to invert a matrix and compute the symbolic and numerical derivatives w.r.t. the matrix. These matrices come from observations of medical data and are d by n matrices with n being a huge number, and d is normally 2 or 3. After that, I've to compute the parallel transport along a curve c, which'll involve solving a system of first order linear ordinary differential equation with matrix entries depending on the derivative c' and the Christoffel symbols

differential equations - Stopping NDSolver at time of error

I am using NDSolver and WhenEvent to solve a system of differential equations. I get this message: NDSolve::ndsz: At t == 49169.954923435114`, step size is effectively zero; singularity or stiff system suspected. The solution I get is pretty stable until that time, then blows off completely. At each evaluation I get the same behaviour at different times. I understand that the problem might lie with the fact that I am solving for very long times, and eventually the algorithm just starts having problems handling all the data. Is there a way to stop the solver as soon as the error comes up? Answer First, a test case: sol = NDSolve[{x'[t] == -1/x[t], x[0] == -1}, x, {t, 0, 2}] NDSolve::ndsz: At t == 0.499999735845871`, step size is effectively zero; singularity or stiff system suspected. >> Consult What's inside InterpolatingFunction[{{1., 4.}}, <>]? or InterpolatingFunctionAnatomy and you will discover that InterpolatingFunction comes with lots of utilities and me

parallelization - ParallelTable and Precision

I'm using ParallelTable[] to calculate a function over a range of my parameters , ($\omega,\ell$). This seems to be working well (in terms of speed increase) except for some strange Precision issues. I set the $MinPrecision=40 at the start of the notebook as well as my working precision, precision goal and accuracy goal for some computations later in the notebook as wp=$MinPrecision; ac=$MinPrecision-8; pg=wp/2; The rest of my code basically defines some helper functions before going on to the main function (that I feed into ParallelTable ). This main function uses the helper functions along with NDSolve and NIntegrate to do some computations, and it's in these that I feed the Working Precision->wp , AccuracyGoal->ac , PrecisionGoal->pg . I have used DistributeDefinitions on all my variables, helper functions, and the main function, and even on $MinPrecision , also all my initial conditions for NDSolve have N[...,wp] wrapped around them, but still when I use

files and directories - Relative paths for portable notebooks in Mathematica

I cannot find how to use relative paths in Mathematica. My directory structure is simple. Import["G:\\Research\\Acc and Vel Runs\\5-24\\Mathematica\\Data\\250 \ Acc.xls"][[1]] // TableForm That demonstrates the absolute path by using the insert path from the menus. I want this notebook to be portable. I want to give someone the "Mathematica" directory and I want them to be able to run the code. I don't want the paths to break because It will be run on a different machine. Basically I just want to use a relative path starting at the Mathematica level shown above. Answer If your notebook is in the top directory, you can use Import[FileNameJoin[{NotebookDirectory[], "path", "to", "your", "file.xls"}]] where the string is the relative path from that directory. If your notebook is elsewhere in the directory tree and you want to set paths relative to a different directory, then you could define a global $ParentDirectory and

Extracting lists from list based on length

I have a list looking like this; {{"ADS GY Equity", "", "", "ALV GY Equity", "", "", "BAS GY Equity", "", "", "BAYN GY Equity", "", "", "BEI GY Equity", "", "", "BMW GY Equity", ""}, {"Date", "PX_LAST", "", "Date", "PX_LAST", "", "Date", "PX_LAST", "", "Date", "PX_LAST", "", "Date", "PX_LAST", "", "Date", "PX_LAST"}, {"addidas", 17.925, "", "alvac", 287.292, "", "basse", 24.875, "", "bayern", 42.34, "", "begge", 23.667, "", "BMW", 29.49}, {{2000, 1, 4, 0, 0, 0.}, 17.5, "", {2000, 1, 4, 0, 0, 0.}, 285.934, "", {2000, 1, 4, 0,

front end - Delete the current notebook cell using the keyboard

Is there another way than pressing Ctrl + . until the whole cell is selected and then pressing Del ? If this is not built in, can I create some sort of a global macro to do this and bind it to a keyboard shortcut? Answer Referencing Szabolcs's answer, here is the code that must be added to KeyEventTranslations.tr : Item[KeyEvent["m", Modifiers -> {Control}], FrontEndExecute[{ FrontEnd`SelectionMove[FrontEnd`SelectedNotebook[], All, Cell], FrontEnd`FrontEndToken["Clear"] }]], I chose Ctrl+M at random; change it to whatever you want. See this before you edit the file.

replacement - Safely nesting RuleDelayed

Say I have the following, straightforward-seeming functions: makeARuleDelayed[a_, b_] := With[{anotherRule = makeAnotherRuleDelayed[b]}, v : a[b] :> ((v == 1 - v) /. anotherRule)]; makeAnotherRuleDelayed[x_] := v : h_[x] :> foo[h, x]; If I use them to create a RuleDelayed , I get an error message: a[b] /. makeARuleDelayed[a, b] RuleDelayed::rhs: Pattern v$:h$_[b] appears on the right-hand side of rule v$:a[b]:>(v$==1-v$/. v$:h$_[b]:>foo[h$,b]) . Examining the result indicates the problem: v$ : a[b] :> (v$ == 1 - v$ /. v$ : h$_[b] :> foo[h$, b]) Using this rule fails in about the way you'd expect it to. The only workaround I could think of is adding a Module to the body of makeAnotherRule : makeAnotherRuleDelayed[x_] := Module[{v}, v : h_[x] :> foo[h, x]] This doesn't help at all; evidently there must be some sort of magical renaming going on somewhere inside of RuleDelayed that truncates the $nnn part of the name of the symbol generated by Module

Mathematica Precision

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

plotting - Interpolate throughout a 3d data list without extrapolation

I have a 3D list of data for which I'd like to plot an interpolated surface. There are several ways to achieve this, but none I cannot find a method which ONLY plots the ENTIRE interpolated surface without extrapolating at all. I have to use a substantial list of data to demonstrate, so I've uploaded it on dropbox. I hope this is okay. I'm enthusiastically open to suggestions of other ways to link to the data. It does seem to import properly on my system (Mathematica 9.0.0.0 on XP SP3): hcp = Import[ "https://www.dropbox.com/s/a10if7ek4ako5q2/example.dat?dl=1", "TSV"]; data = {Most[ToExpression[#]], Last[ToExpression[#]]} & /@ DeleteDuplicates[hcp]; int = Interpolation[data, InterpolationOrder -> 1] Show[ Plot3D[int[x, y], {x, -.807372, -.586589}, {y, .31889, .393084}], ListPointPlot3D[hcp] ] Show[ ListSurfacePlot3D[hcp], ListPointPlot3D[hcp] ] Show[ ContourPlot3D[ z == int[x, y], {x, -.807372,

linear algebra - What if do NOT want Mathematica to normalize eigenvectors with Eigenvectors[N[matrix]]?

ORIGINAL QUESTION Question speaks for itself. Mathematica normalizes the eigenvectors automatically when you type Eigenvectors[N[matrix]] . What if I do NOT want the vectors to be normalized? I looked around and found that N[Eigenvectors[matrix]] would in principle do the trick. I mean, that is the form I would like to have them expressed. However, I can't do it because I get this message (which by the way I don't fully grasp): "Incorrect number 20 of eigenvectors for eigenvalue 1/2 (-1+Sqrt[5]) with multiplicity 2." The size of the matrix is $2^8$ by $2^8$. EDIT I see that there's some confusion on what I am asking. Obviously, as any (nonzero scalar) multiple of an eigenvector is equivalent to the same eigenvector, my question is not making that much sense the way it is asked. Apologies for that, I asked in a rush. I will try to put in context what I am doing so that maybe it will be more clear what my point is. I have a $2^8$ by $2^8$ matrix, call it $H$. I wan

performance tuning - Slow work of SQLInsert with SQLite

I want to store my data in SQLite database, but writing large numbers of data its too slow. For example: db = JDBC["SQLite", "f:\\test1.db"]; conn = OpenSQLConnection[db]; SQLCreateTable[conn, SQLTable["TEST"], {SQLColumn["COL1", "DataTypeName" -> "INTEGER"], SQLColumn["COL2", "DataTypeName" -> "DOUBLE"]}]; SQLInsert[conn, "TEST", {"COL1", "COL2"}, RandomReal[{-10, 10}, {100, 2}]]; // AbsoluteTiming (*{11.814676, Null}*) Inserting 100 lines of data take more than 10s on my PC, but when I use SQLite Database Browser (external software) for creating table with more than 80000 lines its take less than 1 minute. Why inserting from Mathematica so slow? EDIT But HSQL much more faster 3.5s for 80000 lines

fitting - 2D smoothing spline interpolation

Does Mathematica have 2D smoothing spline interpolation built in? I requires an interpolation method with smooth first derivatives and cubic bivariate splines fulfill this nicely. In python I would use RectBivariateSpline or SmoothBivariateSpline . A quick search only revealed this answer , which I guess could be adapted to 2D with some effort. Here is some test data: RANGEX = 8; RANGEY = 8; F[x_, y_] := Sin[.5 y] Cos[.9 x]/Sec[0.1 x y] - 0.01 (x^2 + y^2) RiemannSiegelZ[1.5 Sqrt[x^2 + y^2]] data = N[Flatten[ Table[{x, y, F[x, y]}, {x, -RANGEX, RANGEX, 1}, {y, -RANGEY, RANGEY, 1}], 1]]; (*add some noise*) data[[All, 3]] = data[[All, 3]] + RandomVariate[NormalDistribution[0, 0.1], Length[data]]; PlotPointsAndSurface[points_, surface_, label_] := Module[{}, Show[ ListPointPlot3D[points, PlotStyle -> {Directive[PointSize[0.01], Red], Directive[PointSize[0.01], Green]}, PlotLabel -> label, ImageSize -> Medium], Plot3D[surface, {x, -RA

graphics - How can text-specific antialiasing be disabled in Rasterize?

While tinkering with the code in the Falling Matrix question , I was hoping to improve the rendering speed by making the rasterizations of the text grayscale. I changed the base color of the text to white and left the background black. However, this did not yield a grayscale raster. The problem seems to be that Mathematica tries to help with the readability of text by using special antialiasing schemes. Consider the following test: GraphicsRow[ Rasterize[#, Background -> Black, RasterSize -> 15, ImageSize -> 150] & /@ {Style["\[FilledCircle]", White], Graphics[{White, Disk[]}]}] Interesting and (I think) undocumented, but the relevant question for me is: How can I control or eliminate this behavior? Adding a ColorConvert[#,"Grayscale"] or just taking the Norm s of the ImageData gives an acceptable result but is pretty slow. Answer One possible way would be to extract the text outline as in this answer (scroll to the end) and rasterize the

precision - Diagnosing the numerical stability of a function

I have programmed a function f[x] that seems to be very unstable numerically. More precisely, I noticed that for certain arguments in arbitrary precision, the precision of the output is halved compared to the precision of the input. This is very bad. I would like to visualize the precision of f[x] relative to the precision of x , for different values of x . I am thinking of a plot of f[x] with error bars, but I am not sure how to compute and access these error bars. This sounds like something might have thought of before, perhaps in a package or in some Mathematica function that I don't know of. In general terms my question is about the best ways to probe the numerical stability of a function f[x] ? And hopefully find ways of improving it.

list manipulation - Selecting multiple columns from a matrix?

Sample data: data = { {{2013, 1, 1}, 24.13, 167.67, 231.82}, {{2013, 1, 2}, 32.15, 170.92, 225.99}, {{2013, 1, 3}, 35.43, 172.68, 221.67}, {{2013, 1, 4}, 36.73, 173.05, 218.32}, {{2013, 1, 5}, 58.19, 165.96, 197.05}, {{2013, 1, 6}, 69.99, 163.50, 187.52}, {{2013, 1, 7}, 71.37, 154.21, 175.58}, {{2013, 1, 8}, 72.51, 149.66, 163.25}}; I want a DateListPlot with three graphs, so for a matrix formed by columns 1 and 2, one for columns 1 and 3, and 1 for columns 1 and 4. At the moment I'm using this code: data2 = Transpose[{data[[All, 1]], data[[All, 2]]}]; data3 = Transpose[{data[[All, 1]], data[[All, 3]]}]; data4 = Transpose[{data[[All, 1]], data[[All, 4]]}]; DateListPlot[{data2, data3, data4}, Joined -> True, Filling -> {3 -> {1}}] but I have a hunch that this can be done more efficiently. I don't like the Transpose s in particular. Any ideas? edit (for extra credit) What if I need to multiply the second column by 2, which in my solution is simp

parallelization - Is there a method to send different Cell evaluation to different core?

I am running Mathematica on a computer with multi CPU and every CPU has multicore. I am wondering if there exist a method to send different cell evaluation to different core? So if I already have a cell being evaluating for a long time, I can still add other cells into evaluation at the same time, while won't have to stop the current evaluation or wait until the current evaluation to be done. Answer You can use the Evaluator option of Cell for this. You should define several kernels through the Kernel Configuration Options... dialog, then you can use a name of configured kernel as value for the Evaluator option. For example, create new local kernel with name "My" . Then generate an Input Cell by the following code: CellPrint@Cell[BoxData[MakeBoxes[Do[Print[n]; Pause[1], {n, 20}]]], "Input", Evaluator -> "My"] In another Cell just type Do[Print[n]; Pause[1], {n, 20}] and evaluate both Cells with Do expressions simultaneously by selecting b

plotting - VectorScale Explanation

I'm having great difficulty understanding VectorScale . Here are the definitions from the documentation. With the explicit specification VectorScale -> {unitlen,aratio,sfun} each field vector is constrained to fit in a vector box oriented in the direction of the field, centered at the location of the vector. The unitlen is given as a fraction of the diagonal of the overall bounding box and is used as a local scale for vector boxes, aratio is the aspect ratio for vector boxes, sfun is a scaling function that determines the width of vector boxes. I've used it with VectorPlot and have gotten the desired result, but I still just can't understand the above definitions. I've even read some authors saying "don't worry about how this works, but here is how you get a good picture." I just think I need to be a little more ready than that to explain things to my students. Is it possible to draw a picture, maybe just a few arrows, and show their vector boxes

graphics - Drawing a graph with vertex avoiding edges? (Handling vertices that must be colinear?)

I'd like to draw something like the following graph: testGraph = Graph[{1 \[UndirectedEdge] 2, 1 \[UndirectedEdge] 4, 2 \[UndirectedEdge] 3, 2 \[UndirectedEdge] 5, 3 \[UndirectedEdge] 4}, VertexLabels -> {1 -> "1", 2 -> "2", 3 -> "3", 4 -> "4", 5 -> "5"}, VertexCoordinates -> {{0, 0}, {1, 1}, {2, 3}, {4, 1}, {3, 3}}, ImagePadding -> 10] However, without changing any of the explicitly specified vertex positions, I'd like edges to curve to avoid vertices. For example, while it's fine that the edges between vertices 2 and 5, and 3 and 4 cross, what if I have an edge between vertices 1 & 5 (if I actually do this, Mathematica v9 appears to no longer respect my vertex coordinates) and what if I would like this edge not to pass through a small sphere about vertex 2? Is there any way to enforce vertex positionin

graphics - Drawing a quadrilateral inscribed within a circle

I would like to draw a quadrilateral inscribed within a circle. How can I construct this figure, taking into account arbitrary (specified) side lengths, while still ensuring that the vertices of the quadrilateral lie on the circle? Answer I hope I understood your question correctly. When you place your figure at {0,0}, meaning the center of the circle and the center of the rectangle is there, you don't need to calculate very much. Indeed, everything is then fixed by exactly one point p defining a corner of the rectangle and the radius of the circle. A dynamic version of your graphics can be written down in only a few lines of code Manipulate[ Graphics[{FaceForm[None], EdgeForm[Thick], Rectangle[-p, p], Thick, Red, Circle[{0, 0}, Norm[p]]}, PlotRange -> {{-2, 2}, {-2, 2}}], {{p, {1, 1}}, Locator} ]

fitting - Generating an "average curve" from a dense set of "semicontinuous curves" which clear trends

This question is related to a previous one of mine: Partitioning a superset of coordinates into subsets that generate continuous curves , where the challenge was to partition a data set into two clusters representing distinct "semicontinuous curves" (we mean this in the loose sense that a ListPlot generated two curves that by eye appeared to be continuous). The user rm -rf illustrated and demonstrated that FindClusters could very nice solve the problem using a Euclidean distance metric (a hat tip also to g3kk0 who elaborated on this approach). My question here is how one would approach a much more pathological case, where we have multiple closely spaced curves, displaced some amount vertically, and we would like to generate an "average" curve that represents a sort of average for the shape of all the semicontinuous curves. Take a look at the following plots (data uploaded to: https://www.dropbox.com/sh/751invayqe3ip9b/r6raIrdvLF ): Plot A: Plot B: In both cases, we

formatting - Column makes fonts smaller

When you use Column (or Grid ) a previously styled element with explicit font-size setting appears much smaller. Here is an example cell = Framed[Style[(2*x^(3/2))/3, FontSize -> 14], FrameMargins -> 10, FrameStyle -> {AbsoluteThickness[1], LightGray}, RoundingRadius -> 3]; {cell, Column[{cell}]} I looked through the options of Column , Grid , and GridBox but I couldn't find how I can prevent this when I output an expression with nested columns or grids. And setting the font-size larger, so that it appears to be non-scaled sounds like a bad idea. Can anyone give me some insight? With the help of Roman's answer, I could fix my layout. However, there seems to be a bug in Panel which does not respect the settings. Please compare the two usages of Panel without and with a title : Column[{Item[cell, AllowScriptLevelChange -> False]}] Panel[Column[{Item[cell, AllowScriptLevelChange -> False]}]] Panel[Column[{Item[cell, AllowScriptLevelChange -> False

complex - Conjugating symbolic expression

I am trying to conjugate a symbolic expression, and I have explicitly stated the real terms. However, I simply can't get it to work: Conjugate[ ComplexExpand[ I Cos[z] Sin[y] + Sin[z] + A (Cos[z] - I Sin[y] Sin[z]), {z \[Element] Reals, A \[Element] Reals, y \[Element] Reals}]] What am I doing wrong here? Answer Just do the ComplexExpand after the Conjugate ComplexExpand[Conjugate[I Cos[z] Sin[y] + Sin[z] + A (Cos[z] - I Sin[y] Sin[z])]] (* A Cos[z] + Sin[z] - I (Cos[z] Sin[y] - A Sin[y] Sin[z]) *)

numerical integration - Calculate mean normed distance and normed variance of cone-shaped distribution in N-dimensions

I would like to calculate the mean and variance of the normed distance of a cone-shaped distribution, $f(x) \propto \exp(-|x|)$ , where $x\in\mathbb{R}^d$ , where $d$ can be any positive integer. In two-dimensions, this distribution looks like a cone! I can calculate the normalising constant for this distribution using, Integrate[Exp[-Norm[{x,y}]], {x, -Infinity, Infinity}, {y, -Infinity, Infinity}] which is $2\pi$ . I can then calculate the mean normed distance using, Integrate[Norm[{x,y}]Exp[-Norm[{x,y}]], {x, -Infinity, Infinity}, {y, -Infinity, Infinity}] which is 2. Its second moment, Integrate[Norm[{x,y}]^2Exp[-Norm[{x,y}]], {x, -Infinity, Infinity}, {y, -Infinity, Infinity}] then allows me to calculate the variance $\mathrm{Var}(|x|) = \mathrm{E}(|x|^2) -\mathrm{E}(|x|)^2 = 2$ . Calculating the normalising constants is easy enough in higher dimensions, but I run into trouble with finding the mean

plotting - Filling option failing when ListLinePlot given my data

Context I want to do Filled plot such as: dat1 = {Table[{i^2, i + 1}, {i, 5}], Table[{i^2, i}, {i, 5}]} ListLinePlot[dat1, PlotStyle -> Red, Filling -> {1 -> {2}}] But when I apply this to my own data: dat = { {{3.0779456558039593`, 3.842486584798708`}, {1.2951669675555262`, 4.05402324780319`}, {0.9196161755899819`, 3.939944632202657`}, {0.5722748507275665`, 3.8875332289711`}, {0.29373287932080444`, 3.7317102841786385`}}, {{3.0779456558039593`, 7.125115694053534`}, {1.2951669675555262`, 5.8724983311100605`}, {0.9196161755899819`, 5.707473500231869`}, {0.5722748507275665`, 5.114513590881306`}, {0.29373287932080444`, 4.240800591615147`}} } It fails to fill the region: ListLinePlot[dat, PlotStyle -> Red, Filling -> {1 -> {2}}] Question Am I missing something obvious? Answer The cause is your data is out of order. So, the workaround is ListLinePlot[SortBy[First] /@ dat, PlotStyle -> Red, Filling -> {1 -> {2}}] I believe it is not a

performance tuning - Making sure that Timing[] isn't thrown off by caching

In playing with and comparing the various answers to my question here , I tried applying Timing[] to see how fast things ran, but it seemed that some of the answers (but not all of them) were a lot faster when run for a second time. How can I make sure that there isn't some kind of caching of intermediate results throwing off the Timing[] ? Answer Completely restarting the kernel will of course work. If we don't restart the kernel, then we need to clear all caches. The caches used for symbolic and some numeric calculations can be cleared using ClearSystemCache[] . The documentation page of this function says: ClearSystemCache can be useful in generating worst-case timing results independent of previous computations. I do not know if there are any other caches as well, not affected by this.

graphics - Drawing a quadrilateral inscribed within a circle

I would like to draw a quadrilateral inscribed within a circle. How can I construct this figure, taking into account arbitrary (specified) side lengths, while still ensuring that the vertices of the quadrilateral lie on the circle? Answer I hope I understood your question correctly. When you place your figure at {0,0}, meaning the center of the circle and the center of the rectangle is there, you don't need to calculate very much. Indeed, everything is then fixed by exactly one point p defining a corner of the rectangle and the radius of the circle. A dynamic version of your graphics can be written down in only a few lines of code Manipulate[ Graphics[{FaceForm[None], EdgeForm[Thick], Rectangle[-p, p], Thick, Red, Circle[{0, 0}, Norm[p]]}, PlotRange -> {{-2, 2}, {-2, 2}}], {{p, {1, 1}}, Locator} ]

plotting - How can I make a grid of plots with no spacing, and have the plots line up perfectly?

I am making a bunch of two dimensional plots and I would like to have them arranged in a grid with no space in between them. That is, I want their frames touching each other. My problem is twofold. First I don't know how to get the plots to have a consistent size. When I try to give the plots the same size via ImageSize , it applies the size to the overall image, including the tick marks and labels. But when I have two different plots, one with tick labels and one without, giving the same value to ImageSize doesn't give the result I'm looking for. Secondly, I want to get rid of any white space around the images such that when I give Grid the option Spacings ->{0,0} there really is no visible space between the plots. In the example code I use the CustomTicks package. (*an example of what I might plot, simple sum of two dimensional \ Lorentzians*) lzn[x_, w_, g_] := (x - w + I g)^-1; exampledata2D = Table[Re[lzn[w1, .2, .1] lzn[w2, .3, .2] + lzn[w1, .4, .1] lzn[

pattern matching - How to collect terms with positive powers in polynomial

I am trying to collect all terms with non-negative powers of $x$ in polynomials like $\frac{1}{x^2}\left(a x^2+x^{\pi }+x+z\right)^2$ First expand the polynomial Expand[1/x^2 (x + x^π + a x^2 + z)^2, x] This gives $a^2 x^2+2 a x^{\pi }+2 a x+2 a z+2 x^{\pi -2} z+x^{2 \pi -2}+2 x^{\pi -1}+\frac{z^2}{x^2}+\frac{2 z}{x}+1$. Now try to select those terms with positive or zero powers of x. My best guess is Plus@@Cases[%, (Times[___, Power[x, g_.], ___] /; g >= 0)] However, this only yields the term $a^2 x^2$. And why does this not work for the other terms? How can I collect the other terms with positive or zero powers of x? Answer Alternatively, you can use Pick and Exponent : list = List @@ Expand[1/x^2 (x + x^Pi + a x^2 + z)^2, x]; Pick[list, Positive[Exponent[#, x] & /@ list]] (*{2 a x,a^2 x^2,2 x^(-1+Pi),2 a x^Pi,x^(-2+2 Pi),2 x^(-2+Pi) z}*) Or a little shorter, since Exponent has attribute Listable (thanks to Mr. Wizard for pointing that out): Pick[list, Positive@Exponent[

plotting - Legend Missing In The Plot

I tried to save the plot P1 by right clicking on the plot and pressing save as. I found that the PlotLegend is not saved. Please help. P1 = Plot[{Sin[ t], Cos[ t], Tan[ t]}, {t, 0, 10}, PlotStyle -> {{Blue, Dashing[None], Thickness[0.005]}, {Red, Dashing[Tiny], Thickness[0.005]}, {Green, Dashing[Small], Thickness[0.005]}}, Axes -> False, Frame -> True, PlotLegends -> Placed[LineLegend[Automatic, {"sin", "cos", "tan for b=1"}, LegendMarkerSize -> {{20, 10}}], Top]]

front end - Having variables appear aqua in user defined function

In many of the inbuilt mathematica function, variables appear aqua like in: However, when creating your own function, variables no longer have that green coloring and are instead colored like an undefined variable Is there any way to define functions so that variables used in arguments like in the manner above can get the aqua syntax coloring? Answer You can use SyntaxInformation . In this case, SyntaxInformation[Lim] = {"ArgumentsPattern" -> {_, _, OptionsPattern[]}, "LocalVariables" -> {"Limit", {2}}} does what you want.

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

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