How to 'merge' a list like FromDigits, but with a mixture of numbers and symbols?

How do I go from `{C,4,G,5,S,7}` to `C4G5S7`


What is the signature for a callback function for FinancialIndicators?

I'd like to write my own indicators to use with functions like `TradingChart`. From the context, it's clear that one needs to write a function whose parameters provide access to the underlying list of `"OHLC"` bars. Also, I don't know whether these indicator funtions are called after every bar is seen or just once. If the latter, then the list is sufficient but if the former, then there has to be another parameter that lets you know where you are.


Is it possible to Print expressions in reverse order?

Let's say I'm debugging a program step by step and want to `Print` some expressions (using ShowIt, for example). Is there a way to output the result of `Print` on top of already printed expressions instead of at the bottom?


Finding all shortest paths between two vertices

The built-in `FindShortestPath` and `GraphDistance` functions find the shortest path between two particular vertices in a graph. I can't think of a simple way to finding _all_ shortest paths between two vertices. Any ideas? My graph has weighted edges and the weights are arbitrarily large, so I'm dead against mapping weighted edges to many unweighted edges. **Motivation** : I have a graph of city traffic routes from point A to point B. I'd like to take the union of shortest paths from A to B to get a subgraph that, I posit, contains (many of) the most frequented intersections.


Manually accept elements of a list

Let's say I have a list like:               {"good element 1", "bad element 1", "good element 2", "good element 3", "bad element 2", ...}      I would like to build a function that will display each element of this list one at a time, and if I press the "left" key it will append the focus element to a list of "good" elements, whereas if I press "right" it will append it to another list of bad elements. Can Mathematica do this and with what kind of functions? I usually come up with a bit of code of my own but this time I really don't know with what functions to start from.


Ivar error with Fit inside Plot

I'm trying to plot this `Plot[Fit[med,{1,x},x],{x,0,10}]` Why this doesn't work? I find out that if I do `Plot[Evaluate@Fit[med,{1,x},x],{x,0,10}]` works fine. But can somebody explain me why this happens in first place?


Fit line similar to power of trendline in Excel

