Skip to main content

Posts

Showing posts from April, 2017

output formatting - How do I indent C code generated by SymbolicC?

I'm continuing to experiment with the SymbolicC` package, and it's crucial to be able to inspect the generated code in order to do, well, anything useful with it. The ToCCodeString makes this possible, but as far as I can tell, produces code with sensible line breaks but no indentation. Reading unindented code is sort of possible, but not at all fun. Is there an option to turn indentation on? Right now, I've set things up so I can use the "Artistic Style" package for this purpose, and while it looks like a pretty nice program, relying on it means one more dependency on top of Mathematica and Visual Studio. UPDATE to add: I'm interested in inspecting code that I generate programmatically, and developing the program to do the generation interactively in a notebook. I'd prefer not to have to take manual steps like using ToCCodeString to generate the string, and then copy'n'paste it to Visual Studio to inspect it unless I really have to. Answer ...

programming - Combinations of multiple matching patterns

I wonder if there is any nice way to combine DownValues (or any other suitable rule-/pattern-/function -based Mathematica construct) when multiple patterns match an expression. Let me explain what I mean with a somewhat silly example: f[x_?(Mod[#,2]==0 &&Mod[#,3]==0&)]:= "FizzBuzz" f[x_?(Mod[#,2]==0& )]:= "Fizz" f[x_?(Mod[#,3]==0&)]:= "Buzz" f[x_]:=x Range@15 //Map@f (* {1,Fizz,Buzz,Fizz,5,FizzBuzz,7,Fizz,Buzz,Fizz,11,FizzBuzz,13,Fizz,Buzz} *) It would be really nice if one could do away with the first DownValue of f which checks if an expression is divisible by both 2 and 3 (since this is just a combination of the PatternTests used by the two DownValues defined beneath it). In this simple case one additional DownValue might not be an issue but if one adds more and more "rules" the number of additional combinations to check increases rapidly with the number of "rules". For instance: g[x_?(Mod[#,2]==0 &&Mod[...

conversion - Built-in way to convert Integer to Ordinal String

Is there a built-in way to convert an integer into its ordinal string representation (as per this page ). That is, something akin to {1 -> "1st", 2 -> "2nd", (*etc...*)} or {1 -> "First", 2 -> "Second", (*etc...*)} Answer The coolest way is to check the answer to this question by David Carraher. I am shamelessly stealing his code here to write a function that gives you rules for up to maxNumber : ordinalRule[maxNumber_Integer] /; maxNumber > 0 := Block[{p}, Thread[ Function[{x}, x -> StringSplit[SpokenString[p[[#]]]][[2]] &[x] // Quiet] /@ Range[maxNumber] ]]; For example: ordinalRule[100] (*out*){1 -> "1st", 2 -> "2nd", 3 -> "3rd", 4 -> "4th", 5 -> "5th", 6 -> "6th", 7 -> "7th", 8 -> "8th", 9 -> "9th", 10 -> "10th", 11 -> "11th", 12 -> "12th", ...

plotting - Make a scatter plot from two lists

I have two lists of values xx = {0.1, 0.3, 0.35, 0.57, 0.88, 1.0} yy = {1.2, 3.5, 4.5, 7.8, 9.0, 12.2} I want to make a scatter plot (list plot) with xx as x axis and yy as y axis. The help document on ListPlot tells me I have to use ListPlot[{{x1, y1}, {x2, y2}, ...}] How do I create something like ListPlot[{{0.1, 1.2}, {0.3, 3.5}, ...}] from xx and yy? Thank you. Answer First off, your syntax is incorrect; you need to use braces to define your lists: xx = {0.1, 0.3, 0.35, 0.57, 0.88, 1.0}; yy = {1.2, 3.5, 4.5, 7.8, 9.0, 12.2}; You can then create a 2x6 matrix from xx and yy , and transpose it to get a 6x2 matrix of pairs, which is the correct format: data = Transpose@{xx, yy}; ListPlot[data]

calculus and analysis - How to take derivative of parameterized coordinate?

Suppose I have a vector in $\mathbb{R}^n$ but $n$ is not known in advance. I want to be able to write functions which operate on the components of that vector, and then I'd like to be able to take derivatives with respect to the components. As an example, consider the relation: $$\frac{\partial}{\partial x_j} \sum_i x_i$$ Under the assumption that the $x_i$ are independent, I want a call to Simplify[] to return 1 . Similarly, calling Simplify[] on $\frac{\partial x_i}{\partial x_j}$ should give KroneckerDelta[i,j] . It's not clear how I should represent generic coordinates like this. I've seen this , but I'm not sure it provides an answer. As the linked post suggests, I could do this for a fixed $n$, but that's not situation I'm working on, especially since I want to see the generic form for any $n$. For reference, it seems that sympy let's you do something close to this. from sympy.tensor import IndexedBase, Idx x = IndexBase('x') i, j = map(Idx...

differential equations - Monitoring the Evaluation of NDSolve: time to finish estimation

My problem is quite simple: I run a NDSolve with a system of many ODEs, a calculation that will run for many hours, and I would like to know the progress of the calculation while it goes on. More precisely, calling f[n][t] the functions to be solved in the interval {tin,tfin} , It will be sufficient to print at regular intervals t the value of Sum[f[n][t]] for example, and possibly to save them as well. As a side effect, this will also give me an idea of when the calculation is going to end. However I don't want to sacrifice a significant amount of runtime for this monitoring. One option could be really to split the calculation in intervals (a table of NDSolve ) and print the intermediate results at each point. But I am afraid to have a significant overhead due to the reconstruction of the system of equations every time (I also use the method "EquationSimplification"->"Solve" which I believe transforms symbolically the system before integrating it) so I ...

plotting - Generating a broken or snipped axis in ListPlot

I have two data sets, data1 and data2 . For example: data1 = {{1, 1.1}, {2, 1.5}, {3, 0.9}, {4, 2.3}, {5, 1.1}}; data2 = {{1, 1001.1}, {2, 1001.5}, {3, 1000.9}, {4, 1002.3}, {5, 1001.1}}; ListPlot[data1, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Red] ListPlot[data2, PlotRange -> All, Joined -> True, Mesh -> Full, PlotStyle -> Blue] Their $y$- values are in vastly different regimes, but their oscillations in $y$ are comparable, and I'd like to compare them visually using ListPlot . But if I simply overlay them, it is nearly impossible to see and compare their oscillations, because of the scaling: Show[{ ListPlot[data1, PlotRange -> {{1, 5}, {-100, All}}, Joined -> True, Mesh -> Full, PlotStyle -> Red, AxesOrigin -> {1, -50}], ListPlot[data2, Joined -> True, Mesh -> Full, PlotStyle -> Blue] }] Is there a way to "break" or "snip" the $y$ axis so that I can compare data1 and data2 on th...

plotting - Mathematica and gaps in continuous plot

I have a bit of trouble with Mathematica and it's plotting stuff. I tried to plot Jacobi amplitude function: JacobiAmplitude[Sqrt[0.1]*x, 10], {x, 0, 50}] but the result leaves gaps where the roots of the function should be (particularly for this function around x = 3, 6, 10, ... ). I've done a bit of googling and found that either Exclusions set to None or raising PlotPoints should help. Well, it didn't. I even tried to set MaxRecursion to 8 , PlotPoints to one million , waited several hours for the plot and it didn't change. Funny thing is, that when I added Mesh -> None , I've found out, that mathematica added plot points even at the gaps, but it didn't join them with lines! This is something like bug, or how should I deal with that? Any help'd be appreciated. P.S.: I'm using Mathematica 9.0 Answer There's a small but nontrivial complex part to the value being plotted that arises from using MachinePrecision numbers for plotting. Use arb...

filtering - Discard Elements of list with given criteria

I have the following list: {{3506, 0.120908, 0.213813, {7, 9, 18, 20}, 6 -> {15}|>}, {3726, 0.119108, 0.209133, {6, 8, 9, 13, 18, 20}, 3 -> {15}|>}, {3761, 0.116293, 0.203036, {6, 8, 14, 18, 20}, 2 -> {12}, 4 -> {15}|>}, {3946, 0.107619, 0.192869, {6}, 1 -> {7, 18, 20}, 2 -> {12}|>}, {4016, 0.104384, 0.190066, {6, 7, 10, 15, 18, 20}, 6 -> {12}|>}, {4086, 0.106909, 0.187285, {11, 12}, 4 -> {15}, 1 -> {18, 20}|>}, {4236, 0.103937, 0.188204, {5, 6, 8, 14, 18, 20}, 5 -> {12}|>}, {4271, 0.103541, 0.186671, {4, 7, 11, 13, 18, 20}, 5 -> {12}, 2 -> {15}|>}, {4421, 0.101325, 0.186022, {5, 7}, 1 -> {6, 13, 18, 20}|>}, {4491, 0.101609, 0.180121, {4, 6, 7, 15, 18, 20}, 6 -> {11}|>}, {4491, 0.100645, 0.184125, {7}, 7 -> {10}, 1 -> {18, 20}|>}, {4526, 0.0989646, 0.17942, {5, 6, 14, 18, 20}, 2 -> {10}, 7 -> {12}|>}, {4561, 0.0945528, 0.175016, {5, 18, 20...

calculus and analysis - Integrate over a piecewise function

I want to calculate the indefinite Integral of $$f(x)=\begin{cases} 2x\cos(\frac{1}{x})& \text{ if } x\ne 0 \\ 0& \text{ if } x=0 \end{cases}.$$ I use the following code: F[x_] := Piecewise[{0, x==0}, {2*x*Cos[1/x], x != 0}]; Integrate[Piecewise[{{0, x == 0}, {2*x*Cos[1/x], x != 0}}], x] It doesn't evaluate. I don't know why it doesn't evaluate the piecewise function. Maybe this is quite simple question, but it's not easy for me, a greenest amateur.

numerics - Display All Output Numbers in HEX

How might I modify Mathematica such that I can get the following functionality when working with HEX values. The odd lines are input and the even output. Red values should be the HEX values. What would be the most portable and functionally useful way to display all numbers in HEX? I would like to use either Notation, Symbolize, or Interpretation to display the numbers as HEX but allow them to be interpreted as actual numbers internally. Answer Here is my first pass at implementing what you describe. If you find that it deviates from your intended behavior let me know and I shall attempt to refine it. MakeBoxes[foo_, form_] /; format`hex =!= True := Block[{format`hex = True}, ToBoxes[foo, form] /. s_String?DigitQ :> With[{n = FromDigits@s}, InterpretationBox[StyleBox[#, RGBColor[1, 0, 0]], n] &[ "\"" IntegerString[n, 16] "\"" ] ] ] Now:

plotting - Exporting BarChart3D as PDF produces artifacts

So I think the following image already shows the problem, similar to Avoiding white lines inside filled area in RegionPlot exported as PDF or PS the pdf export of the chart creates thin lines in the plot. The fixing rule proposed in the related question seems not to work (sorry I am really new to mathematica). Disabling the Antialiasing doesnt improves the situation! Answer Solution The problem seems to be that the polygonal regions in the exported PDF file do not have edge strokes. It can be partially solved by reimporting the figure and correct this. (* FILENAME.pdf contains an exported BarChart3D figure *) (* 't' gives the desired edge thickness *) chart = Import["FILENAME.pdf"]; chart = chart /. {FaceForm[n__] :> {FaceForm[n], EdgeForm[{Thickness[t], n}]}}; Export["NEW_FILENAME.pdf", chart]; I tested this code only for BarChart3D output. It seems that in the reimported figure all colored regions are defined by FilledCurves and all additional line...

performance tuning - How can I speed up this code with 4 variables sum

I have to make a sum over 4 variables. My code is very very slow. I want to know how to speed up this code. This problem is related to but different from one previous problem . Any help or suggestion will be highly appreciated! The code is shown below: data = Table[ Exp[-((i + j - 20.)/5)^2] Exp[-((i - j)/5)^2], {i, 20}, {j, 20}]; data = Chop[data, 0.00001]; data = data/Sqrt[Sum[(data[[i, j]])^2, {i, 1, 20}, {j, 1, 20}]]; ListDensityPlot[data, InterpolationOrder -> 0, Mesh -> All, PlotRange -> All, ColorFunction -> (Blend[{Hue[2/3], Hue[0]}, #] &)] c = 3*10^8; Δ = 0.5; λ0 = 1500; CC1[i_, j_, k_, l_, t_] := (data[[i, l]] data[[j, k]] Cos[π*(c/(λ0 - 10 + i*Δ - 0.5 Δ) + c/(λ0 - 10 + l*Δ - 0.5 Δ)) t] Cos[π*(c/(λ0 - 10 + j*Δ - 0.5 Δ) + c/(λ0 - 10 + k*Δ - 0.5 Δ)) t] + data[[i, k]] data[[j, l]] Cos[π*(c/(λ0 - 10 + i*Δ - 0.5 Δ) + c/(λ0 - 10 + k*Δ - 0.5 Δ)) t] Cos[π*(c/(λ0 - 10 + j*Δ - 0.5 Δ) + c/(λ0 - 10 + l*Δ...

plotting - How to set the properties of a plot that's already been plotted?

Let's say I have a function that I've plotted, like so: a = Plot[f, {x, 0, 5}, Background -> Blue] So I don't really have access to the function anymore, but I want to replot it with a changed property of the graph, for example, I want to make the color of the line Black , or the background Red . How can I do that without replotting it, or not having access to the function again? I know I can access the original color using Option[] , like: Last@Last@Options[a, Background] But SetOptions and SetProperty don't really work. It seems like SetOptions sets the general property for plots in general, and SetProperty isn't for this. ( SetProperty[a, Background -> Red] gives the error that my plot isn't an object with properties. SetOptions[a, Background -> Red] says that my argument plot isn't a symbol or stream.) Is there a way to do this?

List of functions to list of parameters

I am working in a Dataset and I need to create a function for a ChartStyle option of a BarChart that takes a list of the items to be plotted. I would like to lighten the plot style colour by the value of the item to be plotted. I have created a function that gets me the list of functions for each PlotStyle . Function[{value}, Nest[Lighter, #, 3 - value]] & /@ {Yellow, Orange, Blue} value will be an integer between 0 and 3 inclusive. Is there some use of Through or Outer or Inner or something that will map a list of length to each position in this list of functions such that: {f1, f2, f3}[{x1, x2, x3}] -> {f1[x1], f2[x2], f3[x3]} This is in a Dataset query so I'm hoping for something concise that is easy to read and that is a one liner with the function list definition given above. Answer Inner[#1[#2] &, {f1, f2, f3}, {x1, x2, x3}, List] (* {f1[x1], f2[x2], f3[x3]} *) #[[1]][#[[2]]] & /@ Transpose[{{f1, f2, f3}, {x1, x2, x3}}] (* {f1[x1], f2[x2], f3[x3]}...

plotting - Fixed arrow size in parametric 3d plot

I'm trying to add arrows to a trajectory in ParametrcPlot3D ParametricPlot3D[{Cos[t], Cos[t] Sin[t], t}, {t, 0, 10}, BoxRatios -> {1, 1, 1}, PlotRange -> All] /. Line[x_] :> {Arrowheads[{0, 0.04, 0.04, 0.04, 0.04, 0}], Arrow[x]} The arrow that I obtain change with the 3d view. the closer ones look larger and the further ones look small. how can I have the size of the arrow fixed for all 3d views? Update: It is important that the size of the arrow can be controlled, i.e, the symbolic presentation of Tiny to Large are not sufficient.

customization - Customize front end to add notifications when evaluation finishes?

Is it possible to add some customization code to the front end, so that when all cells have finished evaluating, some user code can be run? Background: I'm currently running some Mathematica programs that take 3 to 4 hours. I'd like to get a notification when they finished. ("A watched program never completes...") The code I want to add is (at its most basic): Run["/usr/local/bin/growlnotify -n \"Mathematica.app\" -a \"Mathematica\" \"finished\""] which sends a Growl alert to all connected machines (including my iPad, via Prowl). Although this specific mechanism is MacOS X specific, the mechanism would presumably be good for all Mathematica platforms. Answer Here's a quick solution. Note that it's only tested in Ubuntu - please test it in other operating systems and make any changes that are necessary. First we define a sendNotification command and then show how to create a style of input cell that automatically calls...

calculus and analysis - How does Mathematica integrate?

Basically, this question can be considered to be an extenstion to my other question . What I wanted to do was this integral as homework (it is indefinite BTW so no approximations using Simpson's Rule or Boole's Rule ) $$\int(x^{3m}+x^{2m}+x^{m})(2x^{2m}+3x^{m}+6)^{\frac1{m}}dx$$ So using Mathematica's Integrate function the answer was Apparently, after rigorous substitutions and transformations the answer was found to be correct. What I wanted to know was how Mathematica integrates these functions that require a human tons of intuition to compute, within seconds, and often in the most simple way and also presents them in the most humanly computable form. (Even differentiation for that matter) Answer I can only direct you to Some Notes on Internal Implementation : Differentiation and Integration Differentiation uses caching to avoid recomputing partial results. For indefinite integrals, an extended version of the Risch algorithm is used whenever both the integrand and in...

plotting - combining manipulate with "static" plot

Is there a way to show a plot of a "static" function as background for a manipulate panel ? In other words: I have put into a manipulate a trajectory (solution of a system of two differential equations): solcontrol = FullSimplify[ DSolve[{y'[t] == - y[t] - u z[t], z'[t] == -1 -2 z[t] + u y[t], y[0] == 0, z[0] == -.5}, {y[t], z[t]}, t]]; Then, I use Manipulate {{ysol[t_], zsol[t_]}} = Simplify[{y[t], z[t]} /. solcontrol, Assumptions -> Element[u, Reals] && t > 0]; With[{y = ysol[t], z = zsol[t]}, Manipulate[ ParametricPlot[{y, z}, {t, 0, tend}], {{tend, .1}, 0, 20},{{u, .7}, 0, 20}]] Remark/problem:I'm using Mathematica 9 on a Debian. I don't know if you see the same manipulate panel as me on (say) Windows, but my panel sets its dimension "dynamically" respect on the form of trajectories. Finally, my problem is to show the result of manipulate with this contour plot: DeltaA[y_, z_] = -y^2 - z -2 z^2;...

interoperability - How can I use Dynamic to run a script when a new file is added to a directory?

I have an external program saving files to some directory on my hard disc. I'd like to run a script that imports and runs a script on each file as it is added to the directory. Is there a simple way to do this using Dynamic ? Is it necessary to use Refresh ? For example, I'd like to be able to save a series of text files to a directory (with arbitrary names) and then print the contents in near real-time. Answer How about using ScheduledTask ? This sets up a Monitor button that if pushed, starts monitoring the given directory ( $UserBaseDirectory ). If you set timeRes to a smaller value, you can get closer to realtime updating. By specifying nb beforehand, one can redirect printing to the actual notebook. The monitor checks if there is any newly added file in the directory, and lists them immediately in the notebook (unless files were removed, as then an empty list is returned). It is easy to put any further script at the indicated part of the code to e.g. check the content...

interoperability - Clipboard with transparency

After reading this question I have determined that Rasterize[Graphics[Circle[]], "Image", Background -> None] allows you to do Save As on the Image and the keep the transparency. But if you use the the menus Edit->Copy As->Bitmap or Edit->Copy As->Metafile I have noticed that graphics fail to keep their transparency when pasting into other applications. Now I can Export an image and copy and paste it back into Mathematica(or another application) and everything works just fine, therefore the clipboard can hold references to transparent images. Doing some further investigation, here is an image of ClipSpy showing how CF_HDROP and FileNameW (FileName doesn't seem to contain the entire piece of text) contain the location of the png file, allowing you to paste it into other applications. When working with lots of images, exporting every image becomes quite tedious. It seems like their should be some way to automatically have Mathematica export the file and...

numerics - Why is MainEvaluate being used when LinearSolve can be compiled?

According to this question LinearSolve can be compiled. However, CompilePrint[] shows a call to MainEvaluate[] but no warning is generated. It appears that LinearSolve is not compilable, given the presence of MainEvaluate[] . But the lack of any warning is surprising. Something more subtle appears to be going on. Consider the following. In[1]:= SetSystemOptions[ "CompileOptions" -> "CompileReportExternal" -> True]; In[2]:= In[3]:= v2 = Compile[{{m, _Real, 2}, {v, _Real, 1}}, LinearSolve[m, v] ]; In[4]:= CompilePrint[v2] Out[4]= " 2 arguments 3 Tensor registers Underflow checking off Overflow checking off Integer overflow checking on RuntimeAttributes -> {} T(R2)0 = A1 T(R1)1 = A2 Result = T(R1)2 1 T(R1)2 = MainEvaluate[ Hold[LinearSolve][ T(R2)0, T(R1)1]] 2 Return " There are no warnings generated, but I am not sure why there is a call to MainEvaluate[] in the ...

cdf format - CDF plugin no longer launches in Chrome

I exported a web-embeddable CDF, and created an html page with the automatically generated code. Both are in a local folder. When I open the HTML page in a Chrome browser, i get the PNG image telling me to download the Plugin. But I already have it, and indeed downloading again does not fix the problem. I then went to several CDF files that I have uploaded to server, and that worked in the past, and none of them work. However, all work in Safari. What has changed? I suspect this may have to do with Chrome blocking certain plugins, but I do not see CDF in the list at chrome://plugins On my local machine I am running Mma 10.0.1, under Mac OS 10.9.5. Chrome is Version 39.0.2171.71 (64-bit). Answer I had contacted tech support at Wolfram about one of my demonstrations, and got a reply from Ed Pegg (one of the editors at the Wolfram Demonstration site) which included this: "Mathematica 10 turned out to be incompatible with the server our Demonstration site runs on, so we're needi...

list manipulation - Clustering of space-time data

Below is an example of a gaze sequence I recorded during a 3 seconds display. That is, where the eye was at every millisecond. While we should have 3000 points, we are missing some due to blinking. Fixation or visual fixation is the maintaining of the visual gaze on a single location. I need to extract those fixations. That is group of gazes that are both contiguous in time and space. Below is the location of fixations. Of course we'll have to implement thresholds. In this file available for download , you will find 7 sequences there if you simply open and run the attached notebook. gazeSeq[1] is the first out of 7 sequences made out of 3000 sublists representing each gaze record as {x,y,time} : gazeSeq[1][[1]] Out[1]= {-0.562, 0.125, 1000.} where time goes from 1000 to 4000 corresponding to the 3 seconds of display. As said above some data points might be missing. While I tried to use GatherBy , I could not manage to include the condition of "time contiguity" and woul...

geography - Rotate Geographic map

I want the map to be rotated by -45 Degree. I want to coast to be horizontal (perfect -45 degree). I already have: loc = GeoPosition[{52.57243, 5.51780}]; loc1 = GeoPosition[{52.57718, 5.52193}]; loc2 = GeoPosition[{52.57449, 5.52636}]; loc3 = GeoPosition[{52.56495, 5.51071}]; loc4 = GeoPosition[{52.56765, 5.50631}]; GeoGraphics[{Red, Thick,GeoPath[{{loc1, loc2}, {loc2, loc3}, {loc3, loc4}, {loc4, loc1}}], GeoStyling["StreetMap"]}, GeoZoomLevel -> 14,GeoScaleBar -> Placed["meters", {Center, Top}], GeoCenter -> loc,GeoRange -> Quantity[2, "Kilometers"]] I already tried the rotate function which gave unsatisfying results. The code (without rotation) gives the following result: But I want it to look like this (inluding a -45 degree rotation and where coordinates are still displayed correctly): I also tried the following which is an edited copy from Mathematica documentation center: upsidedown = (ImageTransformation[#, RotationTransform[Pi/4], Data...

list manipulation - Importing Data and Devoting Their Names to Them

There are some files in a directory. I have used of SetDiroctory to access all of them. SetDirectory["C:\\Users\\SE7EN\\Desktop\\mathematica\\test"]; I can visit all theirs contents with filenames = FileNames[] {"Ronaldo.txt", "Messi.txt", "Beckenbauer.txt", "Zeydane.txt"} loaddata[filenumber_] := Import[Part[FileNames[], filenumber]] For example: loaddata[4] 2 8 7 13 77 These are contents of Zeydane file. But I want to have imported files with the respectively devoted names. For example, desired result after that process, (which I do not know how it can be done), be same as bellow: Ronaldo={2,3,5,8,0,1} Messi={21,2,45,6} Beckenbauer={11,42,5,2,7,21} Zeydane={2,8,7,13,77} One way is: importing them separately, Messi=Import{.....,'data'} . But it is not the desired process, The desired process must be done automatically. Automatically importing data from directory and devoting their names in that directory to the...

regions - Computing the intersection area of two disks in 3D

Closely related to this question about highlighting intersection of two disks , I am trying to figure out if one can do so similarly for disks embedded in $3D$ (e.g. in a bounding box). The difference is that, in $3D$ the orientation of the disks matters in how much of overlap/orthogonal-projection there is between them. The orientation of a disk is simply the vector normal to its surface and centered at its center. Therefore, each disk has a center vector (for its position) $\mathbf v$ and a normal vector $\mathbf n$ for its orientation. As an example, 2 disks $i,j$ have maximal overlap if $\mathbf n_i \parallel \mathbf n_j$ and the difference vector of their center positions $\mathbf v_j-\mathbf v_i$ also being parallel to their normal, then the overlap area is exactly $\pi r^2,$ $r$ being the radius of the disks. Intuitively, computing such projection is as if we computed the shadow two drawn particles (here disks) create onto one another when visualizing them. But is the...

performance tuning - Manipulate executes expressions multiple times

I am using Manipulate for a rather intricate front end for data visualization. I was getting very sluggish performance and was able to boil the problem down to a very similar question (Why does Manipulate execute the expression twice?) . The suggestions of using ContinuousAction->False and TrackedSymbols does not seem to work in this case. Let's simplify the problem by producing a simple array of numbers and mapping a simple function through them. The array of numbers needs to change dynamically, here we just change the length based on a manipulation parameter, i : manipulateSlow[] := Module[{data, updated}, Manipulate[ Print[i]; data = RandomReal[{0, 1}, 100*i]; updated = Map[Sin, data]; , {i, {1, 2, 3}}]] manipulateFast[] := Module[{updated}, Manipulate[ Print[i]; updated = Map[Sin, RandomReal[{0, 1}, 100*i]]; , {i, {1, 2, 3}}]] When one plays with the parameter i in manipulateSlow manipulateSlow[] the code internal to Manipulate is called multi...

scoping - What are some advanced uses for Block?

I read the answers to this question ( What are the use cases for different scoping constructs? ) and this one ( Condition, Block, Module - which way is the most memory and computationally efficient? ). According to those, Block is safer (if something aborts, it restores the values) and faster (perhaps something to do with the low-level pointer redirection that I believe it uses) than Module , but less memory-efficient if the function is defined a certain way . That being said, (1) why does Leonid say that Module is "safer" when it doesn't have as-good garbage collection, and (2) if I am to use Module for most of the time, what are some of the "advanced" uses which require Block ? Answer Safety Module is safer than Block because: It is a lexical scoping construct, which means that variable bindings are only tied to a specific piece of code. Variables outside that piece of code are never affected by these bindings. In contrast, Block basically binds a ...

matrix - SingularValueDecomposition causes kernel crash in 11.3

Bug introduced in 11.3 or earlier and persisting through 11.3 or later test = Table[RandomReal[{-2, 2}], {3600}, {11}]; Dimensions[test] {3600, 11} Calling SingularValueDecomposition on test crashes the kernel: {u, s, v} = SingularValueDecomposition[test]; Version 11.3 running on Windows 7 (64 bit). Can anyone duplicate this behavior? Answer I contacted support and here is their response: Thank you for contacting Wolfram Technical Support. I was able to reproduce the issue, and consequently, I filed a report with our development team raising the issues and also included your contact information with them so you can be notified once the issue is resolved.

pattern matching - Delete duplicates in a list, depending on the sequence of numbers

Below, list is a representative sample of my list, which contains lists of integers. I would like to be able to input: list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}}; f[list] and obtain the output: {{1, 2, 3}, {2, 1, 3}} In other words, {3, 2, 1} is considered to be the same as {1, 2, 3} , since in reverse it is exactly {1, 2, 3} . However, {2, 1, 3} is not considered to be the same as either {1, 2, 3} or {3, 2, 1} , because it does not match these lists in forward or in reverse. What function f can I use to accomplish this? I tried this: DeleteDuplicates[list, MemberQ[list, #] || MemberQ[Reverse /@ list, #] &] but it does not work, although I'm not sure why. ADDENDUM Now suppose I want to input: list = {{1, 2, 3}, {3, 2, 1}, {2, 1, 3}, {1, 2, 3}}; and obtain: list = {{1, 2, 3}, {2, 1, 3}}; where the "second" {1, 2, 3} is removed as a "normal" duplicate. How can I do this? I could do: DeleteDuplicates[DeleteDuplicates[list, (#1 == Reverse[#2] &)]] but i...

plotting - Flipping axis on a plot

I want to make a 2D plot where the x-axis is flipped so the higher numbers are on the right and lower numbers are on the left. I've managed to do it by flipping the data and making new Ticks but this solution is manually and requires manipulating the data. I was hoping there was a better way. For the normal plot: data = Table[{x, x^2}, {x, 20, 100}]; ListLinePlot[data] And for the flipped data and the new plot: data = Table[{100 - x + 20, x^2}, {x, 20, 100}]; ticks = Table[{x, 100 - x + 20}, {x, 20, 100, 10}] ListLinePlot[data, Ticks -> {ticks, Automatic}] I couldn't seem to find any options like ReverseAxis . Answer @Mr. Wizard pointed to a thread that mentioned the option ScalingFunctions which works for BarChart and Histogram according to the documentation and supports a Reverse option. I simply tried this with ListLinePlot and although the ScalingFunctions appears in red, it works! ListLinePlot[data, ScalingFunctions -> {"Reverse", Identity}] Thanks...

scoping - Getting variables out of Dynamic Modules after restoring the program

The scrap of code below [from Mathematica's Help on DynamicModules ] generates a Pane of Locator s, and a line showing the interpolation between the datapoints. DynamicModule[{pts = {{0, 0}, {1, 1}, {2, 0}, {3, 2}}}, LocatorPane[Dynamic[pts], Dynamic[Plot[InterpolatingPolynomial[pts, x], {x, 0, 3}, PlotRange -> 3] ]]] When the program is saved,and reloaded, the Plot persists with the then current values of the points. Suppose, after reloading the file (but not reinitializing the DynamicModule ), I want to use the values of the points (which I moved in interacting with the program before saving it). In otherwords, I'd like to be able to access a list of the modified points with, perhaps, new functions. I realize I could just read out variables in the original function, store them, then load them as part of the initialization procedure when restarting a program a second time, but this in effect means running the original program hist...

numerics - Is there a way to globally set when to treat a very small number as zero?

I understand that I can use Chop to force a very small number to be treated as 0 and can use PossibleZeroQ to as a way to test whether such a number might effectively be 0 , but applying Chop every time a small number is close to zero in order to "make it be" zero is tedious and error prone; while PossibleZeroQ seems to have its own ideas about what constitutes 0 . Are there global settings that will let me treat every number smaller than some specified value as 0 , effectively applying Chop automatically to all results; and specify how large a number PossibleZeroQ should recognize as 0 ? Answer As was pointed out in the comments, $Post is a way to go here. Take as an example: FourierDCT[FourierDCT[{0, 0, 1, 0, 0}, 2], 3] (*{0., -5.55112*10^-17, 1., 1.38778*10^-17, 1.38778*10^-17}*) Now lets set $Post to Chop with tolerance 10^-13 . $Post = Chop[#, 10^-13] &; This will apply the Chop function to every output thereafter. FourierDCT[FourierDCT[{0, 0, 1, 0, 0}, ...