Slow image manipulation

This is some extremely simple code that shows an image and manipulates a circle (that will be used to select a region of the image to analyze). All those `Dynamic`s eliminate some terrible lag, I understand the one for the circle, but why are the other necessary?               theImage = pickAnImage;  (*mine is 368 by 252*)     Manipulate[      circularSelector = Graphics[{Yellow, Dynamic[Circle[center, radius]]}];      xRange = Dynamic[{center[[1]] - radius, center[[1]] + radius}];      yRange = Dynamic[{center[[2]] - radius, center[[2]] + radius}];             Column[{Show[theImage, circularSelector],        xRange,        yRange}],           {{center, {184, 126}}, {0, 0}, {368, 252}, 1, Locator, Appearance -> None},      {{radius, 50}, 2, 100, 1, Appearance -> "Labeled"}]      Consider now adding one line of code to show the section of the image in the selection, something like               ImageTake[theImage,xRange,yRange],      Well, that doesn't work. It works if the `Dynamic`s are removed from the definition of `xRange` and `yRange`, but then all the lag is back!:               theImage = pickAnImage;  (*mine is 368 by 252*)     Manipulate[      circularSelector = Graphics[{Yellow, Dynamic[Circle[center, radius]]}];      xRange = {center[[1]] - radius, center[[1]] + radius};      yRange = {center[[2]] - radius, center[[2]] + radius};           Column[{Show[theImage, circularSelector],        xRange,        yRange,        ImageTake[theImage, yRange, xRange]}],           {{center, {184, 126}}, {0, 0}, {368, 252}, 1, Locator, Appearance -> None},      {{radius, 50}, 2, 100, 1, Appearance -> "Labeled"}]       How do I fix this? More importantly, what's the reason behind it? When using `Manipulate`, I seem to run into lag and this `Dynamic` stuff seems to be behind it. I've checked the usual resources, but something as simple as this (A `Manipulate` with several images, or how to optimize code for snappiness) is rarely described. EDIT: As requested by Nasser (thanks btw) I'm adding the code that doesn't work (selection is not shown):               theImage = pickAnImage;  (*mine is 368 by 252*)     Manipulate[      circularSelector =        Graphics[{Yellow, Dynamic[Circle[center, radius]]}];      xRange = Dynamic[{center[[1]] - radius, center[[1]] + radius}];      yRange = Dynamic[{center[[2]] - radius, center[[2]] + radius}];           Column[{Show[theImage, circularSelector],        xRange,        yRange,        ImageTake[theImage, yRange, xRange]}],              {{center, {184, 126}}, {0, 0}, {368, 252}, 1, Locator, Appearance -> None},         {{radius, 50}, 2, 100, 1, Appearance -> "Labeled"}]      As mentioned before, if the `Dynamic` are removed from xRange and yRange this works (second code above), but moving the circle is laggy compared to the first code (and it will get worst once more complex code is added).


Finding central point in a ContourPlot