Is there a way to fit a line similar to `power` trendline in Excel? Something in this fashion: `Fit[data, {1, x, x^(-n)}, x]` EDIT:               modelFit = NonlinearModelFit[data, a*x^n, {a, n}, x];          Show[      ListPlot[data, PlotStyle -> Red],      Plot[modelFit[x], {x, 10, 300}]      ]      Gives a result which is a little off: ![enter image description here](http://i.stack.imgur.com/DjRaz.png) Data:               data = {{10, 0.229456252}, {11, 0.197084485}, {12, 0.190385018}, {13,      0.167211837}, {14, 0.162024048}, {15, 0.146360843}, {16,      0.141582714}, {17, 0.128658408}, {18, 0.12634757}, {19,      0.115664973}, {20, 0.112934492}, {21, 0.103436493}, {22,      0.101525578}, {23, 0.094280256}, {24, 0.093998465}, {25,      0.087612133}, {26, 0.085961964}, {27, 0.081235224}, {28,      0.079490311}, {29, 0.075953893}, {30, 0.073722495}, {31,      0.070194375}, {32, 0.069373963}, {33, 0.066115294}, {34,      0.064971653}, {35, 0.061982956}};


Printing a Dynamic variable inside Dynamic

I'm trying to `Print` the variable `a` inside the Dynamic wrapper. Seems like such a simple question, but I haven't been able to get it to work. Here's what I tried.               Dynamic[      mQ[n_] :=        75.63510582933174 - 35.87130621205199 n + 86.18343750838301 n^2 -         55.324190072519976 n^3;      mV[t_] := -29.619999999999976 + 5.499999999999998 t +         18.333333333333325 t^2;      a = xVariable + 2 - yVariable;      {Slider[Dynamic[n, Automatic]],         Dynamic[{n, xVariable = mQ[n]},          ContinuousAction -> False]} {Slider[Dynamic[t, Automatic]],         Dynamic[{t, yVariable = mV[t]}, ContinuousAction -> False]}]      I need to print the results of "a" I've updated the example code minus the plot to try and better explain the problem. I have tried the usual Print["a= ", Dynamic[a]] only to find it returns NULL or nothing at all. The variable is being calculated because it plots. So I believe the problem is more complex than I have explained above, and the issue now comes from the fact that the print statement must be closed with a ";" for the rest of the code in the Dynamic wrapper to run. That effectually keeps the print statement from writing to the nb. The code is long and complex but is many calculated variables that take input from dynamic sliders and then create a 3D plot. Debugging this has proved impossible when the variables that take input from the sliders are wrapped in Dynamic[]. Remove that and the variables do not get input from the sliders and their output can not be checked. I hope that helps to explain the problem better. Thanks for your help!


eccentric anomaly expansion equation

I try to use this simple algorithm (paper) to calculate the Eccentric Anomaly expansion:               a[0]=0;     Do [     t1 = 1-a[k-1]^2/2+a[k-1]^4/24;     t2 = a[k-1]-a[k-1]^3/6;     a[k]=Expand[e*Sin[u]*t1+e*Cos[u]*t2,Trig->True];     Simplify[a[k]];     TeXForm[a[k]] >>"tex.01";     Print [a[k],k], {k,2}]      The result should be this one ![from Paper](http://i.stack.imgur.com/lOQQR.png) but maybe because the algorithm is write with an old version of Mathematica I have as an output this different (in terms of trigonometric function) ![result](http://i.stack.imgur.com/nB7As.gif) How can I re-arrange it to have the one in the paper? And when I have the result of the paper is it possible, then, to regroup the equation in terms of power series of sin(u), something like that: ![equation](http://i.stack.imgur.com/ZMwBM.gif) Thanks a lot !


Plot graphs with ListPointPlot3D and different colours and size of points

Hello I am New in Mathematica. I have a set of points and I want to visualize in Wolfram Mathematica. I want to see big blue points and small green points in one picture. Big Blue points               {{0.35, 5.9709, -0.494276},       {0.25, 6.4709, -0.794276},      {0.3, 6.2709, -0.564276},       {0.3, 5.6709, -0.594276}}      Little Green points               {{0.3, -3.41212, -1.20591},       {0.4, -3.21543, -1.12591},       {0.4, -3.61472, -1.33312}}      I wrote the code, but it doesn't work               gg4 = ListPointPlot3D[{{0.35, 5.9709, -0.494276}, {0.25,          6.4709, -0.794276}, {0.3, 6.2709, -0.564276}, {0.3,          5.6709, -0.594276}}, PlotStyle -> {Blue, PointSize[0.04]}]     gg2 = ListPointPlot3D[{{0.3, -3.41212, -1.20591}, {0.4, -3.21543, \     -1.12591}, {0.4, -3.61472, -1.33312}},       PlotStyle -> {Green, PointSize[0.01]}]     Show[gg4, gg2]      I see 2 problems:   1. The function `Show` , shows date only from `gg4`   2. The `PointSize` function doesn't work. It is working, when I write `PlotStyle -> { PointSize[0.01], Green}` , but the colour function is not working in this case.


When should I, and when should I not, set the HoldAll attribute on a function I define?

I have seen a number of examples on this site (such as in syntax highlighting and checking evaluation status) in which functions definitions are preceded with               SetAttributes[f, HoldAll]      without comment, and even though it seems unnecessary for the specific task at hand. This leads me to believe that at least in some cases it is simply good practice to do so. Is that the case? If so, why? Are there instances in which it would not be the best practice? My understanding of the situation is that if, for example, I have `x=5` and then pass `1+x` to my function `f`, the argument as seen internally by `f` will still be represented as `1+x` instead of `6`. But it seems to me that in most cases if this were true I'd simply want to `Evaluate[1+x]` before proceeding. This would lead me to conclude that setting `HoldAll` would be the exception, not the rule. **Update:** My question is not whether the two examples I provided actually require `HoldAll` to work, but rather > How do I determine, when writing a new function, whether or not to set > `HoldAll` on it? What I am concerned about is the possibility of creating a function which behaves as desired without the `HoldAll` setting (or with it, for that matter) for the test cases I throw at it, but which misbehaves later if something else gets passed to it. What possibilities and issues must I consider to ensure I make the correct choice? What are explicit use cases for each of the two options?


Calibrating a difference equation system

Sorry for not posting it in the first attempt properly. Consider the simple problem of a first-oder difference equation:               RSolve[{s[t + 1] == e[t] + b*s[t], s[0] == s0}, s[t], t][[1, 1]]           where I like to use the solution in the FitModelenvironment to calibrate the paramter b for a sequence of exogenous variables e[t] and an initial value s0.


RevolutionPlot3D: Inconsistency between Mathematica 8/Linux and Mathematica 9/OSX

The following code runs error-free in _Mathematica_ 8.0 under Linux.               ClearAll["Global`*"];     x = RandomReal[{0.1, Pi}, 100];     g[t_] := x[[Ceiling[t]]]/Max[x]     RevolutionPlot3D[         {g[t] Sin[t]^2 + 1, t},         {t, 0, 5},                    (* see comment in 'EDIT' regarding the t=0 case *)         {θ, 0, 2 Pi}]      The same exact code produces the following errors when is executed in _Mathematica_ 9.0.1 under Mac OSX (copied by hand): > Part:pspec : Part specification Ceiling[t] is neither a machine-sized > integer nor a list of machine-sized integers.>>   >  General::stop : Further output of Part::pspec will be suppressed during > this calculation.>> **EDIT** : `g[0]` yields `0.32669List`, but changing the domain to say `{1,5}` does _not_ fix anything. Despite the errors an almost original image is produced. I used an evaluation monitor to check whether `g[t]` is properly calculated like:               ClearAll["Global`*"];     x = RandomReal[{0.1, Pi}, 100];     g[t_] := x[[Ceiling[t]]]/Max[x]     RevolutionPlot3D[         {g[t] Sin[t]^2 + 1, t},         {t, 0, 5},                    (* see comment in 'EDIT' regarding the t=0 case *)         {θ, 0, 2 Pi}, PlotPoints->3,  (* restrict points or else we will get flooded *)         EvaluationMonitor :> Print["t=", t, ", g[t]=", g[t]]]      The output I get is of the form: > ... Part::pspec : ...   >  t[2.5x10^-6, g[t]=0.40655   >  t[2.5], g[t]=0.811194   >  ... which looks ok. Finally, I don't think that my problem has to do with `RevolutionPlot3D[]` per se, but rather with the way I define and call `g[t]` in this context.


Input as an ordered pair instead of as a matrix

when I input pp = {{2.0, 10}, {4, 19}, {6, 31}, {8, 40}, {10, 51}, {12, 59}, {14, 70}} and press enter I get a matrix output. I want it as an ordered pair to find the best fit line, using Fit[pp,{1,x}x], which it does but when I plot the line and the try to plot the points mathematica interprets my data as a matrix and does not plot it. Why? Before I did this same method and was able to plot both the points and the line on the same graph. Please help anyone.


How does Mathematica solve eigenvalues?

I believe mathematica uses some techniques beyond our book. According to the text book it is not possible to solve eigenvalues of which the matrix has not completely eigenvectors, or of those matrix has cluster eigenvalues and multiple matrix yet not symmetric. How does mathematica solve that? On mathematica book they say they use interpolation for the characteristic polynomials, yet there are no thesis pertaining to this. I want to know the algorithm, how can I do so?


ParametricPlot3D[] Question

I know this is very similar to a previous question I asked, but there are some differences. When I graph:                ParametricPlot3D[      If[Part[RotationMatrix[-ArcCos[7/Sqrt[83]], {-5, 3, 0}] . {9*Cos[s]*      Sin[(Pi/7) t], 10*Sin[s]*Sin[(Pi/7) t],       11*Cos[(Pi/7) t]}, 3] < 21/Sqrt[83],       RotationMatrix[-ArcCos[7/Sqrt[83]], {-5, 3, 0}] . {9*Cos[s]*      Sin[(Pi/7) t], 10*Sin[s]*Sin[(Pi/7) t],       11*Cos[(Pi/7) t]}, {7*(Cos[s]) (7 - t)/7 + 5,       4*(Sin[s]) (7 - t)/7 + 5, t + 5}], {s, 0, 2 Pi}, {t, 0, (7/Pi)*Pi}]      I get: ![enter image description here](http://i.stack.imgur.com/RGABj.png) But I want to get a clean combination of:                 ParametricPlot3D[       If[Part[RotationMatrix[-ArcCos[7/Sqrt[83]], {-5, 3, 0}] . {9*Cos[s]*       Sin[(Pi/7) t], 10*Sin[s]*Sin[(Pi/7) t],        11*Cos[(Pi/7) t]}, 3] < 21/Sqrt[83],        RotationMatrix[-ArcCos[7/Sqrt[83]], {-5, 3, 0}] . {9*Cos[s]*       Sin[(Pi/7) t], 10*Sin[s]*Sin[(Pi/7) t],        11*Cos[(Pi/7) t]}], {s, 0, 2 Pi}, {t, 0, (7/Pi)*Pi}]      ![enter image description here](http://i.stack.imgur.com/a3ztu.png) (this picture should not have a scratchy top, I don't why it does, please help) and:               ParametricPlot3D[{7*(Cos[s]) (7 - t)/7 + 5, 4*(Sin[s]) (7 - t)/7 + 5,      t + 5}, {s, 0, 2 Pi}, {t, 0, (7/Pi)*Pi}]      ![enter image description here](http://i.stack.imgur.com/4I9vy.png) When I say combination, I want to be able to have an equation that represents the combination of both graphs which is able to manipulated (rotated, shifted,etc...). If I combine them using Show[] this is quite difficult, because Show[], is not an actual math equation that is manipulable. I especially want to be able to apply RotationMatrix[] to the resulting combination equation. Please help. Thank You.


Interaction of InputField with Row (but not Column, Grid or Panel)

In Mathematica 9, there's an interaction between `InputField` and `Row`. The following fragment (without or without `Module` and options):                 Module[{opts},          opts = { FieldSize -> 10, FieldHintStyle -> {Black},             Appearance -> Framed};          Row[           {InputField["", String, FieldHint -> "Field 1", opts],            InputField["", String, FieldHint -> "Field 2", opts],            InputField["", String, FieldHint -> "Field 3", opts]}]          ]      Will correctly output the row of input fields and correctly handle text entered in the first field chosen by the user (not necessarily "Field 1"), but tabbing to and entering text in next field is converted to input form. Whereas, removing `Row`, as in:               {InputField["", String, FieldHint -> "Field 1"],      InputField["", String, FieldHint -> "Field 2"],      InputField["", String, FieldHint -> "Field 3"]}      Results in correct operation (including tabbing across fields). Passing the above list to Panel, `Column` or `Grid` (make two sets lists) also works fine. Known issue?


Automatization of SyntaxInformation and argx?

Does anybody have a good way to automate the setting of SyntaxInformation for any custom function? I have a ton of functions for which I want to set SyntaxInformation, and doing it by hand seems a little pointless. Here's what I've come up with so far:               SetSyntaxInformation[symbol_Symbol] :=        Module[{argcounts, transposecounts, argpatt},        argcounts = With[{sym = symbol},          Cases[           DownValues[sym],           HoldPattern[Verbatim[HoldPattern][sym[args___]] :> _] :> CountArguments[args]           ]          ];        transposecounts = Transpose@PadRight[argcounts];        argpatt = ArgumentCountToPattern@Union[#] & /@ transposecounts;        SyntaxInformation[symbol] = {"ArgumentsPattern" -> argpatt}       ];          ArgumentCountToPattern[{1}]=_;     ArgumentCountToPattern[{0,1}]=_.;     ArgumentCountToPattern[{0,Infinity}]=___;          CountArguments[args___] := CountArgument /@ {args};     CountArgument[Verbatim[PatternTest][pat_, _]] := CountArgument[pat];     CountArgument[Verbatim[Pattern][_,(Verbatim[Blank] | _)[___]]] = 1;     CountArgument[Verbatim[Pattern][_,Verbatim[BlankSequence][___]]] = Sequence[1,Infinity];     CountArgument[Verbatim[Pattern][_,Verbatim[BlankNullSequence][___]]]=Sequence[Infinity];      This attempts to count the number of arguments for each downvalue of a given symbol, and turns this into a `"ArgumentsPattern"` type list which is subsequently set. Here's an example:               F[x_] := x^2     F[x_, y_] := x^2 + y^2          SetSyntaxInformation[F]     (* {"ArgumentsPattern" -> {_, _.}} *)      Although this seems to get the job done, the code seems a little bit unwieldy and might not be that robust, as it's certainly missing a few cases (like e.g. options). So my question is: is there any better way to tackle this problem? (And does anybody have something similar for setting argx messages?)


Cannot solve a system of 5 square-root simultaneous equeations

Solve[{274.6 = a*Sqrt[x + h] + c, 370 = a*Sqrt[x + h + 1000] + c,              159.3 = a*Sqrt[z + h] + c, 161.5 = a*Sqrt[z + h + 1] + c,              74.2 = a*Sqrt[1/12 + h] + c}, {a, x, h, c, z}]      > Set::setraw: Cannot assign to raw object 274.6`. Set::setraw: Cannot assign > to raw object 370. Set::setraw: Cannot assign to raw object 159.3`. > General::stop: "Further output of Set::setraw will be suppressed during this > calculation." Solve::naqs: c+a Sqrt[h+x]&&c+a Sqrt[1000+h+x]&&c+a > Sqrt[h+z]&&c+a Sqrt[1+h+z]&&c+a Sqrt[1/12+h] is not a quantified system of > equations and inequalities. >> > > Output Solve[{c + a Sqrt[h + x], c + a Sqrt[1000 + h + x], c + a Sqrt[h + > z], c + a Sqrt[1 + h + z], c + a Sqrt[1/12 + h]}, {a, x, h, c, z}] Any help would be much appreciated. I have tried using the double `==`, however that just gives me a blank output of > >     {} >


Changing face as you type in an expression in notebook

I've a Mathematica notebook for my class notes. When writing plain text in cells, I can dynamically bold and unbold with the ctrl+b shortcut. However, when in a mathematical expression, this shortcut only works when the selection to have its face changed is highlighted first (which slows workflow down). The same thing goes for italicizing and underlining. Is it possible to change face as you type in an expression? To illustrate, with plain text:   * ![enter image description here](http://i.stack.imgur.com/CLpZy.png)   * ![enter image description here](http://i.stack.imgur.com/0QSvU.png)   * ![enter image description here](http://i.stack.imgur.com/GZYhx.png) In an expression, have to type, then highlight text, then press ctrl+b:   * ![enter image description here](http://i.stack.imgur.com/KHZn7.png)   * ![enter image description here](http://i.stack.imgur.com/r79GK.png)   * ![enter image description here](http://i.stack.imgur.com/3UPTZ.png)


Selecting parts of a matrix via indices given by a vector

I have a column vector of the form $\\{1, 1, 2, 3, 2, 3\\}^t$ and an associated matrix that has the same number of rows as the column vector, $6$, and a number of columns that is equal to the maximum of the values in the vector, $3$. I would like to construct a matrix that has a specific value at the positions $\\{1, 1\\}, \\{2, 1\\}, \\{3, 2\\}, \\{4,3\\}, \\{5,2\\}, \\{6, 3\\}$ and zeroes everywhere else, that is, the row index corresponds to the row index in the column vector and the column index corresponds to the value at that row index. A solution using a loop is clear to me, is there also a nifty Mathematica trick that does the job?


What does DisplayFunction->Identity do to graphics functions?

Does `DisplayFunction->Identity` do anything at all in Mathematica 8? In the third edition of _Programming in Mathematica_ , Roman Maeder gives the following explanation: > The option setting `DisplayFunction->Identity` causes the graphics functions > `Plot[]`, `Plot3D[]`, `ParametricPlot[]`, and so on to generate the graphics > in the normal way, but not to render the images. We use it if we want to > manipulate the graphics further. Afterwards, we can render the images with > `Show[graphics,DisplayFunction->$DisplayFunction]`. He is referring to the following piece of code:               z = x + I y;     cz = {Re[z], Im[z]};     vlines = Table[ N[cz], {x, -Pi/2, Pi/2, Pi/12} ];     vg = ParametricPlot[ Evaluate[vlines], {y, -1, 1}, DisplayFunction -> Identity ][[1]]      `SameQ` tells me that even without `DisplayFunction->Identity`, I will still get the same result for `vg`. Is Maeder's precaution no longer necessary in Mathematica 8?


Evaluation of a large integral

I have a complicated large integral I want to evaluate (does not have a closed form, need an approximation), but _Mathematica_ seems to keep "Running...". Is there any way to make _Mathematica_ use more CPU power or anything to speed the calculations up? The integral is the following:               Integrate[x (0.25 - x)^0.5*1/(Integrate[(1 - ((2 x/(1 - 2 x))*       Cos[z])^2)^0.5, {z, 0, Pi}])*Sin[y]*       (1 - ((2 x/(1 - 2 x))*Cos[y])^2)^0.5, {x, 0, 0.25}, {y, 0, Pi}]      Also, how long should I expect this to take? Thank you for any help!


System of integral equations with integrals on both sides

I'd like to solve the following equation numerically for $a_1$, $a_2$, $\alpha_1$ and $\alpha_2$: $\displaystyle\int_0^{\infty}\Big[L_1\Big(\frac{k^2}{2}\Big)\Big]^2e^{-k^2}L_m(k^2)\ dk=$ $\displaystyle\int_0^{\infty}\bigg(1+\frac{k\cdot a_1}{2\alpha_1}e^{-\frac{k^2}{4\alpha_1}}-\frac{k\cdot a_2}{8\alpha_2}e^{-\frac{k^2}{4\alpha_2}}\Big(\frac{k^2}{\alpha_2}-4\Big)\bigg)e^{-k^2}L_m(k^2)\ dk\ \ \ \text{for}\ \ m=1,3,5,7$ where $L_m(x)$ is the Laguerre polynomial. Is there a nice way to do this in mathematica? Naively I've tried `FindRoot` and `Solve`, but run into all sorts of trouble. I guess looking into some approximations could do it, just wanted to check if there is an (more or less) obvious way first.


How to Solve a Sequence in Mathematica

Given the input and the output, how do you interpolate a function in _Mathematica_? For example if you know that $f(1)=\frac{1}{2}$, $f(2)=\frac{1}{3}$, $f(3)=\frac{1}{4}$,... how would you solve for $f(n)$ I guess what I am really asking is how would one solve a sequence in _Mathematica_?


dynamically set fit parameters and models with FindFit

I want to fit a gaussian profile by setting some values dynamically, but `FindFit` returns an error and i can't see the problem. with a given gaussian:               gauss = Table[{x,      E^(-((x - 10)^2/(2 3^2))) + RandomReal[{-0.05, 0.05}]}, {x, 0, 20,      0.05}];      I set the model to:               gaussmodel = b Exp[-((x - d)^2/(2 g^2))];      With fitparameters set non-dynamically everything is fine:               fit = FindFit[gauss, gaussmodel, {{b, 1}, {d, 10}, {g, 3}}, x]     (*{b -> 1.00439, d -> 10.0109, g -> 2.9804}*)      Now I want to set the startingvalues as following:               InputField[Dynamic[startvalueb], Number]     InputField[Dynamic[startvalued], Number]     InputField[Dynamic[startvalueg], Number]     Checkbox[Dynamic[bool1]]          xx0 = {Dynamic[        Which[bool1 == True, {b, Dynamic[startvalueb]}, bool1 == False,          Null]], Dynamic[        Which[bool1 == True, {d, Dynamic[startvalued]}, bool1 == False,          Null]], Dynamic[        Which[bool1 == True, {g, Dynamic[startvalueg]}, bool1 == False,          Null]]}      witch returns just the form I need, but maybe not??!? Anyway               fi2 = FindFit[gauss, gaussmodel, xx0, x]      returns the following error:               FindFit::vloc:The variable {b,1} cannot be localized so that it can be assigned to numerical values.>>      What can I do to fix this?


Pure function in Nest

I can't figure out what I'm doing wrong here:               Table[Nest[# + 0.1 * -i *  #^2 &, 2, 1] , {i, 0, 0.5, 0.1}]     (* {2., 1.96, 1.92, 1.88, 1.84, 1.8} *)      The problem is that it keeps using 2 in the argument instead of the last result. Normally the first parameter is the starting point, when using the pure function. The output should be something like               (* {2., 1.96, 1.883, 1.777, 1.651, 1.514} *)


Mathematica 10 hangs when modifying plots/themes from Suggestions bar

I am using _Mathematica 10_ on a computer running _Windows 7 (64-bit)_ with all the most recent updates from _Microsoft_. My problem is as follows:   1. I create a plot using the `Plot[]` function.   2. When I click on the plot, the _Mathematica_ suggestions bar appears under it, with items like `theme ..`, `labels ..`, `axes`, `image size`, `more`.   3. If I click on `theme`, `labels` or `axes`, _Mathematica_ hangs.   4. If I click on `more`, a more detailed menu opens up underneath the plot, containing the same menu items (plus a few more). If I then click on `theme` or `label` or `axes` in this larger menu, _Mathematica_ again hangs. By "hang" I mean that _Mathematica_ becomes unresponsive. CPU usage maxes out at near 100% (for one core of my CPU). I have waited as long as 15 minutes, but nothing changes, the program continues to be unresponsive. At this point, I can only close and restart _Mathematica_ through _Task Manager_. Here is a screenshot showing the `theme` and `labels` buttons that make _Mathematica_ hang up when clicked. I have circled them in red: ![](http://i.imgur.com/GPIWSwH.png) Here is a screenshot showing the _Windows_ ' "Application has become unresponsive" notice: ![](http://i.imgur.com/5jsQ4Mm.png) I have tried resetting the _Mathematica_ interface by holding down the `Ctrl` and `Shift` keys while starting _Mathematica_. This resets the interface all right, but the hanging problem persists. **Can anyone reproduces it?** Any help is much appreciated!


How to export attributes or annotations to an HDF5 file?

I'm trying to export attributes and annotations to an HDF5 file. But the documentation here is horrible and there are no examples of this. I spent some time playing, but I can't get it to work. Here is the simplest example that should have helped me to get started:               Export["test.h5", {{{1, 2}, {2, 3}}, {{10, 11}, {12, 13}}}, {"Datasets", {"m1", "m2"}}]     r = Import["test.h5", "Rules"]     Export["test1.h5", r, "Rules"]      but it fails with: > >     Export::errelem: The Export element Dataset1 contains a malformed data > structure and could not be exported to HDF5 format. >> >     Export::noopen: Cannot open C:\Users\ajasja\Documents\test1.h5. >> >   So my question is: **How can one export attributes with datasets?** (preferably using built in _Mathematica_ functionality) **EDIT** For reference here are some external MMA HDF5 packages that might provide the required functionality, but I have not yet managed to write any attributes:   * HDF5WrappersForMathematica Uses .NET libraries to implement all the HDF5 calls   * H5DumpImport which works through ascii dump files   * h5mma which is a C implementation (but has read-only functionality)


Performance of compiled functions (Project Euler No14)

I was playing around with the project euler problem 14. The solution I came up with is listed below as `cf1`. The solution works fine but I get the compiler warning:               Compile::cset: Variable max of type _Integer encountered in assignment of type _Real.      I don't get this message at all since the only assignment of max is `max=l` while `Head@l == Integer`. This error can be fixed by substituting with `max=Round[l]`. Any ideas?               cf1 = Compile[{}, Module[{l, max = 0, maxN = 0},       Do[        l = Length[NestWhileList[If[EvenQ[#], #~Quotient~2, 3 # + 1] &, n, # != 1 &]];        If[l > max, max = l; maxN = n];        , {n, 1, 10^4}];        {max, maxN}       ]];     cf1[] // Timing          {6.349241, {262, 6171}}      I also found a solution with much better performance listed below as `cf2`. Is it just that `NestWhileList` doesn't compile very good or is there another reason why this solution is so much faster?               cf2 = Compile[{}, Module[{n1, l, max = 0, maxN = 0},       Do[        n1 = n;        l = 1;        While[n1 != 1, n1 = If[EvenQ[n1], n1~Quotient~2, 3 n1 + 1]; l++];        If[l > max, max = l; maxN = n];        , {n, 1, 10^4}];        {max, maxN}       ]];     cf2[] // Timing          {0.374402, {262, 6171}}


Speeding up a simple simulation with random extractions

I wonder if anybody can help, I need a hand with a simple simulation I am writing with Mathematica (I am using version 8). Basically it creates a list (called l) with numbers from 1 to n and a random number v in the same interval. Then it draws a random number s from l and checks if it is equal to v. If s is not equal to v, that number is dropped from l and another s is drawn and so on, the cycle stops when s=v. The number i is used to count the draws and the list k to show all the i's. Here is the code with n=5000 and 5 runs               n = 5000;     runs = 5;     (* initialization *)     k = ConstantArray[0, runs];     Table[      {v = RandomInteger[{1, n}];       s = 0;       i = 0;       l = Range[1, n];       While[s != v,         s = RandomChoice[l];        p = Flatten[Position[l, s]];        l = Drop[l, p];        i = i + 1;];       k[[j]] = i}      , {j, 1, runs}]     k      The problem is I would like to run thousands of simulations with n raging from 30000 to 50000, but this code is way too slow. Is there a way to speed it up?


Cover a rectangle with size constrained rectangular regions

I have a big grid (indicated on the image in grey) that is divided in several blocks (each with a maximum width of 3 units). Now I would like to divide a region (indicated on the grid in red) by the corresponding blocks. ![enter image description here](http://i.stack.imgur.com/Ii9sO.png) To give an example, I would like the 'block regions' (represented {X,Y,Width,Height}): A: {2,3,2,1} B: {4,3,3,1} C: {7,3,1,1} D: {2,4,2,3} ... The only information that I have is the size of the blocks in the grid (in this case 3) and the dimensions of the region: {2,3,6,5} (= {X,Y, width, height}) Does anybody know how to do this in an efficient way? I thought about the use of mround to calculate the first boundaries of the blocks, but that lead to a dead end. Thanks in advance!


Product of edge weights in path

I need to calculate the product of graph edge weights on the path taking into account edge direction. I.e. for graph               g={1->2,2->3,1->3};     ew={2,3,4};     Graph[g,EdgeWeight->ew]      for path 2->1->3 we should get 4/2=2 for path 1->2->3 we should get 2*3=6


How could I make a drawing canvas?

My question is related to Change all Options of Plot Dynamically where _Mathematica_ remembers the series of changes in the appearance of a drawing using `Plot` or similar commands like `ParametricPlot` etc. I would like to generalize my question: I want to use the `Show` command for making a nice drawing. I am going to use `Plot`, `ParametricPlot`, `ListPlot`, `Graphics`, etc., so I need   1. a popup menu with these commands    2. An `InputField` for the data or functions or graphics primitives to be ploted and    3. a popup menu with the corresponding options. For example, if I select `ParametricPlot` then I will take the list of options for this command. The series of changes in the drawing have to be "recorded" so that the user could make any possible adjustments at any time! How would I build such a canvas on which the plots can be added and modified step-by-step?


Counting sublists containing 0

Given a list: `data = {{0, 2}, {0, 0}, {1, 0}, {1, 2}, {2, 3}}`. I would like to count the number of sublists which contain zero.               Count[data, {0, _}] + Count[data, {_, 0}] - Count[data, {0, 0}]      Is there any better/efficient way to do this?


FindHamiltonianCycle is not invariant to edge permutation

Found this bug-like behaviour today: if the order of edges is changed so that `VertexList` does not return the vertices in canonical order, `FindHamiltonianCycle` is not always able to find the Hamiltonian cycle, that is obviously there.               edges = {1 -> 2, 2 -> 3, 3 -> 1, 1 -> 3, 3 -> 4, 4 -> 1};     g1 = Graph[edges, VertexLabels -> "Name", ImagePadding -> 10];     g2 = Graph[RotateLeft@edges, VertexLabels -> "Name", ImagePadding -> 10];          {g1, FindHamiltonianCycle[g1, All], VertexList@g1}     {g2, FindHamiltonianCycle[g2, All], VertexList@g2}      ![enter image description here](http://i.stack.imgur.com/YkGZv.gif) ![enter image description here](http://i.stack.imgur.com/MBJip.gif) If a vertex list is specified, that might help, but not always:               g3 = Graph[{1, 4, 2, 3}, RotateLeft@edges, VertexLabels -> "Name", ImagePadding -> 10];     g4 = Graph[{4, 1, 3, 2}, RotateLeft@edges, VertexLabels -> "Name", ImagePadding -> 10];          {g3, FindHamiltonianCycle[g3, All], VertexList@g3}     {g4, FindHamiltonianCycle[g4, All], VertexList@g4}      ![enter image description here](http://i.stack.imgur.com/oAjZD.gif) ![enter image description here](http://i.stack.imgur.com/IPzOz.gif) Is this a bug? If so, at least it is consistent with `HamiltonianGraphQ`:               HamiltonianGraphQ /@ {g1, g2, g3, g4} ==> {True, False, True, False}      _Mathematica_ 9.0.1, Windows 7, x64.


creating some smooth density functions

I would like to create some density functions based on some distance measure $D$. As a base density function lets say I have a Gaussian density $f$ with mean $-1$ and variance $1$. I would like to create some smooth and nice density functions $g$ randomly which are at least $\epsilon$ close to my base density $f$. The set of all possible densities can be written down as $${\cal{F}}=\\{g_0: D(g,f)\leq \epsilon\\}$$ with $$D(g,f)=\int_{-\infty}^\infty g(y)\log \left(\frac{g(y)}{f(y)}\right)\mathrm{d}y$$ and since $g$ are densities, we also have additionally $$\int_{-\infty}^\infty g(y)\mathrm{d}y=1,\quad g(y)>0 \quad\forall y$$ How can I create such $g$ functions in Mathematica? is there a simple way? Thank you very much for reading this post and thanks in advance for any help.


Separating disconnected graph objects without losing vertex coordinate assignments

Say I have a graph `Gtest`, which has multiple disconnected components. I found that I can isolate individual components while retaining vertex coordinate specifications if I use `VertexDelete` in the manner of:               VertexDelete[Gtest, ConnectedComponents[Gtest][[2]]]      Here assuming that `Gtest` has only two connected components. However, this seems like a ridiculous way of proceeding. Is there a one-liner that will let me make a list of graphs `Glist = {g1, g2, g3, ...}` where each $g_i$ corresponds to a particular connected graph in `G`? How can I do this while respecting my original vertex coordinate assignments for `G`?


Change all values of a series to positive values

I would like to change all values of a series to positive values. I refer to my previous question, answered in the most part, very elegantly by RunnyKine. However, there remains a slight glitch that I can't seem to overcome:               expr1 = x + (2 x^2)/y - (3 x^3)/y^2;     expr1 /. {Times[-1, c_] :> Times[1, c], Rational[-1, d_] :>      Rational[1, d], n_?Negative :> -1 n}      gives:               x + 2 x^2 y + 3 x^3 y^2      I can't seem to fathom where the missing '/' has gone from between the x & y values.


How to pick a solution from a list of solutions using a test?

I have a list of solutions that depends on a parameter `b3` and I'd like to get the solution for which the `x` value is minimal when the parameter value is substituted. for example:               b3 =.;     f[x_] := x^2 - b3     solutions = Solve[f[x] == 0, x]      > >     {{x -> -Sqrt[b3]}, {x -> Sqrt[b3]}} >   I'm trying to get the element for which `x/.element` is minimal (which should be `b3`-depended). I started with:               f[x_] := x^2 - b3     solutions = Solve[f[x] == 0, x]     minsol := Pick[solutions, x /. solutions, Min[x /.solutions]]     pickminimum = minsol /. {b3 -> 2}      but when trying the above I got: > >     Pick::incomp: "Expressions {{x->-\[Sqrt]b3},{x->\[Sqrt]b3}} and > {-\[Sqrt]b3,\[Sqrt]b3} have incompatible shapes." >     Pick::incomp: "Expressions {{x->-\[Sqrt]2},{x->\[Sqrt]2}} and > {-\[Sqrt]2,\[Sqrt]2} have incompatible shapes" >   Then I tried to remove the extra `{}`:               f[x_] := x^2 - b3     solutions = Solve[f[x] == 0, x]     minsol := Pick[((#[[1]]) & /@ solutions), x /. solutions, Min[x /. solutions]]     pickminimum = minsol /. {b3 -> 2};      for which I got: > >     Rule::argr: Rule called with 1 argument; 2 arguments are expected >     Rule::argrx: Rule called with 0 arguments; 2 arguments are expected. >   Trying just to see if it works for some list, also got me nowhere:               f[x_] := x^2 - b3     solutions = Solve[f[x] == 0, x];     minsol := Pick[{1, 2}, x /. solutions, Min[x /. solutions]]     minsol /. {b3 -> 2}      > >     {} >   I think I understand why I get the first error - but I have no idea why the second/third won't work. **clarification** I'd like to have an expression for any value of b3. this is because later I'm interested at various quantities which are related to this point for many values of b3 (for example draw the first derivative of this 'minimal point' as a function of b3). so I'm less interested in a solution for a particular value of b3


Interpolate throughout a 3d data list without extrapolation

I have a 3D list of data for which I'd like to plot an interpolated surface. There are several ways to achieve this, but none I cannot find a method which ONLY plots the ENTIRE interpolated surface without extrapolating at all. I have to use a substantial list of data to demonstrate, so I've uploaded it on dropbox. I hope this is okay. I'm enthusiastically open to suggestions of other ways to link to the data. It does seem to import properly on my system (Mathematica 9.0.0.0 on XP SP3):               hcp = Import[           "https://www.dropbox.com/s/a10if7ek4ako5q2/example.dat?dl=1", "TSV"];     data = {Most[ToExpression[#]], Last[ToExpression[#]]} & /@            DeleteDuplicates[hcp];     int = Interpolation[data, InterpolationOrder -> 1]     Show[           Plot3D[int[x, y], {x, -.807372, -.586589}, {y, .31889, .393084}],           ListPointPlot3D[hcp]     ]     Show[           ListSurfacePlot3D[hcp],           ListPointPlot3D[hcp]     ]     Show[           ContourPlot3D[           z == int[x,            y], {x, -.807372, -.586589}, {y, .31889, .393084}, {z, -.3, 1},            RegionFunction ->            Function[{x, y, z},            Sqrt[2] + 4 Sqrt[3] (z - .204124) >= 0 &&            4 Sqrt[3] (z - .204124) <= 3 Sqrt[2] + 8 Sqrt[6] (x + .57735) &&            4 Sqrt[3] (Sqrt[2] (x + .57735) + (z - .204124)) <=            3 Sqrt[2] (1 + 4 y) &&            4 (Sqrt[6] (x + .57735) + 3 Sqrt[2] y + Sqrt[3] (z - .204124)) <=           3 Sqrt[2]]],           ListPointPlot3D[hcp]     ]      The following plots are then generated: ![enter image description here](http://i.stack.imgur.com/st6kz.jpg) As you can see, `Plot3D` of the `Interpolation` does well within the range of the data, but extrapolation always occurs. I want to either avoid extrapolation by specifying variable domains, or to just clip the surface along the edges of the data. ![enter image description here](http://i.stack.imgur.com/L8GLz.jpg) As you can see, `ListSurfacePlot3D` also does a decent job within the data domain, but issues inevitably arise along the edges, where it either extends 'square flaps' well outside the data, or stops short of the data edges. ![enter image description here](http://i.stack.imgur.com/oAvAg.jpg) Finally, `ContourPlot3D` is similar to `Plot3D` in that extrapolation outside the data occurs, which I don't want. In the example I've specified a `RegionFunction`, so that the surface is clipped within a tetrahedral shape. Perhaps I need an automated way to find the outer {x,y} boundary of the data, and then use that function as a `RegionFunction`. I neither know how to do that, nor know how to find out how to do that. **EDIT:** A similar question was asked in ListSurfacePlot3D[] generates ugly artifacts ... I've tried to apply the method of that solution to my data (which I've reformatted and uploaded as a different file):               hcp = ToExpression[        Import["https://www.dropbox.com/s/a7nwxz24a9hjaqb/example2.dat?dl=1", "TSV"]];     Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"];     fu[k_InterpolatingFunction, p_] :=       k[p (Length @@ InterpolatingFunctionCoordinates[k] - 1) + 1]     t = Append[#, First@#] & /@         Transpose@         Table[{fu[Interpolation[#[[All, 1]]], p],              fu[Interpolation[#[[All, 2]]], p], #[[1, 3]]} & /@ hcp, {p, 0,            1, .05}];     s = BSplineFunction[t];     ParametricPlot3D[s[u, v], {u, 0, 1}, {v, 0, 1},       PlotStyle -> {Orange, Specularity[White, 10]}, Axes -> None,       Mesh -> None]     t = Transpose@        Table[{fu[Interpolation[#[[All, 1]]], p],             fu[Interpolation[#[[All, 2]]], p], #[[1, 3]]} & /@ hcp, {p, 0,           1, .05}];     s = BSplineFunction[t];     Show[      ParametricPlot3D[s[u, v], {u, 0, 1}, {v, 0, 1},        PlotStyle -> {Orange, Specularity[White, 10]}, Axes -> None,        Mesh -> None],      ListPointPlot3D[t,        PlotStyle -> {Black, Red, Orange, Yellow, Green, Blue, Purple, Gray}]      ]      Which generates this figure: ![enter image description here](http://i.stack.imgur.com/tXXzd.jpg) This again fails to interpolate over the entire data range (the `SplineKnots->"Clamped"` option does not change this), and it also introduces strange zig-zag surface features, which I'm not sure how to smooth. In the example I'm emulating, each sub-list of "z=constant" data was connected to its neighboring sub-lists by smooth interpolated surfaces. Is the nature of my data spoiling the `BSplineFunction`, or can this be rectified? **EDIT:** The Non-Grid Interpolation Package at... http://library.wolfram.com/infocenter/MathSource/7760/ ...also comes very close to what I want. It is good at non-grid 3D interpolation which does not extrapolate outside the data. After running that package I use the commands:               hcp = ToExpression[        Import["https://www.dropbox.com/s/a7nwxz24a9hjaqb/example2.dat?dl=1", "TSV"]];     ?NonGridInterpolation`*     hcpf = DelaunayTriangulationPiecewiseLinear[      ProcessDuplication[Flatten[hcp, 1]]];     Show[      Plot3D[hcpf[x, y], {x, -1, 0}, {y, -.5, .5}],      ListPointPlot3D[hcp, PlotStyle -> Black]     ]      Generating this figure: ![enter image description here](http://i.stack.imgur.com/KIQvz.jpg) By reformatting the data it is possible to have the surface extend to the points not reached in the current example (on the left side in the figure). This does a good job at 3D interpolation without extrapolation. Notably, the `ProcessDuplication` function is used for duplicate abscissa {x,y} data, which it handles by simply taking the average {z} value for the repeated points. Unfortunately, I got what I wished for in that the package interpolates over the entire dataset. As you can see, the concave curvature of my data (on the right side in the figure) is bridged over by the interpolating surface. I haven't had luck in working around this. This package would nevertheless represent the best solution for the problem as I stated it.


Why the difference?

When I do the double sum using the sigma notation I get $$1 + \sum_{n=0}^{\infty}\sum_{k = n}^{\infty} \frac{1}{(k+2)k!}$$ $1 + e - \cosh[1]$ When I do the sums as below, I get the expected answer.               1 + Sum[Sum[1/((k + 2) k!), {k, n, Infinity}], {n, 0, Infinity}]        $e$ Why the difference? **Edit** for those who might like to see the only identity I could find:               Defer[1 + Sum[Sum[1/((k + 1)! + k!), {k, n, Infinity}], {n, 0, Infinity}]]


Controlling what is plotted in a multi-curve plot

My question is on trying to cut off certain plots within a `Plot` with multiple expressions being plotted. I want to be able to stop the two dashed- line plots at their point of intersection, without affecting how the other two plots are rendered. Please see the image below: ![Example Plot](http://i.imgur.com/wx4Yuba.jpg) Is there a way to limit the plotting range to a certain value for some of the expressions, but not the others? Again, I want the two dashed lines to stop plotting at the point where they intersect. This image shows 4 different plots: two quadratic functions that are offset by 1 and -1, a straight line, and a parabolic function. EDIT: Code included:               \[Lambda]1 = N[Table[(2 m - 1)/2*\[Pi], {m, 1, Nterms}]];     \[Theta][1][\[Eta]_, \[Xi]_, Nterms_] := 1 - 2 \!\(     \*UnderoverscriptBox[\(\[Sum]\), \(m = 1\), \(Nterms\)]\(     \*FractionBox[     SuperscriptBox[\((\(-1\))\), \(m +             1\)], \(\[Lambda]1[\([\)\(m\)\(]\)]\)] Cos[\ \[Lambda]1[\([\)\     \(m\)\(]\)]*\[Eta]]*Exp[\(-4\)*     \*SuperscriptBox[\(\[Lambda]1[\([\)\(m\)\(]\)]\), \(2\)]\ \[Xi]]\)\)          Manipulate[      Rotate[       Plot[        {         a (η - 1)^2,         a (η + 1)^2,         xL + 0.2*θ[1][η, ξ, Nterms],         xL         },        {η, -1, 1},             PlotRange -> {0, 1},        Filling -> {3 -> xL},        PlotStyle ->         {          {Thick, Dashed, ColorData[1, 2]},          {Thick, Dashed, ColorData[1, 2]},          {Thick, ColorData[1, 1]},          {Thick, ColorData[1, 2]}         },        AspectRatio -> 1.5        ]       , rotateAngle],           {ξ, 0, 0.1},      {xL, 0, 1},      {{a, 1}, 0, 1},      {{rotateAngle, -Pi/2}, {0, -Pi/2}}      ]      EDIT: A solution with Show and 3 Plots, but I would prefer a more elegant way to do this inside of one Plot command:               Manipulate[      Rotate[Show[        Plot[{a (\[Eta] - 1)^2}, {\[Eta], 0, 1},         PlotRange -> {{-1, 1}, {0, 1}},          PlotStyle -> {Thick, Dashed, ColorData[1, 2]}, AspectRatio -> 1.5],             Plot[{a (\[Eta] + 1)^2}, {\[Eta], -1, 0},         PlotRange -> {{-1, 1}, {0, 1}},          PlotStyle -> {Thick, Dashed, ColorData[1, 2]}, AspectRatio -> 1.5],             Plot[         {xL + 0.2*\[Theta][1][\[Eta], \[Xi], Nterms], xL}, {\[Eta], -1, 1},         PlotRange -> {0, 1}, Filling -> {1 -> xL},          PlotStyle -> {{Thick, ColorData[1, 1]}, {Thick, ColorData[1, 2]}},         AspectRatio -> 1.5]        ], rotateAngle],           {\[Xi], 0, 0.1},      {xL, 0, 1},      {{a, 1}, 0, 1},      {{rotateAngle, -Pi/2}, {0, -Pi/2}}      ]      ![Imgur](http://i.imgur.com/3ZzL4H9.jpg)


Proper Filling of Self-Intersecting Polygon

I have a spiral pattern that I would like to fill, which self-intersects. My desired behavior is to have filling between neighboring lines only, and to represent this figure as a single polygon. The default behavior is somewhat different, producing an alternating color pattern: ![enter image description here](http://i.stack.imgur.com/H3S2i.png) The outer parts of the spiral are filling properly (only between the neighboring line), but the inner parts are not. There is probably a particular ordering of points that can be passed to Polygon that would produce the desired behavior, but I am not sure how to accomplish that. The data is here, here's the code I use to currently generate the figure:               bhpl = Graphics[{Black, Circle[{0, 0}, 3.22823*10^11]}];     streampl = Graphics[{Red, Polygon[polydat]}];     Show[streampl, bhpl,        PlotRange -> {{-9.68468*10^11, 9.68468*10^11}, {-6.45645*10^11, 3.22823*10^12}}


Account for powers of 0 and 1 when defining function

I have a function that I am defining as (assume m,n,a,b are non-negative integers):               myfcn[x_^m_ p_^n_, x_^a_ p_^b_] := basefcn[m, n, a, b];      and then extending to all polynomials by linearity. The way I defined the function above works as long as m,n,a,b are all greater than 1, but fails otherwise. For instance, I want `myfcn[x p^2, p]` to evaluate to `basefcn[1,2,0,1]`, but mathematica does not recognize that this is what I want. How do I extend my function definition to include these cases without explicitly writing out all possible input forms? Thanks.


How draw dynamic empty rectangle over a bitmap?

I am trying to make a cookie cutter that will extract a small square from a much larger bitmap with a click of the mouse. The `LocatorPane` appears to be a useful way to move the cookie cutter around, but I'm not having much luck in drawing the small dynamic rectangle over the bitmap. I would like to change the appearance of the locator icon to a small rectangle, or just make the locator icon disappear. The `LocatorPane` option `Appearance -> Graphics[Rectangle[]]` didn't work. Beyond that there is the question of how to capture a point value with a mouse click. This is my first use of `Dynamic`. I suspect I am going about this all the wrong way and perhaps I should be doing something with mouse functions and cursor images. If so, I would appreciate it if someone would point me towards a pertinent page or two. I have not been able to find one. This script draws the locator on a bitmap labeled "background":               Clear[background]

         background = Image[Graphics[{LightGray, Rectangle[]}]];     DynamicModule[
    {pt = {180, 180}},
     LocatorPane[Dynamic[pt], background]
    ]      But when I add code for the dynamic rectangle, I find that it draws outside the background bitmap.
DynamicModule[
{pt = {180, 180}},
        {LocatorPane[Dynamic[pt], background],
        Graphics[
          {EdgeForm[{Thick, Red}],
           FaceForm[],
Rectangle[Dynamic[pt]]}
        ]}
       ]


How can I find lines of a certain angle(s)?

`ImageLines` implements the Hough transform, but how do I search for only lines within some threshold of a certain angle(s)?


Is there a way to continuously update only *some* variables in Manipulate?

I have a Manipulate control, the main element of which is a single slider. Moving the _one_ slider triggers calls to _two_ functions - one which is evaluated very quickly, the other more slowly. I'd like to see 'live' update ( i.e. ContinuousAction->True ) for the fast one, but would only like to update the slow one when the mouse is released. Is there a simple way to achieve this? Thanks in advance!


How to do the polynomial stuff over finite fields extensions fast?

This question is raised from the problem of package `FiniteFields` being very slow (please, see the corresponding question): I have had an evidence that Mathematica takes the exponential time from count of multiplications/additions to compute, say, just the value of polynomial at specified point. Please, see the following example:               << FiniteFields`;          Table[       AbsoluteTiming@         Sum[           GF[2, 12][RandomInteger[{1, 2}, 12]] x^i,           {i, 0, deg}         ] //. {x -> GF[2, 12][{0, 1}]},       {deg, 12, 22}      ]      For Intel(R) Core(TM) i5-2540M CPU @ 2.60 GHz I have received the following results of computation time (in seconds):               {0.0440, 0.0780, 0.1550, 0.3350, 0.7230, 1.5470, 3.1891, 6.7934, 14.3468, 30.1807, 64.2497}      I have to do common polynomial stuff over finite fields extensions. For instance, factorization (looking for roots) and multiplication. Does any fast solution exist for this? Thank you!


Addition and subtraction of TimeObjects in v10

Documentation states that "TimeObject allows addition and subtraction of time quantities". I can see that subtraction is fine, (example from doc page) TimeObject[{16, 17, 21}] - TimeObject[{10, 12, 34}] . This evaluates to time Quantity but if I change minus to plus the expression remains unevaluated. However, both subtraction and addition works if TimeObject is used with time Quantity (e.g. 13 hours) instead of another TimeObject. Subtraction is specifically mentioned in the following line from the docs: "Subtracting two TimeObject constructs yields a time quantity". How about addition? Am I missing something or is it an obvious bug?


How to create a progress bar?

I would like to create a progress bar tool that allows me to see how my computations are going. I found answers to this question on many sites, I even found a package for it ( http://www.physics.ohio-state.edu/~jeremy/mathematica/progress/#download ), but unfortunately, I have no knowledge whatsoever on programming and such, so I could not really understand the instructions for installing it properly (didn't know wether to use a notebook to create the package, go to the kernel, or something else?). So I would really really appreciate if somebody could provide detailed step by step instructions for me to be able to get the progress bar going.


Differential equation

Why mathematica not solve this equation: In: DSolve[{z''[t]==(z'[t])^2+(z[t])^2-Sin[t]-1, z[0]=0,z[Pi/2]=1},z[t],t] Out: DSolve[{z''[t]==(z'[t])^2+(z[t])^2-Sin[t]-1, z[0]=0,z[Pi/2]=1},z[t],t] There is other command for solve it?


Get the first positive coefficient in polynomial?

I have Polynomial $F(x) = \sum_{i \leq n}{a_ix^i}$. How to get the first $a_i > 0$? Thanks,


How to map HoldForm?

I'm trying to compare between Sqrt[3.] and Sqrt[3]. To display the result, I mapped HoldForm to display the expressions on the left hand column (code at end), but it seems like Sqrt[3.] had been evaluated before it was mapped on to. Is there any way to stop that to happen? ![Mapping HoldForm](http://i.stack.imgur.com/WnKid.png)               Grid[Prepend[{HoldForm[#], Precision[#],           MachineNumberQ[#]} & /@ {Sqrt[3.], Sqrt[3]}, {"Number",         "Precision[]", "MachineNumberQ[]"}],      Frame -> All]


Partition a set into $k$ non-empty subsets

The Stirling number of the second kind is the number of ways to partition a set of $n$ objects into $k$ non-empty subsets. In Mathematica, this is implemented as `StirlingS2`. How can I enumerate all the sets? Ideally I would like to get a list of lists, where each list contains $k$ lists. The question Partition a set into subsets of size k seems relevant.


Add/replace a rule in a list of rules based upon the rule's lhs without regard for the rule's rhs

I have the following lists of rules:               {x -> 1, y -> 2}     {x -> 1, y -> 2, z -> 4}     {x -> 1, y -> 2, z -> 2}      For each list of rules, I would like to add the rule `z -> 3` or replace any rule whose lhs is `z`   with `z -> 3` . I am able to get this to work for specific rules, for example `z -> 4`               AddReplaceRule[rules_List] :=      Module[{newRules},       If [MemberQ[rules, z -> 4],        newRules = DeleteCases[rules, z -> 4];        ,        newRules = rules;        ];       Append[newRules, z -> 3]       ]      * * * **Results** _Note I am expecting to see_ `{x -> 1, y -> 2, z -> 3}` _for all three cases, but that is not the case, since I need to generalize_ `z -> 4` _in AddReplaceRule._               In[]:= AddReplaceRule[{x -> 1, y -> 2}]     Out[]= {x -> 1, y -> 2, z -> 3}          In[]:= AddReplaceRule[{x -> 1, y -> 2, z -> 4}]     Out[]= {x -> 1, y -> 2, z -> 3}          In[]:= AddReplaceRule[{x -> 1, y -> 2, z -> 2}]     Out[]= {x -> 1, y -> 2, z -> 2, z -> 3}


Time-frequency analysis beyond wavelets

What possibilities are there for time-frequency analysis in Mathematica beyond wavelet decomposition? I could not even find a simple STFT.


Dynamically updating linked Manipulate variables

I am trying to write a simple cylindrical tank design notebook. Once the user inputs the desired capacity in gallons, it will compute the required volume (in cubic feet) and then offer sliders for height and diameter. However, since the volume (and capacity) must stay constant, if the user changes the height, the diameter will have to change accordingly, and vice versa. Here is an image of what I'm trying to go for. The little thing on the right is an approximately six foot person for scaling purposes: ![example](http://i.stack.imgur.com/xmamO.jpg) My issue is getting the sliders to change dynamically as the user changes the other variable. How can I write a relation to make sure that the calculated volume of the cylinder using height and diameter ALWAYS equals the user- defined volume? I've looked into a couple similar solutions with dynamic updating of variables, but I was still confused and I wasn't sure if it applied in this case. These are a couple of the ones I tried to use: Alternative updating of a dynamic expression How to anchor a Pane's scroll position to the bottom? Code included below:               Manipulate[      Graphics3D[{        Cylinder[{{0, 0, 0}, {0, 0, h}}, d/2],        Cuboid[{15.25, 0.75, 0}, {16.75, -0.75, 4.5}],        Sphere[{16, 0, 5}, 1.5]        },       ImageSize -> 500,       PlotRange -> {{-15, 25}, {-15, 15}, {0, 30}}],           {{cap, 8000, "gallons:"}, ImageSize -> Tiny},      Spacer[10],      Dynamic@Row[{Style["      volume:   ", 12],          NumberForm[cap/7.4813, 4],          Style["  \!\(\*SuperscriptBox[\(ft\), \(3\)]\)", 12]}],      Spacer[10],      {{h, 5, "height (ft):"}, 5, 25, Appearance -> "Labeled"},      {{d, 5, "diameter (ft):"}, 2, 20, Appearance -> "Labeled"},      Spacer[10]           ]      Thank you very much!!


Generating a list of standard normal random variables

Im trying to generate a list of random (standard) independent normal variables. For this, I first generate a random list of, say, 100 real numbers in the range [0, 1000], and then make them standard independent random variables. However, this strategy is not working in _Mathematica_. Is there an alternate way to approach this problem?


Improving ListContourPlot mesh triangulation

I have a irregularly placed measurement data. I bring here a small example. I am sorry for that. > mdata = {{20., 1.6, 0.218084}, {4.02807, 1.71068, 0.227565}, {19., 1.6, > 0.240074}, {18.8333, 1.60667, 0.278783}, {17.5, 1.62, 0.406884}, {21.9127, > 1.72134, 0.427501}, {16.89, 1.61925, 0.438591}, {7.22189, 1.70931, > 0.455631}, {16.1132, 1.62516, 0.515403}, {8.51871, 1.68045, 0.524135}, > {8.4419, 1.69226, 0.531889}, {9.6625, 1.68612, 0.601701}, {14.1699, 1.63774, > 0.639421}, {14.5437, 1.63975, 0.65735}, {13.5583, 1.64633, 0.700959}, > {11.9613, 1.66151, 0.704242}, {11.276, 1.67761, 0.706502}, {12.9152, > 1.65519, 0.718618}, {12.3724, 1.66034, 0.719962}, {12.2406, 1.66432, > 0.724829}, {12.9876, 1.6586, 0.734248}, {13.1918, 1.65804, 0.750541}, > {13.8071, 1.6563, 0.754093}, {13.1619, 1.66528, 0.759312}, {13.111, 1.66365, > 0.764214}, {13.2852, 1.67032, 0.787843}, {14.4106, 1.6628, 0.805543}, > {22.6391, 1.68181, 0.810923}, {13.9972, 1.7042, 0.817875}, {14.8398, > 1.66263, 0.818304}, {22.2249, 1.68764, 0.824216}, {19.9883, 1.70148, > 0.827452}, {16.1394, 1.66178, 0.840096}, {15.3544, 1.67243, 0.873424}, > {15.6949, 1.67557, 0.903093}};               ListContourPlot[mdata, Mesh -> All]      ![problematic listContourPlot](http://i.stack.imgur.com/gWIMp.png) So the data is not so bad, but the _traingulation(?)_ of the mesh looks ugly. It seems to be issue with the aspect ration of the data as the fallowing plot looks much better:               ListContourPlot[{1, 100, 1} (# - {0, 1.6, 0}) & /@ mdata, Mesh -> All]      ![hack1](http://i.stack.imgur.com/flu76.png) The downside of this trick is, that now I will have to implement the y axes label override in order to show the correct numbers. Is there a smarter workaround? Weakly related is Smoothing ListContourPlot contours but it is about data smoothing. I want to show the actual data. I have the same issue with both _Mathematica_ 8&9. **EDIT** Here is my attempt using overriding the tick labels.               rescaleParams = {1, 100, 1};     dataRanges = {Min@#, Max@#} & /@ (Transpose[mdata][[{1, 2}]]);     tickF[rescaleParam_, min_, max_] := {rescaleParam #, N@#} & /@         FindDivisions[{min, max}, 5];     ListContourPlot[rescaleParams # & /@ mdata, Mesh -> All,       FrameTicks ->        MapThread[        tickF, {rescaleParams[[{1, 2}]], dataRanges[[;; , 1]],          dataRanges[[;; , 2]]}]]      ![enter image description here](http://i.stack.imgur.com/vZD3z.png) As I was afraid, it is messy. It is also problematic in the case I want to combine it with some other plots using `Show`. If you made this override method more elegant or at least improve the rounding of the tick labels, it would be appreciated as well.


Inserting rows of one matrix into rows of another matrix sequentially

I have two matrices M1 and M2. Both have same number of columns but different number of rows. I want to make a new matrix M which should have 1st row form M1, second row form M2, third row form M1, fourth row from m2 and so on. For example,               M1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};     M2 = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}, {19, 20, 21}, {22, 23, 24}};      and my final matrix should be               M = {{1, 2, 3}, {10, 11, 12}, {4, 5, 6}, {13, 14, 15}, {7, 8, 9}, {16, 17, 18}, {19, 20, 21}, {22, 23, 24}};      Please note length of each matrix is over 1000. Thank you for your help.


Interpolation function evaluation and timing

Lets define two identical functions $f$ and $g$ in a slightly different way               f = Interpolation[Table[{i, i^2}, {i, -5, 5}]];     g = Function[x, Interpolation[Table[{i, i^2}, {i, -5, 5}]][x]];     Timing[Do[g[1], {i, 1000}]]/Timing[Do[f[1], {i, 1000}]]     {12.0023, 1}      Does the second definition calculates the interpolating function every time $g$ is evaluated?


Creating hexahedral finite elements in Mathematica

Is it possible to do FEM using hexahedral elements in _Mathematica_? If it possible, is there any help to do that?


Table to text string

I know this is a simple question and there is a single command to do this but I have been looking for the command for 30+ minutes and cannot find it. I have a list that I want to put tabs between columns and new lines between rows. As a simple example, I have a list                 list = {{1, 2, 3}, {a, b, c}}      and I want to convert it to the string                 "1\t2\t3\na\tb\tc"


Problem with plotting eigenvalues

I want to plot the eigenvalues of a matrix which is dependant on a parameter (well, actually I want to plot a tight-binding electronic band structure). The dimension of the hamitonian matrix is greater than 5, so of course there is no analytical solution. But anyway, when I use `Eigenvalues` directly, _Mathematica_ will give results containing `Root`. So I just use these `Root`s to plot. I thought that theoretically the plot will be fine. Because it is just a root searching process, so if _Mathematica_ searches the roots little by little the eigenvalue curve will be fine. But it turns out that things are not that simple. I give all the code that I have written as follows:               n = 5;     h = Table[0, {i, 1, 2 n}, {j, 1, 2 n}];     a[m_] := 2 m - 1     b[m_] := 2 m     Do[      h[[b[i], a[i]]] = E^((I k)/2) + E^((-I k)/2);      If[i + 1 <= n, h[[b[i + 1], a[i]]] = 1, Null];      If[i - 1 > 0, h[[a[i - 1], b[i]]] = 1, Null];      h[[a[i], b[i]]] = E^((I k)/2) + E^((-I k)/2)      , {i, 1, n}]      the above code is to generate the hamiltonian matrix with dimension 2n               eigen = Eigenvalues[h];          Plot[x /. x -> eigen[[1]], {k, 0, \[Pi]}]      the plot is as follows: ![eigen](http://i.stack.imgur.com/DoTsP.gif) It is quite good at the beginning, but totally messed up in the end. **So the first question is: What was wrong with the ugly tail?** Finally, about plotting eigenvalues, I only have one more method, that is to calculate the eigenvalues at the discrete point within the range of the parameter and then `ListPlot` them. But this method has a disadvantage, Because all the eigenvalues are in random order. So which point belongs to which curve can only be judged by eyes, and using this method, I can not plot different eigenvalue curve with different color especially when two curves intersect. **So is there better solutions?**


Replace all symbols in a matrix with their numbered forms

I have a matrix made mostly from `"x"` with a few `0`'s thrown in:               list = {{0, "x", "x", 0}, {0, "x", "x", "x"}, {0, "x", "x",         "x"}, {"x", "x", "x", "x"}, {"x", "x", "x", "x"}, {"x", "x", "x",         "x"}, {"x", "x", "x", "x"}, {"x", "x", "x", "x"}, {0, "x", "x",         "x"}}      I know that there are 31 `"x"`'s in the matrix, and I want to replace each of them with a numbered variable: `x1`, `x2`, and so on til `x31` (without quotations). Here's the expected result:               (* {{0, x1, x2, 0}, {0, x3, x4, x5}, {0, x6, x7, x8}, {x9, x10, x11,        x12}, {x13, x14, x15, x16}, {x17, x18, x19, x20}, {x21, x22, x23,        x24}, {x25, x26, x27, x28}, {0, x29, x30, x31}} *)      Below is the list of the numbered variables that you may use:               numberedx = Table["x" <> ToString@i // Symbol, {i, Range@Count[list, "x", {2}]}]     (* {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10,      x11, x12, x13, x14, x15, x16, x17, x18, x19, x20,      x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, x31} *)      I can't for the life of me figure out how to do this. My gut tells me that some procedural method is in order since each `"x"` is replaced by its numbered form, then the next `"x"` down the line is replaced by the next member in the list of numbered variables. Unfortunately I'm very uncomfortable with procedural programming. I also tried `MapIndexed` but the `0`'s are mapped as well. I'd really appreciate any help or insight.


How can I find the lines that go through?

I have a 80 x 80 x 50 dataset. From this dataset, I get some curves. These curves are randomly seeded, by which I mean that their starting points have been chosen randomly. Below, you can find an example of points that form a curve :               points = {       {81.7317, 64.6811, 14.7966}, {81.7316, 64.6588, 14.8941}, {81.7294, 64.6378, 14.9918},       {81.7228, 64.6176, 15.0895}, {81.7087, 64.5979, 15.1865}, {81.6867, 64.5785, 15.2821},       {81.6576, 64.5595, 15.3758}, {81.6223, 64.5413, 15.4676}, {81.5825, 64.5243, 15.5577},       {81.5395, 64.5088, 15.6467}, {81.4945, 64.4953, 15.7349}, {81.4486, 64.4841, 15.8231},       {81.4027, 64.4756, 15.9115}, {81.3576, 64.4704, 16.0006}, {81.3128, 64.4684, 16.09},       {81.2674, 64.4693, 16.179}, {81.2217, 64.4729, 16.2679}, {81.1761, 64.4792, 16.3567},       {81.1306, 64.488, 16.4453}, {81.0853, 64.4992, 16.5338}, {81.0403, 64.5127, 16.622},       {80.9954, 64.5283, 16.71}, {80.9497, 64.5457, 16.7972}, {80.9025, 64.5649, 16.8833},       {80.8539, 64.5861, 16.9681}, {80.8043, 64.6094, 17.0517}, {80.7555, 64.6349, 17.1352},       {80.7075, 64.6628, 17.2184}, {80.6604, 64.693, 17.3012}, {80.6143, 64.7256, 17.3837},       {80.569, 64.7605, 17.4658}, {80.5249, 64.798, 17.5473}, {80.4818, 64.838, 17.6282},        {80.4398, 64.8809, 17.7082}, {80.399, 64.9267, 17.7872}, {80.3595, 64.9757, 17.8649},       {80.3213, 65.0279, 17.9411}, {80.2848, 65.0819, 18.017}, {80.2493, 65.1363, 18.093},       {80.2144, 65.1902, 18.1696}, {80.1795, 65.2433, 18.2469}, {80.1444, 65.295, 18.3249},       {80.1088, 65.3453, 18.4037}, {80.0722, 65.3938, 18.4831}, {80.0344, 65.4404, 18.5631},       {79.9951, 65.485, 18.6435}, {79.9539, 65.527, 18.7243}, {79.9104, 65.566, 18.8055},        {79.8646, 65.6019, 18.8868}, {79.8163, 65.6347, 18.968}, {79.7657, 65.6645, 19.0489},       {79.7136, 65.6922, 19.1296}, {79.6598, 65.7174, 19.2101}, {79.6044, 65.7397, 19.2903},       {79.5475, 65.7588, 19.3703}, {79.489, 65.7743, 19.4499}, {79.4291, 65.7861, 19.5291},       {79.3681, 65.7943, 19.6079}, {79.306, 65.7989, 19.6862}, {79.2432, 65.8002, 19.764},       {79.1798, 65.7984, 19.8413}, {79.116, 65.794, 19.9181}, {79.0519, 65.7873, 19.9945},        {78.9878, 65.7782, 20.0708}, {78.9239, 65.7658, 20.1467}, {78.86, 65.7502, 20.222},       {78.7959, 65.7318, 20.2965}, {78.7317, 65.7111, 20.3703}, {78.6672, 65.6885, 20.4433},       {78.6023, 65.6644, 20.5155}, {78.5371, 65.6392,20.587}, {78.4715, 65.6133, 20.6579},       {78.4053, 65.587, 20.7281}, {78.3387, 65.5606, 20.7979}, {78.2716, 65.5344,20.8672},       {78.204, 65.5085, 20.9361}, {78.1358, 65.4831, 21.0048}, {78.0668, 65.4575, 21.0725},       {77.9969, 65.4312, 21.139}, {77.926, 65.4039, 21.204}, {77.8541, 65.3753, 21.2673},        {77.7812, 65.3455, 21.3289}, {77.7071, 65.3148, 21.3887}, {77.6319, 65.2835, 21.4466},       {77.5553, 65.2517, 21.5026}, {77.4776, 65.2198, 21.5568}, {77.3985, 65.188, 21.6091},       {77.3183, 65.1564, 21.6597}, {77.2368, 65.1252, 21.7087}, {77.1543, 65.0947, 21.7562},       {77.0708, 65.0648, 21.8023}, {76.9863, 65.0358, 21.8473}, {76.901, 65.0074, 21.8911},       {76.8149, 64.9795, 21.9336}, {76.7278, 64.9523, 21.9745}, {76.6398, 64.9257, 22.0138},       {76.5509, 64.8996, 22.0515}, {76.4613, 64.8738, 22.0877}, {76.371, 64.8486, 22.1225},       {76.2801, 64.8238, 22.1558}, {76.1885, 64.7995, 22.1879}, {76.0964, 64.7757, 22.2187},       {76.0038, 64.7524, 22.2483}, {75.9108, 64.7293, 22.2768}, {75.8174, 64.7061, 22.304},       {75.7237, 64.6826, 22.3299}, {75.6297, 64.6588,22.3544}, {75.5354, 64.6346, 22.3774},       {75.441, 64.6098, 22.3988}, {75.3463, 64.5844, 22.4184}, {75.2514, 64.5581, 22.436},       {75.1565, 64.5307, 22.4515}, {75.0616, 64.502, 22.4645}, {74.9668, 64.4717, 22.4748},       {74.8723, 64.4401, 22.4826}       }


How to solve this iteration in the functional programming way?

I am trying to come up with a functional programming method to calculate a list of replacements, that depend on previous replacements. Since there is always a finite number of steps, I would like to use `Fold`, `Nest`, `ComposeList` or any related function in an elegant way. Now I only have the the following procedural code: Given an initial list of assignments ( _temp_ ), an empty set for storing replacement rules ( _rules_ ) and an arbitrary function _f_ of one argument:               temp = {d -> {d}, c -> {c, d}, a -> {a, c, d}, b -> {b, d}}     rules = {};     f[_[x_, {x_}]] := RandomReal[]; (* if input rule is x -> {x}, evaluate... *)     f[_[x_, {x_, y__?NumberQ}]] := RandomReal[]; (* if input rule is x -> {x, num.1, num.2, ...}, evaluate... *)          Do[      rules = Append[rules, temp[[i, 1]] -> f@temp[[i]]];      temp = Replace[temp, rules, {3}];        (* {3} is needed to replace only at the rhs of rules in temp *)      , {i, Length@temp}]      the output is:               rules          (*     ==> {d -> 0.236483, c -> 0.998187, a -> 0.818906, b -> 0.819079}     *)          temp          (*     ==> {d -> {0.236483}, c -> {0.998187, 0.236483},       a -> {0.818906, 0.998187, 0.236483}, b -> {0.819079, 0.236483}}     *)      This problem might be considered as an entertaining code golfing example, but believe me, this is not entertaining for me at all. **Edit:** Note, that `f` in reality is such a function that evaluates **only** if the right hand side of its input rule has already been evaluated (i.e. it is a list of random reals in this example). I have modified `f` accordingly: now it evaluates only if the input rule has the same element on lhs and rhs (rhs is wrapped in `List`) OR if the rhs contains elements that already have numeric values. Since numeric values depend on previous evaluations, therefore it is required that the algorithm processes the initial list from left to right. The initial _temp_ list is **always** such that at the end all right-hand-sides are evaluated. **Edit 2:** This algorithm would do the synchronous update of a Bayesian network, which is a direct acyclic graph. That's why the sorting of nodes is not according to lexicographic order: nodes in `temp` are sorted according to topological order, and each member is a `*node* -> *parents_of_node*` pair. The actual `f` function (not the simple one above) assigns the output state to the node given the states of its parents and the present state of itself. Since I don't know of any ready-made package available to deal with Bayesian inference and co., I started to do it from scratch. It is also good to code things to understand the concepts of a new field.


When plotting vector fields what is the difference between the following?

I am a new Mathematica user, and I have run into a question. What is the difference between the output of the commands:               VectorPlot[{x, Sin[x - y]}, {x, -3, 3}, {y, -3, 3}]      and               VectorPlot[{1, Sin[x - y]}, {x, -3, 3}, {y, -3, 3}]      The only difference is the argument in the first braces, x and 1, but I am not sure what that means in terms of the vector field that is generated. I understand this generates two vector fields. I did not understand how the input affects the generated output, i.e., what exactly does Mathematica require the entries here to be, and how does it interpret the difference in these two arguments for the VectorField command: {x, Sin[x - y]} and {1, Sin[x - y]}.


Animating a circle to move along an curve

Basically, I want to move a graphic (such as a circle) along a given path (such as sin(x)). I was thinking that the trick might be making the x and y coordinates of the circle vary based on the equation, but I have not been able to make anything except a circle that just sits there.


Initial Image Size of dynamic plot

I have a dynamic plot. I want to set an initial image size and then be able to resize it by dragging with the mouse. When the image is updated, I want to maintain the "dragged" size. A naive attempt with a simplified example:               Slider[Dynamic[n], {0, 5}]     Dynamic[Plot[n (x - n)^2, {x, 0, 5}, ImageSize -> Large]]      It sets ImageSize->Large. I can resize the plot by select and dragging, but as soon as I change n with the slider, the plot is evaluated and the size reverts to Large. So how can I apply setting ImageSize->Large only as an initial condition and keep the "dragged" size as n changes? Thanks in advance for your expert help!


"Save Graphic As..." does not include plot legends

I am creating some plots with `Show` but unfortunately the `PlotLegends` seems to be out of the bounding box when saving the graph. Sample code:               data1 = {1, 2, 3};     data2 = {3, 4, 5};     Show[ListPlot[data1, PlotLegends -> {"Somedata1"}],      ListPlot[data2, PlotLegends -> {"Somedata2"}]]      Is there a way to include them so they can be exported along with the image?


3D orbits and inaccuracy over time

I wrote a little program to use Newton's Law of Universal Gravitation to animate 3 planets orbiting a central star, but I have run into a problem. Here is the code that I used to create the program (I apologise about the messyness):               orbit1 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 1000, y[0] == 1000, z[0] == 1000,      x'[0] == 0, y'[0] == -100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbit2 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 500, y[0] == -1000, z[0] == -1000,      x'[0] == -110, y'[0] == 100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbit3 = NDSolve[{     x''[t] == (-(6.672*10^-11) (7*10^17) x[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      y''[t] == (-(6.672*10^-11) (7*10^17) y[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      z''[t] == (-(6.672*10^-11) (7*10^17) z[t])/(x[t]^2 + y[t]^2 + z[t]^2)^(3/2),      x[0] == 0, y[0] == 100, z[0] == 500,      x'[0] == 350, y'[0] == -100, z'[0] == 0}, {x[t], y[t], z[t]}, {t, 0, 1000}];          orbitplotunion =       Animate[Show[{ParametricPlot3D[{{x[t], y[t], z[t]} /.         orbit1, {x[t], y[t], z[t]} /. orbit2, {x[t], y[t], z[t]} /.         orbit3}, {t, 0, a},       PlotRange -> {{-1600, 1600}, {-1600, 1600}, {-1600, 1600}},       AxesLabel -> {x, y, z}],      Graphics3D[{Yellow, Sphere[{0, 0, 0}, 100], Green,        Sphere[{x[t], y[t], z[t]} /. orbit1 /. t -> a, 50], Blue,        Sphere[{x[t], y[t], z[t]} /. orbit2 /. t -> a, 50], Purple,        Sphere[{x[t], y[t], z[t]} /. orbit3 /. t -> a, 50]}]}], {a, 0,      Infinity, 0.1}]      As you can see, there is one orbit calculation for each planet, and these are then animated. Now, my first problem has to do with `NDSolve[]` and its calculation from `t = 0` to `t = 1000`, which means that the animation will break once `t = 1000` is hit. Is there a way to allow the animation to go on indefinitely, instead of having to reset it once `t = 1000` comes along? Secondly, the planets and their trailing lines start out orbiting the star perfectly in the beginning, but over time, the trailing lines of each planet become more and more jagged, until eventually the animation looks horrible. Here is what the orbits look like in the beginning: ![orbits at start](http://i.stack.imgur.com/s81yd.png) And this is what they look like some time later: ![later orbits](http://i.stack.imgur.com/DHagW.png) If anyone knows how to solve the jagged line problem (maybe by editing the amount of trailing line that is allowed, so that it doesn't redraw over itself continually) and knows how to make the animation continue indefinitely, I would love to know. Regards, Alex * * * ## EDIT: After looking at the $n$-body wiki page, I thought I'd give it a go and start out small with a simple Earth-Sun simulation, and if that worked, then move my way up to $3,4,5,\dots$ bodies as well. Unfortunately, as expected, I seem to have run into a problem almost immediately. Here is the code that I am currently using:               G = 6.672*10^-11;     m1 = 5.972*10^24; (* mass of Earth *)     m2 = 1.989*10^30; (* mass of Sun *)          orbitearthsun = NDSolve[{     x1''[t] == -((G (m2) (x1[t] - x2[t]))/Abs[x1[t] - x2[t]]^3),     y1''[t] == -((G (m2) (y1[t] - y2[t]))/Abs[y1[t] - y2[t]]^3),     x2''[t] == -((G (m1) (x2[t] - x1[t]))/Abs[x2[t] - x1[t]]^3),     y2''[t] == -((G (m1) (y2[t] - y1[t]))/Abs[y2[t] - y1[t]]^3),     x1[0] == 1000, x2[0] == 0, x1'[0] == 100, x2'[0] == 0,     y1[0] == 1000, y2[0] == 0, y1'[0] == 100, y2'[0] == 0},     {x1[t], x2[t], y1[t], y2[t]}, {t, 0, 1000}]          NDSolve::ndsz: At t == 3.049010336028579`*^-6, step size is effectively zero;     singularity or stiff system suspected. >>      Does this occur because the denominator of each term becomes zero as they collide?


How to open hyperlinks (from web-embedded CDF) in a new tab

I have a problem with `Hyperlink` (in a web-embedded CDF) opening links in the same browser tab and I couldn't find an option to avoid that. I have the following constraints:   1. CDF is web-embedded (created by me).   2. The hyperlink should open only after mouse clicking, no combinations with keyboard keys are allowed. **Failed attempts:**   * I've tried to click it with `Shift` like it is written in `Help` but it does not work. It doesn't matter because of constraint #2 above. However if it is possible to mimic the `Shift` key being pressed (in some other way than pressing the key) maybe that will help?   * I've tried to replace `Hyperlink` by `Button[ "link", SystemOpen["link"]]` but there is no reaction. I don't think this is important, but this is how I'm testing it:   * I create a CDF file using _Mathematica_   * Export as "web embeddable..."   * I paste script received in the end to a `.txt` file -> save -> switch to `.html` It is quite important for me to find a solution to this, because the CDF resets every time the link opens in the same tab.


How can i get the solution of complicated equation?

![enter image description here](http://i.stack.imgur.com/XfRtk.png) This is the equation about zeta. `NSolve[eq]` could not solve this equation. (I think it is too complex to solve by `NSolve`.) I want to know how can I solve this equation, which has such a complicated form. This should be the code for the equation:               eq = (0. - 30.1996 I) ζ^6 +       (0. + 9.81486 I) ζ^5 Sqrt[(0. - 640.701 I) + ζ^2] +       (0. + 20.3847 I) ζ^4 ((0. - 640.701 I) + ζ^2) +       (0. + 20.3847 I) ζ^5 Sqrt[(0. - 1127.53 I) + ζ^2] -       (0. + 20.3847 I) ζ^3 ((0. - 640.701 I) + ζ^2) Sqrt[(0. - 1127.53 I) + ζ^2] +       (0. + 9.81486 I) ζ^4 ((0. - 1127.53 I) + ζ^2) -       (0. + 9.81486 I) ζ^3 Sqrt[(0. - 640.701 I) + ζ^2] ((0. - 1127.53 I) + ζ^2) +       408.549 (         (0. - 0.630868 I) ζ^3 - (0. + 14.0909 I) ζ^2 Sqrt[(0. - 640.701 I) + ζ^2] -         (0. + 1.21667 I) ζ ((0. - 640.701 I) + ζ^2) -         (0. + 6.45738 I) ζ^2 Sqrt[(0. - 1127.53 I) + ζ^2] +         (0. + 14.7217 I) ((0. - 640.701 I) + ζ^2) Sqrt[(0. - 1127.53 I) + ζ^2] +         (0. + 0.585806 I) ζ ((0. - 1127.53 I) + ζ^2) +         (0. + 7.08825 I) Sqrt[(0. - 640.701 I) + ζ^2] ((0. - 1127.53 I) + ζ^2)) == 0;


Plotting several functions

I'd like to plot a function of one real and one integer variable, but I don't want them all shown in the same 2-D plot - I'd like to see them as separate curves so I can see both 'axes', more like `Plot3D` works. I'm sure Mathematica can do this, but how? Edit: Rephrased, I'd like to `Plot3D` a function of one real and one integer variable. Instead of seeing a surface, I'd like a discrete set of curves in three space.


3D plots with a continuous and discrete input

How can I plot a function with one discrete and one continuous input? Plot3D wants everything continuous while ListPlot3D and ListPointPlot3D want everything discrete. I would like be able to say something like               HybridPlot[f[dsc, cnt], {dsc , min, max step}, {cnt, min max}]      or               HybridPlot[f[dsc, cnt], {dsc, someArray}, {cnt, min max}]      I am not seeing a simple way to do this in the docs.


Isolating string characters

I have the following string:                string=  {{"D(2.00225050736308e-15*A01 - 0.0201549279513608) = \         0.0820842279730734 + 0.08923448712*delay(A35",            " 17) + 0.08669543966*delay(A88",            " 20) + 1.98960079968027e-16*A57 - 0.3146216003*erf(delay(A01",            " 2)) - 0.3157150548*erf(sin(0.00541313376373593*cos(0.\         129564165001876 + 2.22963213427193e-15*A57 - \         gauss(0.00170510841714258 + 1.87338787507e-15*A51)) + delay(A27",            " 24) + gauss(gauss(0.00170510841714258 + 1.87338787507e-15*A51)) - \         2.17740845675611e-15*A81*cos(0.129564165001876 + \         2.22963213427193e-15*A57 - gauss(0.00170510841714258 + \         1.87338787507e-15*A51))))"}}      I want to isolate all characters within the brackets of the **delay** part e.g. delay(A27, 24). In other words I want the characters A24 and 24. My best bet was to go with               StringCases[string,"delay("~~__~~")"]      in order to get all String between the brackets, but this does not work. Still a little bit confused about using string patterns :/.


Looking to create a lesson on sensory perception of sound

I'm looking to show students a lesson on sensory perception, more specifically on masking. I know a little _Mathematica_ but sound processing has evaded me.   1. I would like to create a white noise and play it, show characteristics etc              noise = RandomReal[1,{5000}];     ListPlay[noise];     Spectrogram[noise];     Histogram[noise];        2. Bandpass the white noise to produce different bandwidth sounds. This didn't work. Bandpassing the noise produces an amplitude constrained sound, but I was looking to constrain the sound to a specific frequency spectrum. How is this possible?   3. Also looking to play two sounds at the same time. `Sound[{sound1,sound2}]` plays sounds in sequence. How can I get them to overlap? The idea would be to show how one sound can mask other sounds.


Filtering elements from a list that appear only once

I want to be able to select elements from a list that only appear once. I originally had this:               Select[Table[Count[list, i], {i, list}], # == 1]      But the issue is that my list has about 60,000 elements, and it takes way too long. The only way I could think of speeding it up would be to make a function like Count, but that would return after seeing the same element twice, and I have no idea how to do that in Mathematica. Also, I'm not sure if it's important, but the list is actually a list of lines (with a line defined by two 2D points). The goal is to find the edges that are only used by one triangle, hence making them a perimeter edge. Thanks!


Can you make the new "Choose color scheme" helper larger?

Mathematica 10 has a cool new "color data chooser" feature: ![enter image description here](http://i.stack.imgur.com/OYljG.png) My question is: Can you make that window larger? Right now, I can only see 3-4 color schemes at once, even though all 51 gradients would easily fit on the screen at once, if the windows were a little larger, and showed more than one row, e.g. like this:               Labeled[ColorData[#, "Image"], #] & /@ ColorData["Gradients"] //        Partition[#, 5, 5, {1, 1}, {}] & // Grid      ![enter image description here](http://i.stack.imgur.com/GF6Cx.png)


How to unthread?

For example               {a + b} == {c + d} // Thread     (*{a + b == c + d}*)      how to get `{a + b} == {c + d}` from `{a + b == c + d}` ? This is my try               Equal @@ List /@ Join @@ {a + b == c + d}      Are there other ways to do this?


Read and write files

I have a text file, its content is(for example):                388, 399, 100      *Nset, nset=All, internal, generate       1,  48,  1     *Elset, elset=All, internal, generate       1,  35,   1     ** Section:solidplane     *Solid Section, elset=All, material="rigid body"     *End Instance      Now I want use Mathematica read the above content and modify it; for example, (1) I want the number "48 (3rd line)" to change to number"388 (1st line)", (2) I want the word "All (4th line)" to change to word "Whole", How can I realize it? So the output is:                388, 399, 100     *Nset, nset=All, internal, generate       1,  388,   1     *Elset, elset=Whole, internal, generate       1,  35,   1     ** Section:solidplane     *Solid Section, elset=All, material="rigid body"     *End Instance      I have used the function "ReadList" but failed... Hope someone can help me


Problem with Poincare section

these are equations for some double oscillators: $x'(t)=p, p'(t)=-x-3y, y'(t)=q, q'(t)=-y-3x$ I would like to plot the Poincare section for collection of $(y,q)$ when $x=0$ and $x'(t)>0$ (or for $(x,p)$ when $y=0$ and $y'(t)>0$). I benefited from documentation and nice answer by Mr. belisarius here and I wrote:               abc = {x'[t] == p[t], p'[t] == -x[t] - y[t], y'[t] == q[t], q'[t] == -y[t] - x[t]};     psect[{x0_, p0_, y0_, q0_}] :=     Reap[NDSolve[{abc, x[0] == x0, p[0] == p0, y[0] == y0, q[0] == q0,     WhenEvent[x[t] + 0*y'[t] + 0*p[t] + 0*q[t] == 0,     If[p[t] >= 0, Sow[{y[t], q[t]}]]]}, {x, p, y, q}, {t, 0, 200},     MaxSteps -> \[Infinity], MaxStepSize -> .0005]][[2, 1]];     ps = psect /@ Table[{0.01, 0.005, 0.01, i}, {i, -.01, .01, .00125}];     ListLinePlot[#[[FindCurvePath[#][[2]]]] & /@ ps, Mesh -> All, PlotRange -> All]      But I don't receive anything. I expect to obtain something like this: ![enter image description here](http://i.stack.imgur.com/IbgaN.png) Many thanks for your attention.


How to add named characters to Mathematica 10?

It appears that native support for the Klingon alphabet has been removed from version 10:               \[KlingonA]      > Syntax::tsntxi: "\"!(\\[ KlingonA])\" is incomplete; more input is > needed.!(\"\")" (Curiously `"Klingon"` remains in the `$CharacterEncodings` list.) As an exercise I wish to restore support of this character set but the underlying character system has been modified; specifically I cannot find the `UnicodeFontMapping.tr` file and I assume it no longer exists. Quoting `TechnicalNotes.nb` found in the `Prerelease` folder: > On all systems, the Mathematica family of fonts (Mathematica*1-7) has been > replaced with a single Mathematica font. > > On Windows, the single Mathematica font is no longer installed under > "c:\windows\fonts". Instead, the user interface loads the font from the > installation directory. > > For prerelease testing, we are interested in learning about any issues > related to this change. `UnicodeCharacters.tr` does remain and the format appears unchanged so I should be able to restore recognition of `\[KlingonA]` etc., but without being able to map these characters to font glyphs that is largely pointless. (Though it would correct unrecognized syntax in legacy code.) ### How can one create named characters and bind them to specifc glyphs in v10?


How can I troubleshoot a PDF that fails to import?

I'm trying to import a PDF file whose text I'd like to parse, but I'm getting an error with no explanation:               Import["foobar.pdf", {"PDF", "Plaintext"}]     (* $Failed *)      I know the file exists as named, because if it didn't, $Mathematica$ would show a message:               Import["foobaz.pdf", {"PDF", "Plaintext"}]     (* Import::nffil: File not found during Import. *)     (* $Failed *)      Is there any way to get more information than the `$Failed`?


Why do Plot and ListPlot use the last PlotStyle when only one thing is plotted?

When a list of `PlotStyle`s is given, `ListPlot` behaves as expected when there are multiple things to plot:               ListPlot[{RandomReal[{-1, 1}, 100], 2 RandomReal[{-1, 1}, 100]}, PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/BQwqv.png) When there's only one thing to plot, it chooses the _last_ `PlotStyle` instead of the first one.               ListPlot[RandomReal[{-1, 1}, 100], PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/4uXAE.png) Enclosing the single thing to be plotted in `{}` appears to cause things to behave as expected.               ListPlot[{RandomReal[{-1, 1}, 100]}, PlotStyle -> {Red, Green, Blue}]      ![enter image description here](http://i.stack.imgur.com/fWLQZ.png) `Plot` shows the same behavior. This does not appear to happen with the default `PlotStyle`s, but it does happen if you modify the default styles using this kind of technique. Why is a single plot argument treated as a special case? Can this behavior be changed?


Why is my rasterized graphic blank?

Consider the following code:               jet[u_?NumericQ] :=        Blend[{{0, RGBColor[0, 0, 9/16]}, {1/9, Blue}, {23/63,            Cyan}, {13/21, Yellow}, {47/63, Orange}, {55/63, Red}, {1,            RGBColor[1/2, 0, 0]}}, u] /; 0 <= u <= 1;     caxis[x_, {min_, max_}] :=        If[x < min, jet[0], If[x > max, jet[1], jet[(x - min)/(max - min)]]];          data1 = Table[        Sinc[x*y] + RandomReal[{0., 0.2}], {x, -2 Pi, 2 Pi, 0.05}, {y, -2 Pi, 2 Pi, 0.05}];     data2 = Table[        Sinc[x*y] + RandomReal[{0., 0.2}], {x, -2 Pi, 2 Pi, 0.02}, {y, -2 Pi, 2 Pi, 0.02}];          Row[{Graphics[Raster[data1, ColorFunction -> (caxis[#, {-0.5, 2}] &)],         ImageSize -> 200],       Graphics[Raster[data2, ColorFunction -> (caxis[#, {-0.5, 2}] &)],         ImageSize -> 200],       Graphics[Raster[data2, ColorFunction -> "BlueGreenYellow"],         ImageSize -> 200]}]      It gives the output: ![enter image description here](http://i.stack.imgur.com/uAShX.png) Why is the second plot blank? If the dynamic updating is turned off, all of the three are blank. ![enter image description here](http://i.stack.imgur.com/qsGi7.png) Why does _Mathematica_ behave like this? I'm using OSX 10.8.4 on a Macbook Air with 1.7 GHz Intel Core i5 and 4GB memory.


Computing residues of matrix valued functions symbolically

I have a somewhat specific application in mind, but I've run into this kind of problem a few times and never found an elegant solution. Is there an efficient way to get Mathematica to recognize that some variables in a symbolic computation are non-commutative (matrices) while others are commutative (scalars) while still being able to do elementary calculus operations on the commutative variables? Specifically, I have expansions of the form $$ f_j(z) = \frac{\psi_{j,1}}{t \zeta_j(z)} + \frac{ \psi_{j,2} }{t^2 \zeta_j(z)^2} + \frac{ \psi_{j,3} }{t^3 \zeta_j(z)^3} +\dots, \qquad j=1,2,3,\dots \\\ $$ where the $\zeta_j(z)$ are explicit scalar functions with $\zeta_j(0) = 0$ and the $\psi_{j,k}$ are symbolic constant matrices. In the computations I'm doing I need to compute things like $$ G_{j,k}(w) =\operatorname{Res}\limits_{z=0} \frac{f_j(z) f_k(z)}{z-w} . $$ up to some order in $t$ as $t\to \infty$. This is a toy example where the non-commutativity isn't a problem. In the full problem I then need to iterate the computation by computing similar residues on the $G_{j,k}$'s so the commutativity becomes an issue. Is there a way to hand _Mathematica_ the functions $\zeta_j(z)$ and have it compute $G_{j,k}(w)$ and $G_{k,j}(w)$ correctly, _i.e.,_ so that it doesn't think $G_{j,k} - G_{k,j} = 0$? I would like to do this purely symbolically, but as a minimal example one could take $\zeta_1(z) = z$ and $\zeta_2(z) = \sin z$. **My naïve attempt** Here's what I had hoped might work. I included a parameter $t$ in $f$ and an $O(t^{-5})$ term in $G$ to truncate the number of terms in the output.               $Assumptions = {       Table[P[i] \[Element] Matrices[{2, 2}], {i, 1, 4}],      (\[Zeta] | t) \[Element] Complexes     };     \[Zeta][0] = 0;       f = Sum[  \[Psi][j]/(t \[Zeta][w])^j, {j, 1, 4}];       G = Residue[f.f/(w - z), {w, 0}] + O[t, Infinity]^5      This fails though; _Mathematica_ returns only the $O(t^{-5})$ term (the residue is left unevaluated). If I replace the last line with the scalar product               G = Residue[f*f/(w - z), {w, 0}] + O[t, Infinity]^5      then it outputs, but the order of matrix multiplication is lost.


How do I randomly select 'k' positions in a list and shuffle their respective elements without effecting the other elements?

Imagine I have some list:               listA = {"a","b","c","d","e","f","g","h","i","j"};      I'd like to randomly select `k` positions in the list, for example `k = 3` and we select positions `{1,9,10}`, then randomly shuffle the elements at these positions e.g. giving us ONE of the following five possible outcomes:               listApartialscramble1 = {"a","b","c","d","e","f","g","h","i","j"};     listApartialscramble1 = {"a","b","c","d","e","f","g","h","j","i"};     listApartialscramble2 = {"i","b","c","d","e","f","g","h","j","a"};     listApartialscramble3 = {"i","b","c","d","e","f","g","h","a","j"};     listApartialscramble4 = {"j","b","c","d","e","f","g","h","i","a"};     listApartialscramble5 = {"j","b","c","d","e","f","g","h","a","i"};      Is there a simple way to do this, perhaps with `RandomSample`?


RSolve gives a Context::ssle error

I want to solve the following recurrence equation               RSolve[{(k + 2) c[k + 2] q^(k + 1) - c[k] == 0}, c[k], k]      During calculation in Mathematica I get this persistent error: Context::ssle: "Symbol, string, or HoldPattern[symbol] expected at position Context[Zeta$^{(1,0)}$]. I tried to solve this equation with Maple and obtained a result $\left\\{ \begin{array}{cc} c (0)\frac{ 2^{-\frac{k}{2}} q^{-\frac{1}{2} k \left(\frac{k}{2}-1\right)} \left(\frac{1}{q}\right)^{k/2}}{\Gamma \left(\frac{k}{2}+1\right)} & k\text{::}\text{even} \\\ c(1)\frac{\sqrt{\pi } 2^{-\frac{k}{2}-\frac{1}{2}} q^{-\left(\frac{k}{2}-\frac{1}{2}\right) \left(\frac{k}{2}-\frac{3}{2}\right)} \left(\frac{1}{q^2}\right)^{\frac{k}{2}-\frac{1}{2}}}{\Gamma \left(\frac{k}{2}+1\right)} & k\text{::}\text{odd} \\\ \end{array} \right.$ So is it just a bug in Mathematica 9 or am I missing something?


I want to get a special curve in a picture

I have a picture,and I want to get a special curve in this picture ,than draw the line in a new picture.inbut I can't do this . Like this: ![example](http://i.stack.imgur.com/9fza9.jpg) The picture is this ![enter image description here](http://i.stack.imgur.com/coBQa.jpg) Anybody have an idea?


Need an efficient method for finding certain matrices

I am trying to write a function which produces square matrices with certain characteristics. The function should have two inputs:   1. number of the rows, `n`   2. number of the times each element in the range 1, 2, 3, ..., n should be repeated in the matrix So assuming the function is called `KOCH` then `KOCH[4, {2, 4, 5, 5}]` means the matrix should be 4 x 4 with 1, 2, 3 and 4 repeated respectively for 2, 4, 5, 5 times in the matrix, but each row in the output should be nondecreasing. And finally the function should find all the possible matrices, not only some of them. The code I prepared is as following               Koch[n_, num_] :=        Module[{list},         list = Flatten@Table[Range[n], {i, n}];         list = DeleteDuplicates[Sort /@ Tuples[list, {n}]];         list = DeleteDuplicates[Sort /@ Tuples[list, {n}]];         For[i = 1, i < n + 1, i++,            list = list[[Flatten@Position[Map[Count[#, i, 2] &, list], num[[i]]]]]];         list]      But as you notice what I am doing is to reproduce a large pool of the possible matrices and then filtering them with regards to the constraint on the number of repeatings. So it's inefficient. My function works for up to `n = 4` even though it takes seconds for `n = 4` but for `n = 5` it fails because of memory constraint with shooting this error > General::nomem: The current computation was aborted because there was > insufficientmemory available to complete the computation. I need to compute for up to `n = 15` and, therefore, need a better algorithm to find all the possible matrices given the constraints.


Partitioning a list and gathering statistics on the distribution of values across partitions

I have a one-dimensional array of 200 elements consisting of the numbers 0, 1, 2. This array needs to be divided into 10 groups (20 items each). Then, for each group, I want to count how many of the elements 0, 1, 2 is in each of them. These findings should be stored in three arrays, n0, n1, n2: n0 containing the statistics for the zeros, n1 the statistics for the ones, n2 the statistics for the threes. For example, one might get `n0 = {3, 4, 3, 6, 8, 12, 1, 9, 15, 16, ...}`, so in the first 20 elements of the original array there were 3 zeros, in the following 20 there were 4 zeros, and so on. I have _Mathematica_ 5.0. Please keep in mind that functions first appearing in later versions are not available to me.


How can I make controls have Button-like behaviour?

The `Button` control is very easy to understand               Button["Press Me", Print["Pressed"]]      I press the button, I execute the function. No Dynamic tom-foolery (I'll be honest, I struggle with Dynamics when they get above a certain level of complexity). I would like to be able to do the same with other controls. For example.               SetterBar[1, Range[5]]      gives 5 buttons for use in Dynamic settings. I'd like something simpler. I'm thinking of something like               SetterBar[1, Range[5],Foo]      Where `Foo` is a function that gets called when I click on a button on the SetterBar, ideally with an argument corresponding to the button I pressed. So, if I press '5', Foo[5] gets called. Any ideas?