title: Are there Min and Max functions that work properly on Intervals?

text: Mathematica overloads the `Min` and `Max` functions to retrieve the lower and upper bounds of an interval. I need functions that work properly on `Interval` arguments. For example, the minimum of `Interval[{3,4}]` and `Interval[{2,5}]` should be `Interval[{2,4}]`. To clarify based on comments, I'm looking for the tightest possible bounds for the `Min` and `Max` functions, given the constraints of the intervals. For example, the `Max` function of the intervals {2,3} and {7,8} will be {7,8}, because all values in the interval {7,8} are greater than any value in the interval {2,3}. (Note: I'm not looking for an ordering relation for intervals. The `Min` and `Max` operations often produce new intervals. See the first example, above.) I've written my own functions to do this, that only work for simple intervals:               intervalopf[a_Interval, b_Interval, op_] :=       Flatten[Outer[op, {Min[a], Max[a]}, {Min[b], Max[b]}]]     intervalop[a_Interval, b_Interval, op_] :=       With[{v = intervalopf[a, b, op]}, Interval[{Min[v], Max[v]}]]      Are there built-in functions I should be using? And, how can I generalize this to intervals that are unions?


title: Maple like collect command in Mathematica

text: In Maple I often simplify expressions for functions of same argument using the collect command:               > collect(a*f(x)+f(y)+x*f(x), f, factor)     (a+x)*f(x)+f(y)      where the extra option factor will factor the coefficients. In contrast Mathematica:               > Collect[a*f[x] + f[y] + x*f[x], f]     a f[x] + x f[x] + f[y]      Is there some command in Mathematica which achieves the same?


title: How can I properly Partition "IntensityData" output from "ComponentMeasurements"? (Recovering the (x, y) dimensions of a rect. morph. component?)

text: When I ask `ComponentMeasurements` to return "IntensityData" for some set of rectangular morphological components:               m = MorphologicalComponents[image, Method -> "BoundingBox"];     intensityDataArray = ComponentMeasurements[{m, image}, "IntensityData"][[All, 2]];      The pixel value data is returned as an unpartitioned one-dimensional array. This makes it difficult for me to understand where a particular pixel is in the image. Now, if I know the exact dimensions of each morphological component, I suppose I could fix the problem using `Partition`. I could also fix the problem with `Partition` if I could ask for something like a bounding square instead of a bounding rectangular box, though I don't think this is possible (is it?). Besides manually measuring the dimensions of each rectangular morphological component, is there a workaround to fix this problem? Letting `m` consist of strictly rectangular morphological components, it would, for example, be very nice to be able to write something like:               ComponentMeasurements[m, "Dimensions"][[All, 2]]      And have this return something like:               {{5,8}, {87, 40}, {7, 7}, ...}      Meaning that we have morphological components of dimensions $(x, y) = (5 \times 8)$, $(87 \times 40)$, $(7 \times 7)$, and so forth. Here, we're provided ordered values for the extent of the component along the $x$- and $y$-axes, respectively, allowing us to trivially use `Partition` to restore the cropped section of an image underlying a morphological component (i.e. the image one would have if a morphological component is used as a "cropping mask"). * * * Clarification: Masking approaches are really neat, but not quite what I'm looking for here unless they're part of a larger approach. I need a method of grabbing the pixel data strictly underlying a morphological component (for a set of morphological components) and retaining $(x, y)$ data for each pixel. My downstream procedure then does further image processesing on this rectangular matrix. If I do a matrix multiplication masking procedure, I still need to trim away the dark space to get down to a bounding box (the size of the morphological component mask). Also, it seems a little wasteful to have to perform multiplication operation on all pixels in the image to accomplish my goal?


title: Skip the revert dialog

text: When saving a file and making changes to it one can revert using `File->Revert` in the menu or by entering `FrontEndExecute[FrontEndToken["Revert"]]` before reverting a dialog window opens to ask if you are sure. I would like to skip this dialog by automatically answering with yes. Is that possible? **Edit:** Here is a picture of the dialog. ![enter image description here](http://i.stack.imgur.com/11PLp.png)


title: Outline Numbering for Mathematica Section/Subsection Cells

text: I am trying to create a LaTex-style document with Section numbers of the form 1.0 and then subsection numbers 1.1, 2.1, etc. I need the numbering to be automatic such that if I insert a new subsection, the numbering of subsequent subsections will automatically adjust. Is there an easy way to do this (presumably by editing the stylesheet??). I've looked at a bunch of options but can't seem to find the appropriate one.


title: Number format in Legend Labels

text: I would like to use the usual (new and nice) `BarLegend[]` with something like               BarLegend[{"LakeColors", 1/10000 {-2, 2}}]      which looks like ![Example BarLegends-Plot](http://i.stack.imgur.com/PzQny.png) I don't like the numbers, i would like to use `ScientificForm[]` on them, hence get $0.0002 = 2\times10^{-4}$ or even better - get just $2$ at the label and $\times 10^{-4}$ in the bottom right or something like that. Is there a way to obtain `ScientificForm[]` for these labels? I searched the Documentation of the new `~Legends` and haven't found anything. And the very best would be, to be able to specify the number of digits used (where i would like to have 3, e.g. $2.00\times10^{-4}$, so best would be `ScientificForm[#,3] &` to be applied to every number of the Legend. ## Update Surprisingly - following the approach of @Nasser M. Abbasi the two lines               f[x_] := ScientificForm[x, 2];     BarLegend[{"LakeColors", 1/10000 {-2, 2}}, LegendFunction -> f]      produce a Legend like ![second approach](http://i.stack.imgur.com/yR5uN.png) Though the second argument of `ScientificForm[]` gets ignored. Any further ideas why that does happen? ## Update #2 Changing `f` to `f[x_] := ScientificForm[N[{x} /. {DirectedInfinity -> Identity}], 2];` actually _does_ change the number of digits, but returns the `BarLegend` in an Array and produces errors, that `(1.,4.}` is not a List of positive Integers (though they look quite Integer to me). Why there is an `DirectInfinity` approaching, I haven't found out yet, without the replacement, the `1.` is a `DirectedInfinity[1.]`


title: Mathematica: how to make Z transformation of data from CSV File

text: I have a discrete Signal in my CSV File and I want to transform it in Z. I import the data with                Data=Import["T:/data.csv","CSV"]      and I try to transform it               ZTranform[Data[n],n,z]      but I get this Error:               $RecursionLimit::reclim : Recursion depth of 256 exceeded >>      What is the meaning of this?


title: How to Chop correctly?

text: I want to count degeneracies in a list called `spectrum`. The list contains numbers of double (~ 15digits) precision. So it makes no sense if the noise below this precision is taken into account since it falsifies the result of degeneracy counting using `Tally[]`. So I applied `SetPrecision`.               degList = Tally[{#1, SetPrecision[#2, 15]} & @@@ spectrum];      But I still get e.g. {-0.047063080371693544`, 4} {-0.047063080371693294`, 4} (last number is the degeneracy level) which should be seen as equal numbers but are counted by `Tally[]` as different ones. What am I doing wrong?


title: Can Depth be used as an equivalent for MatrixQ?

text: Given an expression `x`, are the following two statements interchangable with no exceptions?   * `Depth[x] - 1 == 2`   * `x // MatrixQ` If they are, which is evaluated faster? Other than for speed, is there a reason one should be used rather than the other?


title: Using mesh for a single function inside Plot

text: Plot[{Sin[x], Cos[x]}, {x, 0, 10}, Mesh -> {{0, \[Pi]}},           MeshShading -> {Black, Red}]      In the above, how can I specify that I want the mesh for just, say the Sine function and not the Cosine? I know I can use two plots and combine them with Show, but this is not what I want.


title: Find asymptotics of a function

text: Can _Mathematica_ find the asymptotics of a function in the following sense? I have               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]) - 1)^2]      and I would like to know an asymptotic approximation when $n$ is large. That is a simple function that is within a constant multiplicative value in the limit when $n \rightarrow \infty$. If instead it was               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]))^2]      then I know that               Log[1/n^2]/Log[4^(-Sqrt[Log[n]]) + (2^(-Sqrt[Log[n]]))^2]/Sqrt[Log[n]]       tends to a constant value. My question is how could you use _Mathematica_ to discover that $\sqrt{\log{n}}$ is the right answer in the second case and to find whatever the right solution is in the first case? By trial and error I happen to know that the right answer in the first case is somewhere between $2^{\log^{1/2}{n}}$ and $2^{\log^{1/2+\epsilon}{n}}$.


title: keeping parentheses size the same in Input cells when using 2D math