I am using `ContourPlot` for defining a 2-parameter space feasibility of a function. This function simply returns 1 if everything is `True`, or -1 if everything is `False`. My question is, without knowing the algebraic expression of the function, how can you find the point inside the feasibility region that is most distant from the border? Just as an example, if my contour was a square, the point I would be looking for would be in the center.               ContourPlot[Sin[y] + Sin[x], {x, -4.7, 1.6}, {y, -4.7, 1.6},       Contours -> 1,      FrameLabel -> {x, y}]      ![enter image description here](http://i.stack.imgur.com/dR000.png) Any ideas are appreciated! Thank you in advance


DateList Segmentation of data

I've been trying to separate large segments of DateList formatted data (years worth at a time) into individual days using the `Split` function.   The data has the form:               data = {{{y,m,d,h,m,s}, 154},{{y,m,d,h,m,s}, 157},...}       and unfortunately there is not a uniform length of data per day (or I would have just partitioned it). This is what I've been trying (or variations of it):               splitData = Split[data,#2[[1,3]]>#1[[1,3]]&];      or               splitData = Split[data,Less[#1[[1,3]],#2[[1,3]]]];      and plenty of other versions, but it doesn't split where I need it to. I thought if I compared the days in the DateList slot the data would split (as days of a month are increasing until the new month begins. My current solution (which is very inefficient) pulls the dates out of data and applies `Union`, `Union@data[[All,1]]`, then iterates through each data point comparing dates using nested tables. ... I know, a very poor method. Anyone see how to us `Split` or another more efficient method to separate? If you need test data to work with I've been using this instead of the real data (a much smaller set):               dpmo[month_, year_] := DateDifference[{year, month, 1}, {If[month == 12, year + 1, year], If[month == 12, 1, month + 1], 1}];     dates = Flatten[Table[Table[{2012, month, day, 0, 0, 0}, {day, 1, dpmo[month, 2012]}], {month, 1, 12}], 1];     data = Flatten[Table[Table[{dates[[m]], RandomInteger[{100, 250}]}, {100}], {m, 1, Length@dates}], 1];      The code generates the equivalent to a years worth of data, however there is a definitive set of data per day (100) which I do not have in the actual set. I didn't feel like adding that to the test data.


Fourier-Motzkin Elimination

Is there any method available in mathematica to eliminate variable from set of inequalities? I tried Eliminate function available, but I guess it works on equalities only.


Infix form of PutAppend ( >>> ) does not work with variable

I'm new to _Mathematica_ , so I suspect this question involves either a misunderstanding involving variables or the usage of `>>>`. On a _webMathematica_ page (backed by _Mathematica_ 5.2), I have the following:               foo[arg_] := Module[{argN},         ArgN = arg;         filenameS ="Absolute/Path/To/File";         ArgN >>> filenameS; (*Problem Line*)     ];     foo["test"];      Running this appears to do nothing. When I replace the line               ArgN >>> filenameS;      with               PutAppend[ArgN, filenameS];      It works perfectly, appending `"test"` to the file. Why doesn't the infix form of `PutAppend` work in the same way?


Change base font for all graphics objects

How can I change the base font style for _all_ graphics objects, including the ones generated using plotting functions? I would like to change this _a single time_ and have it affect all graphics generated from there on (i.e. not specify the font on a plot by plot basis). Say, I'd like to use 16 point Helvetica for everything by default. * * * My original thought was `SetOptions[Graphics, BaseStyle -> {...}]`, but this will be overridden on graphics created using the various plotting functions (e.g. `Plot`). My second try was changing the `BaseStyle` in the `GraphicsBoxOptions` of the notebook, but this didn't have an effect.


SinglePredictionBands versus MeanPredictionBands from NonlinearModelFit

From my Statistics lectures I know the term confidence and prediction interval, whereas the confidence interval is smaller than the prediction interval. If I plot the mean and single prediction bands with the same confidence level in _Mathematica_ , than the mean prediction band is smaller than the single prediction band interval. Anyone who can explain me what are the differences between the `“SinglePredictionBands”` and `“MeanPredictionBands”` which are standard properties from `NonlinearModelFit`?   Or is it just a different terminology for confidence and prediction interval used by _Mathematica_? If no it would be useful if someone can tell me which properties I have to apply for the confidence and the prediction interval.


Finding average error of the data

Considering I have some data, and I want to fit the data to a linear fit and find the average error from the linear fit, how can I do that using Mathematica? I have               temp = WeatherData[location, "MeanTemperature", {start, end, "Day"}];     Show[ListPlot@Partition[Reverse@temp["Values"], 2, 1], Plot[line, {x, 0, 40},        PlotStyle -> Red]]      Which generates ![enter image description here](http://i.stack.imgur.com/fN4JA.jpg) How can I find the average error of this linear fit?


Visualize a tree structure using TreeGraph

I have a code that generates a tree of graphics objects. The structure can be visualized like this, with each `Rule` constituting a parent child relationship:               children[list_] := ReplaceList[list, {a___, x_, b___} :> Rule[x, children[{a, b}]]]     children[{a, b, c}] // TreeForm      ![tree](http://i.stack.imgur.com/skwTP.png) A better way of visualizing the result I want, courtesy of Halirutan is this:               children[list_] :=  ReplaceList[list, {a___, x_, b___} :> (x @@ children[{a, b}])]     children[{a, b, c}] // TreeForm      ![result example 2](http://i.stack.imgur.com/dnDMs.png) However my real code like I said has graphics in it. So each symbol in the above image is a graphics object. An example of this:               r[col_] := Graphics[{col, Rectangle[]}]     treeData = children[{r[Red], r[Green], r[Blue]}];      I would like to visualize this tree using `TreeGraph` where each `VertexShape` is the corresponding graphics object. So for the leftmost branch I expect graphics object `a` and from it two arrows one two graphics object `b` and one to graphics object `c` and so on. Example of expected output from `children[{r[Red],r[Blue]}] // renderTree`:               TreeGraph[{       DirectedEdge[1, 2],       DirectedEdge[1, 3],       DirectedEdge[2, 4],       DirectedEdge[3, 5]       }, VertexShape -> {        2 -> r[Red],        3 -> r[Blue],        4 -> r[Blue],        5 -> r[Red]        }, VertexSize -> 0.5]      ![example tree](http://i.stack.imgur.com/4ocwy.png) Speed is not important since I will only be doing this on relatively small trees for visualization purposes. I can change the code that generates the tree data so you are free to do that as well, you don't have to work with the data as it is. You might want to insert custom heads for example. That is one approach I've tried. However I don't have any code to share, I hope that will not cause a riot. But if it does I shall accept it stoically I hope, I know how important showing an effort is to some of you. I don't know what a good start is.


Cells overwritten as "Null"

Last week an entire _section_ of a notebook was overwritten(?) such that all cells (headers, text, inputs, and outputs) were merely `Null`. It was in a section of the notebook that I wasn't using at the time, but fortunately I noticed and was able to recover from a backup file without too much difficulty. Today, I noticed a different, but entire _subsection_ that exhibited the same behavior (I haven't yet recovered my work on this portion). The only clue that something strange was happening was that last week MMA informed me that an outside program had altered the contents of the notebook, so it was saving a new copy. This happened several time last week when the issue first presented itself. I haven't seen it since then, however, so this symptom was apparently not present for the current case. Here's what I'm running: OS X 10.9.2 MMA 9.0.1.0. Hopefully this isn't a red herring, but the notebook does happen to be in Dropbox, which makes me wonder. Has anybody seen anything like this? Any ideas? Below is a screenshot of the original case. ![original section of my notebook showing Null in every cell](http://i.stack.imgur.com/CHQ0H.png)


Place title outside of GraphicsGrid in Manipulate

I want to be able to place a text title centered just inside the bounding box generated by Manipulate yet above the `GraphicsGrid` and run boxes you see when executing the code. My stripped down code is               Manipulate[       GraphicsGrid[{{Graphics[{Rectangle[]}]}}, ImageSize -> {400, 400}],      {{run, 0}},      ControlPlacement -> Left]      Thank you


Manipulate Discrete Values Labelling

I have 3 lists of plots (generated in other code), `rawplots`, `weightplots`,`linearizedplots`. Each list of plots is the same length, and I wanted to use `Manipulate` to access one plot at a time. I attempted to use the following: `Manipulate[plot[[n]], {plot, {rawplots, weightplots,linearizedplots}, PopupMenu}, {n, 1, Length@files, 1,RadioButtonBar}]` This works, but in the Popup Menu I have plots. I would like to instead have words in the popup menu. Additionally, I have a variable `files` which is a list of filenames. Ideally, I would like to have the radio buttons named `files[[n]]`, i.e. the file name from the variable `files`. Thanks!


How to fix problems solving for values of BSpline function?

I generated a spline function called `f` using the `BSplineFunction` with domain `{t,0,1}`.               f = BSplineFunction[{{0., 5.81152}, {-0.909122, 5.73997}, {-1.86805, 5.5031},        {-1.79586, 5.52709}, {-2.40811, 5.28912}, {-3.4109, 4.70527}, {-4.68131,   3.501},        {-4.93131, 2.99958}, {-5.09697, 2.6673}, {-5.34697, 2.16588}, {-5.59697, 1.66446},        {-5.84697, 1.16304}}, SplineWeights -> {10, 10, 10, 1, 1, 1, 1, 1, 1, 10, 10, 10}]      I then wanted to find the point at which the function intersects the line from which points used to generate the spline were taken from. Graphically, I know the intersection occurs within the domain of `f`.               k[t_] = {-4.93131 - 0.915666 t, 2.99958 - 1.83654 t}      However, running the code:               FindRoot[First[k[0]] == First[f[t]], {t, .5, 0, 1}]      where `k[0]` is the end of the line produces a negative number. Is there a way to solve for the meeting points of those two functions?


Dataset Mathematica 10.0

I started to use the new funcationality 'Dataset'in Mathematica 10.0.                  dataset = Dataset[{           <|"a" -> 1, "b" -> "x", "c" -> {1}|>,           <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,           <|"a" -> 3, "b" -> "z", "c" -> {3}|>,           <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,           <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,           <|"a" -> 6, "b" -> "z", "c" -> {}|>}]      Then I get a error as show in the next image ![enter image description here](http://i.stack.imgur.com/pjUfI.jpg) I tried the same syntax in combination with Needs["TypeSystem`"];, but wiyth the same result. Who has a suggestion to solve this issue? Thanks Michiel


How can I plot implicit equations?

If you enter the following into Wolfram | Alpha, you get nice graphs:               graph 4 x^4 + y^2 = 2       ![enter image description here](http://i.stack.imgur.com/LG0sb.png) How do you do this in _Mathmatica_? I realize that these are not functions, because the graphs do not pass the straight line test. But what does Wolfram Alpha do to put these things into something that _Mathematica_ can understand?


Inspecting non-variable state from a breakpoint in Workbench

Suppose I'm stopped at a breakpoint in Workbench, say at one of the `y = ...` lines in:               foo[a_] := Block[{y},          If[Sin[a] > 0,             y = -1,             y = 1             ]         ]      How can I find out what `Sin[a]` is? Or more generally do some other evaluation using the current state of my program?


Manipulating List

I have a list:               b={{1, 1}, {2, 2}, {3, 3}, {5, 5}, {6, 6}, {8, 8}, {10, 10}}      I want to insert the elements in this list:               ClearAll[n];     n = 1;     While[n < 10,      If[Unequal[n, b[[n, 1]]], Insert[b, n, b[[n, 1]]]]       n++      ]      I expect to get this:               b={{1, 1}, {2, 2}, {3, 3}, {4, 1},{5, 5}, {6, 6}, {7, 1}, {8, 8}, {9, 1}, {10, 10}}      However I get this errors:               Part::partw: "Part 8 of {{1,1},{2,2},{3,3},{5,5},{6,6},{8,8},{10,10}} does not \     exist"      Part::partw: "Part 9 of {{1,1},{2,2},{3,3},{5,5},{6,6},{8,8},{10,10}} does not \     exist"


How to import a ".numbers" spreadsheet?

Does Mathematica support importing a ".numbers" spreadsheet file (from the "Numbers" '09 (ver. 2.3 554) spreadsheet program in Apple's OS X iWork office suite)? A ".numbers" file is actually a zip file,                $ file foo.numbers       foo.numbers: Zip archive data, at least v2.0 to extract      and the contents of the spreadsheet is stored in "index.xml":               $ unzip -t foo.numbers     Archive:  foo.numbers      testing: QuickLook/Thumbnail.jpg   OK      testing: buildVersionHistory.plist   OK      testing: index.xml                OK     No errors detected in compressed data of foo.numbers.      Although it would be technically possible for me to parse it myself, I imagine a tool already exists for that. Thoughts? Thanks, Justin **Edit:** Here is an example .numbers spreadsheet.


How could I code the following nonlinear regression?

I am an extremely limited user of _Mathematica_. Could someone tell me how to set the following nonlinear regression problem :               Y = Sum[a[i] F[i,X] , i = 1,4]          in which                F[i,x] = X^b[i] (b[i] LerchPhi[X,1,b[i]] - 1 / (1-X))        the parameters to be adjusted being the `a[i]` and `b[i]`. Preliminary work provides me reasonable estimates of all parameters. How can I use them at the input level to make Mma's life easier ?


Why cant Mathematica 9 interpret this unit?

I'm using Mathematica 9.0.1. Sorry for using an image, but pasting code messed up the output formatting. I'd like to represent 25 Btu/(hr ft F). ![enter image description here](http://i.stack.imgur.com/LVn2r.jpg) All units are spelled correctly as identified in the second attempt... not sure what is going wrong in the first attempt? I've also tried: "DegreesFahrenheit" "DegreesFahrenheitDifference" "BritishThermalUnitsIT" No luck. I've seen other posts where people used the Wolfram Alpha capabilities to "interpret" which units were used... I hope I don't need internet connectivity for this simple task?


Unexpected behavior from VectorPlot

I am surprised at the behavior of VectorPlot in the following sense: plotting a vector field and examining the output at a point $(x_0,y_0)$ reveals that _Mathematica_ doesn't draw the _tail of the arrow_ at $(x_0,y_0)$ but rather it draws the _base of the arrowhead_ at $(x_0,y_0)$. (Of course, the output points the arrow in the correct direction.) This is, in my opinion, confusing/misleading for students learning about vector fields. Has anyone developed an efficient workaround to this, so that when we plot the vector field we get output that positions the tail of the arrowhead at the point $(x_0,y_0)$ rather than the base of the arrowhead? Here is some output which perhaps more clearly portrays the issue:               pts = Flatten[Table[{i, j}, {i, -1, 1, .5}, {j, -1, 1, .5}], 1];     p1 = ListPlot[pts, PlotStyle -> {{Red, PointSize[Large]}}];     p2 = VectorPlot[{x + y, 1}, {x, -1, 1}, {y, -1, 1}, VectorPoints -> pts, VectorScale -> Medium];     Show[p2, p1]      ![enter image description here](http://i.stack.imgur.com/POY7q.png)


DatePlus and DateList are inconsistent with numerical handling of the final element

If you run this code you will see that `DatePlus` and `DateList` are inconsistent in the format of the lowest order element of the date list.               DatePlus[DateList["2012-1-1" ], {5, "Month"}] === DateList["2012-6-1"]     DatePlus[DateList["2012-1-1" ], {5, "Month"}] == DateList["2012-6-1"]     DateList[DatePlus[DateList["2012-1-1" ], {5, "Month"}]] === DateList["2012-6-1"]     DatePlus[DateList["2012-1-1" ], {5, "Month"}] // FullForm     DateList["2012-6-1"] // FullForm     DateList[DatePlus[DateList["2012-1-1" ], {5, "Month"}] ] // FullForm      This leads to issues when you try to locate elements in a list as follows:               Position[{DatePlus[DateList["2012-1-1" ], {5, "Month"}]}, DateList["2012-6-1"]]     Position[{DateList[DatePlus[DateList["2012-1-1" ], {5, "Month"}]]}, DateList["2012-6-1"]]      What is even more annoying is that I have found that wrapping a date generated by `DatePlus` in `DateList` doesn't always fix the problem and I can not tell what circumstances are required to make it work and not work. Any insight would be appreciated. I may try to open a case with Wolfram, but my past experiences with their support team have been an unsatisfactory use of my time.


measure minimum distance of dots from edge

I want to measure minimal distance of small dots from the edge of an image: Image of bright dots: ![enter image description here](http://i.stack.imgur.com/GmXiM.png) Edge image ![enter image description here](http://i.stack.imgur.com/N2P7t.png) ImageAdd looks like following: ![enter image description here](http://i.stack.imgur.com/vZQjy.png)


Does mathematica 9 on mac depend on these dynamic libraries?

The Mac package installing program "brew" suggests I remove some of these dynamic libraries, but I am worried that mathematica 9 might depend on them. As far as mathematica 9 is concerned, is it OK to remove them? And, how does one know?               Unexpected dylibs:         /usr/local/lib/libasan.0.dylib         /usr/local/lib/libatomic.1.dylib         /usr/local/lib/libg2c.0.0.0.dylib         /usr/local/lib/libg2c.0.dylib         /usr/local/lib/libg2c.dylib         /usr/local/lib/libgcc_ext.10.4.dylib         /usr/local/lib/libgcc_ext.10.5.dylib         /usr/local/lib/libgcc_s.1.dylib         /usr/local/lib/libgfortran.3.dylib         /usr/local/lib/libgomp.1.dylib         /usr/local/lib/libitm.1.dylib         /usr/local/lib/libquadmath.0.dylib         /usr/local/lib/libssp.0.dylib         /usr/local/lib/libstdc++.6.dylib


Implement planar correction for skewed 3D profilometric data

I have some data that represents small-scale surface topography. The data is planar but not flat because it's impractical to level this microscope to a tolerance of microns. It looks like this: ![An example of 3D profilometric data with a nonzero planar slope](http://i.stack.imgur.com/nQcLB.jpg) I'd like to postprocess that slope out, such that the major axis is colinear with the long side of the blue rectangle and the vertical axis can then be rescaled to show meaningful topographic variation instead of the (really large) planar slope. One approach here might be to do an orthogonal transformation via (basically) principal component analysis, eg. find the three eigenvalue/eigenvector pairs, and then treat the eigenvectors corresponding to the largest two eigenvalues as the new X and Y axes. I'd be very interested to see how this (or some better way) might be done efficiently in Mathematica (this data is generally in the millions of rows). An example of my data is here. and this is the code I've written so far (which depends on version 9+ for `Downsample[]`):                   pathToDatafile = "path\\to\\file\\6000s.xyz";         data = Import[pathToDatafile,"Table","HeaderLines"->15];         data = DeleteCases[data,{__,_String,_String}]; (*remove the "no data" lines that the instrument creates*)         data=Delete[data,-1]; (*throw away the instrument's pound sign at the end of the file*)         data = Downsample[data,{100,1}];(*downsample by a lot because we have way too many datapoints*)         ListPlot3D[data,         Mesh->None,         BoxRatios->Automatic,         PlotStyle->LightBlue,         Boxed->False,     Axes->{True,True,True},     AxesLabel->{"\[Mu]m","","\[Mu]m"},     PlotRange->{Automatic,Automatic,{0,250}},     ImageSize->Large     ]


How to properly remove the CUDAResources paclet?

I have Mathematica 8.0.0.0 installed on my Mac, and while I tried to see what it could do with CUDA, it downloaded a large directory (~1 GB) named `CUDAResources-OSX-8.0.0.8` in `~/Library/Mathematica/Paclets/Repository/`. However, after the download, I tried to see what it would give but `CUDAQ[]` returns `False` on my system. Seeing that CUDA's not going to be useful on this machine, how can I reclaim this disk space? In other words, how to get rid of this downloaded data?


Stereographic Projection

Say I want to represent points of the complex plane in the sphere $\Bbb S^2$ using stereographic projection. That is, the Riemann sphere: ![Riemann Sphere](http://i.stack.imgur.com/6zeHc.jpg) Specifically, it would be nice to be able to:   1. Given the coordinates $(x,y)$ of a point of the plane, see the point and its spherical image, and optionally, the line through the north pole and $(x,y,0)$.   2. Given a circle in the plane, (that is its center $(x,y)$, and its radius $r\gt 0$), see the circle and its spherical image.   3. Optionally: it would be nice as well but is not necessary, being able to project in the sphere other kinds of sets, say polygons, sets of points, maybe straight lines, etc. How can we do this? Is this already possible in Mathematica, I mean as built in functions? Thanks.


Is it possible to concatenate sounds?

I used to be able to make a `Table` of `ListWaveform` objects, and `Export` them; `Export` would automatically concatenate the sounds. This no longer works. Is there a way to concatenate sound objects?


Matching variables with Subscripts yielding True and False

I am trying match variables with subscripts just returning true or false depending if pattern is matched. My try is to use `Cases`. However the following does not return a match               Cases[Subscript[x, 2], Subscript[x, l_] /; l > 1]      Moreover, if this would work there must something nicer than               Length[    Cases[Subscript[x, 2], Subscript[x, l_] /; l > 1]]>=1


Dates as FrameTicks on a ListLinePlot

For reasons too lengthy to explain, I would like to display a list of dates or years (as numbers or strings) as `FrameTicks` on a `ListLinePlot`. An example of what I have so far follows:               xle = FinancialData["XLE", All];     DateListPlot[xle, ImageSize -> 350]     ListLinePlot[xle[[All, 2]], ImageSize -> 350]     firstDateByYear = First /@ SplitBy[xle[[All, 1]], #[[1]] &]     positions = Flatten[Position[xle[[All, 1]], #] & /@ firstDateByYear]     years= firstDateByYear[[All,1]]      ![Plots](http://i.stack.imgur.com/4I9fK.png)               {{1998, 12, 22}, {1999, 1, 4}, {2000, 1, 3}, {2001, 1, 2}, {2002, 1, 2},{2003, 1, 2}, {2004, 1, 2}, {2005, 1, 3}, {2006, 1, 3}, {2007, 1, 3}, {2008, 1, 2}, {2009, 1, 2}, {2010, 1, 4}, {2011, 1, 3}, {2012, 1, 3}}          {1, 8, 260, 512, 760, 1012, 1264, 1516, 1768, 2019, 2270, 2523, 2775, 3027, 3279}          {1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012}      I thought that identifying a position at which I wanted to place a label would help. The following earlier question Formatting Ticks and FrameTicks labels with a function relates to what I want to do, but I haven't understood it sufficiently to adapt it to my needs. Doing something like placing a string for the year at every other position in the list "positions" would give me a clear idea of how to do more complicated things on my own.


Sum slowing down computations

I am trying to compute higher order Casimir invariants for some representations of certain groups. I can get the quadratic, cubic and quartic but beyond that things are taking too long to the point I don't know if anything is really happening. For example, I have an oscillator representation of $SO(4,2)$ where the generators $G_{AB}, (A,B=1,\ldots,6)$ are bilinears in oscillators. I have already defined a function for normal ordering of noncommuting oscillators which works reasonably well. Now I am trying to compute Casimirs in this representation for example quadratic Casimir is as follows:               Cas2 =Sum[g[[ind1, ind3]]G[ind3, ind2]g[[ind2,ind4]].G[ind4, ind1], {ind1, 1, 6}, {ind2,                   1, 6}, {ind3, 1, 6}, {ind4, 1, 6}];      where $g_{AB}$ is the metric to raise and lower the indices and $G_{AB}$ are the generators. Note that I have defined $.$ as the noncommutative product with certain properties. After summing this up, I use my custom simplification function to simplify it. The problem is that for 6th order Casimir the sum which looks like this               cas6 = Sum[g[[ind1, ind7]] g[[ind2, ind8]] g[[ind3, ind9]] g[[ind4,ind10]]g[[ind5,ind11]]                g[[ind6,ind12]] G[ind7,ind2].G[ind8,ind3].G[ind9,ind4].G[ind10,ind5].G[ind11,                ind6].G[ind12,  ind1], {ind1, 1, dim}, {ind2, 1,dim}, {ind3, 1, dim}, {ind4, 1,                dim}, {ind5, 1,dim}, {ind6, 1,dim}, {ind7, 1, dim}, {ind8, 1, dim}, {ind9, 1,                dim}, {ind10, 1,dim}, {ind11, 1, dim}, {ind12, 1, dim}];      where $dim=6$, takes far too long. I am not even doing any simplification at this step which will cause so much time. I was wondering if there is any alternative to sum or anything else I can do to speed it up. I tried ParallelSum which reduced the time a little bit for other invariants but that hasn't worked too well on this either. I have waited for over 4 hours without any completion. I need to do the same thing for $SO(6,2)$ which has indices $A,B=1,\ldots, 8$ and has been a nightmare too.


Basic questions about GUI

I have created the following simple GUI:               {num10, num20, path0, date0} =       DialogInput[        {num1 = 100, num2 = 10, path = "a path", date = "11/11/2012"},        Column[{          "First number", InputField[Dynamic[num1], Number],          "Second number", InputField[Dynamic[num2], Number],          "Path of InputData", InputField[Dynamic[path], String],          "Type in a date (DD/MM/YYYY)",           InputField[Dynamic[date], String],          Button["Proceed", DialogReturn[res = {num1, num2, path, date}],            ImageSize -> Automatic]}]];      After filling in the required information and clicking the "Proceed"-button a simple code/calculation follows:               {num10 + num20, path0, AbsoluteTime[{date0, {"Day", "/", "Month", "/", "Year"}}]}      Here is what I would like to do:   1. **Displaying only GUI** : I would like to create a file "MyProgram" which - when opened - pops up immediately the GUI (the notebook will be opened in the background for further calculations but not displayed to the user).   2. **Drag & Drop:** In the third field I ask for a path for input data. Is it possible to insert the path by dragging the file (in this case a xls-file) and drop it into the field inserting its path?   3. **Displaying results in GUI:** After clicking the button "Proceed" I would like to display the results in the same GUI, below the input fields.   4. **Info button** For the fourth field I added information on the format of the date. It would look much nicer when this information would pop up when clicking on a "?"-button. How can I implement this button?


Backward compatibility issues while DumpSaving Interpolation polynomials

I have bkwrd compatibility issues when I save my NDSolve result (which is an interpolating polynomia) using `DumpSave` from Mathematica 8 on Windows 7 and then try loading it using Mathematica 7 on Linux. Is there any way I could specify backward compatibility (and cross compatibility: files can be imported into different OS with or without the same version of mathematica) in `DumpSave`? I have read this and this but they don't address the same issue. Also, is there anyway the interpolating functions can be saved in a human readable format? Example code to work on, for convenience.


Installing RLink on Linux

I'm trying to install RLink here.               Needs["RLink`"]     InstallR[]      After downloading it throws an error:               InstallR::fail: Failed to install R. The following error was     encountered: Unable to load dynamic libraries >>      And then:               RSet["myVar",10]     JLink`Java::excptn: A Java exception occurred: com.wolfram.links.rlink.exceptions.RLinkException: Unable to load dynamic libraries         at com.wolfram.links.rlink.RLinkInit.<init>(Unknown Source)         at com.wolfram.links.rlink.RLinkInit.getInstance(Unknown Source)         at com.wolfram.links.rlink.RLinkInit.getRExecutor(Unknown Source).     JLink`Java::argx: Method named rPut defined in class com.wolfram.links.rlink.dataTypes.inTypes.RIntegerVectorInType was called with an incorrect number or type of arguments. The arguments, shown here in a list, were {myVar,$Failed}. >>         REvaluate::err: General error in function RLink`Private`withRTemporaryVariables >>         First::normal: Nonatomic expression expected at position 1 in First[$Failed]. >>     StringReplace::strse: String or list of strings expected at position 1 in StringReplace[StringTrim[First[$Failed]],RLinkFunctionHash12345[[~~DigitCharacter..~~]]:><function>]. >>         RSet::puterr: Error putting the expression 10 into a variable myVar in R. The last error message issued by R was StringReplace[StringTrim[First[$Failed]],RLinkFunctionHash12345[[~~DigitCharacter..~~]]:><function>] >>     $Failed      It isn't java's fault. I've tried pointing `JRELocation` option of `InstallR` to different JREs, error stays the same. I'm on Ubuntu 12.04 64 bit.


ErrorListPlot Legend with Markers

I'm trying for some days now to integrate markers in my legend. I have a ErrorListPlot with markers and a legend but difficulties to realize the markers in the legend as well. Thanks a lot for your answers in advance! Here is my Mathematica Code:               Needs["ErrorBarPlots`"];     Needs["PlotLegends`"];          K = {{{4, 14.5566}, ErrorBar[0.2789/2]}, {{19, 15.46581},          ErrorBar[0.27794/2]}, {{26, 17.76820}, ErrorBar[0.33368/2]}};          F = {{{1, 12.634}, ErrorBar[0.216414/2]}, {{11, 13.84994},          ErrorBar[0.402/2]}, {{18, 15.622}, ErrorBar[0.26659/2]}};          ClearAll[simpleLegend]     simpleLegend[legendItems__, pos_] :=       Module[{legendLine, offset, legend},        offset = Module[{s, o, insetpts = 10},          s = pos /. {Left -> 0, Right -> 1, Bottom -> 0, Top -> 1};         o = insetpts pos /. {Left -> 1, Right -> -1, Bottom -> 1, Top -> -1};         Offset[o, Scaled[s]]];       legendLine[{lbl_,           lineStyle_}] := {Graphics[{lineStyle, Line[{{0, 0.5}, {1, 0.5}}]},           ImageSize -> {20, 10}, AspectRatio -> 0.5],          Style[lbl, FontFamily -> "Arial", Bold, FontSize -> 12,           TextAlignment -> Left, LineBreakWithin -> False]};       legend = GraphicsGrid[legendLine /@ legendItems, Alignment -> Left];       Graphics@Inset[legend, offset, pos]]; PlotMarkers -> {{\[FilledUpTriangle],         18}, {\[FilledDownTriangle], 18}};          labels = {"928", "927"};     styles = {Directive[{RGBColor[0.639216, 0.329412, 0.772549]}],         Directive[{Blue}]};     plot = ErrorListPlot[{F, K}, PlotStyle -> styles,        FrameTicksStyle -> Directive[Thick, FontFamily -> "Arial", 12, Bold],        PlotMarkers -> {{\[FilledUpTriangle], 18}, {\[FilledDownTriangle], 18}},        Joined -> True,        PlotRange -> {{0, 50}, {12, 18}},         FrameLabel -> {Style["Alter / Tage", 12, Bold, FontFamily -> "Arial"],          Style["Absorption / dB/cm", 12, Bold, FontFamily -> "Arial"], None,           None}, Frame -> True];     Show[plot, simpleLegend[Thread@{labels, styles}, {Right, Top}]]      ![Mathematica graphics](http://i.stack.imgur.com/CjGu2.png) edit: for clearing my probelem: I'd like to have the same markers as in the plot in the legend lines as well..


How to differentiate a geometric sum

How do I differentiate both sides of the equation shown below with respect to r? ![enter image description here](http://i.stack.imgur.com/NYvo9.png)


Radius Values not Displaying in (List)PolarPlot

I'm having troubles with the `PolarAxes` option in `ListPolarPlot` under Mathematica 8.0. To be more specific, when I run the following:               z1 = Import["01_01-rshoulder-deg-1.mat"];     ListPolarPlot[z1, Joined -> True, ImageSize -> {Automatic, 750},      BaseStyle -> {FontFamily -> "Helvetica", FontSize -> 20},      PolarAxes -> True, PolarTicks -> {{0, "0%"}, {Pi/12, "4.16%"}, {Pi/6, "8.33%"}, {Pi/4, "12.5%"}, {Pi/3, "16.67%"}, {5 Pi/12, "20.83%"}, {Pi/2, "25%"}, {Pi/12 + Pi/2, "29.16%"}, {Pi/6 + Pi/2, "33.33%"}, {Pi/4 + Pi/2, "37.5%"}, {Pi/3 + Pi/2, "41.67%"}, {5 Pi/12 + Pi/2, "45.83%"}, {Pi/2 + Pi/2, "50%"}, {Pi/12 + 2 Pi/2, "54.16%"}, {Pi/6 + 2 Pi/2, "58.33%"}, {Pi/4 + 2 Pi/2, "62.5%"}, {Pi/3 + 2 Pi/2, "66.67%"}, {5 Pi/12 + 2 Pi/2, "70.83%"}, {Pi/2 + 2 Pi/2, "75%"}, , {Pi/12 + 3 Pi/2, "79.16%"}, {Pi/6 + 3 Pi/2, "83.33%"}, {Pi/4 + 3 Pi/2, "87.5%"}, {Pi/3 + 3 Pi/2, "91.67%"}, {5 Pi/12 + 3 Pi/2, "95.83%"}, Automatic},     PolarGridLines -> True, PlotRange -> Automatic,      GridLinesStyle -> Directive[Dotted, Thick, Gray],      PlotStyle -> Thickness[0.0125], ColorFunction -> "DarkRainbow",      PlotLabel -> Style["Right Shoulder\n Region Joint Angle", 55,      LineSpacing -> {0.9, 0}]]      The corresponding polar plot is being truncated: ![Truncated polar plot](http://i.stack.imgur.com/ZhbNa.jpg) My guess is that Mathematica is only displaying the relevant plotted component. When I changed `PolarAxes` to `PolarAxes -> Automatic`, the issue is fixed. However, I lose the values for the radius of the plot: ![Non-truncated polar plot](http://i.stack.imgur.com/9yHln.jpg) Is there an option that I can add to the `ListPolarPlot` command so that it still displays the radius values and without having to specify each value manually? The corresponding dataset can be downloaded from: https://www.dropbox.com/s/cpt01ary5ws4j0i/01_01-rshoulder-deg-1.mat


Feasibility of Linear Program

I have a set of (real) linear equations/inequalities and I want to know whether they have a solution, and to find at least one. The goal is to do this quickly. `FindInstance` seems rather slow -- it is possible that it's just the size of my problem, but I thought it could be done faster. In particular, since all my equations are linear, I thought I might try to see if `LinearProgramming` would be faster. Unfortunately, the function doesn't seem to take parameters the way I want it to: I have 0-1 matrices $M_1$, $M_2$, and seek a vector $x$ such that $M_1x = 0$ and $M_2x \geq 1$. The vector $x$ is however allowed to have negative entries. Any help for how to solve this problem is appreciated. Edit: on request, here is an example of $M_1$ (in fact, it always looks like three identity matrices, though its size varies) and of $M_2$ (which has, to the best of my knowledge no nice pattern except that it has precisely 3 ones per row):               M1 = {{1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0},            {0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0},            {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0},            {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1}};          M2 = {{0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},            {0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0},            {0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0}};      I am looking for a real vector $x$ of length 12 (in this case) such that $M_1x = 0$ and each entry of $M_2x$ is at least 1.


Extract Positive Solutions in Logical Expand

I am using Mathematica version 7. I have an expression named `fd` and I took the derivative of `fd` with respect to `t` which I will note the outcome as `Dexprdt`. Basically, I am trying to understand if `Dexprdt` is negative or positive (Comparative Statics) and in order to do this I have the following set-up which was proposed here by b.gatessucks and it works really well. `solPos` shows the logical expansion which makes `Dexprdt` positive. However, as seen in the below code there are 2576 possible combination of solutions and I only want to extract the solutions (inequalites) where `Y1`, `Y2`, `a`, `b`, `d`, `p` are **positive reals**. I tried to use `Pick` command and it was not really useful. I really need help with the methodology. Here is the code:               Remove["Global`*"]     q = 1 - p;     fd = (b d (p - q) Y1 Y2 (p Y1 - q Y2) + a p q t (Y1 + Y2)^2 (p (-1 + Y1^2) Y2 +      q Y1 (-1 + Y2^2)))/(a p q t (Y1 + Y2)^2 (p (-1 + Y1^2) Y2 + q Y1 (-1 + Y2^2)));     expr = FullSimplify[fd];     Dexprdt = Simplify[D[Numerator[expr], t] Denominator[expr] -      Numerator[expr] D[Denominator[expr], t]];     (*Normally in Dexprdt we should have D[Denominator[expr]^2 dividing \     but since it is always positive it is enough to check the Numerator \     of the derivative*)          solPos = LogicalExpand[Reduce[Dexprdt > 0, Reals]]     (*solPos is the possible solutions that makes Dexprdt positive*)          solPos // Dimensions;     (*{2576} - number of possible solutions*)          (*N[Dexprdt]/.First@FindInstance[solPos[[1]],{Y1,Y2,a,b,d,p}]*)     (*5.59992*10^11*)


NumberForm in logarithmic plot (with LevelScheme package)

I am trying to plot some data using the `LevelScheme` package, but changing the logarithmic scale to display values in `NumberForm` instead of `ScientificForm`. I.e. I want to see the axes displaying values as `1`, `10`, `100` and `1000` instead of `10^0`, `10^1` etc. Do you have any tips on how I can achieve this? I was trying to play with `TickLabelFunction` but I guess this is not meant to be used as I want. Here's a minimal working example:               randomdata = Sort@Transpose@{        Log[10, RandomReal[{1*^-7, 1*^-5}, 1000]],        Log[10, RandomReal[{0.1, 1000}, 1000]]     };          ListPlot[randomdata, PlotRange -> {{-7, -5}, {-1, 3}}, Joined -> False,      Axes -> False, Frame -> {{True, False}, {True, False}},       FrameStyle -> {{Automatic, None}, {Automatic, None}},      FrameTicks -> {{LogTicks[10, -1, 3,TickLabelFunction -> (ScientificForm[#] &)],None},                      {LogTicks[10, -7, -5], None}}     ];      ![enter image description here](http://i.stack.imgur.com/zxaP7.jpg) (Interestingly, this pseudo-data is not so randomly distributed at all ;) **edit:** nevermind, I didn't remember the data was in logspace)


Simulating Electrochem Rxns with Mathematica? Availability?

How can I get a copy of Michael Honeychurch book **Simulating Electrochem Rxns with Mathematica** with a CD containing Mathematica notebooks? There seems to be a Nook version at Barnes and Noble but no easy way to get notebooks. Thank you


ParallelTable with nonstandard iterator

This works as expected:               Table[x[1], {x[1], 1, 10}]      However, the parallel version               ParallelTable[x[1], {x[1], 1, 10}]      complains that the expression cannot be parallelized. (The same applies to other iterators like Subscript[x,1] etc. instead of x[1].) How can I fix that?


Handling of non-file URI

According to the manual, Hyperlink “represents a hyperlink that jumps to the specified URI when clicked”. OneNote produces hyperlinks that begin with onenote://. In Mathematica, creating a hyperlink to a OneNote page does not work. It returns a message: “The file that you tried to open was not found…” According to the manual again, “non-file URI open in a web browser”. When I paste the onenote URI in my web browser, it opens the target. 1) Can you confirm this bug in Mathematica? 2) Does anyone know of a workaround? * * * Steps: 1) In OneNote right click on a page label and select Copy Link to Page. The clipboard contains something like: > onenote:///XXXX#Compound%20expressions,%20Get%20and%20Goto&page- > id={7D74D7D4- E640-4217-9575-877E08975BED}&end 2) Create a text cell, put some text, select and press `Ctrl+Shift+H`. Paste the OneNote hyperlink. 3) Click in the hyperlink. * * * **Update** Following this answer, running               Hyperlink["test", MathLink`CallFrontEnd[ FrontEnd`SystemOpen[      "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]]      creates a hyperlink that jumps correctly when it is created. If one clicks on the hyperlink, then nothing happens. On the other hand, running               Button["test", MathLink`CallFrontEnd[ FrontEnd`SystemOpen[      "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]]      creates a button with that works correctly. I will report this as a bug to Wolfram (in the no so near future). * * * **My workaround** For the sake of …, I'll post this workaround. It produces a hyperlink-looking button.               Button[Style["test","Hyperlink"], MathLink`CallFrontEnd[ FrontEnd`SystemOpen[       "onenote:///\\\\myComputer\\The%20Notebook&page-id={7D74D7D4E640-4217-9575-877E08975BED}&end"]]       , Appearance -> None]


FrameTicks puts tick markers on both sides of plot?

I have a framed plot and I want to use Ticks to create customized tick marks, along the lines of               Plot[x, {x, 0, 1}, Frame -> True, FrameTicks -> {Automatic, {0, 1}}]      The problem is this puts the y-axis ticks (0 and 1) on both the left and right-hand sides. How do I keep the ticks only to the left side of the plot as usual?


how to make contents of package visible to the autocomplete system?

I have created a package file like this, in "/path/to/lib/tools.m":               BeginPackage["tools`"]          columnVectorQ::usage = "columnVectorQ[v] returns True if v is a list of length-1, rank-1 tensors.";          Begin["`Private`"]          columnVectorQ[v_]:= VectorQ[v,(TensorRank[#]==1 && Length[#]==1)& ];          End[]     EndPackage[]      Now in my notebook, I do this:               ClearAll["Global`*"];          Get["/path/to/tools.m"]      Now I am able to USE `columnVectorQ[{{1},{2},{3}}`, for example... but I am unable to **autocomplete** `columnVectorQ`. I can only autocomplete `tools`columnVectorQ`. Is there a way to make the contents of my package visible to the autocomplete system, so I don't need to prefix package symbols with the name of the package?


Torn edge paper effect for images

In my answers to Plotting Error Bars on a Log Scale I used a so called "torn edge" effect from on one of the images. @SjoerdC.deVries commented: "BTW I liked the ripped-out look of your InputForm picture; Mathematica? It's ideal for pictures that have to convey the message "There's more of this, but that's not important". Though it was a software called Snagit, I think _Mathematica_ can easily do it. For example, this train of thought: Imagine you have an image which you'd like to limit with torn edge:               a = Image[Rasterize[RandomReal[1, 50], RasterSize -> 700]]      ![enter image description here](http://i.stack.imgur.com/MyHN2.png) Generate random walk:               b = ListLinePlot[SeedRandom[4]; Accumulate[RandomReal[{-1, 1}, 2000]],        Axes -> False, Filling -> Bottom, FillingStyle -> White,        AspectRatio -> 1/13,  PlotStyle -> {Thickness[0.0015], GrayLevel[.0],        Opacity[.5]}, PlotRangePadding -> {0, 5, 0, 5}, ImageSize -> 1000]      ![enter image description here](http://i.stack.imgur.com/U2gki.png) Make shadow:               c = ListLinePlot[SeedRandom[4]; Accumulate[RandomReal[{-1, 1}, 2000]],        Axes -> False, Filling -> Bottom, FillingStyle -> White,        AspectRatio -> 1/13, PlotStyle -> {Thickness[0.005], Opacity[.3],        GrayLevel[.2]}, PlotRangePadding -> {0, 5, 0, 5}, ImageSize -> 1000]      ![enter image description here](http://i.stack.imgur.com/KD3ff.png) And compose everything:               d = ImageCompose[b, c, {Left, Bottom}, {Left, 5}];     e = ImageCompose[a, d, {Left, Bottom}, {Left, Bottom}];     ImageCompose[e, ImageRotate[d, Pi/2], {Right, Bottom}, {Right, Bottom}]      ![enter image description here](http://i.stack.imgur.com/EpqNc.png) This kind of works - but is obviously very raw. Right bottom corner is problematic for example. So can we make it work? Some perhaps good things to think of:   * Single function where we feed image and pointers which edges to torn.   * All image sizes would work   * All methods are good, no need to use random walks This question maybe helpful: How can I make a 2D line plot with a drop shadow under the line?


Multiple histograms grouped in a chart

I have this problem: I have three distributions and the relative histograms. But I would like to create an histogram in which the three columns of each single histogram for the same bin are put together (grouped) by the same x axis value. There is someone could help me?


Install trial version of Mathematica 9 next to genuine Mathematica 8

This morning I installed the trial version of Mathematica 9. After I discovered that `Export[]` is disabled in trial versions, I wanted to use my genuine Mathematica 8 again, but I discovered that the installer of MMA 9 apparently made MMA 8 a trial version too. When I try to re-register mma 8 it returns "You have already registered this product". I'm running the student version of Mathematica 8.0.4.0 on Ubuntu 12.10 (64-bit). **Question: How can I make Mathematica 8 fully functional again?**


Set the scale in ColorFunction

The following plot (A)                ListLinePlot[{0,1,2,3},ColorFunction->"TemperatureMap"]      goes from blue to read. The following plot (B)               ListLinePlot[{4,5,6,7},ColorFunction->"TemperatureMap"]      goes also from blue to read. I want the colors to be correlated to the number to be plotted, not the position in the list (as above). Therefore I would like (A) to go from white to yellow (approx.) and (B) from yellow to red (approx.). How can I make the color to be correlated with the value of the number to be plotted and not the position in the list?


Increasing recursion speed in Hull-White trinomial tree calculation

First timer here and have been finding these boards very useful in learning Mathematica. I'm trying to implement a numerical procedure for the Hull-White trinomial tree in Mathematica. Despite using memoization, I'm finding it very slow when I get a few steps into the tree. In the first step I need to solve an equation to get an alpha(x). Only then can I proceed with solving the range of Q(x+1,j). I was expecting the fact that since the x-steps are stored in memory, the x+1 steps would be done rather quickly. EDIT: From Q and alpha I can get the rates I am trying to simulate. Once I have my rates, I can calculate a payout at the end of the tree (nodevalue). I then go back through the tree to get the value of the nodevalue(0,0) i.e: The price of such a payout on day1. This fails for a larger number of steps and is rather slow. Any tips on optimising? I get the following message for 50 steps which takes about 30 seconds:               In[436]:= Timing[nodevalue[0, 0]]          During evaluation of In[436]:= Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>          During evaluation of In[436]:= Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>          During evaluation of In[436]:= Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>          During evaluation of In[436]:= General::stop: Further output of Solve::ratnz will be suppressed during this calculation. >>          Out[436]= {3.719, 0.0100418}      I have included some minor changes from my initial post. Also highlighted in comments where I think the code may be slowing me down.               Unprotect[M];      Unprotect[Q];      Unprotect[P];           (*input here*)          tenor = 5;      steps = 50; (*<- Code Fails for a number bigger than 51...*)     a = 0.1;      sigma = 0.01;      f[r_] := r; g[x_] := x;      zerorate = 3; dfData = {{0., 1.}, {0.25, 0.992023586787659},            {0.5, 0.984368170142745}, {0.75, 0.977171337237306}, {1.,         0.970130543530332},            {1.25, 0.962597668870528}, {1.5, 0.955366107894445}, {1.75,         0.948429429702776},            {2., 0.941083365231486}, {2.25, 0.933654274758575}, {2.5,         0.926206583554808},            {2.75, 0.918741332047699}, {3., 0.911259555496316}, {3.25,         0.903801785010502},            {3.5, 0.896334959688613}, {3.75, 0.888859978997039}, {4.,         0.881295802567575},            {4.25, 0.873576189971488}, {4.5, 0.865919722663361}, {4.75,         0.858328277043492},            {5., 0.850550741079475}, {5.25, 0.842846646720007}, {5.5,         0.835217448771243},            {5.75, 0.827664434924383}, {6., 0.819937775990933}, {6.25,         0.812205585525199},            {6.5, 0.804552663713649}, {6.75, 0.796980136312276}, {7.,         0.789237583106047},            {7.25, 0.781505055652225}, {7.5, 0.77402686027691}, {7.75,         0.766557832213359},            {8., 0.759098675520764}, {8.25, 0.751650086883238}, {8.5,         0.744212755551351},            {8.75, 0.736787363285735}, {9., 0.729374584302738}, {9.25,         0.721894203851475},            {9.5, 0.714508798782454}, {9.75, 0.707218557903375}, {10.,         0.699782433930927},            {10.25, 0.690835814909544}, {10.5, 0.681956382812677},            {10.75, 0.673147423947596}, {11., 0.664118563293887},            {11.25, 0.655066776897885}, {11.5, 0.646092713575233},            {11.75, 0.637100851957785}, {12., 0.627994883834108},            {12.25, 0.618863849860742}, {12.5, 0.61001555866861},            {12.75, 0.601452720972706}, {13., 0.592305728759494}, {13.25,         0.58344808791873},            {13.5, 0.57459130321309}, {13.75, 0.565737328419695}, {14.,         0.556888097001247},            {14.25, 0.548045521596268}, {14.5, 0.539211493523719},            {14.75, 0.530387882302119}, {15., 0.521576535183242},            {15.25, 0.513266517651005}, {15.5, 0.505068785221317},            {15.75, 0.496894639770595}, {16., 0.488656405115787},            {16.25, 0.480444844598625}, {16.5, 0.472349543622504},            {16.75, 0.464370791774091}, {17., 0.456245727354391},            {17.25, 0.448152213475503}, {17.5, 0.440178388577009},            {17.75, 0.432324309215909}, {18., 0.424331272572483},            {18.25, 0.416202749238728}, {18.5, 0.408369203376619},            {18.75, 0.400828120870626}, {19., 0.392815561804551},            {19.25, 0.385097371741437}, {19.5, 0.377419607786398},            {19.75, 0.369783221910831}, {20., 0.36218914499444}};      P[t_] := P[t] = Interpolation[dfData, t];      payout[r_, k_] := payout[r, k] = Max[r - k, 0];      strike = 3.19/100;           (*definitions*)     M = Exp[(-a)*deltat] - 1;      V = sigma^2*((1 - Exp[-2*a*deltat])/(2*a));      deltat = tenor/steps;      jMax = IntegerPart[-0.184/M] + 1;      jMin = -jMax;      deltax = Sqrt[3*V];      probMiddle[j_] := {1/6 + (j^2*M^2 + j*M)/2, 2/3 - j^2*M^2,         1/6 + (j^2*M^2 - j*M)/2};      probUpward[j_] := {1/6 + (j^2*M^2 - j*M)/2, -(1/3) - j^2*M^2 + 2*j*M,             7/6 + (j^2*M^2 - 3*j*M)/2};      probDownward[j_] := {7/6 + (j^2*M^2 + 3*j*M)/2, -(1/3) - j^2*M^2 - 2*j*M,             1/6 + (j^2*M^2 + j*M)/2};           q[k_, j_] := Which[jMin < k < jMax, probMiddle[k], jMax <= k, probDownward[k],               k <= jMin,          probUpward[k]][[Which[jMin < k < jMax, k - j + 2, jMax <= k,                k - j + 1, k <= jMin, j - k + 1]]];           (*Tree Geometry, suspect sb here could be improved or more elegant*)     sb[i_Integer /; Inequality[0, LessEqual, i, Less, steps],             j_Integer /; jMin <= j <= jMax] :=        Which[i - Abs[j] == 0, If[j > 0, {-1}, {1}],               i - Abs[j] == 1 || Abs[j] == jMax,          If[j == 0, {0}, If[j > 0, {-1, 0}, {0, 1}]],               j > jMax || j < jMin, If[j > 0, {-1, 0}, {0, 1}],          jMax - 2 == jMin + 2 &&                 i > jMax && j == 0, {-2, -1, 0, 1, 2}, j == jMax - 2 && i > jMax,               {-1, 0, 1, 2}, j == jMin + 2 && i > jMax, {-2, -1, 0, 1},          0 < 1, {-1, 0, 1}] +             j;           n[m_] := Min[jMax, m]               (* =====      THINK BELOW IS WHERE THINGS ARE SLOWING DOWN    =====*)               bigAlpha[0] = zerorate;      Q[0, 0] = 1;           bigAlpha[m_Integer /; Inequality[0, LessEqual, m, Less, steps]] :=           bigAlpha[m] = alpha[m] /. NSolve[P[(m + 1)*deltat] ==                 Sum[Q[m, j]*Exp[(-g[alpha[m] + j*deltax])*deltat], {j, -n[m], n[m]}],           alpha[m],                 Reals];                Q[m_Integer /; Inequality[0, LessEqual, m, Less, steps],             j_Integer /; jMin <= j <= jMax] :=           Q[m, j] = Sum[Q[m - 1, sb[m, j][[k]]]*q[sb[m, j][[k]], j]*                Exp[(-g[bigAlpha[m - 1] + sb[m, j][[k]]*deltax])*deltat], {k, 1,           Length[sb[m, j]]}];      rate[i_Integer /; Inequality[0, LessEqual, i, Less, steps],             j_Integer /; jMin <= j <= jMax] :=        rate[i, j] = g[bigAlpha[i] + j*deltax];      jEnd = Min[jMax, steps];                nodevalue[i_Integer /; Inequality[0, LessEqual, i, Less, steps],             j_Integer /; jMin <= j <= jMax] := nodevalue[i, j] =             Which[i == steps - 1, payout[rate[i, j], strike], jMin < j < jMax,               probMiddle[j] . {nodevalue[i + 1, j + 1], nodevalue[i + 1, j],                   nodevalue[i + 1, j - 1]}, jMax <= j, probDownward[j] .                 {nodevalue[i + 1, j], nodevalue[i + 1, j - 1],            nodevalue[i + 1, j - 2]},               j <= jMin,          probUpward[j] . {nodevalue[i + 1, j + 2], nodevalue[i + 1, j + 1],                   nodevalue[i + 1, j]}];       More info on Hull-White tree. Trying to implement pg13-14 in the journal: (PDF)


How to make the StringExpression not occur in my case?

Why is there a `StringExpression` in the following code?               f["a b c"] //. x_String :>          StringReplace[x, (StartOfString ~~ x1__ ~~ "b" ~~ x2__ ~~ EndOfString) :> f["BBB"]]     (*         f[StringExpression[f[BBB]]]     *)      Though I can remove it, I'd rather it not appear in the first place, because I'm not sure this method is safe:               f["a b c"] //. x_String :>          StringReplace[x, (StartOfString ~~ x1__ ~~ "b" ~~ x2__ ~~ EndOfString) :> f["BBB"]] /.          StringExpression -> Sequence     (*         f[f[BBB]]     *)


Plot the plane so different condition has a different color

I have a list of functions defined on the plane, and I want to know which one of those functions is smaller than the other functions at particular points. Currently, what I do is               Plot3D[{1 + 3/2 v, 1 + 2/3 m + 1/6 v, 9/4 + 1/8 v, 10/7 m,        m + Min[2/3, 1/2 m, v]}, {m, 1, 2}, {v, 0, 1},       PlotStyle -> {Orange, Red, Blue, Green, Black}, ViewPoint -> Bottom]      And I get a picture like this (it is a little bit rotated because I can't view 3D plots unless I'm moving it... but that's another question) ![enter image description here](http://i.stack.imgur.com/OfFPC.png) I feel there must be a smarter way than doing this without invoke plotting a 3D diagram.


How to make a region plot indicating the largest among a set of functions

I want to make a `RegionPlot` (or possibly a `ContourPlot`) in $x$-$y$ space that indicates which among a set of functions is the biggest value for a given $(x, y)$. Suppose I have (in this example) three functions assembled in a list:               f[x_, y_] = Sin[x*y]     g[x_, y_] = Cos[x*y/2]     h[x_, y_] = Sin[x*y^2/7 + 2 \[Pi]/E]     (*and possibly more...*)          list[x_, y_] = {f[x,y], g[x,y], h[x,y]}      and I want to paint a region _blue_ if `f[x]` is largest in that region, _magenta_ if `g[x]` is largest and _dark yellow_ if `h[x]` is largest. The end result would be collage of colors corresponding to largest among the functions. Is there a way using functional coding to do this? I'm looking for fastest fastest possible computing speed. Any hints on possibly helpful _Mathematica_ functions would be welcome.


Numerical underflow for a scaled error function

I calculate scaled error function defined as               f[x_] := Erfc[x]*Exp[x^2]      but it can not calculate `f[30000.]`. `f[20000.]` is not very small (`0.0000282`). I think Mathematica is supposed to switch to high precision instead of machine precision, but it does not. It says: > General::unfl: Underflow occurred in computation. >>   >  General::ovfl: Overflow occurred in computation. >> How can I calculate `f` for large values of `x`? Even with `N[f[30000], 50]`, it does not use high precision and fails.


RSolve and incomplete gamma function

I am interested in how _Mathematica_ uses the incomplete gamma function to solve difference equations. For example, if we have this inhomogeneous, 2nd order equation and use `RSolve`:               RSolve[{(n - 2)*a[n - 2] + (n - 1)*a[n - 1] == a[n], a[0] == 1,        a[1] == 1} , a , n]      The solution given is:               (2 n Gamma[n] Gamma[3, -1] + 2 n Gamma[1 + n] Gamma[3, -1] -         n Gamma[n] Gamma[4, -1] - n Gamma[1 + n] Gamma[4, -1] +         2 Gamma[2 + n, -1])/(2 n (3 Gamma[3, -1] - Gamma[4, -1]))      I am wondering if there is some very general algorithm that solves recurrence relations in terms of the incomplete gamma functions, and if so, what are the conditions on the difference equation that lets us apply the theorem. Any reference would be greatly appreciated.


another way to do this mapping of a two argument function

Sorry, I'm just starting to learn mathematica. I have the following two-argument function:               h[{x_, y_}] := x ^ y      When I do the following:               Map[h, {{1, 2}, {2, 2}, {3, 2}}]      I get the expected output:               {1, 4, 9}      I was wondering what I'm doing wrong with the following rewrite of the above map expression (I want to learn how to use `#1` ... `#n` 's):                #1 ^ #2 & /@ {{1, 2}, {2, 2}, {3, 2}}      the error messages I'm getting are: > Function::slotn: "Slot number 2 in #1^#2& cannot be filled from > (#1^#2&)[{1,2}]" > > Function::slotn: "Slot number 2 in #1^#2& cannot be filled from > (#1^#2&)[{2,2}]." > > Function::slotn: "Slot number 2 in #1^#2& cannot be filled from > (#1^#2&)[{3,2}]."


Can NDSolve handle discountinuos data?

It is possible to _numerically_ solve a differential equation if not-smooth data are involved? For example the following instruction return the error NDSolve::bvdisc:               NDSolve[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,        u'[1] == 0}, u, {x, 0, 1}]      > NDSolve::bvdisc: NDSolve is not currently able to solve boundary value > problems with discrete variables. >> Here I suppose _discrete variable_ means _discontinuous functions_ but maybe the problem is completely different. This error is reported in Mathematica 10, where the Finite Element Framework should be able to return weak, not classical, solutions and should be definitely able to deal with such a simple equation, but maybe we need to enable some option or methods. Please note I know I can do               DSolve[{-u''[x] == UnitBox[(x - 0.5) 0.5/0.2], u[0] == 0,        u'[1] == 0}, u, {x, 0, 1}]      ![result](http://i.stack.imgur.com/czGjQ.png) but in more complex scenarios I cannot hope to get an analytical answer.


Path must include /TypeSystemLoader.m?

I have encountered a number of odd issues using the Wolfram Workbench 3.0 Debugger. Whenever I try to step into a Switch[] statement, I get the following error message: "Problem Occurred - Debug source lookup has encountered a problem. - An internal error occurred during "Debug Source Lookup." Details: An internal error occurred during: :Debug Source Lookup". Path must include project and resource name: /TypeSystemLoader.m The code producing this error is:               dv:= Switch[majorAxis,                 "x",                     xElectrodeVoltage[testPtx, testPty, testPtz, ex1, ex2, ey1, ez1, chargeDist],                 "y",                       yElectrodeVoltage[testPtx, testPty, testPtz, ey1, ey2, ex1, ez1, chargeDist],                 "z",                     zElectrodeVoltage[testPtx, testPty, testPtz, ez1, ez2, ex1, ey1, chargeDist],0];                      voltage += dv      Is this a Mathematica system package that I need to locate and load in init.m?


Confused about Unevaluated

Why does               Map[Unevaluated, Table[PauliMatrix[i], {i, 1, 3}]      give > {Unevaluated[{{0, 1}, {1, 0}}], Unevaluated[{{0, -I}, {I, 0}}], > Unevaluated[{{1, 0}, {0, -1}}]} while               Table[Unevaluated[PauliMatrix[i]], {i, 1, 3}]      gives > {{{0, 1}, {1, 0}}, {{0, -I}, {I, 0}}, {{1, 0}, {0, -1}}} I think they should give the same result! Why not?


How to apply or map a list of functions to a list of data?

Say I have a group of functions:               f1[a_] := a * -1;     f2[a_] := a * 100;     f3[a_] := a / 10.0;      and some data in a list:               data := Range[1, 20];      I would like to apply this group of functions to the data: the first function applied to the first item of data, the second to the second, and so on. Because there are more data elements than there are functions, the first function is also applied to the fourth data element, and so on. A simple work-round is this:               Flatten[{f1[#[[1]]], f2[#[[2]]], f3[#[[3]]]}  & /@ Partition[data, 3]]      giving               {-1, 200, 0.3, -4, 500, 0.6, -7, 800, 0.9, -10, 1100, 1.2, -13, 1400,        1.5, -16, 1700, 1.8}      but this isn't an ideal solution: the slots have been 'hard-wired', and it wouldn't be possible to modify the list of functions easily. Is there a `Map`-related function that could do this elegantly? I've not been able to discover it yet. (This is a toy example, of course!)


ODE and BVP: NDSolve errors

The mathematical problem is shown here. I tried to solve writing the               A0 = 2.0377638272727268`;     A1 = -7.105521894545453`;     A2 = 9.234000147272726`;     A3 = -5.302489919999999`;     A4 = 1.1362478399999998`;     h0 = 45.5;     \[Sigma]M = 0.00592251     \[Lambda]1 = 1.025;     \[Lambda]2 = 1.308;          f1[y_, x_] = A1 + 2 A2 y[x] + 3 A3 y[x]^2 + 4 A4 y[x]^3     b[y_, x_] = h0^2/12 (5 A1 + 8 A2 y[x] + 9 A3 y[x]^2 + 8 A4 y[x]^3)/y[x]^6     g[y_, x_] = -(h0^2/12) (A1 + 2 A2 y[x] + 3 A3 y[x]^2 + 4 A4 y[x]^3)/y[x]^5          Sys = First@NDSolve[{     f1[y, x] + b[y, x] y'[x]^2 + g y''[x] == \[Sigma]M,     y[0] == \[Lambda]1,     y[15] == \[Lambda]2     }, y, {x, 0, 15}]      When I evaluate this code, Mathematica answers with the following errors: > Power::infy: Infinite expression 1/0.^6 encountered. >> Infinity::indet: > Indeterminate expression 0. ComplexInfinity encountered. >> > > Power::infy: Infinite expression 1/0.^6 encountered. >> > > Infinity::indet: Indeterminate expression 0. ComplexInfinity encountered. >> > > Power::infy: Infinite expression 1/0.^7 encountered. >> > > General::stop: Further output of Power::infy will be suppressed during this > calculation. >> > > Infinity::indet: Indeterminate expression 0. ComplexInfinity encountered. >> > > General::stop: Further output of Infinity::indet will be suppressed during > this calculation. >> > > NDSolve::ndnum: Encountered non-numerical value for a derivative at x == > 0.`. >> As suggested here (section: "StartingInitialConditions") I tried to wrote:               Sys = First@NDSolve[{           f1[y, x] + b[y, x] y'[x]^2 + g y''[x] == \[Sigma]M,           y[0] == \[Lambda]1,           y[15] == \[Lambda]2}, y, {x, 0, 15},            Method -> {"Shooting","StartingInitialConditions" -> {y[0] == \[Lambda]1, y'[0] == 0.1}}]      followed by the following error: > NDSolve::ndnum: Encountered non-numerical value for a derivative at x == > 0.`. >> How can I overtake this errors? What am I doing something wrong?


Why is 1. x (Times[1.`, x]) not simplified to x?

This is maybe a silly question, but I could not think of any logical reason why it is not simplified automatically. I was working with a big linear equation system with some constrained inequalities and noticed a lot of "1. xyz" terms. I tried `Simplify[1. x == x]` which gives `True`, but `1. x` stays `1. x`. I'm using the simple rule `Rule[1., 1]` to simplify the "1. xyz" terms in my equation system; it just looks somehow "better" (in my opinion). Function `Times` was last modified in version 3, so this behaviour should exist for a long time now. What is the logical reason behind?


Function that evaluates in notebook does not evaluate in CDF

I am trying to access the values of a dynamic value outside function package. Within the function package, the function is defined under the Dynamic module option. There is an error with this. I cannot extract the value.               inputCreate[no_, user_values_] := (DynamicModule[{value = Table[0, {no}, {user_values}]},        (If[(no > 0),          ({Table[(With[{i = i, j = j},               (Row[{Column[{MouseAppearance[                     EventHandler[                      Style["\[FilledUpTriangle]", Bold, Black, {15, 15},                        ShowStringCharacters ->                         False], {"MouseClicked" :> (value[[i, j]] =                          value[[i, j]] + 1)}],                     "LinkHand"],                    MouseAppearance[                     EventHandler[                      Style["\[FilledDownTriangle]", Bold, Black, {15, 15},                        ShowStringCharacters ->                         False], {"MouseClicked" :> (If[(value[[i, j]] <=                          0), (value[[i, j]] = 0), (value[[i, j]] =                          value[[i, j]] - 1)])}],                     "LinkHand"]},                   Spacings -> 0, Alignment -> Center,                    Background -> RGBColor[0.65, 0.65, 0.65]],                   Dynamic[If[(value[[i, j]] === Null), (value[[i, j]] = 0)];                   InputField[Dynamic[value[[i, j]]], Number,                     ContinuousAction -> True, ImageSize -> {50, 20},                     Alignment -> Center]]}])]),             {i, 1, no}, {j, 1, Length[Part[value, i]]}],            Dynamic[value = If[value === Null, 0, value]]})          ])])      ![Mathematica graphics](http://i.stack.imgur.com/IyNCx.png) When I deploy in CDF, this function works but I am unable to extract the value of myInput that I need to write into another file. Also, in the CDF, when I delete the zero and add click the uparrow, the value keeps incrementing + NUll whereas everytime I want to reset it to zero when the user deletes the values within the InputField. So, just to extract the values, I implemented the same function with Module. However, within module, the initial value is not set to zero even though I have explicitly initialized it within the module.


Mathematica Minecraft

Some time ago I asked myself: with all these great graphics and interactive capabilities of _Mathematica_ , what kinds of 3D games can be implemented in it? And the answer which came to mind is Minecraft classic. The scene in this game is almost static, the first person view and controls can be easily implemented, the terrain textures are freely available, and the overall functionality does not seem to be complicated... There is even a related demonstration on the Demonstrations Project! So, can Mathematica really handle Minecraft classic game functionality?


How to convert a string of number into real numbers without precision loss

I searched and did not find similar answers which can resolve the 'no precision loss' issue. A sample string is:               "-5.100686209408900133332e+02 -1.294005398404007344443e+01 -2.59376479781563728887e+02 -1.3043629998334040122222e+02"      If I immediately convert them into real variable by `ImportString` or `StringToDouble`, then there will be precision loss, the resulted precision is only `$MachinePrecision`. How to convert them into real number which should have higher precision than `$MachinePrecision`.


Issue with FindCurvePath

I have a problem with the function `FindCurvePath`. In some cases it crashes the _Mathematica_ 9 Kernel. Here an example, where it crashes the kernel:               data = {{368, 195}, {368, 196}, {368, 197}, {368, 198}, {368, 201}, {368,      202}, {368, 206}, {368, 208}, {368, 209}, {368, 215}, {368,      244}, {368, 252}, {368, 253}, {368, 254}, {368, 255}, {368,      257}, {368, 268}, {368, 273}, {368, 277}, {368, 297}, {368,      300}, {368, 311}, {368, 323}, {368, 325}, {368, 327}, {368,      332}, {368, 333}, {368, 334}, {368, 335}, {368, 339}, {368,      342}, {368, 345}, {368, 348}, {368, 357}, {368, 376}, {368,      390}, {368, 395}, {368, 405}, {368, 414}, {368, 447}, {368,      450}, {368, 453}, {368, 500}, {368, 522}, {368, 530}, {368,      538}, {368, 554}, {368, 558}, {368, 560}, {368, 570}, {368,      580}, {368, 585}, {368, 602}, {368, 604}, {368, 618}, {368,      619}, {368, 620}, {368, 621}, {368, 622}, {368, 624}, {368,      632}, {368, 677}, {368, 719}, {368, 724}, {368, 753}, {368,      756}, {368, 759}, {368, 764}, {368, 824}, {368, 832}, {368,      835}, {368, 847}, {368, 856}, {368, 879}, {368, 882}, {368,      896}, {368, 906}, {368, 918}, {368, 944}, {368, 954}, {368,      958}, {368, 975}, {369, 7}, {369, 13}, {369, 37}, {369, 38}, {369,      49}, {369, 50}, {369, 57}, {369, 69}, {369, 71}, {369, 74}, {369,      84}, {369, 89}, {369, 92}, {369, 93}, {369, 97}, {369, 99}, {369,      105}, {369, 106}};          FindCurvePath[data];      If I change, e.g. the last number in "working" from 106 to 105 it works fine!               data // ReplacePart[#, {-1, 2} -> 105] & // FindCurvePath      Does anybody know a solution to circumvent this problem?


Issue with NSolve

I defined the following function:               sw[ θ_, ϕ_, h_] =  1/2 Sin[2 (ϕ - θ)] + h Sin[ϕ]      Based upon whether I use Solve or `NSolve`, I get different answers:               Solve[ sw[ π/2, ϕ, -1] == 0 && 0 <= ϕ <= π, ϕ]      I get different answers from:               NSolve[ sw[ π/2, ϕ, -1] == 0 && 0 <= ϕ <= π, ϕ]      The answer using `Solve` is complete and correct. However, with `NSolve` it only gives you a partial answer `ϕ == 0` but not `ϕ == π`. Does anyone have any idea why _Mathematica_ 9 is doing this?   How do I get the same answer from both the methods?


MAP a business cycles model

There is a Business Cycles Map on Phaser 3.0 and I've trying to run it on _Mathematica_ the last four days without succes. The equations are $$ x_1 = (1.0 - a s)x_1 + a \left[s m + g \left(\frac{s m}{d} - x_2\right) + \mathrm{atan}(x_1 - m)\right], $$ $$ x_2 = (1.0 - d)x_2 + s m + g \left(\frac{s m}{d} - x_2\right) + \mathrm{atan}(x_1 - m) $$ with the initial conditions $$ t = 0, \quad x_1 = 17, \quad x_2 = 30, $$ and $$ a = 8.0, \quad d = 0.2, \quad g = 0.4, \quad m = 15, \quad s = 0.4. $$ ![How it is showed on Phaser](http://i.stack.imgur.com/Du8An.png) I'd just copy the result on Phaser, but i have the trial version. The code I thought it could work is this:               a = 8.0; d = 0.2; g = 0.4; m = 15; s = 0.4;     x[0] := 17; y[0] := 30;     x[t_] := x[t] = (1.0 - a s) x[t - 1] +         a (s m + (g*(((s m)/d) - y[t - 1])) + ArcTan[x[t - 1] - m])     y[t_] := y[t] = (1.0 - d) y[t - 1] + s m + (g*((s m)/d) - y[t - 1]) +         ArcTan[x[t - 1] - m]     data = Table[{x[t], y[t]}, {t, 0, 100}];     ListPlot[data, AxesLabel -> {"x[t]", "y[t]"}, Joined -> False,       PlotRange -> {{0, 30}, {25, 35}}, Mesh -> Full, PlotMarkers -> None]      But it doesn't. Any suggestions?


Random reals according to conditions

I'd like to create a list of triplets $(x,y,z)$ which satisfy the following properties: $$0<x<1/2 \\\ 0<y<1/2-x \\\ -1<z<-2(x+y)$$ Basically I would like to uniformly generate random points inside a pyramid which is what these inequalities represent. I'm not sure how to place these restrictions on the RandomReal command or how to tell _Mathematica_ to exclude points that do not satisfy these conditions. Any help? Thank you.


Inverse of a restriction of a non-invertible matrix

Let $A∈R^{4×4}$ be a non-invertible matrix, with $2$-dimensional kernel. How can I compute the inverse of the restriction of $A$ on a subspace where it is invertible: $A^{-1}v \,\,\,\,$ where $\,\,\,\,v∉kerA$ I have the matrix $A$ precisely, but the vector $v$ depends on some parameters and is really complicated, but I know that it doesn't belong to the kernel. More precisely               e=0.001;     A={{e, -1, e, 1/2+e}, {-e, 1/2, -e, -e}, {e, 1/2+e, e, -1}, {-e, -e, -e, 1/2}};     NullSpace_A={{(1-2e)/(2e), 1, 0, 1}, {-1, 0, 1, 0}};      The above NullSpace_A was computed using the function NullSpace of Mathematica, so we see that $$kerA=span\\{(c_0,1,0,1);(-1,0,1,0)\\}=\\{(c_0α-β,\,\,α,\,\,β,\,\,α) \,\,/\,\,α,β∈R\\}$$ where $c_0$ is a given constant. P.S. Maybe this is trivial, but I am new to _Mathematica_.


How many Christmas gifts?

This question is based on the old song, The Twelve Days of Christmas In a comment made on a recent question, Yves Klett remarked, "no seasonal questions this year?" This reminded me of one I solved six years ago. It's very easy, but has the virtue of giving a pretty expression for the general case. Can you get _Mathematica_ to tell you how many gifts True Love give over the 12 days of Christmas? Better yet, can you get a general expression for how many he would he give over a gift-giving period of n days? I'm not going to post my answer unless no one posts an equivalent answer in the next 24 hours. I will be very surprised if that happens. ### Update My interpretation of the song is on each day True Love repeats each gift from the previous day and adds a new gift with multiplicity equal to the day index. That means 364 gifts for 12 days. I'm looking for the general formula for $n$ days. It's still an easy problem, but the general formula is rather nice.


Matrix generation

I have a $2x2$ matrix $M$. $M$ has the following form:               M = {{a, bExp[-2ikz]}, {bExp[2ikz], a}}      $a, b, k - const.$ `z` is variable that takes values from the range `0, 10, 20, 30, 40 ......300`. I need `30` different matrices `M1, M2....M30` corresponding to the values of `z` \- `0, 10, 20.....300` and then multiply those matrices. How can I do that with _Mathematica_ ?


How can I mark categories in a BarChart with one instead of multiple labels?

given the following data organized by year               y2011 = {121.68, 70.82, 82.62, 111.03, 76.9, 76.51, 86.07, 70.03,        72.14, 114.14, 135.51, 104.51}     y2012 = {97.19, 72.03, 116.25, 78.66, 89.94, 152.21, 70.03, 85.07,        129.75, 87.94, 125.58, 157.15}     y2013 = {154.21, 106.78, 116.62, 70.03, 121.69, 110.52, 159.96, 71.66,        70.03, 89.14, 0, 0}      I want to draw the following diagram, grouping the data of the same months together:               BarChart[Transpose[{y2011, y2012, y2013}],       ChartLabels -> {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",         "Aug", "Sep", "Oct", "Nov", "Dec"}]      ![BarChart of yearly data grouped by month](http://i.stack.imgur.com/fXNN2.png) How can I show just one `ChartLabel` per month/category?


How to debug error triggered by replacement rule?

The second line below produces the errors shown:               p = LogLogPlot[Abs[10^2/((I ω)^2 + 100)], {ω, 10^0, 10^5}];     p /. x_ /; And @@ NumericQ /@ x :> x[[0]];     Part::pspec: Part specification True is neither a machine-sized integer nor a list of machine-sized integers. >>     Part::pspec: Part specification True is neither a machine-sized integer nor a list of machine-sized integers. >>      I have run out of ideas for pinpointing the specific reason for the error (let alone fixing the rule to avoid it). Is there some command or tool or systematic way to debugging such errors?


How can I eliminate equivalent equations from a list?

I want to find the numbers $a$, $b$, $c$, $d$ of the plane $ax + by +cz +d = 0$ which make the distance from the point $M(1,2,3)$ to the plane equal to 2. I tried               SetSystemOptions[       "ReduceOptions" -> "ExhaustiveSearchMaxPoints" -> {10000, 100000}];          Clear[n, M];     n = {a, b, c};     M = {1, 2, 3};     TraditionalForm[Simplify[a  x +  b y +  c z + d == 0]] /.       Solve[{Abs[n . M + d]/Norm[n] == 2,         1 <= a <= 10, -5 <= b <= 10, -5 <= c <= 10, a > b > c}, {a, b, c,         d }, Integers]      The set of equations in _Mathematica_ 's output contains duplicates, for example: $8 x+6 y-40=0$ and $4 x+3 y-20=0$. How can I eliminate the duplicates?


Command to change binary mlf terms into Subscripted mlf terms?

I express multilinear functions in the following format. Is there any ready command to convert them to multilinear functions easily? **Input**               posTerms = {2, 4, 9, 13, 19};     negTerms = {6, 11, 26};     IntegerString[posTerms, 2]     IntegerString[negTerms, 2]          {"10", "100", "1001", "1101", "10011"}     {"110", "1011", "11010"}      **Intended Output**               x_2+x_3+x_4*x_1+x_4*x_3*x_1+x_5*x_2*x_1-(x_3*x_2+x_4*x_2*x_1+x_5*x_4*x_2)      **Intended Output in Mathematica**               Subscript[p, 2]+Subscript[p, 3]+Subscript[p, 4]*Subscript[p, 1]+Subscript[p, 4]*Subscript[p, 3]*Subscript[p, 1]+Subscript[p, 5]*Subscript[p, 2]*Subscript[p, 1]          -Subscript[p, 3]*Subscript[p, 2]-Subscript[p, 4]*Subscript[p, 2]*Subscript[p, 1]-Subscript[p, 5]*Subscript[p, 4]*Subscript[p, 2]


In a ListPlot of LinearModelFit, plot error band

This is similar to this question. The fitted line can be plotted alongside with the data with this code:               Show[ListPlot[data], Plot[lm[x], {x, 0, 5}]]      I would like to include a band around this line indicating the average error. How can I do this? **Example data:** {{0.300369, 0.316832}, {0.450271, 0.485149}, {0.327772, 0.435644}, {0.573727, 0.594059}, {0.966333, 0.940594}, {0.5,0.356436}, {0.648136, 0.663366}, {0.830708, 0.831683}, {0.932212,0.950495}, {0.616441, 0.663366}, {0.616441, 0.613861}, {0.351864,0.415842}, {0.858684, 0.881188}, {0.626629, 0.554455}, {0.781502,0.841584}, {0.24901, 0.178218}, {0.776995, 0.811881}, {0.327772,0.405941}, {0.288312, 0.336634}, {0.60677, 0.663366}, {0.81564,0.811881}, {0.5, 0.455446}, {0.5, 0.60396}, {0.0592884,0.108911}, {0.951739, 0.940594}, {0.376411, 0.346535}, {0.5,0.435644}, {0.288312, 0.346535}, {0.781502, 0.831683}, {0.5,0.485149}, {0.5474, 0.584158}, {0.990885, 0.980198}, {0.376411,0.435644}, {0.937525, 0.980198}, {0.5, 0.455446}, {0.763858,0.841584}, {0.845342, 0.821782}, {0.616441, 0.70297}, {0.0158381,0.039604}, {0.836982, 0.881188}, {0.634059, 0.683168}, {0.258183,0.277228}, {0.867029, 0.80198}, {0.937525, 0.910891}, {0.130091,0.168317}, {0.971463, 0.990099}, {0.5, 0.455446}, {0.782699,0.792079}, {0.60314, 0.60396}, {0.977697, 0.960396}, {0.81564,0.90099}, {0.60677, 0.623762}, {0.39686, 0.455446}, {0.573727,0.574257}, {0.4526, 0.435644}, {0.5, 0.455446}, {0.236142,0.346535}, {0.5, 0.514851}, {0.60314, 0.584158}, {0.648136,0.693069}, {0.426273, 0.554455}, {0.373371, 0.465347}, {0.60314,0.524752}, {0.60677, 0.534653}, {0.383559, 0.524752}, {0.300369,0.277228}, {0.895366, 0.950495}, {0.426273, 0.455446}, {0.39323,0.29703}, {0.320827, 0.39604}, {0.979305, 0.990099}, {0.19846,0.207921}, {0.951739, 0.980198}, {0.0141859, 0.019802}, {0.265205,0.316832}, {0.783454, 0.831683}, {0.351864, 0.366337}, {0.763858,0.792079}, {0.648136, 0.673267}, {0.763858, 0.762376}, {0.678731,0.693069}, {0.376411, 0.376238}, {0.5, 0.514851}, {0.70727,0.712871}, {0.763858, 0.772277}, {0.5, 0.574257}, {0.258183,0.386139}, {0.893117, 0.831683}, {0.478985, 0.376238}, {0.104634,0.168317}, {0.235301, 0.188119}, {0.727486, 0.851485}, {0.327772,0.277228}, {0.5, 0.425743}, {0.648136, 0.712871}, {0.161454,0.158416}, {0.812018, 0.772277}, {0.365941, 0.39604}, {0.426273,0.485149}, {0.478985, 0.49505}}               lm = LinearModelFit[data, x, x]          Show[ListPlot[data, Plot[lm[x], {x, 0, 1}, PlotStyle -> Red], AxesOrigin -> {0, 0}]      ![enter image description here](http://i.stack.imgur.com/8bvFW.jpg)


How to extract data from contour plot as a text file?

I have the following expression from which I want to extract data for a contour plot.               a = (r^2/2 + (r BesselI[1, 2 r])/(      2 BesselI[0,         2 (1 + 0.24` z + 0.2` Sin[6.2834` z])])) (1.386371389484812` +       0.4367320268554276` (2.289733608959785` -          0.7936052912509126` (1 + 0.24` z +             0.2` Sin[6.2834` z])^2) + (-45.44` BesselI[0,            2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] -          4 (1.386371389484812` +             0.4367320268554276` (2.289733608959785` -                0.7936052912509126` (1 + 0.24` z +                   0.2` Sin[6.2834` z])^2) +             0.346592847371203` (1 + 0.24` z +                0.2` Sin[6.2834` z])^2) (4 BesselI[1,               2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z +                0.2` Sin[6.2834` z]) -             4 BesselI[0,               2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z +                0.2` Sin[6.2834` z])^2))/(4 (BesselI[1,             2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] -            4 BesselI[0,              2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z +               0.2` Sin[6.2834` z])^2)) +       0.346592847371203` (1 + 0.24` z + 0.2` Sin[6.2834` z])^2);               ContourPlot[a, {z, 0, 1.5}, {r, 3, 5.5},        PlotPoints -> 180, Frame -> True, FrameStyle -> {Thickness[0.0005]},        Axes -> False, FrameStyle -> {Thickness[0.0005]}, ContourShading -> False]      The output should be a text file.


Generating a graph object where vertices are pixel coordinates and edges represent two pixels being in the same Moore neighborhood

I have a list of integer pixel positions, `pts`, and I wish to create one or more graph objects where vertices at these pixel positions share an edge if they are within one-anothers 8-cell Moore neighborhoods. To clarify what I mean by "one or more graph objects", I mean that the above process might generate disconnected graphs. For an example, consider the contour pixels from my previous question: (Generating a list of contour pixels for a morphological component).               shape = Import["http://pixelduke.files.wordpress.com/2010/01/jnbdec2008-hello-world-example2.png"];     m = MorphologicalComponents[ColorNegate[ImageCrop[shape, {300, 100}]]];          mlist = Thinning[EdgeDetect[Image[m /. x_Integer /; x =!= # -> 0 // Rescale]]] & /@ Range[Length[ComponentMeasurements[m, "Count"]]];          pts = Position[ImageData[mlist[[6]]], 1];     Graphics[Point[pts]]      Where `pts` is an example set of pixel positions to be transformed into a graph object. In this case, there should be two disconnected graphs since `mlist[[6]]` represents the contour of the "o" in "Hello, World.". I've seen other solutions for generating random geometric graphs here, for example (Is it possible for me to explicitly specify a point list for SpatialGraphDistribution?) however, is there a more efficient way to do this provided my connectivity rule? Here's the way to do it using the method of Szabolcs from Is it possible for me to explicitly specify a point list for SpatialGraphDistribution?:               r = Sqrt[2];     distances = With[{tr = Transpose[pts]}, Function[point, Sqrt[Total[(point - tr)^2]]] /@ pts];     am = UnitStep[r - distances] - IdentityMatrix@Length[pts];          AdjacencyGraph[am, VertexCoordinates -> pts]      However, this is much too slow for larger points sets where we have something like `Length[pts] = 10000` or so. Also, and this may be grounds for a separate question, after construction of these simplified geometric graph objects, I would like to have some method of pruning away vertices when: (a) the vertex is strictly connected to two nearest-neighbors / has degree two, and (b) when the edges from the vertex to its two nearest neighbors fall along the same line / it is colinear with its two nearest-neighbors. In other words, I want to find the minimum set of vertices to give the set of connected edges the same morphology / geometry. It strikes me that there ought to be an automated routine for this in Mathematica 9, however, I can't seem to hunt one down.


2D Fourier transform of a table - ArrayPlot issue

Recently, I have encountered an issue with ArrayPlot after performing a Fourier transform of a table. ![ArrayPlot of a 2D table with precalculated values](http://i.stack.imgur.com/y1IuJ.png) Picture presented above is an ArrayPlot of a 2D table. Using Fourier on this 2D table I obtain the following ArrayPlot: ![Fourier transform of the first image.](http://i.stack.imgur.com/3lO3a.png) After this procedure one ends up with the result which consists of data at four vertices of the square. The thing is that I would like the result to be in this form: ![enter image description here](http://i.stack.imgur.com/oA5Qe.png) I have tried different Fourier transform parameters but none of them had delivered the demanded image. Thank you in advance for your reply!


Simultaneously fitting data sets with many variables as free parameters

I found a partial answer in the documentation centre, but would like to expand on it and know how can I fit multiple sets of data and extract the parameters from them. It is an eigenvalue problem - We have a 3x3 matrix               {{E(θ)-E, V1, V2}, {V1, E1-E, 0}, {V2, 0, E2-E}}      We set `Det(matrix)=0` to get the $E$ eigenvalues, though the `E[θ] = E0*(1-(Sin[θ]/neff)^2)^(-0.5)`. So the eigenvalues will change with angle. Now I have 3 data sets to fit the 3 solutions of my problem and have to extract the free parameters $V1,\,V2,\,E0,\,neff$ that best fit my data. Any suggestions ?


Using IntegerPartitions for distinct integers

What I would like to do is to find a way to test how many ways `m` **distinct** integers from the set `{1,..., n}` where `n ≥ m` can sum to a given integer `K`?


How to find the numbers $a$, $b$, $c$, $d$ of the function?

I want to find four numbers $a$, $b$, $c$, $d$ of the function $f(x)= \dfrac{a x + b}{c x + d}$ satisfying the conditions $f(-6)=4$, $f(-5)=5$, $f(1)=3$ and $f(2)=2$. I tried               f[x_] := (a x + b)/(c x + d);     Solve[{f[-6] == -4, f[-5] == -5, f[1] == 3, f[2] == 2}, {a, b, c, d}]      But I can not get the result. How to tell _Mathematica_ to do that?


Generating a list of contour pixels for a morphological component

I have a set of pixilated shapes, and after transforming each shape into a morphological component, I want to be able to return the coordinates for pixels that lie on the contour of the shape. More specifically, I want pixels that have some number of background neighbors in their von Neumann or Moore neighborhoods. Say this "shape" is a phrase like the following: http://pixelduke.files.wordpress.com/2010/01/jnbdec2008-hello-world- example2.png We can isolate and color all of the morphological components / pixilated shapes we care about as follows:               shape = Import["http://pixelduke.files.wordpress.com/2010/01/jnbdec2008-hello-world-example2.png"]     m = MorphologicalComponents[ColorNegate[ImageCrop[shape, {300, 100}]]] // Colorize      How can we return a von Neumann or Moore-neighborhood connected set of contour pixels for each component?


Retaining and reusing a one-to-one mapping from a sort

Imagine I sort the elements of an array $Q$ by some means. Perhaps I sort strictly by the elements in the first column, perhaps I use SortBy[...] to sequentially sort by the elements in successive columns, etc. Here, regardless of what I do, the result of this sort will be some one-to-one mapping from items in $Q$ to some items in the sorted array, $Q^*$. Can I somehow retain or reuse this particular one-to-one mapping function on some other array with the same dimensions as $Q$? Very specifically, I mean that if we move element $q_i \in Q$ at position $(a_1, a_2, ...)$ in $Q$ to some new position $(b_1, b_2, ...)$ in $Q^*$, then we corresponding move the same element $h_i \in H$ from $(a_1, a_2, ...)$ in $H$ to $(b_1, b_2, ...)$ in $H^*$. And we do this regardless of the identity of $h_i$, i.e. we're not repeating the sort. * * * To provide a specific example of where I'm getting in trouble, I'd like to sort the following list by the first column, then the second (with this priority):               data = {{4, 5}, {6, 1}, {11, 87}, {24, 52}, {90, 4}, {4, 4}};           In[...]:= SortBy[data, {#[[1]], #[[2]]} &]      Out[...]:= {{4, 4}, {4, 5}, {6, 1}, {11, 87}, {24, 52}, {90, 4}}      However:                 In[...]:= Ordering[SortBy[data, {#[[1]], #[[2]]} &]]       Out[...]:= {1, 2, 3, 4, 5, 6}       What I wanted from Ordering[...] was:                 Out[...]:= {6, 1, 2, 3, 4, 5}      How can I make the above work?


sorting of expression with complex parts

I have an expression:               a + i*b + d + i*e + r = 0      Now I want _Mathematica_ to sort this like: > >     a + d + r + i(b + e) >   How can I do that?


Constraining solution's sign with NSolve

I am solving some equations in 4 variables, however, there are many solutions which are basically the same but changing relative signs of each other ... i.e. {x->-1,y->1} and {x->1,y->-1}. Nevertheless I am only interested in solutions with positive values for x and negative values for y. Is there anyway to implement this in NSolve? I was trying to add an additional equation               NSolve[eq1==a&&eq2==b ... &&y<0,{x,y}]      However, this is not working. Is it the wrong way tom implement it?


Log function - why is Log[b,b] not being evaluated to 1?

Have been experimenting with the Log function to demonstrate simple Log relationships such as Log[xy], Log[x+y] etc.               Clear[x,y,m,n];     m =b^x;     n = b^y;     Log[b,m]+Log[b,n]       The output i get is               log(b^y)/log(b)+log(b^x)/log(b)      Why is Log[b,b] not being evaluated to 1 ? Also Log[b,b^x]=x so why is it not showing this ? Also the log statements in the output have no base shown ? I tried               Log[b,m]//Trace      which gives me ![Result](http://i.stack.imgur.com/jQR2b.jpg) Simplify doesn't seem to do anything Thanks David.


Mathematica not simplifying square root expressions even with assumptions

I have the following expression:               expr=(Sqrt[2]r Sqrt[(4+r^2) (2+r (r+Sqrt[4+r^2]))])/(4+r (r+Sqrt[4+r^2]))      Then               FullSimplify[expr, r > 0]      just returns the expression. However               Plot[expr, {r, 0, 10}]      shows that it is just r in disguise. Is there any way I can tell Mathematica to be smarter? Which tricks should I use in cases like that above?


How can I get Inset to use ImageScaled, but preserve aspect ratio?

This code produces two identical images, despite the difference in the rectangles:               r1 = Rectangle[{-1, -1}, {1, 1}];     r2 = Rectangle[{-1, -1}, {0, 1}];     f[img_] :=       Show[ParametricPlot3D[{{t, 0, 0}, {0, t, 0}, {0, 0, t}}, {t, -1, 1}],        Graphics3D[{Inset[          Show[Graphics[img], ImageSize -> Large], {0.25, 0, 0}, Automatic,           ImageScaled[0.25]]}]]     f[r1]     f[r2]      If I do `{Automatic,ImageScaled[0.25]}`, I am told that it should be a pair of numbers, or a scaled or offset form. I want the height of the inset to be 25% of the overall graphic, and the width to be scaled accordingly. I want it to work for any `img`, not just the two rectangles I gave; my actual use case involves .gif files. How do I make it so that `f[r1]` and `f[r2]` show different insets, i.e., inset the rectangles shown by `Show[r1]` and `Show[r2]`, with the height scaled to 25% of the total height of the image?


Finding the square root of a random number with Newton's method, using While/Do/For loops?

I am trying to construct a program that will find the square root of a number, using Newton's method, which is $$x(n+1) = x_n- f(x) / f'(x_n)$$ The number, will be a random number, generated by: `RandomInteger[{1000000, 10000000}]` I am setting the first Newton estimate to be 1, so I can iterate my loop until the difference in the estimate from Newton's method after n iterations to the first estimate of 1, being less than 0.001. Since I am trying to construct this fully, I am not using any `Sqrt[x]` function or $n^.5$ relationship either. My current thoughts: So I have set:               f[x]:=x^2 + k      where               k = RandomInteger[{1000000, 10000000}]      Since I want to know what number I am taking the SQRT of, I am Printing that information out with:               Print["The Square Root of ", k, " is ", ---]      where --- will be my program. Since I need to take an unknown number of iterations, I am thinking of using a `For` loop, as that checks the loop invariant condition until it is `False` then stops. This is the part I am stuck on -- what I can't grasp: how do I make the loop check for a condition that is outside of the loop? Any help or hints would be greatly appreciated.


Parallelizing or optimizing a script for calculating the size of all pairwise intersections between collections of sets

I need to speed up or parallelize an operation that looks essentially like this:               comparisonSetsA = Round[Table[RandomReal[1., {100, 2}], {k, 1, 100}], 0.05];     comparisonSetsB = Round[Table[RandomReal[1., {100, 2}], {k, 1, 100}], 0.05];          intersectionSizes = Table[Length[Intersection[comparisonSetsA[[a]], comparisonSetsB[[b]]]], {a, 1, Length[comparisonSetsA]}, {b, 1, Length[comparisonSetsB]}] // AbsoluteTiming      Here, we're computing the length of intersections between all pairs of sets in `comparisonSetsA` and `comparisonSetsB` (containing real numbers), which, while less trivial in my actual application, are roughly about the same size as above. Simply writing `ParallelTable` makes things about 3.56 times worse in terms of timings on an 8-core machine. Is there any way to efficiently parallelize or optimize the above process? Note that I cannot make assumptions about the size of any of the intersections, and the sets can be assumed to not contain duplicates. Update - If it helps, I only need to know if the size of the intersection is greater than a smaller threshold value, e.g. $||A \cap B|| \geq 2$ or $3$. I don't need to know anything more than this. Update 2 - I'd like to extend ybeltukov's to handle cases where the sets in A and B are not necessarily of equal size. Is there a simple way to do this that doesn't add much in the way of overhead? I'd asked a question about a possible "padding" method here: http://mathematica.stackexchange.com/questions/32770/equalizing-the-sizes-of- sets-in-an-array-using-non-intersecting-integer-elements Update 3 - Let me be a bit more explicit about Update 2, since I did a poor job earlier communicating. I meant that I would like to extend ybeltukov's very nice result to the cases where internal to sets A and B, the sets are of different sizes. Say, for example, the case where list A has sets of size 5, 6, and 7, and set B has sets of size 8, 9, and 4. I believe one calls these "ragged" lists.