text: I like to group the 2 parts of the `If` statement and others like it by using `()` to help me be able to still understand what my code is doing the next day I look at it. I started to use 2D math in input cells, and it is a nice feature of Mathematica. But noticed that `()` changes size depending on what is inside them. So I end up with non-symmetrical (different size) parentheses within the same logical grouping. An example will help show this: ![enter image description here](http://i.stack.imgur.com/l4Z0U.png) Notice how the top `()` are small compared to the lower `()`. The code will look better on the screen if the sizes of these `()` are kept the same. (either both large, or both small, is not important, as long as the size is the same) This happens with `With` and any other such command. I know the `()` are not needed. I just use them to make the code easy to read. When I have complicated logic, these help me see the parts more clearly. Here is the actual code that generated the above converted to `InputForm` in order to paste it here               Clear["Global`*"]     If[x == 1, x = 0, x = Sqrt[y^2] ];       Question is: Is there a way to control this aspect of the display in input cells for 2D math so that parentheses are the same even if using 2D math?


title: Clustering 3D Data Points on a Periodic Cubic Grid

text: I have a set of 3D data points on a cubic grid. The data can be downloaded from here https://skydrive.live.com/redir?resid=F96524B72DCD75FB!14240 and read into a variable `lis` using `lis = ReadList["filename", {Number, Number, Number}]`. How can one cluster the points into groups such that the points in each group are related by the fact that they are only one grid point away from their nearest neighbor in all directions (taking periodic boundaries in all directions into account). By all directions I mean the six faces of a cube. The `EuclideanDistance` between grid points is `0.055089` . Here is a plot of the data (well solution, see below). ![enter image description here](http://i.stack.imgur.com/wWZ5X.jpg) Actually, I was able to solve this problem using object-oriented programming in _C#_ , but I've come up short trying to reproduce it in _Mathematica_. I've tried a combination of `FindClusters` and `Nearest` with no success. Any help will be much appreciated. I have tried to include as much information as I think is needed to solve this problem but if more information is needed I'll gladly provide it. Note: In the plot above, I've removed groups that has less than 20 points.


title: Checking differential equation solution

text: I have this differential equation:               eq=D[ψ[r],r]+A*ψ[r]-(B/(A*r))ψ[r]==0;      And `DSolve` sucessfully solves it:               sol = DSolve[eq,ψ[r],r];      But when I check by replacing all, in this case it doesn't replace the derivative of the function:               Simplify[eq/.sol]      Derivative still must be replaced too. If I do:               Simplify[eq/.sol/.D[sol,r]]      Then this gives `True`. In other cases _Mathematica_ replaced the function and its derivatives in one shot. What's happening in this case?


title: Window ▶ Show Handwriting Input

text: How might I force Mathematica to display the Handwriting Input menu? Currently I'm on W7 using a Wacom Tablet and unable to find the Handwriting Input option. It doesn't display under Windows>.


title: How Do I Convert A Binomial Distribution to a Smooth Histogram in a Manipulate?

text: Manipulate[BarChart[Table[PDF[BinomialDistribution[n, p], i], {i, 0, 20}],       PlotRange -> {{-.5, 21.5}, {-.1, 1}},       Epilog -> {PointSize[0.03], RGBColor[1, 0, 0], Point[{n*p + 1, 0}]},       ImageSize -> {450, 350}],        {{n, 10, "Variables"}, 1, 20, 1,Appearance -> "Labeled"},        {{p, .5, "Skew"}, 0, 1, Appearance -> "Labeled"}]      Ladies and Gentlemen! How do I convert the binomial distribution inside this `Manipulate` (above) to a `SmoothHistogram`? Or, more simply put, where do I insert the term `SmoothHistogram` in this script?


title: Recursion evaluate Table power exceeded limit

text: I wrote 2 simple recursive functions for calculating the power of a table.               pol3[Tb_List, n_Integer?Positive] := If[n == 1, Tb, Tb.pol3[Tb, n - 1]]      and               pol4[A, 1] := A      pol4[A, n_Integer?Positive] := A.pol4[A, n - 1]      Tb, A are 3x3 arrays. Functions works for n<255 but if I try to call them for n=256 or greater then I take wrong results and the message:               $RecursionLimit::reclim: Recursion depth of 256 exceeded      I'm not very familiar with the Mathematica so I would appreciate any ideas on what I'm doing wrong.


title: Plot complex path (essentially a 2D path) expressed in one real parameter

text: Consider a complex path expressed in one real parameter, such as $$f(\alpha)=\frac{1}{e^{i \alpha} + 1},$$ which is a Möbius transformation of the unit circle. I know I can expand it all out and use the parametric plot, but it is cumbersome and not very easy (sometimes practically impossible) to do so. Therefore, I want to know if there is some plotting function specifically designed for this. (I searched for it in the documentation but did not find it; sorry if it's all obvious.)


title: Display ALL keys in dataset

text: I created a dateset (estimates) with 25 keys (my columns), and about a hundred rows. I'd like to be able to list the keys from the dataset. I did this:               estimates[Keys]      which returned: ![enter image description here](http://i.stack.imgur.com/jsMAQ.png) I also tried:               estimates[1]      which returned: ![enter image description here](http://i.stack.imgur.com/yBwlb.png) How can I display the entire list of keys? My code is below:               Module[     {fileTemp, header, data},      fileTemp = Import[NotebookDirectory[] <> "test.xlsx", {"Sheets", "estimates"}];     header = fileTemp[[1]];     data = fileTemp[[2 ;;]];     estimates = Dataset@Map[AssociationThread[header, #] &]@data;      ] The following is part of the Excel sheet: ![enter image description here](http://i.stack.imgur.com/N2lyK.png)


title: How to convert sine wave into square wave? (analog to digital signal)

text: I've got this plot with two sine waves ![enter image description here](http://i.stack.imgur.com/cykyF.png) and what I need is follow: ![enter image description here](http://i.stack.imgur.com/GfuJB.jpg) Amplitude values can diverge from time to time like here min 100 and max 700 but another time it's 300 600. I guess I will not be able to get these nice phased waves from those on my picture.. But let's assume we have only one sampled sine wave. How to translate it to 001111110000011111 where 1s are for sine above "zero"(that's the main problem, every time it will be different point, like here it's around 400) and 0s for below zero. And another difficulty it would be nice to get this conversion on the go/online. Like I don't have whole sampled signal but only let's say 100 last values(10-60 these sine slopes). Please, can you at least say what I should google? Thank you :) **UPDATE** I've asked a little wrong.. How can I get zero line from signal like this? To apply suggested Sign[]. It's vary bad scenario sine wave.. In my case it's bouncing not around zero but some changing Y. It lasts around one value only few slopes.. ![enter image description here](http://i.stack.imgur.com/6N726.png) **ANSWER** Well, that's up to how you want to treat the data. I suppose the simplest way is to take the Mean of the data streams, and treat that as the "zero" - so just subtract it from the stream and then do the Sign. Also take a look at Rescale, Clip, and Standardize - all can be used to good effect here, e.g. waveSquared[[All, 2]] = Sign@Standardize@waveSquared[[All, 2]];... – @rasher Now it looks like this ![enter image description here](http://i.stack.imgur.com/eQfJc.png)


title: Workaround for automatic replacement of "\r" to "\n"

text: When I run the following code in an empty notebook               SetOptions[EvaluationNotebook[], testOption -> "\n\r"]      and then open the notebook in Notepad, I find > $CellContext`testOption -> "\n\n" (1) Can you confirm this bug/feature in other versions/operative systems? I am using Mathematica 9.0.1 in Win8Prox64. (2) Is there a workaround?


title: Importing Output from Linux mpstat to Calculate Aggregate and Per-CPU Averages, Creating Tables and Graphs

text: I'm a Mathematica noob, running a trial version for the moment, but have run into the wall trying to handle this in Excel and am looking for other options. While running a benchmark application I'm gathering output from the Linux command "mpstat -P ALL 1" and exporting it to a CSV. The data is as follows:               Time, CPU, %usr, %nice, %sys, %iowait, %irq, %soft, %steal, %guest, %gnice, %idle      10:11:04 AM, all, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 0, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 1, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     10:11:04 AM, 2, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     ...     more interesting data in the middle     ...     11:18:55 AM, 12, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 13, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 14, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00     11:18:55 AM, 15, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 100.00      There are 21 unique tests in the benchmark which are clearly visible when each sample with "CPU = all" is graphed. (The Y axis is calculated as (100 - %idle). ![Excel Graph of "ALL" CPU utilization over Time](http://i.stack.imgur.com/sePMO.png) What I need to do is the following:   * Separate the idle periods from the periods when the benchmark is running. (There are short idle periods before testing starts, in-between each test, and an idle period after all tests are complete.) This is the part that gives me the biggest problem since the number of idle samples between tests is not entirely predictable.   * For each period when the performance test is running, find the average CPU utilization for each CPU (0, 1, 2, ..., 14, 15, all).   * Create a table that indicates the test name (e.g. Test 1, Test 2, etc.) and the average CPU utilization for each CPU sampled. > >     +--------+---------+-------+-------+-------+-------+ >     |  Test  | CPU ALL | CPU 0 | CPU 1 | CPU 2 | CPU 3 | >     +--------+---------+-------+-------+-------+-------+ >     | Test A |   30%   |  25%  |  35%  |  24%  |  36%  | >     +--------+---------+-------+-------+-------+-------+ >     | Test B |   25%   |  20%  |  31%  |  24%  |  30%  | >     +--------+---------+-------+-------+-------+-------+ >     ... >   The full data source can be found here: mpstat.zip


title: Interpolation problem on the list

text: I have a List of Latitude, Longitude and Measurement.               a = {{{93, 104}, 290}, {{94, 103}, 292}, {{95, 105}, 291}, {{97, 109},          294}, {{97, 102}, 295}};      And, I want to Interpolate this list and plot them using ContourPlot and CountryData. However, error has occured when I use Interpolation:               Interpolation[a]     Interpolation::udeg: Interpolation on unstructured grids is currently only supported for InterpolationOrder->1 or InterpolationOrder->All. Order will be reduced to 1.     Interpolation::umprec: Interpolation on unstructured grids is currently only supported for machine numbers. The data will be coerced to machine precision.      The list is a just peace of my full list. I don't know how to solve this.


title: Counting multiplications (complexity function)

text: I'm trying to count the number of times multiplication appears in an expression (for the purpose of constructing a ComplexityFunction that would help me simplify a terrible algebraic expression for later numerical crunching in matlab). For example, I consider the following expression to involve 3 multiplications:               a b c + d e      two in "abc" and one in "de". I've tried Level, but unfortunately mathematica sees the term "abc" as one "Times" with three arguments:                In:= Level[a b c + d e, {-1}, Heads->True]     Out:= {Plus, Times, a, b, c, Times, c, d}      In principle I could reverse-engineer the multiplicity of arguments of "Times" from the above, but that seems like an unnecessarily cumbersome way. i'd greatly appreciate any help.


title: How to get a country's official languages?

text: According to Wikipedia > Of the 193 widely recognized countries, 178 have an official language at the > national level (NB:or more than one) The only exceptions are: > Cyprus, Czech Republic, Denmark, Eritrea, The Holy See, Luxembourg, San > Marino, Sweden, Tuvalu, Ukraine, United Kingdom, United States, Uruguay, > Uzbekistan, and Yemen `CountryData[]` supports three language related properties: > "Languages", "LanguagesDialects", "LanguagesFractions" But none of them seems to return the "Official Languages". Is there a way to get a country's official languages within Mathematica?


title: What does rule 30 mean in this example?

text: This starts with the list given, then evolves rule 30 for four steps.               In[1]:= CellularAutomaton[30, {0, 0, 0, 1, 0, 0, 0}, 4]          Out[1]= {{0, 0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 1, 0, 0}, {0, 1, 1, 0, 0, 1,        0}, {1, 1, 0, 1, 1, 1, 1}, {0, 0, 0, 1, 0, 0, 0}}


title: Projection of a set of 4D points to the 3D space

text: Consider the following set of points in the 4D space:               points = {{Log[5], Log[2], Log[8/5], Log[23/16]}, {Log[5], Log[2], Log[23/17],        Log[17/10]}, {Log[5], Log[16/11], Log[11/5], Log[23/16]}, {Log[5],        Log[17/12], Log[23/17], Log[12/5]}, {Log[5], Log[23/18], Log[11/5],        Log[18/11]}, {Log[5], Log[23/18], Log[3/2], Log[12/5]}, {Log[5/3],        Log[6], Log[8/5], Log[23/16]}, {Log[5/3], Log[6], Log[23/17],        Log[17/10]}, {Log[11/7], Log[16/11], Log[7], Log[23/16]}, {Log[3/2],       Log[17/12], Log[23/17], Log[8]}, {Log[11/7], Log[23/18], Log[7],        Log[18/11]}, {Log[3/2], Log[23/18], Log[3/2], Log[8]}, {Log[4/3],        Log[6], Log[2], Log[23/16]}, {Log[17/13], Log[6], Log[23/17],        Log[13/6]}, {Log[4/3], Log[12/7], Log[7], Log[23/16]}, {Log[17/13],        Log[13/8], Log[23/17], Log[8]}, {Log[9/7], Log[23/18], Log[7],        Log[2]}, {Log[9/7], Log[23/18], Log[7/4], Log[8]}, {Log[23/19],        Log[6], Log[2], Log[19/12]}, {Log[23/19], Log[6], Log[19/13],        Log[13/6]}, {Log[23/19], Log[12/7], Log[7],        Log[19/12]}, {Log[23/19], Log[13/8], Log[19/13],        Log[8]}, {Log[23/19], Log[19/14], Log[7], Log[2]}, {Log[23/19],        Log[19/14], Log[7/4], Log[8]}}      All the points lie on a 3D hyperplane since `MatrixRank[# - points[[1]] & /@ points]` returns 3. How can I show the points in a 3D space (e.g., using `Graphics3D`) so that the distance of points are kept intact?


title: Improve the performance of solutions to Project Euler (#14)

text: Problem I have following code, when n<=10^5 it's not slow, but n>2*10^5 it's became very slow. I think maybe some temp value greater than 2^31-1, so make compile invalid. Could you give any idea make it can be compiled? As far as possible not to use recursive algorithm.               pe14 = Compile[{},        Module[{n1, len, maxLen = 0, res = 0},         Do[n1 = n;          len = 1;          While[n1 != 1,           n1 = If[EvenQ@n1,  n1~Quotient~2, = 3 n1 + 1];           len++           ];          If[len > maxLen, maxLen = len; res = n],          {n, 1, 10^6}];         {maxLen, res}         ]        ];          pe14[] // AbsoluteTiming


title: What does Internal`InheritedBlock do?

text: What does the function `Internal`InheritedBlock` do? How is it different from the regular `Block`?


title: How can I imitate the style of a certain 3D bar chart?

text: I would like to get a 3D visualization of a given matrix. Here is a figure which may come from _Mathematica_. I want to plot something like it. When I use `ListPlot3D` or `BarChart3D` to plot my matrix, it does not have the style of one shown below, which is what I'm look for. How can I do a nice 3D visualization of my matrix? ![visualization of a matrix](http://i.stack.imgur.com/XRlCG.png)               data = ( {         {1, 2, 3},         {5, 4, 8},         {2, 5, 7}        } );          data = ArrayPad[data, {0, 1}];     xTicks = {{1.5, "A"}, {2.5, "B"}, {3.5, "C"}};     yTicks = {{1.5, "X"}, {2.5, "Y"}, {3.5, "Z"}};     zTicks = {{0, "0"}, 0, {4, "4"}, {8, "8"}};          pic = ListPlot3D[data,        Mesh -> None,        InterpolationOrder -> 0,        ColorFunction -> "Rainbow",       Filling -> Bottom,       FillingStyle -> {Opacity[0.9]},       PlotRange -> {Min[data] - 0.5, Max[data] + 0.2},       BoxRatios -> {1, 1, 0.5},       Ticks -> {xTicks, yTicks, zTicks},       DataRange -> All,       Boxed -> False,       FaceGrids -> {Bottom, Back, Left},       ImageSize -> 400]      this is the code that I plot a matrix using `ListPlot3D`. The cuboids in it are not separate from each other, and the edges of the cuboid are fuzzy. ![my figure for matrix from the above code](http://i.stack.imgur.com/DkBUL.png)


title: Speed of ConvexHullMesh

text: Pick $N$ random points on the surface of the sphere, then use `ConvexHullMesh[]` to compute their convex hull. Empirically, this takes time quadratic time in $N,$ whereas the state of the art as of 1996 is $N \log N.$ Is Mathematica doing something extra, or is its algorithm just 18 years out of date? In the interest of "politeness".               randpt[n_]:= Module[{prept = RandomVariate[NormalDistribution[], 3]}, prept/Norm[prept]]     experiment[n_]:= ConvexHullMesh[Table[randpt[3], {n}]//AbsoluteTiming      **EDIT** Here is the experimental data (the first element in each pair is the number of points, the second the AbsoluteTiming [this on a very fast Windows PC])               {{10000, 6.133357},       {20000, 17.791034},      {30000, 50.460951},      {40000, 106.783207},      {50000, 182.384594}}      This looks awfully quadratic to me. I point out that experiments for small $n$ are meaningless, since there is linear overhead, which has a none-too-small constant, so swamps the quadratic growth. $50000$ points is not that many (and certainly would be a modest number for any FEM mesh), so this is clearly a major performance bug. **ANOTHER EDIT** for comparison purposes, I also installed qhull on the very same machine, and ran `qconvex` on 50000 cospherical random points. The running time was, umm, well, it started spewing output at me the moment I hit return, so I am seeing a roughly three order of magnitude speedup.


title: Mathematica ncurses support

text: I occasionally `ssh` into machines that have _Mathematica_ installed. I then operate _Mathematica_ through the command-line interface. Often, the command-line interface isn't the ideal way to operate _Mathematica_ , but it does have incredible convenience and speed advantages. Is there a ncurses library (maybe even a 3rd party one) to add additional functionality when accessing _Mathematica_ through `ssh`? ### Edit List of ideas for additional functionality   1. Cursor clicking support, so I don't have to use the arrow keys   2. Ability to rerun command (`Shift`+`Enter`)   3. Support for Save As


title: Join a piecewise plot

text: I wrote some code to get a piecewise plot which is displayed correctly. Now I'd like to join the various parts of the plot, using some kind of interpolation, to get a continuous chart even though it's actually a piecewise one. Let me to give you an example. Assuming $f_1(2) = 3$ and $f_2(2) = 1$, how can I join the points $(2,3)$ and $(2,1)$ in the plot?


title: Discrete distribution binomial set up

text: I hope one of you guys can help me out. I am trying to visualize a discrete distribution based on a binomial distribution and a mixed binomial distribution. In the first step I started to determine the parameters:               Remove["Global`*"];     m = 45; (*total number*)     n = 3;  (*target number*)     AV = 55605000;     DV = 52474000;     μ = 0.06     σ = 0.10;     T = 5;     ρ = 0.22;       Then I started with the binomial distribution which is given by _Mathematica_. In order to calculate the probability that `x ≥ 3`, I need the single probability which is calculated by:               p = (CDF[NormalDistribution[], -(Log[AV/tV] + (μ - 0.5*σ^2)*T)/(σ*Sqrt[T])])      the result for p is 0.068 than I want to calculate the probability that x ≥ 3 to to so I enter the following:               probBDAW = Probability[x >= 3, x \[Distributed] BinomialDistribution[m, p]]      and the result is 0.60. then I want to have a table of the probabilites when x≥1,x≥2,≥´x≥3..etc...in order to do so I entered this:               dataBDAW =       Table[Probability[x >= n1, x \[Distributed] BinomialDistribution[m, p]], {n1, 0, 45, 1}]      this also works and I get a table. In the next step I want to plot the discrete distribution of this probabilites by using the DiscretPlot function. Therefore I enter:               pdfBDAWXX =        DiscretePlot[         PDF[BinomialDistribution[m, p]], n1], {n1, 0, m},          PlotRange -> All, AxesLabel -> {"y", "x"}, ImageSize -> 500,          PlotLabel -> Style["Text", Bold]]      this also works well and I get the follwoing chart: ![enter image description here](http://i.stack.imgur.com/x76ol.jpg) Now I want to use a mixed binomial set up. I already calculated p so want to calculate again that x ≥ 3. To do so I enter:               probMBD =       1 - CDF[NormalDistribution[], ((1/Sqrt[            1 - ρ])*(((Sqrt[ρ])*(InverseCDF[                NormalDistribution[], (3/m)]) - (InverseCDF[               NormalDistribution[], (CDF[                 NormalDistribution[], -(Log[                      AV/DV] + (μ -                         0.5*σ^2)*                      T)/(σ*Sqrt[T])])]))))]      thus I get the probability that x ≥ 3 is 0.187 as before I want to generate a list with the probabiliest x≥1,x≥2,≥x≥3..etc. Hence I enter:               dataMBDAW =       Table[1 -         CDF[NormalDistribution[], ((1/Sqrt[             1 - ρ])*(((Sqrt[ρ])*(InverseCDF[                 NormalDistribution[], (n1/m)]) - (InverseCDF[                NormalDistribution[], (CDF[                  NormalDistribution[], -(Log[                       AV/DV] + (μ -                          0.5*σ^2)*                       T)/(σ*Sqrt[T])])]))))], {n1,         0, m, 1}]      As a result I get a nice table. But when I want to plot the discrete distribution I have some problems. I did something but I am far from sure that this is right. so could please anyone look at this and say if it is corret and if not could you please write me how it is done correctly? ok so I just said that               testx = (dataMBDAW)      then I wrote this function in oder do caputre the discrete density:               ftest[jk_] := testx[[jk]] + testx[[jk + 1]]      In the next step I did the following:               H1 =       ListPlot[Table[testx[[jk]] + testx[[jk + 1]], {jk, 2, 45}],         PlotStyle -> Black, PlotRange -> All, AxesLabel -> {"y", "x"},         ImageSize -> 500, PlotLabel -> Style["text", Bold], Filling -> Axis,        FillingStyle -> Directive[Opacity[0.2], Black]]      and the result is this chart: ![enter image description here](http://i.stack.imgur.com/RRtOm.jpg) I am not sure if this is correctly done. I would be thankful if you could help me out and say if it is correct and if not provide me with a solution for my problem.


title: How do I remove a bounding box (i.e. set Boxed -> False) after rendering a 3D graphic?

text: I have an old notebook with an output from Graphics3D, however, I've lost the data behind the output and recomputing it would take days. I simply want to remove the bounding box Mathematica usually displays unless you specify that "Boxed -> False". Is it possible for me to still do this without having to recompute the graphic? E.g. I want to transform an output generated from running this example command:               Graphics3D[{Sphere[{0, 0, 0}, 1], Sphere[{2, 3, 5}, 1]}]      To an example output generated from running this example command (but without having to regenerate the image since I no longer have access to the sphere coordinates):               Graphics3D[{Sphere[{0, 0, 0}, 1], Sphere[{2, 3, 5}, 1]}, Boxed -> False]


title: How to not include data value outside plot range in the plot

text: Consider this list plot               ls = Table[Sin[t], {t, 0, 100, 0.1}];     p = ListPlot[ls, PlotRange -> {{0., 0.1}, All}, DataRange -> {0, 1}, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/8wlGZ.jpg) If we look at the data in the plot, we see that all the data in `ls` are included in the plot.               ls2 = p[[1, 2, 1, 3, 3, 1]];     Dimensions[ls2]     (* {1001, 2} *)          ListPlot[ls2, Joined -> True]      ![enter image description here](http://i.stack.imgur.com/mvGPJ.jpg) Sometimes this is really helpful because we can just retrieve the data at a later time from the plots and don't need to regenerate the data again. But sometimes I'm only intreated in the range set in the ListPlot, and saving all the data is kindly of wasting of space, especially when I have many plots in a notebook, the notebook size becomes very large and not very responsive. So are there simple ways to tell `ListPlot` to not include the data outside the plot range, other than manually select the data before plot? P.S. Sometimes, ListPlot does drop the data outside the range, see example here.


title: Fastest way to calculate matrix of pairwise distances

text: It is a very common problem that given a distance function $d(p_1,p_2)$ and a set of points `pts`, we need to construct a matrix `mat` so that `mat[[i,j]] == d[ pts[[i]], pts[[j]] ]`. What is the most efficient way to do this in Mathematica? * * * Let's assume that the points are in $\mathbb{R}^n$ for simplicity, and because that's the case I'm dealing with now, but theoretically the points could be any type of object, e.g. strings with $d$ being an edit distance. For the specific problem I have right now I need to calculate the `EuclideanDistance` and `ManhattanDistance` of 2D points. The simplest way to do this is               pts = RandomVariate[NormalDistribution[], {1000, 2}];          mat = Outer[ManhattanDistance, pts, pts, 1]; // AbsoluteTiming          (* ==> {0.595327, Null} *)      This obviously calculates all distances twice, which is wasteful. So I was hoping for an easy $2\times$ speedup, but it isn't as easy as one would hope. Doing the same operation the same number of times in a `Do` loop takes considerably longer (probably because of indexing):               Do[ManhattanDistance[pts[[10]], pts[[20]]], {Length[pts]^2}]; // AbsoluteTiming          (* ==> {1.902417, Null} *)      So what programming pattern do you typically use when calculating such a distance matrix and which one would you recommend for this specific problem?


title: A basic problem with Solve

text: I have this equation:               4b*Cos[2t]-4a*Sin[2t]==4Cos[2t]+8Sin[2t]      Which I would like to solve. Without using mathematica, you can pretty easily see that a = -2 and b = 1, but when I solve it with mathematica it gives me various long results including sometimes tan, sec cot etc. I can break it up into to parts like this:               Solve[4b*Cos[2t]==4Cos[2t],b]     Solve[-4a*Sin[2t]==+8Sin[2t],a]      However, the point with mathematica isn't to make everything manually, and I would hope there is a method to use, without manually editing the equations. So my question is: How do I solve this for a and b, with the results of a = -2 and b = 1?


title: Creating a "Live" Index Notebook --to load other Notebooks

text: I am new here, so let me know if this question is inappropriate. I've been stuck for many hours on this puzzle. I know it should be easy, but for me...? I want to create a Notebook (call it "Index of Related"), located in directory "C:\somewhere\strange" (not necessarily in $Path) which contains a list of notebooks I use at the same time, but quite independently of one another. One application might be a list of all the Mathematica notebooks I use in my microeconomics course. From inside "Index of Related", if I click on a button, I want Mathematica to load some other notebook, just as if I had used File/Open in Mathematica. I can't seem to create buttons to execute simple File/Opens! Every coding I've tried adding to Index of Related" seems to load the other notebooks into or inside Index of Related or generate $Failed. Example X: Example of an application:   * File 1, located in C:\directory1 : Slide show for the talk....   * File 2, located in c:\dogs\small : My text for the talk....   * File 3, located somewhere in $Path : Handouts for the talk....   * File 4: References for the talk....   * Files 5-8, located all over the place: Examples for the talk, created for other projects, so in various other directories.... Now, while creating the talk I first load "Index of Related". I stumble on a reference, so I open Files 2 and 4 and make changes. In a later session, I want to create from this reference a slide, so I open and work in File 2.


title: Inverting a Spline-Function (Bezier or BSpline)

text: I would like to use a Spline-Function to describe a transformation from one range of reals to another, that is I would like to have a function which maps a value $y$ on $x$ and for simplicity let us assume that $x,y \in [0,1]$. The idea was to define a smooth, nonlinear function which is to be within the boundary points $\{(0,0),(\alpha,\beta),(1,1)\}$ with $\alpha,\beta \in [0,1]$, also. Thus a Bezier- or BSpline-Function seemed to be appropriate. Unfortunately I can't see how I can use the Spline-Function directly to map $y$ on $x$ (or vice versa for that). The Spline-Function will one parameter $t$ with $t \in [0,1]$ and will give all points on the curve, e.g. $spline(0) = (0,0), spline(1) = (1,1)$. So to find say the corresponding $x$ value for $y=0.6$, I tried something like this:               f = BSplineFunction[{{0, 0}, {0.2, 0.7}, {1, 1}}];     FindInstance[Last@f[t]==0.6,t]      But what I am getting is the false answer $\{\{t\rightarrow 0.6 \}\}$. The correct answer should have been $t = 0.5$. So far I have also tried Reduce, Solve, NSolve, FindRoot (giving a start value for t) and have of course given the domain to be Reals. But nothing works. Is there a way to do this without having to substitute a simpler function for the Spline-Function (e.g. using `Interpolation[]`)?


title: When using GraphPlot with an adjacency matrix, how can I make Mathematica draw exactly one self loop for any non-zero weight?

text: I have tried using the option `MultiedgeStyle->None`, but apparently Mathematica doesn't treat self loops in the same way it treats edges. For example, I find               GraphPlot[{{1,2},{2,0}}, SelfLoopStyle->All, MultiedgeStyle->None]      ![Graph with one self loop](http://i.stack.imgur.com/KSvNh.jpg) while the same command, but with twice the weight on the self loop gives               GraphPlot[{{2,2},{2,0}}, SelfLoopStyle->All, MultiedgeStyle->None]      ![enter image description here](http://i.stack.imgur.com/xiCHt.jpg) I would like the output from both commands to be the same. I know I could write a function to replace all non-zero values on the diagonal with `1`, but I'd prefer not to for two reasons. One is that it seems as if this should be possible without resorting to that, and the other is that I'm actually using this inside another routine to draw graphs with edge weights displayed, to get output such as ![enter image description here](http://i.stack.imgur.com/r7xC2.jpg) where the label inside the self loop should list the correct weight, taken from the diagonal of the adjacency matrix. Removing the diagonals for later labeling then changing them in the adjacency matrix just seems like a hack.


title: How can I combine my 3D graphics and animate them?

text: I'm just a beginner but can someone tell me how I can take my image of an Elf and put it together with a 3d background and I'm trying to animate it snowing but I wanna use a "play" button. Trying to do a short ten second one. Any ideas? Import["http://i1.ytimg.com/vi/woHs5kFd3dI/maxresdefault.jpg"]               Graphics3D[{Red, Cone[], White, Sphere[{0, 0, -1.5}, 1.03], Red,        Sphere[{0, 0, -3}, 1.09], Red, Sphere[{1, 0, -2.8}, 1/4],        Sphere[{1.4, 0, -2.85}, 1/4.5], Sphere[{1.7, 0, -2.95}, 1/4.9],        Sphere[{-1, 0, -2.8}, 1/4], Sphere[{-1.4, 0, -2.85}, 1/4.5],        Sphere[{-1.7, 0, -2.95}, 1/4.9], Yellow,        Sphere[{1.9, 0, -3.1}, 1/5.3], Sphere[{-1.9, 0, -3.1}, 1/5.3],        Black, Sphere[{-.5, -.80, -1.2}, 1/6],        Sphere[{.5, -.80, -1.2}, 1/6], Black,        Sphere[{-.3, -.84, -1.8}, 1/9], Sphere[{.3, -.84, -1.8}, 1/9],        Sphere[{.15, -.84, -1.9}, 1/9], Sphere[{-.15, -.84, -1.9}, 1/9],        Sphere[{0, -.84, -1.92}, 1/9], Green, Sphere[{0, 0, 0}, .457],        Green, Sphere[{0, 0, -.5}, .68], Green, Sphere[{0, 0, -1}, .901],        Sphere[{0, 0, 1}, 1/6], Green, Sphere[{0, 0, .5}, .235],        Sphere[{0, -1, -3}, 1/7], Green, Sphere[{0, -.87, -2.5}, 1/7],        Green, Sphere[{0, -.87, -3.5}, 1/7], White,        Sphere[{.9, 0, -1.5}, 1/4], Sphere[{-.9, 0, -1.5}, 1/4]}]          Graphics3D[{Translate[flake,        Dynamic[With[{time = Clock[{0, 10, .05}]}, #@time & /@ funs]]]},        Boxed -> False, Lighting -> "Neutral", AxesLabel -> {"x", "y", "z"},        Background -> LightBlue, PlotRange -> {{-10, 10}, {-10, 10}, {0, 20}}


title: Abort not aborting

text: I have a relatively simple bit of code that looks like the following:               ---some code here---     If[statement, Abort[]];     ---more code following---      However, while `$Aborted` appears as output, the evaluation of the rest of the cell does not abort, continuing execution of code beyond the `If` statement. How do I actually get the running cell to cease evaluating the rest of the cell? **Edit:** It seems that one way to accomplish this is to wrap the entire cell in parenthesis, e.g., but this is a fairly ugly solution, especially with auto-formatting turned on (my cell has many lines of code, and the parenthesis are huuuuuge). Anyone have a more elegant solution?               (     ---some code here---     If[statement, Abort[]];     ---more code following---     )


title: Issues with a Counter that is tallying term appearances

text: I am working with an array of textfiles, trying to see how frequent certain terms are. However, I am running into some difficulty with my running counts of bigram frequency. Here is a snippet of my code that has been giving me trouble:               SetDirectory[       "/users/ianmilligan/desktop/project/blah/blah/"];          filelist = FileNames["*bigrams.txt"];     citizenCounter97 = {};          Do[       citizenchecker97 = Get[file];       Clear[bigramHash];       (bigramHash[Sequence @@ #1] = #2) & @@@ citizenchecker97;       count = bigramHash["ottawa", "citizen"];       Print[ToString[file] <> ":" <> ToString[count]];       AppendTo[citizenCounter97, count];       , {file, filelist}];      The file that is being checked looks like this `citizenchecker97`=                 {{{"owner", "further"}, 262}, {{"on", "the"}, 206}, {{"the",        "women"}, 204}, {{"women", "s"}, 197}, {{"maritime",        "baptist"}, 195}, {{"and", "the"}, 193}, {{"for",        "the"}, 189}, {{"the", "maritime"}, 186}, {{"by",        "the"}, 180}, {{"with", "the"}, 170}, {{"the",        "missionaries"}, 146}, {{"that", "the"}, 142}, {{"the",        "mission"}, 141}...}}      As it stands, my `bigramHash` (which stems from an earlier exceptionally helpful SO answer) generates a number if the file contains that bigram (if it appears twice, it generates '2', which I want to `AppendTo` `citizenCounter97`. If it _doesn't_ contain the bigram, however, it generates `bigramHash[ottawa, citizen]`. My plan was to just generate a list, subsequently just `Cases[citizenCounter97,_Integer];` the thing, and have a sense of how often the given term appeared. Problem is, the results did not make sense. When I went in and started de- bugging, I realized that the counts that come out of `Print` were completley different than the lists it was generating! The result for `citizenCounter97` would be like this:               {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \     1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, \     2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, \     2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,       bigramHash["ottawa", "citizen"], bigramHash["ottawa", "citizen"],       bigramHash["ottawa", "citizen"]}      Whereas the real `Print` output would show that the first 12 results were nothing, the 13th was 2, and then nothing again until 27, when it became 1. So basically, I am confused as to what's happening, why my counter is completely divergent from the reality as I do it manually/debug with `Print`. Thanks in advance, and happy to clarify as best I can. **---- edited to add ----** I suspect one solution lies in an `If` statement - i.e. `If` count is an integer, then append that; if the 'If' ends up being not an integer, then return 0. I've tried a variety of calls using `Head` however, and am still hitting a brick wall.


title: Assign variables automatically to a function

text: Lets consider that I've this function:               fn = a*x^2 + b*x + c;      The idea here is to assign automatically the variables `a`, `b`, `c` and `x` to a function so it becomes something like that:               fn[x_,a_,b_,c_] := a*x^2 + b*x + c      In order to do this I've tried to extract the varibles from `fn` using `Variables`:               Sort@Variables@fn      > {a, b, c, x} Then in order to apply it to the function `fn` I do the following:               fn1@Variables@fn /. List -> Sequence      > fn1[a, b, c, x] **Questions:**   * Is it possible to add the `Blank`s to the former expression in order to have `fn1[a_,b_,c_,x_]`?  > One of my fail attempt to do this was to use `Blank@#&/@Sort@Variables@fn` > but it's obviously not working.   * One other point is that if you consider that you've found a way to automaticly have `fn1[a_,b_,c_,x_]`, how to assign the value of `fn` to `fn1[a_,b_,c_,x_]` without having the `fn1[a_,b_,c_,x_] is protected` message?


title: Packed Graph or GraphPlot output with non-square layout?

text: Graph or GraphPlot produce square layouts for disconnected graphs:               Graph[Table[i -> Mod[i^3, 100], {i, 1, 100}]]      ![Mathematica graphics](http://i.stack.imgur.com/bFqCB.png) I´d like to get a rectangular layout with e.g. aspect ratio 1/2, preferably in combination with the `PackingMethod -> "ClosestPackingCenter"` option. Setting `AspectRatio` does not do what I want, because the graph is only rescaled/distorted and not redrawn on a rectanglular grid with said `AspectRatio.` ![Mathematica graphics](http://i.stack.imgur.com/XCfq2.png) Is there a way to achieve something like this (emulated by a gridded copy of the first graph)? ![Mathematica graphics](http://i.stack.imgur.com/f194y.png) Addition: Because of the added interactive graph functionality in newer versions, a solution leaving this functionality intact would be preferrable (and probably more compatible with future developments).


title: Where can I find example of good webMathematica programming?

text: Just now I started to work on webMathematica. I surprised that I can't do whatever I do with mathematica. Can any one suggest me where I can get good practice on webMathematica.


title: How to make Mathematica re-evaluate a cell after some event?

text: I am doing a little project to demonstrate something:               a = 2; b = 5000;      d = 10000; l1 = {};       rc := RandomChoice[{a, b} -> {0, 1}]     c = 1; While[c <= d, AppendTo[l1, rc];c++]      e = ((Count[l1, _] - Count[l1, 0])/d)*100//N      f = 100 - e      I want to insert two InputFields for the values of A and B, but I want it to re-evaluate the rest of the cell whenever I input new values for A and B - I'm also curious for A or B. **Note** - Inserting the inputfields is not my problem, my problems is only the reevaluation of the cell after some event.


title: How to import non-text data from std input in a Mathematica script?

text: Or maybe a better question is - how can I get a `stdin` stream? I need to run on Linux. I did look at Reading from STDIN, or: how to pipe data into Mathematica, but that talks about text data. I need to import an image, sent to standard output by another program. According to Mathematica documentation, there is no pre-defined standard input stream, there's only `$Output`, which is standard output, and `$Input`, which is the script being executed. There are only 2 functions that read from standard input in the expected way - `Input`, which tries to read a Mathematica expression, and `InputString`, which tries to read a string till it gets a newline. Neither of these is good for reading non-text data. What I would prefer to do is read from a stream, preferably using `Import`. I want to use this Mathematica script in a shell script, and pipe data to it. I tried `Import[OpenRead["/dev/stdin"]]`, but this only seems to work if I have an actual file on disk and I redirect input using `<`. It doesn't work if I pipe data to the Mathematica script.


title: Constrained maximum likelihood

text: Trying to solve a MLE with nonlinear constraints that need to be satisfied. However, the given solution do not match the constraints. Am I doing it correctly?               (* Construct Probability Model *)     \[ScriptCapitalD]1 =  NegativeBinomialDistribution[r, \[Alpha]/(\[Alpha] + 1)];     \[ScriptCapitalD]2 =   ParameterMixtureDistribution[BetaBinomialDistribution[a, b, n], n \[Distributed] \[ScriptCapitalD]1];     (* Test for one set of data *)     T = 598; R = 333; A = 78; U = 893; (* X=106; assumed unknown *)     data = {3, 1, 9, 1, 4, 2, 12, 2, 3, 1, 2, 1, 3, 2, 2, 2, 39, 3, 1, 7, 2, 1, 5, 1, 2, 1, 1, 64, 1, 2, 1, 18, 2, 1, 2, 11, 4, 3, 5, 2, 1, 4, 8, 2, 10, 16, 2, 2, 1, 5, 1, 1, 1, 1, 1, 2, 2, 4, 1, 4, 1, 1, 1, 1, 2, 1, 2, 4, 2, 4, 2, 1, 8, 1, 1, 1, 1, 1};     CC = {FullSimplify[Mean[\[ScriptCapitalD]1]] == T/U, Mean[\[ScriptCapitalD]2] == R/U, Probability[z == 0, z \[Distributed] \[ScriptCapitalD]2] == 1 - (A/U)}; (* Constraints *)     CP = {a > 0 && b > 0 && r > 0 && \[Alpha] > 0}; (* Parameter constraints *)     MLE = NMaximize[{LogLikelihood[\[ScriptCapitalD]2, data], Flatten[{CC, CP}]}, {a, b, r, \[Alpha]}]     (* Do they match the constraints? Expressed in terms of known values *)     U*{CC[[1, 1]] , CC[[2, 1]], 1 - CC[[3, 1]]} /. MLE[[2]]     (* X_estimate *)     U*(1 - Probability[y == 0, y \[Distributed] \[ScriptCapitalD]1]) /. MLE[[2]]      When I ran the code received a lot of warnings, including "Simplify::fas: Warning: one or more assumptions evaluated to False." with final output being:               {-338.828, {a -> 4.46969*10^-8, b -> 3.49161*10^-8,  r -> 0.112262, \[Alpha] -> 0.167517}}     {598.446, 335.984, 98.1873}     174.889      However, with trial and error found that the constraints can be satisfied with               {a -> 0.79170676874115343262052276450750130908150706082622,  b -> 0.63003691806728426319650273891989981624150723094542,  r -> 0.045708496520516912401968683076575539420378914371680, \[Alpha] \-> 0.068257002329133115008291066471192704521037320465721}      being one answer. Whether those are the maximum likelihood estimates I am not sure.


title: Default FontFamily for PlotLabel

text: This is probably a rather basic question and I presume I am simply unable to make proper use of the `Options[]` function: I am trying to figure out what the default font (or `FontFamily`, I guess) is for `PlotLabel`. I tried e.g. `Options[PlotLabel, FontFamily]` and some variations, but to no avail. Many thanks.


title: How to prepare (copy/paste) data from Matlab?

text: What is the best way to get data from Matlab to Mathematica? For a new project I want to copy/paste a table (or part of it) of datas from Matlab to Mathematica. Copyed from Matlab it is:               0   0     1,00000000000000e-20    0,100000000000000     1,78810000000000e-09    0,300000000000000     2,94930000000000e-09    0,500000000000000     4,37810000000000e-09    0,700000000000000     5,58330000000000e-09    0,900000000000000     5,60570000000000e-09    1      In Mathematica I get the following:               0 0     1, 00000000000000 e - 20 0, 100000000000000     1, 78810000000000 e - 09 0, 300000000000000     2, 94930000000000 e - 09 0, 500000000000000     4, 37810000000000 e - 09 0, 700000000000000     5, 58330000000000 e - 09 0, 900000000000000     5, 60570000000000 e - 09 1      (In my Mathematica, there are little "x"s between the exponents and the zeros, I guess it is the columns seperator.) So now I have to replace the "," by "." and the "e-" by "*10^-" and so on ... I could, but I don't want to do it manualy, but till now I had no success with any Mma functions. Or is there a better way to do things like this? ... in the end it should look like this:                {{0, 0},      {1.00000000000000*10^-20, 0.100000000000000},      {1.78810000000000*10^-09, 0.300000000000000},      {2.94930000000000*10^-09, 0.500000000000000},      {4.37810000000000*10^-09, 0.700000000000000},      {5.58330000000000*10^-09, 0.900000000000000},      {5.60570000000000*10^-09, 1}}


title: Correlation test issues

text: When using `Correlation[]` function I sometimes get the strange warning:               CorrelationTest::nortst: "At least one of the p-values in {0.0527317}, resulting from a test for normality, is below 0.05`. The tests in \!\({\"PearsonCorrelation\"}\) require that the data is normally distributed."      But take a look that there's only one p-value and it is actually greater than $0.05$:               0.0527317 < 0.05     False      The code that causes this:               x = RandomReal[{-5, 5}, 100];     y = 2 x + 1 + RandomReal[{-0.1, 0.1}, 100];     X = Transpose[{x, y}];     ListPlot[X]     Correlation[X] // MatrixForm     CorrelationTest[X, 99995/100000, "PearsonCorrelation"]      Why this happens? (to reproduce the issue a few repetitions are usually required)


title: Recursion doesn't happen any more or doesn't happen correctly if I store the recursive relationship in a variable first

text: I know the following code will form a recursion:               Clear["Global`*"]     u[i_, n_] := u[i - 1, n] + u[i, n - 1]     u[0, n_] := n     u[i_, 0] := i          u[2, 2]      (* => 8 *)      But if I store the recursive relationship in a variable first, the recursion will fail:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i_, n_] := exp     u[0, n_] = n     u[i_, 0] = i          u[2, 2]      (* ERROR *)      Why? I guess maybe `exp` "shields" `i` and `n`, so, I tried something like:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i1_, n1_] := (i = i1; n = n1; exp)     u[0, n_] := n     u[i_, 0] := i     u[2, 2]     Table[Table[{i, u[i, n]}, {i, 0, 2}], {n, 0, 2}];     u[2, 2]     (* =>5        =>5 *)      …As you see, it doesn't give the right answer. A even "amazing" case is this:               Clear["Global`*"]     exp := u[i - 1, n] + u[i, n - 1]     u[i1_, n1_] := (i = i1; n = n1; u[i, n] = exp)     u[0, n_] := n     u[i_, 0] := i     u[2, 2]     Table[Table[{i, u[i, n]}, {i, 0, 2}], {n, 0, 2}];     u[2, 2]     (* =>5         =>14 *)      Ah…the process of recursion is so complex, how to explain all these? And, how to solve the original problem?


title: Downloading files without using Import

text: A quick question, but which I don't believe has been asked here or at SO. Does _Mathematica_ have a simple way to just download a file from the web? i.e. if I have a list of PDF links (~ 2,000), can I use Mathematica to quickly take them and save them to my system. The obvious way that I've used in the past is to `Import[]` the data, but since we're talking large-ish PDFs I wonder if there's a way to skip that step. I have used wget for this sort of thing in the past, but just seeing if there's an easy way to do it within _Mathematica_. The 'Web Operations' section of the documentation does not seem to have any obvious reference to this. If not, I will obviously just use the 'proper' tool.


title: The "right" way to define a custom Encoding format?

text: I have implemented an `Import|Export` format for xz that behaves like gzip and other encoding formats:               Import["some.ext.gz"]     Import["some.ext.xz"]      But I think I did it in a really roundabout way, is there a more straightforward way than adding `DownValues` for all these things:               ImportExport`EncodingsDump`rundecoder["XZ", infile_String, outfile_String, opts___]     ImportExport`EncodingsDump`runencoder["XZ", infile_String, outfile_String, opts___]     FileFormatDump`$FILEFORMATMATRIX["XZ"] (* $ /mma.SE bug *)     ImportExport`EncodingsDump`InstallCoderQ["XZ"]     ImportExport`EncodingsDump`CreateShortName[infile_ /; StringMatchQ[infile, "*.xz"]]     AppendTo[FileFormatDump`$FILEFORMATS, "XZ"]      Together with:               ImportExport`RegisterImport["XZ", ImportXZ,        "BinaryFormat"->True,        "Extensions"->{"*.xz"},        "Encoding"->True,        "AvailableElements"->{_String},        "FunctionChannels"->{"FileNames"}]      (* Similar for Export *)      What's the best way to do this?


title: How to transform an equation so that the coefficient of a certain term becomes 1

text: Say I have an equation like               A + 5 B + 10 C == 0      and I want to have _Mathematica_ write this as               (A/5) + B + 2 C == 0      i.e., I want to pick a term (B in this case) and choose its coefficient (1 in this case) and have _Mathematica_ divide or multiply the equation appropriately. I can't figure out a way other than using Solve to solve the equation for B, but that's not ideal (especially since it moves B to the other side of the equation). ### Edit A good solution should also be something one can apply after a Collect, a Simplify, etc., without undoing those commands, since the equations I'm dealing with are much more complicated than this simple example!


title: Stopping a head from evaluating more than once

text: While attempting to answer my own question, Is there a way to "hold" prefix / infix / postfix notation?, I came across the need to evaluate a recursive function only one level deep. For example, consider a factorial function:               factorial[n_Integer /; n >= 0] := If[n >= 2, n*factorial[n - 1], 1]      Normally, expressions using `factorial` would be fully evaluated:               2 + 3*(factorial[5] + factorial[7])     (* 15482 *)      However, is there a way to evaluate `factorial` just once, and prevent evaluating any further occurrences? That is, a function, `EvaluateHeadOnce`:               EvaluateHeadOnce[factorial, 2 + 3*(factorial[5] + factorial[7])]     (* 2 + 3 (5 factorial[4] + factorial[7]) *)      I found a method (self-answered below) but it felt rather... inelegant. I'm curious to see how others would implement such a method, as well as hear criticisms / flaws in my approach.


title: Splitting dates into groups in half year steps

text: list = DayRange[{1999, 1, 1}, {2014, 2, 6}]      I want to split this list into sublists one and a half year long, moving a half year forward every time. That would mean that the first dataset would go from 1999 to 2000 June. Next group would go from June 1999 to 2001 and so on. Last dataset group would not be complete due to the fact that the dates only goes to the 6th of February 2014. There are two things that I want to point out.The assumption you made was correct about dividing the dates from Jan to the end of June so one. However, I have lists of dates with different length so I would like to be able to map a function over the different lists of dates where this dividing is occurring. So that no matter how long the list is it would divide it as I asked above. Please note, that the lists vary all from 4 to 20 years. Also some lists are just Business days, so it would mean that in some cases the end of the month is not the last date of that month.


title: Can mathematica resolve this equation?

text: Obviously，the equation $x^2-3 y^2=2 z^2$ doesn't have positive integer solutions. I tried               Exists[{x, y, z}, x > 0 && y > 0 && z > 0 && x^2 - 3 y^2 == 2 z^2]     Resolve[%, Integers]      and               Exists[{x, y, z}, Element[{x, y, z}, Integers],       x > 0 && y > 0 && z > 0 && x^2 - 3 y^2 == 2 z^2]     Resolve[%]      but I don't get any useful result. Am I using these functions incorrectly?


title: Tools for Importing/working with SEED seismographic data in Mathematica?

text: Do you know if exist a library or a package in order to import and work with SEED Seismographic data in Mathematica?


title: Constructing a function with Flat and OneIdentity attribute with the property that otimes[a]:>a

text: I want to have a function (called `otimes`) with the following two properties:   1. it has the attribute `OneIdentity` and `Flat`   2. if evaluated with a single argument it returns that argument The built-in function `Times` has these properties; e.g., evaluating `Times[a]` yields `a`. I am struggling implementing my own function having the same behavior. What I tried is the obvious implementation               SetAttributes[otimes,{OneIdentity,Flat}]     otimes[a_]:=a      However this does not work and leads to an infinite recursion when I evaluate otimes[a,b]. I do not now how to implement the desired behavior consistently. Maybe somebody can help?


title: How do you find the longest sublist within a nested list

text: Say, I have a list               stuff={{eat,tea,now},{how,did,you,say},{the,cat,ate,was,can},{win,din,sin}}      I have a nested list and I want to find the list that has the most words in it and then I want to find the length of those words. How would I do that? I thought it was               Max[StringLength[stuff]]       and               Length[Max[StringLength[stuff]]]      but `StringLength` doesn't do me any good here since the length of each letter is the same.


title: Two questions on strategies for quantifier elimination

text: With the help of people here I was able to solve several cases similar to IC3 but this case - unlike the other cases - does not return an answer. I will try to run it for a day with 8 processors but will be grateful for:   1. Any suggestions on how to solve IC3 (besides more memory or more time)   2. In the end I only care about some other constraints so would help resolve if I add additional constraints on the other variables (a, c and d) when trying to eliminate x and z?              IC3 := (4 d^3 + 24 a d^2 x + 3 (2 a + c) d (-c x^2 + 2 a (x^2 + 4 x z - 2 z^2)) - (2 a + c)^2 (c x^3 + 4 a (x^3 - 3 x^2 z + z^3)))/(6 (2 a + c)^2)              && 0 < -((2 d)/(2 a + c)) < 1     Resolve[{x,z}, (-(2 d)/(2 a + c)) <= x <= 1, (-d/(2 a + c))<=z<=(-(2 d)/(2 a + c)), IC3]


title: RandomVariate does not evaluate a Hyperbolic Distribution

text: Any Idea why I can't get a result from this expression:               In[170]:= RandomVariate[HyperbolicDistribution[59.428`, 18.441`, 3.428`*^-9, -0.00065`]]          Out[170]= RandomVariate[HyperbolicDistribution[59.428, 18.441, 3.428*10^-9, -0.00065]]      I have found this Distribution modelling daily balance of a bank in order to calculate Liquidity Risk.


title: Counting elements skipped using Reap & Sow

text: I am using the following code to filter data based on the percentage change between points.               Reap[z = data[[1]]; Sow[z];               Scan[If[Abs[# - z]/z > delta,               z = #; Sow[z]] &, data]][[2, 1]]      That is, only considering point that were separated but a certain percentage change. While it gives me the correct answer, I would like to count the values that are dropped in between each selected point. How could I do that ?


title: Extrude 2D cross-section to 3D shape with shrinkfactor

text: I would like to create a 3D shape from extrusion and scaling of a 2D contour. The 2D contour that I have looks like this: ![enter image description here](http://i.stack.imgur.com/82RTu.png) and it consists of a bunch of points (here plotted with `ListPlot` with `Joined->True`). I have looked at a bunch of questions and answers here on Mathematica.SE, notably this one and this one, but I don't see how to apply those to my problem in any straightforward manner. For the sake of a MWE I will switch to a circle from this point on:               xdata = Table[x, {x, -1, 1, 0.05}];     ydata = Table[Sqrt[1 - x^2], {x, -1, 1, 0.05}];     circData = {Transpose[{xdata, ydata}], Transpose[{xdata, -ydata}]};     ListPlot[circData, Joined -> True, AspectRatio -> Automatic]      The extruded shape that I would like to make then looks like this: ![enter image description here](http://i.stack.imgur.com/NywlJ.png) It is a shape consisting of slices of the contour with constant radius $r_0$ over some range let's say $-1 < z < 1$ and decrease in radius with $z$ at the tips according to $r(z)=r_0\sqrt{1-(z-1)^2}$ and $r(z)=r_0\sqrt{1-(z+1)^2}$ (depending on which tip). **My question is: how can I do this extrusion for the set of listdata that I have?** Just to be clear, to create the 3D shape for the circle I cheated and used the formula for a circle and a sphere like this:               p = Plot3D[{1 + Sqrt[1 - y^2 - x^2 ], -1 -           Sqrt[1 - y^2 - x^2 ]}, {x, -2, 2}, {y, -2, 2},         PlotStyle -> {Orange}, Lighting -> Automatic, Mesh -> Automatic,         BoxRatios -> Automatic, Boxed -> False, Axes -> None];     q = RegionPlot3D[        Sqrt[x^2 + y^2] < 1, {x, -1, 1}, {y, -1, 1}, {z, -1, 1},         PlotStyle -> {Orange}, Lighting -> Automatic, Mesh -> Automatic,         BoxRatios -> Automatic, Boxed -> False, Axes -> None];     Show[p, q]      **Is there a way to achieve the same with the data from a list?** * * * **[Adaptation to thicknessFunc by @Halirutan and accompanying re-scaling]** To make the thicknessFunc more generic I adapted it to:               thicknessFunc[z_, body_,        b_] := (HeavisideTheta[z] - HeavisideTheta[z - b])*        Sqrt[b^2 - (z - b)^2] +        b (HeavisideTheta[z - b] -           HeavisideTheta[z - body - b]) + (HeavisideTheta[z - body - b] -           HeavisideTheta[z - body - 2 b])*Sqrt[b^2 - (z - body - b)^2]      such that you can set the radius of the circular parts by setting $b$. A consequence of this is that you have to rescale the thicknessFunc in append with $1/b$ like               Append[1/b thicknessFunc[u,2]*fdata[t], u]      I don't fully understand why, but I guess it has to do with the fact that `fdata` is multiplied by `thicknessFunc` and therefore needs the straight ends of `thicknessFunc` to be at 1


title: How to combine objects from different .obj files?

text: I got a screw .obj model with the head diameter of `2cm`, and a board .obj model of `10cmx10cmx4cm` in dimension. I would like the screw duplicated in 25 copies painted with different color and "screw" on the board in an array of `5x5` with random heights. How can I attain this in Mathematica? ![enter image description here](http://i.stack.imgur.com/7Gi69.gif)               (* assuming the .obj files are located in the c: root *)     scw = Import["c:\\screw.obj"];     brd = Import["c:\\board.obj"];     Show[brd, Graphics3D[{        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {1, 0.8, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], { 3, 1, -1}],        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {5, 1.1, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {7, 0.7, -1}] ,        Translate[         Rotate[First[scw], 2 Pi , {0, 0, 1}], {9, 1.0, -1}]          }]      ]      With the code shown above, I got something like this: ![enter image description here](http://i.stack.imgur.com/Ruq74.jpg) I need a better(faster) way to do this, and need to knew how to "paint" the nails and the board.


title: export table with number written in scientific notation

text: I am trying to write on a file the table generated in this way:               error = ConstantArray[0, 3];     error[[1]] = ScientificForm[Sqrt[CovMat[[1, 1]] /. out[[2]]]];     error[[2]] = ScientificForm[Sqrt[CovMat[[2, 2]] /. out[[2]]]];     error[[3]] = ScientificForm[Sqrt[CovMat[[3, 3]] /. out[[2]]]];     Ris = out[[2]] /. Rule -> (#2 &);     par = out[[2]] /. Rule -> (#1 &);     Finale = MapThread[{#1, ScientificForm[#2], #3} &, {par, Ris,          error}] // TableForm      CovMat anf out are generated in a previoous part of the code (a `NMinimize`). Typing Finale on the notebook I find:               M   4.35203*10^(10) 4.2566*10^(9)     \[Delta]    4.10847*10^(5)  2.12356*10^(4)     L   1.01689*10^(9)  1.30717*10^(16)      The problem is that in the file I find:               "M  ScientificForm[1.7467449664329874*^11]  \     ScientificForm[4.784135569792907*^9]          [\Delta]    ScientificForm[606745.0359163599]   \     ScientificForm[10326.21966853348]          L   ScientificForm[2.788541796939519*^10]   \     ScientificForm[1.5410843643505646*^18]"      I used `Export` and               file = OpenAppend["out.txt"]          string = ExportString[Finale,"Table"];          WriteString[file, string]     WriteString[file, "\n"];          Close[file]      (I thought that `ExportString` read the values as they are) but I cannot get rid of that `ScientificForm`. I suspect that I should use something like:               Export["file.dat", {elem1->expr1, elem2->expr2, ...}, "Rules"]      but I cannot find a way to express the rule.


title: How can I use the Rules returned by FindFit?

text: When I evlauate               data = RandomReal[10, {5, 10, 2}];     fit[i_] := FindFit[data[[i]], a Sin[x] + b, {a, b}, x]     fit[1]      I get something like: > >     {a -> 0.177375, b -> 3.91185} >   Then, I try to plot the points and the fitted function together in one figure.               Show[ListPlot @ data[[1]], Plot[a Sin[x] + b /. %, {x, 0, 10}]]      With % I can get the figure I want, but               Show[ListPlot @ data[[1]], Plot[a Sin[x] + b /. fit[1], {x, 0, 10}]]      returns errors. Why does this occur? Why can't I insert fit[1] in `ReplaceAll`, and how can I correct my mistake?


title: Camera Simulator

text: I am developping a perspective camera simulator. For the moment, I am considering only the projection of a quadrics form that gives us a conic. For testing my simulator, I use povray an image rendering software to generate a 2D image for a quadric. My problem is how to plot my resulat in a different standard dimensions (like 800*600, 1080*1920,320*240,…..). Here is a portion of my code.               Conic={{7.08617*10^-6,4.20705*10^-14,-0.00283447},   {4.20705*10^-14,8.77616*10^-7,-0.000219319},{-0.00283447,-0.000219319,1.18635}}     ell=Plot[Evaluate[     y /. Solve[{x, 600 - y, 1}.Conic.{x, 600 - y, 1} == 0, y]], {x, 0,      800}, PlotRange -> {0, 600}, AspectRatio -> 6/8,      Filling -> {1 -> {{2}, RGBColor[{1, 1, 1}]}}, Axes -> False,      Background -> Black, PlotStyle -> {Directive[RGBColor[{1, 0, 1}]]}]     (*Here I plot my conic (ellipse) in (800,600) and for {600-y}, I do this because the   coordinate system between image and graphics are inversed… Then to convert my graphic to image, I use Rasterize() and I tested succefully my result *)      Rasterize[ell,ImageSize -> {400, 300}, Background -> RGBColor[{0, 1, 0}]]      (I need to simulate my camera with image dimensions 320 x 240 ) I changed my code like this               ell=Plot[Evaluate[     y /. Solve[{x, 240 - y, 1}.Conic.{x, 240 - y, 1} == 0, y]], {x, 0,      320}, PlotRange -> {0, 240}, AspectRatio -> 3/4,      Filling -> {1 -> {{2}, RGBColor[{1, 1, 1}]}}, Axes -> False,      Background -> Black, PlotStyle -> {Directive[RGBColor[{1, 0, 1}]]}]      Here I have not get the ellipse. It seems that there is not a point that satify `{x, 240 - y, 1}.Conic.{x, 240 - y, 1}`. But it is not logic because when I use the camera on povray, I can render this image. Any clarification please


title: Why does MemoryConstrained not abort when memory limit is exceeded?

text: I thought I had an idea that might lead to an answer to @yohbs' question, but as I was trying to check out the usage of `MemoryConstrained[expr,b,failexpr]`, I discovered behavior I did not expect.   The following aborts immediately; neither `k` nor `t` are set. (Please don't worry about the `Rule` -- I added `"Abort"->` merely to distinguish an aborted computation):               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10j], {j, 1000}],       2199, "Aborted" -> Table[t[j], {j,k}]]      > Out[2]= Aborted->Table[t[j],{j,k}] I guess that it takes more than 2199 bytes to build the `Table` expression and it does not even evaluate one iteration. If the limit is raised one byte to 2200, then the command does not abort at all.               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10j], {j,1000}],       2200, "Aborted" -> Table[t[j], {j, k}]] // Short      > Out[4]= //Short= {{1,2,3,4,5,6,7,8,9,10},<<998>>,{1,2,<<9997>>,10000}} As you can see below, 41M were used to store the result, not to mention the other 41M stored in `t[_]`.               ByteCount[%]      > Out[5]= 41277832 The last list, `Range[10000]`, is stored in `t[1000]` and exceeds the limit of 2200 bytes:               ByteCount[t[1000]]          > Out[6]= 80144 Any `Range[n]` with `n` equal to 256 or more causes an abort:               MemoryConstrained[Range[256], 2200]      > Out[7]= $Aborted               ByteCount[Range[256]]      > Out[8]= 2160               ByteCount[Range[257]]      > Out[9]= 2416 (It is believable that there are more than 40 bytes of overhead in computing `Range` and that the chunking of memory causes the 256 byte jump, although these are just a random stabs at an explanation.) Does someone know how to make `MemoryConstrained` abort when the limit is 2200? Or can someone explain when memory request counts toward the `MemoryContrained` limit? **Addendum** Thanks for the help so far. I'm on Mac OS 10.8.2, Mma 9.0.0, slightly old MacBook Pro (~2008), 6GB RAM. I restarted Mathematica and tried again. Same result. However, changing the limit on the iterator `j` from 1000 to 100 got it work. Strange.               Clear[t,k];     MemoryConstrained[Table[k = j; t[j] = Range[10 j], {j, 100}],       2200, "Aborted" -> Table[t[j], {j, k}]] // Short      > Aborted->{{1,2,3,4,5,6,7,8,9,10},{1,<<18>>,20},t[3]}


title: Manipulation of InterpolatingFunction

text: Suppose that $q[t]$ is obtained by `NDSolve` as an `InterpolatingFunction`, and I want to define $Q[t]$ to be some function of $q[t]$, say $\sqrt{q[t]}$. How can I define it in such a way that I become able to plot its time derivative for example?


title: Plot a cone in spherical co-ordinates

text: As we all know in spherical coordinates a function `phi = π/3` gives us a cone. The cone makes an angle of `π/3` with the imagined `z`-axis. How do I type this formula into _Mathematica_?


title: Create simple table with function of column values

text: I just want to create a simple table: Three input columns, one output column Call the inputs `{x,y,z}`, each can take values `{-1,0,1}` The output column should be some function `f(x,y,z)` Sample table:               x  | y  | z  | f(x,y,z)          -1 | -1 | -1 | f(-1,-1,-1)          1  | -1 | -1 | f(1,-1,-1)      etc... (all possible combinations) Thanks!


title: How to keep $FrontEnd options from resetting?

text: I'm trying to get _Mathematica_ to look in a different, version-tracked folder for the 'TextResources' files that it uses to build the Front End. I've prepended my version-tracked folder path to the `$FrontEnd` option `PrivatePaths`, both from the Options Inspector and using SetOptions. Both of these methods make _Mathematica_ use my version-tracked files the next time I restart the Front End, but it quickly reverts to the versions at `$InstallationDirectory\SystemFiles\FrontEnd\TextResources\Windows` within one or two Front End restarts. I'm not certain what triggers this switch back to the default directory, but I'd really like to stop it from happening so that I can reliably and persistently use my customized, version-tracked instances of the 'TextResources' files. How might I accomplish this?


title: Solving a pair of recurrence relations

text: Why does this               RSolve[{y[t] == a*y[t - 1]}, {y[t]}, t]      work, while this               RSolve[{y[t] == a[t - 1]*y[t - 1], a[t] == a[t - 1]}, {y[t], a[t]}, t]      does not given any interesting result? * * * My goal is to solve something of the kind:               RSolve[{y[t] == function[y[t - 1],a[t-1]], a[t] == b*a[t - 1]}, {y[t], a[t]}, t]


title: Automating the "Get Indices" right click function

text: Is there a way to do this? What I am trying to do is allow a user to take a lineout averaged over the rows of a user defined ROI (Region of Interest) of an image. I have the bit of code that allows for the lineout but at present the only way I can get the indices of the ROI is to use the right click Get Indices function and then copy and pasting them into the function. I would like to eliminate the need for the copy and paste. I would like the user to click on the image in two locations with locators (or some sort of marker) appearing on the click, then have the lineout be plotted as an output. I need to have the image be full size (1000 x 2000) so that the user can see detail. I will also need to write the indices and the lineout to user defined variables so that multiple lineouts can be plotted together as the user needs them and the image reproduced with the markers overlay-ed on top. I have the code to do the lineouts and the plotting but I am hung up on a way to pass the indices cleanly out of a Module/DynamicModule structure. Would it be cleaner to do this all in 1 Manipulate structure? There will be 50 or so images each with there own lineout that my be compared to one another or all at once. Thanks


title: How do I plot a 3D vector field using a data file with three x y z columns?

text: I have a data file that is the solution of the laplace equation on a rectangular area, which has three columns: x, y and z with their numerical values. How do I plot this data into a vector field with vectors in z direction with magnitude from the third column? When I import that data as "Table", is gives me a list of lists, i.e. {{x1,y1,z1},{},...,{}}, which makes it unsuitable to use with `ListVectorPlot3D[]`... Cheers //edit I would like to use the imported data to interpret it as a vector field and calculate its rotation.


title: When to use indexed variables

text: Still learning the fundamentals of the language I would like to ask you what advantages there might be in writing something like:               a[1] = 2;     a[2] = 4;     a[3] = "x";      It seems to me that it is always better to write               a = {2, 4, "x"};      Do you know about any practical constructs where indexed variables would offer an advantage?


title: is there an option for FitResiduals in FindFit?

text: I know this option exists in NonlinearModelFit and probably in other fit models as well but for some reason the best result i get is with FindFit. Regards Doron


title: Entering block matrices for an arbitrary matrix size

text: Background: How to enter matrices in block matrix format? and the following: I want to create $$ f(A,t) = \left [ \begin{matrix} A & t \\ 0 & 1 \end{matrix} \right ] $$ where $A$ is a $n$ by $n$ square matrix size , and $t$ is a column vector of length $n$. The solution in the question above works for case 2, the following code works for cases 2 and 3:                 Transpose[Append[Transpose[Append[IdentityMatrix[2], {0, 0}]], {a1, a2, 1}]] // MatrixForm       Transpose[Append[Transpose[Append[IdentityMatrix[3], {0, 0, 0}]], {a1, a2, a3,1}]] // MatrixForm      **Question: What is the best code for case $n$?**


title: tol and None in output of CompilePrint

text: **A bit of background:** I'm trying to fit a very complicated symbolic function. By compiling the function I got about 100x speedup, but I would need another 10. Therefore I'm trying to understand if the function is correctly compiled (I allready checked that there are no calls to MainEvaluate). **The problem:** While scanning through the output of `CompilePrint` I see the following snippet repeating a lot               12  B0 = R39 None R38 (tol R42)     13  if[ !B0] goto 46      **The question:** What does line **12** do? Is this R39 * **None** * R38? What is ( **tol** R42)? Here is some more context:                   33 arguments         1 Boolean register         1 Integer register         123 Real registers         Underflow checking off         Overflow checking off         Integer overflow checking off         RuntimeAttributes -> {}              R0 = A1         R1 = A2                 ...         Result = R64          1   R38 = Reciprocal[ R2]     2   R39 = R37 * R38     3   R38 = R36 + R39     4   R39 = Reciprocal[ R38]     5   R38 = - R39     6   R39 = - R2     7   R41 = R40 + R39     8   R39 = Reciprocal[ R2]     9   R41 = R41 * R39     10  R39 = R36 + R38 + R41     11  R38 = I0     12  B0 = R39 None R38 (tol R42)     13  if[ !B0] goto 46     ....     19k something lines:)


title: What is $ sign in Mathematica?

text: Is it a special sign or it can be used as anything else? For creating variables for example.               $x=4


title: Variable naming changes everything

text: I am having a rather unusual problem I do not understand with Mathematica where renaming one of the variables of my function causes the function to stop "working". Here is the example of the code doing what it should:               F[t_, a_, b_, l_] = x[t] /. First@     DSolve[{x'[t] == a*x[t]*(1 - (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t];      Changing one variable name causes the code to throw out error messages. The non-working code is               F[t_, r_, b_, l_] = x[t] /. First@ DSolve[{x'[t] == r*x[t]*(1 -     (x[t]/b)) - l*x[t], x[0] == 0.4}, x[t], t];


title: Strange domain dependency with Maximize

text: I'm using Mathematica 8 and strangely enough this code:                   Maximize[{x*(1-0.01 x),x>0},x,Integers]      produces the result `{8.19,{x->9}}`, which seems at odds with the actual answer of `x->25`. Does anyone know if it is an intended behavior or my mistake?


title: Construct DifferentialMatrices and Kernel for LevinRule for this integral and ODE set

text: I've made a lot of progress on my problem the last few days thanks to all the help I've received on here. I think I'm upto the final step of greatly improving the performance of NIntegrate[..] on my setup. I have an integral that looks like $$\int^{x_f}_{x_i} \mathrm{d}x\, \exp{(ix)} \exp{(i\omega t(x))} \phi^*(x)$$ (* refers to complex conjugation).The $\exp{(ix)}$ is slowly oscillatory compared with everything else. The $x_i,x_f$ are negative; typical values might be $-115,-75$, the closer you get to $-4/3$ the more problematic things get, $x>x_h=-4/3$. Similarly the bigger $\omega$ gets the more oscillatory things are. The function $t(x)$ is $$t(x)=3x_h (x/x_h)^{1/3}+x-3x_h\text{arctanh}{\left((x_h/x)^{1/3}\right)}$$ and satisfies $$\frac{dt}{dx}=\frac{1}{1-\left(\frac{x_h}{x}\right)^{2/3}}$$ and $$\phi''(r)+\frac{2(r-1)}{r(r-2)} \phi'(r)+\left(\frac{\omega^2 r^2}{(r-2)^2}-\frac{2}{r(r-2)}\right)\phi(r)=0$$ where $r=2(x/x_h)^{2/3}$. So this can be transformed into an ODE in x. Is it possible using this information to construct the "DifferentialMatrices" and "Kernel" of the LevinRule? If this turns out not to be possible, is it possible to tell Mathematica to use LevinRule only in some finite range of integration where one of the above factors becomes non-oscillatory and I can lump it in the amplitude.


title: How can I get the unchanged Box form of an arbitrary expression?

text: One may observe that `MakeBoxes` does not give the actual Box form of various expressions:               MakeBoxes[{1*^4, 000123, a*b c}]      > >     RowBox[{"{", RowBox[{"10000", ",", "123", ",", RowBox[{"a", " ", "b", " > ", "c"}]}], "}"}] >   The `1*^4` was expanded, the leading zeros of `000123` were stripped, and the distinction between `*` and (space) was lost. Also, `MakeBoxes` doesn't like syntactically invalid or incomplete strings:               MakeBoxes[0001+`1,*^6*a b]      > Syntax::sntxi: Incomplete expression; more input is needed. How can one get the actual Box form visible with Show Expression (`Ctrl`+`Shift`+`E`) without copy & paste?


title: Problem with using the chain rule

text: I have the functions               w[x_] := x*Cosh[x]       and                x[a_] := n/k*a.       I take the derivative `D[w[x[a]], a]` and get > >     a*n^2/k^2*Sinh[a*n/k] + n/k*Cosh[a*n/k]. >   This is odd because I expected the result > >     n/k*(x*Sinh[x] + Cosh[x]). >   I know I can use replacement rules to achieve this but is there a direct way?


title: BoxWhiskerChart too slow on big datasets, how to speed it up?

text: I have very big dataset, with over 14 000 000 records. And maybe more! Each record consists of Data ( Real ) and Time ( integer ). I group records by time interval, resulting in 300 groups. In each group there are 70 000 records. I need to draw a `BoxWhiskerChart`. BUT, The system has frozen for 15 minutes. And then work is very slow. I think the reason this froze, is that I give it groups that are very large. But what can I do?


title: Visualizing the difference between two sequences (strings)

text: I'm trying to develop a way of comparing two sequences (probably originally text, such as text writing or source code, possibly converted to lists). As a familiar example, consider the revisions display for any typical SE question or the diff output from a command-line `diff`. I found a cool _Mathematica_ function called `SequenceAlignment` which looks promising:               text1 = ExampleData[{"Text", "ToBeOrNotToBe"}];     text2 = StringReplace[text1, {"s" -> "th"}]          (*      To be, or not to be,--that ith the quethtion:-- Whether 'tith nobler     in the mind to thuffer The thlingth and arrowth of outrageouth      fortune Or to take armth againtht a thea of troubleth, And by      oppothing end them? ...     *)      (lisp programming... :) Now:               sa = SequenceAlignment[text1, text2]      gives:               {"To be, or not to be,--that i", {"s", "th"}, " the que", {"s", "th"},      "tion:-- Whether 'ti", {"s", "th"}, " nobler in the mind to ", {"s", "th"},     "uffer " ...      which I want to convert to some kind of colored display. The best I've managed so far is this:                Reap[       If[Length[#] == 2,            Sow[Column[{Style[#[[1]], Red], Style[#[[2]], Green]}]],            Sow[Style[#, Black]]]          & /@       sa]      but it's not a pretty display: ![my attempt](http://i.stack.imgur.com/2R7Eb.png) How can I make this display look like a single piece of text with colored markup, like the SE revisions display? And would it be possible to process _Mathematica_ code as well - without evaluating said code first, obviously?


title: Globally loading packages while using a CellGroup as the default context

text: I have a notebook I wish to set up where the sections are conceptually related to each other. But, I wish to isolate them from each other programmatically, so that they do not interfere with one another. A built-in method of doing this is to set the default context to `CellGroup` so that each group of cells has its own context. However, each section relies on the same set packages, and because one of them is quite large, I do not wish to reload the packages for each section. An option is to put each section in its own context manually using `Begin` and `End`, but I would rather avoid that if possible. Ideally, though, I would like to be able to load the packages in their own separate section and elevate them to the `Global`` (or equivalent) context. Any thoughts on how this can be accomplished?


title: GridLines at TickPositions

text: How can I force the GridLines to be at the positions of the Tick marks? A simple code, `FrameTicks -> Automatic` and `GridLines -> Automatic` will do it, but not this code. The error must be in the function `myTickList`, but I didn't find it. Moreover, `AspectRatio -> 1` seems not to work... Result: ![enter image description here](http://i.stack.imgur.com/ilre0.jpg) Input-File data.dat:               3542228.204 5433969.188     3542221.426 5433999.371     3 1 2 0     40      The code of the notebook:               inffile = OpenRead["data.dat"];     x1 = Read[inffile, Number]; y1 = Read[inffile, Number];     x2 = Read[inffile, Number]; y2 = Read[inffile, Number];     n1 = Read[inffile, Number]; n2 = Read[inffile, Number];      m1 = Read[inffile, Number]; m2 = Read[inffile, Number];      diff = Read[inffile, Number];     grad = Pi/2-ArcTan[y2 - y1, x2 - x1];     winkel=grad*180./Pi;     If[winkel < 0.0, winkel = winkel + 360.0];     s1 = ToString["Drehung erfolgt um "]; s2 = ToString[winkel];      s3 = ToString[" Grad "]; str = StringJoin[s1, s2, s3];     Style[str, FontSize -> 35, Italic, FontFamily -> "Helvetica"]     iend = n1 + n2 + 1;     Do[xkoor[i] = x1 - n2*diff + (i - 1)*diff, {i, 1, iend}]     jend = m1 + m2 + 1;     Do[ ykoor[j] = y1 + m1*diff - (j - 1)*diff, {j, 1, jend+1, 1}]     xvals = Table[xkoor[i], {i, iend}];     yvals = Table[ykoor[j], {j, jend}];     ungedreht = Outer[List, xvals, yvals] // Flatten[#, 1] & ;          myTickList[min_, max_, seg_, shift_?NumericQ, phi_?NumericQ,        len_: 0.01] :=       Table[{i,         Rotate[Pane[Style[AccountingForm[i], LineSpacing -> {0, 12}],           FrameMargins -> {{shift, 0}, {0, 0}}], phi], {len, 0}}, {i,         If[Head[seg] === List, Union[{min, max}, seg],          Range[min, max, seg]]}]          r = RotationTransform[grad, {x1, y1}]; gedreht =       r[ungedreht];          sortiert = SortBy[gedreht, Last];          labelingfunc[v : {x_, y_, w_}, i_, ___] :=        Placed[Grid[{{"Pflock ", i}, {"Koordinaten",            AccountingForm[{x, y}]}}, Frame -> All, Alignment -> Left],         Tooltip];     g = BubbleChart[(Append[#, 1] & /@ sortiert), ChartElements -> \!\(\*     Graphics3DBox[SphereBox[{0, 0, 0}],     Boxed->False,     ImageSize->30,     Lighting->"Neutral",     ViewPoint->{0,      DirectedInfinity[-1], 0}]\),        ColorFunction -> Function[{x, y, r}, Lighter[Yellow, x]],        ChartLabels ->         Placed[Style[#, "Subsection"] & /@ Range[Length@sortiert], Center],        BubbleSizes -> {0.07, 0.07}, LabelingFunction -> labelingfunc,        AspectRatio -> 1, Frame -> True, GridLines -> Automatic,        FrameStyle -> {Thick, Thick, Thick, Thick},        GridLinesStyle -> Directive[Blue, Dashed, Thick],        FrameLabel -> {" Easting [m\!\(\*     StyleBox[\"]\", \"Subsubsection\"]\) ", " Northing [m] ", " ", " ",},        PlotLabel -> "Grid-coordinates",        BaseStyle -> {FontWeight -> "Bold", FontSize -> 24},        FrameTicks -> {{myTickList[Min[gedreht[[All, 2]]] - 40.0,            Max[gedreht[[All, 2]]] + 40., 20, 5, 0],           None}, {myTickList[Min[gedreht[[All, 1]]] - 40.0,            Max[gedreht[[All, 1]]] + 40., 20, 5, Pi/6], None}},        BaseStyle -> {FontWeight -> "Bold", FontSize -> 18},        ImageSize -> {800, 800}       ]


title: ESRI shape files

text: ESRI shape files (shp): importing the polygon data can yield a very large list. It is computationally intensive rendering the polygon. I have been trying to convert to `GraphicsComplex` by extracting all the vertices, indexing them and then specifying the polygon by the vertex index. However, the computational effort of removing duplicates (shared borders) seems to be computationally worse than the original issue (for the large input size of the list of vertices). Can someone advise me if there is a better way to work with these files? I am able to use them but not efficiently.


title: How could I get the value of y[t] at each specific interpolation point?

text: sol = NDSolve[{Derivative[2][y][t] + Sin[y[t]] == 0, Derivative[1][y][0] == 0, y[0] == 1},     y, {t, 0, 2}]      the above-mentioned differential equations can be solved by Numerical interpolated integrations at a series of discontinuous points, and the number of the points depends on the Integration methods selected by the NDSolve. My problem is that how I can obtain all these points selected because I want to get the specific value of `y[t]` at each interpolation point?


title: Multiplicative partition function

text: I am trying to create a multiplicative partition function that would generate something like               f[12]     (*{{2, 2, 3}, {4, 3}, {6, 2}}*)     f[24]     (*{{2, 2, 2, 3}, {2, 2, 6}, {4, 2, 3}, {8, 3}, {12, 2}, {4, 6}}*)     f[48]     (*{{2, 2, 2, 2, 3}, {2, 2, 2, 6}, {4, 2, 2, 3}, {2, 2, 12}, {2, 3, 8}, {2, 4, 6},      {4, 4, 3}, {6, 8}, {4, 12}, {3, 16}, {2, 24}}*)      I have got as far as               n = 30;     i = FactorInteger[n];     r = Range[Length[i]];     Join[{f = Flatten[Map[Table[i[[#]][[1]], {x, 1, i[[#]][[2]]}] &, r]]},     Transpose[{d = DeleteDuplicates[f], Map[n/d[[#]] &, Range[Length[d]]]}]]      but it is turning out to be more complicated than I thought. Is there a more efficient way of tackling this? # Update Have got a little further, but still missing some:               n = 48;     i = FactorInteger[n];     r = Range[Length[i]];     f = Flatten[Map[Table[i[[#]][[1]], {x, 1, i[[#]][[2]]}] &, r]];     p = Drop[Drop[DeleteDuplicates[Subsets[f]], 1], -1];     d = Split[Drop[Drop[Reverse[Divisors[n]], 1], -1]];     Drop[Map[Sort[Join[p[[#]], d[[#]]]] &, Range[Length[d]]], -1]


title: For[] or While[] can't be used inside Manipulate[]?

text: Here is a code sample that creates a control object which calculates the expressions inside `Maniplate` again and again and never stop (it's proved by the code in the note): _Sample 1:_               Manipulate[date = Table[0, {num}];      For[i = 1, i <= num, i++, date[[i]] = Sin[i]];(*Print@i;*)      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      `While` has the same problem: _Sample 2:_               Manipulate[date = Table[0, {num}]; i = 1;      While[i <= num, date[[i]] = Sin[i]; i++];      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      I know if I choose `Do`, the problem will no longer exist: _Sample 3:_               Manipulate[date = Table[0, {num}];      Do[date[[i]] = Sin[i], {i, 1, num}];      ListPlot[{date}], {{num, 2}, 1, 20, 1}]      Still, I know I can solve the problem if I throw the expression into `Module` if what I'm using is `For`: _Sample 4:_               Manipulate[Module[{i}, date = Table[0, {num}];       For[i = 1, i <= num, i++, date[[i]] = Sin[i]];       ListPlot[{date}]], {{num, 2}, 1, 20, 1}]      And…yeah, it doesn't work for the code above with `While`…: _Sample 5:_               Manipulate[Module[{j}, date = Table[0, {num}]; j = 1;       While[j <= num, date[[j]] = Sin[j]; j++];       ListPlot[{date}]], {{num, 2}, 1, 20, 1}]     (*This still creates a problematic control object*)      How to solve the problem with `While`? what actually happens inside `Manipulate`? what's the exact reason for the endless loop? * * * OK, the problem with _sample 5_ turns out to be a collaboration of _Sample 4_ and _Sample 5_ , before I run sample 5, a control object has been already created by _Sample 4_ (let's call it _Object 4_ below, and so we have _Object 5_ for _Sample 5_ ).I think the process should be like this: when `date = Table[0, {num}];` in _Sample 5_ is executed, it's tracked by _Object 4_ , and then `For[i = 1, i <= num, i++, date[[i]] = Sin[i]];` in _Sample 4_ is executed, so it is tracked by _Object 5_ …so this story tells us how important a good programing habit is…


title: Ordering vertices in GraphPlot

text: I'm new here, so forgive me if this question is not well-posed/duplicates an earlier question - although I've searched for similar questions without success. I'm trying to present a plot of connections between elements (correlations between student performance on a set of test questions, actually). It's something like (with options omitted):               test = {{1 -> 5, 1}, {4 -> 3, 3.6}, {6 -> 8, 1}, {2 -> 4, 2}, {2 -> 5,          2.5}, {5 -> 4, 0.9}, {7 -> 8, 2}, {3 -> 8, 1}, {8 -> 2, 1}};     GraphPlot[test, Method -> "CircularEmbedding", VertexLabeling -> True,       EdgeLabeling -> False]      ![Mathematica graphics](http://i.stack.imgur.com/pUnUZ.png) where the {1,2,3,...} are the labels for my questions. I want to order the vertices in ascending order (1,2,3,...), i.e. I want vertices with consecutive labels to be adjacent on the circle, like a clock - i.e. as in the image below, which I had to construct by making the connections more or less consecutive:               test2 = {{1 -> 2, 1}, {3 -> 4, 3.6}, {5 -> 6, 1}, {7 -> 8,      2}, {2 -> 5, 2.5}, {5 -> 4, 0.9}, {7 -> 3, 2}, {3 -> 8,      1}, {8 -> 2, 1}};     GraphPlot[test2, Method -> "CircularEmbedding", VertexLabeling -> True, EdgeLabeling -> False]      ![graphics2](http://i.imgur.com/uFOCu.jpg) Mathematica has its own ideas! It insists on ordering the vertices by the order in which it encounters them in the list of connections, (i.e. 1,5,4,3,...) in the above example. Sorting the list of connections doesn't fix this problem. This issue doesn't seem to be well documented. Any suggestions for a workaround? Thanks in advance!