title: Why do buttons with ChoiceDialog freeze the front end?

text: Pressing the button below will freeze my front end. An unpainted white dialog box comes up, then it completely freezes, and I need to forcibly kill the front end. CPU usage stays at zero during this.               Button["Ask", If[ChoiceDialog["OK?"], Print["OK!"]]]      Why does this happen? What is the proper way to ask for confirmation before an action? * * * **Answers:** My first question has been answered below and in the comment by @JohnFultz: use `Button[..., Method -> "Queued"]`. But this will make a button which doesn't work while evaluations are ongoing. I need a button which works even during evaluations. I came up with the following solution:               Button["Ask",       CreateDialog[       Column[{"OK?",          ChoiceButtons[{"OK"}, {Print["OK!"]; DialogReturn[]}]}]]]      `CreateDialog` returns immediately without waiting for an input, so the front end is not blocked. The functionality is moved completely into the dialog's button. You can test that the button works and reacts immediately even while `Pause[10]` is evaluating. * * * Quoting the two most enlightening comments: > The "Preemptive" method interrupts queued (e.g., Shift+Enter) evaluations to > do its work and cannot itself be interrupted. I.e., you can't preempt a > preemptive calculation. ChoiceDialog is putting up an interface which > independently needs the attention of the Mathematica kernel, but can't get > it because Button has the kernel's sole attention - John Fultz > Button[..., Method->"Preemptive"] (the default Method value) and > InputString[] are effectively exactly the opposite of each other. > Button[..., Method->"Preemptive"] will pause the user interface (causing it > to stop responding to events) until the computation is complete. > InputString[] will pause the computation until the user has input some > value. When you combine these two the user interface is waiting for the > computation to complete while at the same time the computation is waiting > for user interface input. - ragfield


title: Can't see dynamic updating when my function is evaluated inside Dynamic

text: I defined a function, `solve`, with a free variable n, which changes while `solve` is running. Therefore, evaluating               Dynamic[n]          solve[];      allows me to see the changes. But when I put `solve` into any sort of interface element like a button, I dont see n changing. Even if I evaluate               Dynamic[n]          bn = 0;     Dynamic[If[bn === 1, {bn = 0, solve[x]}]]          bn = 1;      I only see n change when the evaluation of `solve` is complete. What do I need to do to be able to observe changes to n as they happen? ### Edit With this, I see n change as evaluation progresses:               n = 0; solve[] :=  Do[n += 1, {1000000}]; Dynamic[n]; solve[]      With this, I only see n change at the end when it reaches 1000000:               bn = 0; Dynamic[If[bn === 1, {solve[], bn = 0}]]; bn = 1;


title: manipulate: time limit on calculations

text: I'd like to disable the 5 second time limit in the manipulate construct. I read about setting                   SynchronousUpdating -> False      But for some reason this does not apply to Evaluations within controls:                   Manipulate[Plot[Sin[a*x], {x, 0, 2 Pi}], {{a, 1}, Button["set a", Pause[6]; a = 2;] &}, SynchronousUpdating -> False]      In the above example a is not set to 2 when pressing the button. When the Pause timespan is set to 5 or below, a is actually set to 2. Does anybody know how to fix that, i.e. how to disable the time limit for evaluations in controls?


title: InputString in Button freezes Mathematica

text: > **Possible Duplicate:**   >  Why does Button[ … , ChoiceDialog[] ] freeze the front end? **Warning: the following code may freeze your session,** as it does mine. I have to wait for the dialog asking whether to abort dynamic updating if that happens. Run this with a fresh kernel:               Button["Pressing this button may freeze your session!",             InputString["Type something", "(or just press Enter)"]           ]      and press the button. Then try to interact with the dialog. I see a spinning wait cursor, then I have to "Abort" dynamic execution twice to get back control of Mathematica (the kernel quits). I found no items under "Possible Issues" for either `InputString` or `Button` that could explain this.   1. Is this a bug?   2. How else could I obtain input from a user who clicks a button? Version 8.0.4 on Mac OSX.


title: High quantum harmonic eigenfunctions?

text: How to obtain high quantum harmonic eigenfunctions? Everything works until, let say 65th eigenfunction, but for higher eigenfunctions values are too high. My code               NoH = Table[1/Sqrt[2^n n!] Pi^(-1/4), {n, 0, ns - 1}];     phi[x_] = Table[NoH[[i]] HermiteH[i - 1, x] Exp[-x^2/2], {i, ns}];      NoH are normalization factors, phi[x] are eigenfunctions. Best regards.


title: Cannot Get Numerical Results to Match

text: I try this numerical summation (in two parts)               a = NSum[(HarmonicNumber[2 m])/m^3, {m, 1, Infinity},            WorkingPrecision -> 100, PrecisionGoal -> 100];     N[Pi^3/24 Log[2]^2 + Log[2] Pi/16 Zeta[3] - Pi^5/960 - Pi/16 a, 100]      and this numerical integration               NIntegrate[x^2 Log[Sin[x]] Log[Cos[x]], {x, 0, Pi/2},        WorkingPrecision -> 100, PrecisionGoal -> 100]      which are supposed to give the same result, and they do, but only to 25 places. Obviously, at least one of the results is off. How can I increase the precision so that these agree past 25 places? If that can't be done, which of these is the more accurate? If I try to evaluate the first quantity symbolically, I get               b = Sum[(HarmonicNumber[2 m])/m^3, {m, 1, Infinity}]      > >     1/144 (π^4 + 72 (EulerGamma + Log[4]) Zeta[3] - 36 Sqrt[π]   >         (HypergeometricPFQRegularized^({0, 0, 0, 0, 0}, {0, 0, 0, 1}, 0))[ >           {1, 1, 1,1, 3/2}, {2, 2, 2, 3/2}, 1]) >   However, `N[b,20]` never returns. The problem seems to be the evaluation of the derivative of `HypergeometricPFQRegularized`.


title: How to show solid bodies using volumetric rendering?

text: **Note:** This question was asked when Mathematica 8 was latest release. Version 9 has built-in support for volume rendering through `Image3D`. * * * There's an example on wolfram.com showing some medical data rendered in 3D. Unfortunately there's no code, only an animation. ![Volume rendering](http://i.stack.imgur.com/3Wf3c.png) Note that the data is shown as a solid three-dimensional body, not only 2D slices of it like in the example on the doc page of `Texture`. Given a 3D texture, how can such a visualization of a solid 3D body be made using Mathematica? You will find the volumetric data on the doc page of Texture, under Applications -> Volume Rendering. I notice there's something included with CUDALink. Unfortunately I can't try it (I don't have the hardware), but it looks quite different from the image I linked to above, so I think there must be an independent way to produce the image above. [With Sjoerd's hardware (it's pretty cool, movements are totally smooth):]   ![Mathematica graphics](http://i.stack.imgur.com/uWMip.png) Link to the MathGroup version of this post.


title: Problem with NDsolve for a system of equations

text: I want to solve a system of differential equations which is not very complicated, but I cannot handle the problem with mathematica!! Please have a look at the problem and result and help me with your comments:               F=3;     ss2 = NDSolve[{3000/7*(u''[x] - 1/56*PHI''[x]*Sign[PHI'[x]]) == 0,                     1000/7*(w''[x] + PHI'[x]) + F == 0,                     125/2744*PHI''[x] - 1000/7*(w'[x] + PHI[x]) == 0,                     3000/7*(u'[3/7] - 1/56*Abs[PHI'[3/7]]) == -1,                     u[0] == 0, w[0] == 0, w[3/7] == 0, PHI'[0] == 0, PHI'[3/7] == 0},               {u, w, PHI}, {x, 0, 3/7}];      And the message Mathematica generates for this:               NDSolve::ndsv: Cannot find starting value for the variable PHI'      Thank you for your attention.


title: Why I cannot use the option "MathOutput"?

text: I'm on Windows 8.1 with Mathematica 9.               Export["test.html",EvaluationNotebook[],"MathOutput"\[RightArrow]"GIF","CSS"->None]          Export["test.html",EvaluationNotebook[],"CSS"->None,"MathOutput"\[RightArrow]"GIF"]      > Export::argt: Export called with 4 arguments; 2 or 3 arguments are expected. > >> > > Export::noelem: MathOutput[RightArrow]GIF is not a valid set of export > elements for the HTML format. >> I think picture is clear to show the problem. ![enter image description here](http://i.stack.imgur.com/WP3hk.png) `"CSS" -> None, "MathOutput" \[RightArrow] "GIF"` are options? right? and order sensitive? `"CSS" -> None` seems to be an argument? of course it's an option in the help page of HTML,


title: add a legend show the expression for each contour?

text: I am trying to visualizing the unit circle under different norm functions, here is the code:               ContourPlot[{     Abs[x]^(1/2)+Abs[y]^(1/2)==1,     Abs[x] + Abs[y] == 1,     x^2+y^2==1,     Abs[x]^3+Abs[y]^3==1,     Max[Abs[x], Abs[y]] == 1     },     {x, -1.1, 1.1}, {y, -1.1, 1.1}     ]      I want to add a legend show the expression for each circle, how can this be done?


title: A problem with polynomial root finding

text: I use the expression               N[(x - Sqrt[2] + Sqrt[3]*I + 10^-20*(1 + I))^50*(x - Sqrt[2] +           Sqrt[3]*I)^25*(x - Sqrt[2] + Sqrt[3]*I +           2*10^-20*(1 + I))^13*(x - Sqrt[2] + Sqrt[3]*I +           3*10^-20*(1 + I))^12, 5000]      to gernerate a highly ill-conditioned polynomial. Then I use               N[Expand[%, x], 5000]      to expand it. Finally, I want to use               NSolve[%, x, 50]      to solve it. However. the kernel breaks down after running thirty minutes or so, without indicating that it is out of memory. Is this a _Mathematica_ bug? Are there any bugs in the Jenkins Traub method? Or are there bugs in _Mathematica_ 's precision control?


title: MaxSteps and Computing time issue for Solving Differential equation in Mathematica

text: When we solve differential equation numerically using `NDSolve` then sometimes we get error like **NDSolve::mxst:** _Maximum steps reached_ According to Mathematica docs the solution is to increase `MaxSteps`. For example if you used `MaxSteps -> 100` and limit of x 0 to 100 but Mathematica calculated up to the `x=50` then increasing steps `MaxSteps -> 200` will solve your problem. My problem is what i got from mathematica is -               During evaluation of In[212]:= NDSolve::mxst:           Maximum number of 10000 steps reached           at the point x == 2.1685790754404513`*^-14.      So even if i want to got from limit 0 to 2 for `x` then my steps should be 10^14 times larger. It will take a huge huge computing time. How much it may take for core i3 processor? **Is there any other way to compute quickly or solve this problem of maxsteps in any other way?** My ODE:               v[x_] := {v1[x], v2[x]} ;     ini = v[0] == {1, 0};       soln = NDSolve[LogicalExpand[I v'[x] == H.v[x] && ini], {v1, v2}, {x, x1, x2}]      where H is matrix


title: Is it possible to regain Mathematica 5.2's palette input focus behaviour with version 8.0?

text: Between Mathematica 5.2 and later versions, there has been a change in determining which notebook gets the palette input focus, which leads to quite unfortunate behaviour if you use focus-follows-mouse as I do. For those who don't know focus-follows-mouse: This mode gives the keyboard input focus to the window which currently contains the mouse pointer. Now consider the following situations: There are two notebooks and a palette open (one of the notebooks might be the help window, which under Mathematica is basically just a notebook). Let's say, the first notebook is on the left, the second one is in the middle, and the palette is on the right. Let's also say that I'm working on the left notebook, and now want to use the palette. Therefore I move the mouse to the palette and press the button I want. In Mathematica 5.2 this had exactly the intended effect: Mathematica remembered that I last interacted with the left notebook, and inserted the input generated by the palette there. However in Mathematica 8.0 the input is instead inserted in the _right_ notebook. Of course it's not hard to understand how this happens (and indeed, the problem is not restricted to Mathematica, but occurs also e.g. with Gimp; however the fact that Mathematica 5.2 got it right gives me hope that it's just some option I have to toggle or some initialization I have to edit to regain the behaviour). When I move the mouse pointer from the left notebook to the palette, it of course crosses the right notebook which is in between, and therefore focus-on-mouse gives the keyboard input focus to that window. Of course it loses the input focus again when I move on to the palette (which ultimately gets the input focus), but newer Mathematica versions obviously record which window had input focus last and use _that_ to determine which notebook the palette should act on. Therefore my question is: Is there some option I can set to recover the old Mathematica-5.2 behaviour? Or if not, is there a way to get it with some Mathematica programming (which I then could put into an init file)? **Edit** As I said in a comment to an answer that was deleted in the mean time, I've found out that Mathematica 7 still behaves in the way I want. So the change was obviously introduced in between 7 and 8. I'm adding that here so that the information is visible to those who cannot see deleted answers (and in case the deleted answer including comments might eventually go away completely). Also note that (as I also wrote in that comment) `SelectedNotebook[]` changes the same way (i.e. follows focus unconditionally in version 8, but changes only on interaction in v7).


title: Clear variables

text: I'm new in Mathematica and I am working with various notebooks. My problem is that when I run a notebook, it seems taking definitions from the previous notebook. For example in 'notebook1' I make an approximation like E=M, and when I run the second notebook it takes also the approximation instead I don't want it to do it. I've tried commands like 'Clear' or 'ClearAll' but I can't get through. Can anybody help me? Thanks


title: Is there a system Reset?

text: > **Possible Duplicate:**   >  How do I clear all user defined symbols? The normal way I reset the Mathematica kernel to its initial state is through the notebook interface: `Evaluation` menu, `Quit Kernel` item, `Local` submenu, then the `Quit` confirmer button in the resulting dialog box. I do this often enough that my fingers know the drumbeat: `Alt-V Q L Q`. But I really need a way to set things back to normal from code. I suppose I could go               ClearAll /@ Names["Global`*"]      or even               Remove /@ Names["Global`*"]      which does much of what I want, but seems really ham-handed to me, and doesn't really guarantee a complete system reset -- at least I don't think. There is also the ancient `CleanSlate` utility, which I can call from inside a notebook or package, but I have heard rumors that it's deprecated and unsupported: ![Mathematica graphics](http://i.stack.imgur.com/zfUgV.png) My attempts to search the documentation and ![Mathematica graphics](http://i.stack.imgur.com/PchYh.png) for something resembling `Reset` or `Restart` or `Clean` yielded nothing useful. Advice? **EDIT** : In case you're wondering, I want this for unit-testing big Packages, where I want to Reset in the unit-testing scripts so that I can have deterministic values for results of certain `Unique[]` evaluations. **EDIT** : I found `Quit[]` and `Exit[]`. That may be as close as we can get. I do not see any difference in them ![Mathematica graphics](http://i.stack.imgur.com/ng4i2.png)


title: How to avoid restart during development?

text: > **Possible Duplicate:**   >  How do I clear all user defined symbols? During package development things get messed up quite often. (especially when playing with notations) Is there a simple way to reset MMA from within a notebook (Maple has "Restart")?


title: Determining whether two k-chromatic graphs are equivalent (not simply isomorphic) using IsomorphicGraphQ?

text: In a previous question of mine, I asked whether Mathematica's built-in routines could determine an isomorphism for two $k$-chromatic graphs, Determining whether two $k$-chromatic graphs are isomorphic (respecting vertex coloration). In response, the user whuber came up with a really neat/clever technique to add a (complete graph) module to the original $k$-chromatic graphs under comparison s.t. an isomorphism exists for the two $k$-chromatic graphs iff an isomorphism exists for their monochromatic forms with the attached module. This, as whubar points out, allows one to proceed using Mathematica's built-in functions IsomorphicGraphQ or FindGraphIsomorphism. Here I'd like to ask a slightly different question - Let $G_1$ and $G_2$ be two $k$-chromatic graphs, i.e. graphs where vertices can be independently assigned one of up to $k$ unique colors (I am open to any method of implementation for this in Mathematica 8 or 9). I'd like to know if $G_1$ and $G_2$ are equivalent rather than simply isomorphic. In other words, I'd like to know if an isomorphism exists for the monochromatic versions of $G_1$ and $G_2$ s.t. the same isomorphism applied to their $k$-chromatic forms works without color reassignment. Is it possible to replace each colored vertex with a monochromatic "widget" s.t. a positive result for IsomorphicGraphQ or FindGraphIsomorphism will imply the equivalence of the $k$-chromatic forms of $G_1$ and $G_2$? Also, is an answer of "False" from IsomorphicGraphQ (or the return of an empty set for FindGraphIsomorphism) necessarily indicative of their being no isomorphism? Or do these algorithms simply time out if the number of graph components are too large? It would be extremely helpful to know if the latter is true since this would require me to write my own implementation.


title: Restricting a plotted expression to reals in a Manipuate

text: I have an expression from which I'm trying to create a plot that I can manipulate. The expression contains `Abs`, and I only want to have it evaluated for reals. What happens when I manipulate the plot is that it is appears to render even when `Abs` is taking on a complex value, which is something I want to prevent. Is there a way to restrict the rendering only when a Real number is produced, and ... I don't know ... show a blank plot otherwise. ### EDIT example function               e1 = Abs[Sqrt[delta*Cos[theta] - b]]     e1 // Manipulate[Plot[#, {theta, 0, 2 Pi}], {b, 0, 2}, {delta, 0, 2}] &


title: How can I download price information for multiple stocks at once?

text: I have a list of stock tickers. Is it possible to download price information over a period of time all in one go, or download other types of information across multiple stocks in one go?


title: DataRange problem in a ListLinePlot within a Manipulate

text: I'm trying to create a simulation of a set of lists with `Manipulate[]` and `ListLinePlot[]`. However, as my simulation starts **with** the $x$-axis pre- defined (`DataRange -> {1, 500}`), the lists behave strangely, i.e., they are not plotted as intended. The lists **do not obbey** the $x$-axis (which is correctly plotted), but instead of that they are always at the right edge of the plot. My code is:               randomWalk[x_]:=Accumulate[Prepend[RandomVariate[NormalDistribution[0, 1], x], 0]]     exchange=Table[Subscript[asset, i] = randomWalk[500], {i, 1, 5}];     Manipulate[ListLinePlot[exchange[[All, 1 ;; n]], DataRange -> {1, 500}], {n, 3,500, 1}]      Could someone give me a hint to solve this problem?


title: Iteration of multiple functions that feed into each other

text: I'm trying to figure out how to iterate through several functions that all "feed" into one-another but am having some trouble. Here are the variables:               r[1]={1,2,3}     r[2]={3,4,5}     G=1     M=2     dt=20     r1 = N[Sqrt[r[1].r[1]]];     r2 = N[Sqrt[r[2].r[2]]];     TA = N[ArcCos[r[1].r[2]/(r1 r2)]]     A = Sqrt[r1 r2 (1 + Cos[TA])]      And here are the functions:               S[z_] := N[(Sqrt[z] - Sin[Sqrt[z]])/Sqrt[z^3]]     c[z_] := N[(1 - Cos[Sqrt[z]])/z]     y[z_] := r1 + r2 - (A (1 - S[z] z))/Sqrt[c[z]]     x[z_] := Sqrt[y[z]/c[z]]     t[z_] := (x[z]^3 S[z] + A Sqrt[y[z]])/Sqrt[G M]     F[z_] := (y[z]/c[z])^(3/2) S[z] + A Sqrt[y[z]] - Sqrt[G M] t[z]     dF[z_] := (y[z]/c[z])^(3/2) (1/(2 z) (c[z] - 3/2 S[z]/c[z]) + 3/4 S[z]^2/c[z]) + (A/8) ((3 S[z] Sqrt[y[z]])/c[z] + A Sqrt[c[z]/y[z]])      and I'm trying to iteratively do the following               z[i + 1] := z[i] - F[z[i]]/dF[z[i]]      I tried using FixedPointList, but the Mathematica help files confused me more than anything once they got past the most basic examples (my knowledge of Mathematica's syntax is quite limited). I'd love it if someone would be able to help. I was extremely tempted to just do it in excel as it would be a lot simpler for me, but I feel like it should be done in Mathematica. EDIT: I've since given up trying to use FixedPointList and have decided to switch to a more intuitive While loop (I know using Whiles are frowned upon, but I like them as they allow one to break the logic down step-by-step). I've also switched from using Newton's method to a bisection method. Here is my code so far, but currently it isn't giving me any output at all (a reference to the loop algorithm is given by http://ccar.colorado.edu/~rla/documents/lambert.pdf near the end of the document):               G = 6.672*10^-11     m[0] = 1.988544*10^30     dt = 254*86400     R[1] = {6.6072*10^10, 1.31631*10^11, -3.64831*10^6}     R[2] = {-1.30112*10^11, -1.90008*10^11, -7.90975*10^8}     R1 = 1.47283*10^11     R2 = 2.30289*10^11     TA = 2 Pi - N[ArcCos[R[1].R[2]/(R1 R2)]];     A = Sqrt[R1 R2 (1 + Cos[TA])];     z = 0     zhi = 4 Pi^2     zlow = -4 Pi     c[z_] := 1/2     S[z_] := 1/6     While[Norm[t[z] - dt] > 1*10^-6,      y[z_] := R1 + R2 + (A (S[z] z - 1))/Sqrt[c[z]];      Print[y[z]];      While[A > 0 && y[z] < 0, zlow = zlow + 1];      X[z_] := Sqrt[y[z]/c[z]];      t[z_] := (X[z]^3 S[z] + A Sqrt[y[z]])/Sqrt[G m[0]];      If[t[z] <= dt, zlow = z, zhi = z];      z = (zhi + zlow)/2;      If[z > 1*10^-6, c[z_] := (1 - Cos[Sqrt[z]])/z;        S[z_] := (Sqrt[z] - Sin[Sqrt[z]])/Sqrt[z^3],        If[z < -1*10^-6, c[z_] := (1 - Cosh[Sqrt[-z]])/z;         S[z_] := (Sinh[Sqrt[-z]] - Sqrt[z])/Sqrt[(-z)^3], c[z_] := 1/2;         S[z_] := 1/6]];      Print[Norm[t[z] - dt]];]       Any help would be greatly appreciated. Thank you guys.


title: How can I separate two parts of power of Exponential functions?

text: How can I separate two parts of power of exponential functions in Mathematica? I have an expression similar to this one:               a*b*Exp[u+v]+c*Exp[u]      I want to set `Exp[v]` to zero. For this target I need to expand `Exp[u+v]` to `Exp[u]*Exp[v]`, then set `Exp[v]-> 0`. How can I expand `Exp[u+v]` to `Exp[u]*Exp[v]` in Mathematica?


title: Why Eigenvalues thinks matrices are non-numerical

text: I use Mathematica version 9.0.1.               matA = DiagonalMatrix[ConstantArray[1, 3]];          matB = Normal[SparseArray[{Band[{1, 1}] -> 200, Band[{1, 2}] -> -100,       Band[{2, 1}] -> -100}, {3, 3}]];      `{matA, matB}` gives               {{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{200, -100, 0}, {-100, 200, -100}, {0, -100, 200}}}      `e1 = Eigenvalues[{matB, matA}]` gives an error: > Eigenvalues::exnum: Eigenvalues has received a matrix with non-numerical or > exact elements. >> `e2 = Eigenvalues[N@{matB, matA}]` gives the answer:               {341.421, 200., 58.5786}      **Question:** Why would `e1` give an error when both matrices are numerical? I don't understand why `N@{matB, matA}` is needed to get their eigenvalues.


title: Is there a way to have Plot draw points on a function where the function is undefined as circles as in textbooks?

text: A very common feature of graphs of functions used throughout textbooks are simple indications, such as open circles, of the points at which a function is undefined. Is there a way to do this in Mathematica? I understand that I can use `Epilog` (or `Prolog`, or other explicit drawing graphics functions) to "manually" draw these elements, but us there a way to automatically do this, or at least return the coordinates of such points for use as arguments to `Epilog`?


title: Estimation of vector autoregressive (VAR) process

text: To estimate 1-dimensional VAR process (which is AR process) you can easily use functions `EstimatedProcess` or `FindProcessParameters` like this:               sample = RandomFunction[ARProcess[{.2,-.4},.1], {1,300}];          EstimatedProcess[sample, ARProcess[{a,b},v]]     (*or*)     FindProcessParameters[sample, ARProcess[{a,b},v]] Now lets say we have sample               alpha = {{.2,.1}, {-.3,.2}};     sigma = {{1.0,0}, {0,0.3}};     sample = RandomFunction[ARProcess[{alpha},sigma], {1,100}] which is based on two dimensional VAR process (I took this definition from `ARProcess` documentation). Then neither of this two ways does work:               EstimatedProcess[sample,ARProcess[{{{a1,a2}, {a3,a4}}}, {{v1,v2}, {v3,v4}}]]          FindProcessParameters[sample,ARProcess[{{{a1,a2}, {a3,a4}}}, {{v1,v2}, {v3,v4}}]] Is it possible to estimate vector autoregressive process in Mathematica?


title: Looping with NDSolve?

text: I have a series of PDE equations that are solved with NDSolve for certain variables $a$ and $b$ - Now, I want to see the output at a time $t$ as $a$ and $b$ change; so I was thinking of a loop formulation, where both variables increment , the PDEs are solved and the output for time $t$ saved. I am not sure how to implement this in mathematica, or whether it's even the best way to do it - I will eventually want to use the outputs for curve fitting to some data. Any suggestions would be appreciated!


title: Background in ItemStyle

text: I would expect the following to output the same grids               {Grid[{{1, 2}, {3, 4}}, ItemStyle -> {, , {{1, 1} -> Directive[30]}},        Background -> {, , {{1, 1} -> Red}}, Frame -> All],      Grid[{{1, 2}, {3, 4}},        ItemStyle -> {, , {{1, 1} -> Directive[Background -> Red, 30]}},        Frame -> All],       Grid[{{NumberForm@1, 2}, {3, 4}},        ItemStyle -> {, , {{1, 1} -> Directive[Background -> Red, 30]}},        Frame -> All]}      instead of ![enter image description here](http://i.stack.imgur.com/MoZkC.jpg) **Update:** The following should all produce identical grids and in fact they (almost) do - provided you mix and match between different Mathematica versions:                {Grid[{{1, 2}, {3, 4}},ItemStyle -> {None, None,{{1, 1} -> Directive[30]}},Background -> {, , {{1, 1} -> Red}}, Frame -> All],        Grid[{{1, 2}, {3, 4}},ItemStyle -> {{} , {},{{1, 1} -> Directive[Background -> Red, 30]}}, Frame -> All],        Grid[{{NumberForm@1, 2}, {3, 4}},ItemStyle -> {Automatic,Automatic, {{1, 1} -> Directive[Background -> Red, 30]}}, Frame -> All],       Grid[{{Item[1, BaseStyle -> {Background -> Red, FontSize -> 30}],2}, {3, 4}},Frame -> All],       Grid[{{Item[Style[1, 30], Background -> Red], 2}, {3, 4}},Frame -> All]}      **V6:** ![enter image description here](http://i.stack.imgur.com/fC03F.png) **V7** ![enter image description here](http://i.stack.imgur.com/ChMiV.jpg) **V8** ![enter image description here](http://i.stack.imgur.com/zsmP8.jpg) **V9** ![enter image description here](http://i.stack.imgur.com/Vlm0g.jpg) The "almost" is that the second Grid - perhaps the cleanest implementation - is yet to fire but perhaps in V10 ...? (As a side note, n.b. the alternative padding (`None`,`Automatic`,`{}`,`,`}) to reach the cell specification in the `ItemStyle` option - maybe one day argument positions might more seamlessly combine with their structure? ) **Upshot:** There seems to be a bug in combining values for the `Background` option with other styling within a single `Directive` but this can be easily overcome by using both specifications as per the first Grid above.


title: Using parallel computing to build a matrix recursively

text: I am trying to compute the product of a sequence of matrices using the command `ParallelDo`. Of course, if I use the simpler command `Do`, I am able to do the computation. In order to set my current problem, I've considered my Table of Matrices (with another less trivial values):               R = ParallelTable[i*IdentityMatrix[2], {i, 0, n}]      And now, I would like to compute something like:               g = IdentityMatrix[2];     Do[g = R[[i]].g, {i, 1, n}]      To reduce the computing time, I would like to use `ParallelDo`. Can someone help me please?


title: Apart may use Padé method: what's that?

text: How does `Apart` work? The page `tutorial/SomeNotesOnInternalImplementation#7441` says, "`Apart` uses either a version of the Padé technique or the method of undetermined coefficients. I know what the latter is (clear of fractions, collect by powers of the variable, equate coefficients of corresponding powers, solve the resulting linear system). What's the former? (I know what Padé approximation is.)


title: Grouping constants in expressions

text: Starting from the general expression:               i A(a x + b y + c z + ...) + j B(a' x + b' y + c' z + ...) + k C(a'' x +b'' y + c'' z + ...)      I'd like to rearrange it to obtain:               x(a i A + a' j B + a'' k C) + y(b i A + b' j B + b'' k C) + z(c i A + c' j B +c'' k C) + ...      Without using $x$, $y$, $z$ etc. as arguments for `Collect`, since there are too many parameters for that to be practical and each of $x$, $y$, $z$ etc. have a form that can't be known beforehand. To clarify, the initial expression would be something like this: $$a_T \sum _{i=1}^6 \sum _{j=1}^6 \left(\text{phi}_{2,1} \text{Bin}[[i,j,5]] \text{Bout}[[i,j,4]]\right)+a_v \sum _{i=1}^6 \sum _{j=1}^6 \left(\text{phi}_{1,4} \text{Bin}[[i,j,6]] (-\text{Bout}[[i,j,1]])\right)+b_T \sum _{i=1}^6 \sum _{j=1}^6 \left(\text{phi}_{1,j} (-\text{Bout}[[2,3,i]]) \text{Bin}[[i,j,6]]\right)+b_V \sum _{i=1}^6 \sum _{j=1}^6 \left(\text{phi}_{2,j} \text{Bout}[[i,2,3]] \text{Bin}[[i,j,5]]\right)+c_V \sum _{i=1}^6 \sum _{j=1}^6 \sum _{k=1}^6 \left(\text{phi}_{5,k} \text{Bout}[[i,j,3]] \text{Bin}[[i,j,k]]-\text{phi}_{6,k} \text{Bout}[[i,j,4]] \text{Bin}[[i,j,k]]\right)$$ Every instance of $phi_{i,j}$, $bin_{i,j,k}$ and $bout_{i,j,k}$ (the elements of the Bin and Bout arrays) is a sum of symbolic terms so that in the end $x$, $y$ or $z$ may end up being something like $\Lambda \Omega \Sigma$. These final combinations are numerous enough that using them as an argument for a command is impractical (as writting them down would defeat the purpose of using the expression in the first place). An example result of the above expression would be $$ 2 c_V \left(-8 \sqrt{2} \Xi ^0 \overline{\Xi ^0} K^{*0}\text{(0)}-12 \sqrt{2} \overline{\Xi ^0} K^0 \Xi ^0+5 \sqrt{6} \overline{\Sigma ^0} \omega _8\text{(0)} \Xi ^0\right) + b_T \left(8 \sqrt{2} \overline{\Xi ^0} K^0 \Xi ^0 + 3 \sqrt{6} \overline{\Sigma ^0} \omega _8 \text{(0)} \Xi ^0 - \sqrt{2} \overline{\Sigma ^0} \Xi ^0 \pi ^0 \right) + b_V\left(6 \sqrt{2} \unicode{f3b5} \unicode{f3b5} \Xi ^0 \overline{\Xi ^0} K^{*0}\text{(0)}+10 \sqrt{2} \overline{\Xi ^0} K^0 \Xi ^0-3 \sqrt{6} \overline{\Sigma ^0} \omega _8\text{(0)} \Xi ^0\right)$$


title: Plotting two functions against each other

text: I have two functions which are functions of `t`. Let's just say `x1[t]` and `x2[t]`. I want to plot `x1` vs `x2`. How do I do this?


title: Problem using OptionValue with functions defined by SubValues, and the use of Options for function dispatch

text: I have a function that looks like:               (a : pump[_, __])["curve QH", opts : OptionsPattern[]] :=       Plot[x, {x, 0, 2}, Frame -> True, FrameLabel -> {"a", "b"},        Evaluate[FilterRules[{opts}, Options[Plot]]]      This code allows me to substitute the option of `Plot`, with whatever I may want (where `pump` acts like a very simple object). Now suppose I want to use an option to define if a `Plot` or a `Table` should be outputed. I imagined something like this:               (a : pump[_, __])["curve QH", opts : OptionsPattern["type" -> "plot"]] :=      Which[       OptionValue["type"] == "plot",       Plot[x, {x, 0, 2}, Frame -> True, FrameLabel -> {"a", "b"},         Evaluate[FilterRules[{opts}, Options[Plot]]]],       OptionValue["type"] == "table",       Table[x, {x, 0, 2, 0.1}]       ]      but it doesn't work. What is the best strategy to use Options with this kind of definition?


title: Why isn't Lookup treated like other symbols?

text: With Mathematica 10, I wanted to overload `Lookup` using `TagSetDelayed`, but it doesn't work. For instance, if I define two objects with head `TempHead`               t1 = TempHead[a -> 1, b -> 2, c -> 3];     t2 = TempHead[c -> 3, d -> 4, e -> 5];      I can overload `Plus` as usual:               TempHead /: Plus[t1_TempHead, t2_TempHead] := TempHead @@ Join[List @@ t1, List @@ t2]      So:               t1 + t2     (* TempHead[a -> 1, b -> 2, c -> 3, c -> 3, d -> 4, e -> 5] *)      But, if I do the same thing with Lookup, it doesn't work:               TempHead /: Lookup[t1_TempHead, t2_TempHead] := TempHead @@ Join[List @@ t1, List @@ t2]     Lookup[t1,t2]     (* Lookup::invrp: The argument TempHead[a->1,b->2,c->3] is not a valid Association or a list. >> *)      Further, you cannot even use `Unprotect` to overload `Lookup`. I thought this was a bug, but when I reported it to Wolfram, they said `Lookup` was designed to give an error on all objects that aren't `Associations`. Certainly there are Mathematica functions that give errors (e.g. `Part`, when you try to access outside the length of a `List`), but you can usually still overload them. Does anyone know if there is a good reason for implementing `Lookup` this way? It seems to break with the "Everything is an expression" principle that Wolfram is always touting. Are there other symbols that act like `Lookup`?


title: Mathematica function Det has unexpected behavior

text: I am using _Mathematica_ "Kernel" -> {"Version" -> "9.0 for Microsoft Windows (64-bit) (January 25, 2013)", "ReleaseID" -> "9.0.1.0 (4055652, 4055188)" on a Win 7 machine. The file listed below uses the _Mathematica_ function `Det` to compute the determinant of a matrix whose matrix elements are either: [1] 0 [2] const + const * m^2 , m may be complex [3] const * k^2 [4] const * w^2 This file computes the determinant of four different matrices. The first two seem OK. However, for the last two determinants [in **BOLD** ], _Mathematica_ has given each result as a RATIO, where the denominator of the ratio may, in fact, vanish. Since the determinant is an algebraic sum of products of matrix elements, I do not understand where the denominators of the last two determinants come from. Does anyone know how to prohibit _Mathematica_ from dividing?               ssg={sg->2^(1/3) Gamma[2/3]};          sys[nt_,start_][k_,w_,m_]:=          Module[{n,var,D5,D6,cLD600,cLD6,residu,ca,q,nx,ret},     If[Not[0=== start || 1=== start],Return[{{}}]];     n=2nt+1;     Print[n(2nt+1)," VARIABLES; ",n(2nt+1+2)," EQUATIONS: TOO MANY EQUATIONS"];     Print[2n," = # EXTRA EQUATIONS"];     If[1=== start,nx=2 n-1];     If[0=== start,nx=2(n-1)];     If[1=== start,q=If[#>= 0,F[#1,#2],-F[-#1,#2]]&];     If[0=== start,q=If[#>= 0,F[#1,#2],F[-#1,#2]]&];     var=Flatten[ParallelTable[q[n8,j],{n8,start,nx,2},{j,-nt,nt}]];     D5=ParallelTable[Sum[-(3/20) X^j q[n8,j]-1/2 m^2 X^j q[n8,j]-n8^2 X^j q[n8,j]-1/2 X^-1 k^2 sg X^j q[n8,j]+1/2 X w^2 sg X^j q[n8,j]-1/9 X^j j^2 q[n8,j]-1/2 X^-1 k^2 sg Sum[((-1)^n8m8 (X^j UnitStep[-2n8m8+n8+nx]q[n8-2 n8m8,j]+X^j UnitStep[nx-(2n8m8+n8)]q[n8+2 n8m8,j]))/(Gamma[5/6-n8m8] Gamma[5/6+n8m8]),{n8m8,1,nx}]+1/2 X w^2 sg Sum[ ((-1)^n8m8 (X^j UnitStep[-2n8m8+n8+nx]q[n8-2 n8m8,j]+X^j UnitStep[nx-(2n8m8+n8)]q[n8+2 n8m8,j]))/(Gamma[5/6-n8m8] Gamma[5/6+n8m8]),{n8m8,1,nx}],{j,-nt,nt}],{n8,start,nx,2}];     D6=ExpandAll[X^(1+nt) D5];     cLD600=Flatten[CoefficientList[D6,X]];     cLD6=Drop[Drop[cLD600,-n],n];     residu=Flatten[{Take[cLD600,n],Take[cLD600,-n]}];     ca=CoefficientArrays[Block[{u},     u=Flatten[cLD6];     Thread[u==Table[ 0,{Length[u]}]]],var];     ret={var,ca,residu};     ret     ]          (* EXAMPLE 1 *)          s1odd=sys[1,1][k,w,m];          Expand[FullSimplify[Det[N[Normal[s1odd[[2]][[2]]]/.ssg]/.{k^2->KS,w^2->KT,m^2->M}]/.{0.`->0}]/.{KT->W/KS}]          (* 0.886661 W^3+0.146364 M W^3+0.0080522 M^2 W^3+0.000147638 M^3 W^3-5.43201*10^-18 W^4-2.51499*10^-19 M W^4          (* EXAMPLE 2 *)          s1even=sys[1,0][k,w,m];          Expand[FullSimplify[Det[N[Normal[s1even[[2]][[2]]]/.ssg]/.{k^2->KS,w^2->KT,m^2->M}]/.{0.`->0}]/.{KT->W/KS}]          (* 0.541822 W^3+0.21145 M W^3+0.0273022 M^2 W^3+0.00116764 M^3 W^3-1.11445*10^-17 W^4-1.47813*10^-19 M W^4 *)          (* EXAMPLE 3 ; PROBLEM WITH Det[] *)          s2odd=sys[2,1][k,w,m];          s2odd[[2]]          (* {SparseArray[<0>,{25}],SparseArray[<187>,{25,25}]} *)          (N[Normal[s2odd[[2]][[2]]]/.ssg]/.{0.`->0})[[1]]          (* {0,0,0,0.719142 w^2,-1.59444-0.5 m^2,0,0,0,0.0486904 w^2,0,0,0,0,0.020049 w^2,0,0,0,0,0.011332 w^2,0,0,0,0,0.00742443 w^2,0} *)          Det[N[Normal[s2odd[[2]][[2]]]/.ssg]]/.{0.`->0}     Denominator[%]     FullSimplify[%]          (* -(NUMERATOR)/(k^142 w^170 (3.41252*10^-54 k^30 w^2+3.47154*10^-56 k^30 m^2 w^2)^2)          k^142 w^170 (3.41252*10^-54 k^30 w^2+3.47154*10^-56 k^30 m^2 w^2)^2          **k^202 (3.41252*10^-54+3.47154*10^-56 m^2)^2 w^174**  *)           (* EXAMPLE 4 ; PROBLEM WITH Det[] *)          s2even=sys[2,0][k,w,m];          s2even[[2]]          (* {SparseArray[<0>,{25}],SparseArray[<187>,{25,25}]} *)          (N[Normal[s2even[[2]][[2]]]/.ssg]/.{0.`->0})[[1]]          (* {0,0,0,0.853041 w^2,-0.594444-0.5 m^2,0,0,0,0.267797 w^2,0,0,0,0,0.170416 w^2,0,0,0,0,0.130318 w^2,0,0,0,0,0.107654 w^2,0} *)          Det[N[Normal[s2even[[2]][[2]]]/.ssg]]/.{0.`->0};     Denominator[%]     FullSimplify[%]          (* k^118 w^206 (1.96078*10^-19 k^6 w^14+2.712*10^-21 k^6 m^2 w^14)^4             k^142 (1.96078*10^-19+2.712*10^-21 m^2)^4 w^262 *)


title: Finding minimum fly-by radius between Mars and spacecraft from interpolating function

text: I've written an interplanetary trajectory solver/plotter that plots the path taken by a spacecraft on an Earth-Mars mission, but have run into a little trouble when the spacecraft actually reaches Mars. I'm hoping to be able to get the spacecraft into an orbit around Mars upon arrival, but before I can do that I need to find its closest approach in order to apply the correct delta-v at the right time (using the wonders of NDSolve's WhenEvent function). The trajectory plot relies on the output of an interpolating function from NDSolve, and it is this interpolating function that I am trying to work with. So far I know when the closest approach occurs to within a day, and it is between days 254 and 255 of the trip. I have put the Heliocentric x-y positions of Mars and the spacecraft (between days 254 and 255) into separate tables using the following:               MarsPosition = Table[{x[2][t], y[2][t]} /. Soln, {t, 254*86400, 255*86400, 86400/100}]      SpaceCraftPosition = Table[{x[3][t], y[3][t]} /. Soln, {t, 254*86400, 255*86400, 86400/100}]      And have then calculated their relative x-y positions using the following:               dxy = Sqrt[(MarsPosition - SpaceCraftPosition)^2]      But I am now trying to calculate the minimum approach radius (i.e. combining the x-y positions into a magnitude) from the above bits of code. My futile attempt of trying               dr = Min[Sqrt[dxy[1]^2 + dxy[2]^2]]      and other similar attempts have unfortunately ended in failure. Some sample output looks like this:                 dxy = {{{2.00946*10^8, 9.69241*10^7}}, {{2.03432*10^8,             9.83663*10^7}}, {{2.05917*10^8, 9.98081*10^7}},...}      Where, for example, the first entry shows the x and y relative position as `{2.00946*10^8, 9.69241*10^7}` and I'm trying to combine those two components into a radius. Combining the x-y position pairs into a radius using `Sqrt[x^2 + y^2]` for the first 3 position pairs given above I would get                dr = {{2.231*10^8},{2.25965*10^8},{2.2883*10^8},...}      But this was done manually for each entry and is not practical for hundreds of entries. From this list of radius positions, I can then use `Min[]` to find the closes approach point for the spacecraft relative to Mars. As can be seen below, the spacecraft gets very close to Mars (where the inner semi-circle is Earth's orbit, the outer semi-circle is Mars' orbit and the line joining the two is the spacecraft's trajectory):![enter image description here](http://i.stack.imgur.com/cLVN7.png) And if propagated further we can see that it gets close enough for Mars' gravity to affect its trajectory:![enter image description here](http://i.stack.imgur.com/MFvR3.png) So it looks pretty close, but exactly how close it what I'm hoping to find out. Any help would be greatly appreciated.


title: ListPlot : range from $0$

text: I want to plot values of a table for example:               table = {0.456, 0.7899, 1.3456, 9.8908}      But I want to Plot points (x,y) like:               (0,0.456), (1,0.7899),(2,1.3456),(3,9.8908)      And the ListPlot commend generates the plot for vaues of x from range `{1,10}`, so points like: `(1,0.456),(2,0.7899),(3,1.3456)...` How can I change to plot from $0$ points which I described?


title: Combine multiple notebook files into a pdf/rtf/word/etc file?

text: It's the end of the semester and I have a prof who wants me to turn in a printout of the nb files ive worked on. I have 33 separate files, and I was wondering if there was any easy way I could combine all of these files in batch to another nb or a document format to print out (pdf/rtf/doc/html anything really). Nothing fancy needs to happen here, basically i just need to make this into a printable file and preserve any plots i've made, and I wanted to have it all in a single file so that it's all contained to just that file. The data in these files is very simple, mainly just evaluating a problem using mathematica instead of by hand. There are no dependencies between any of the files to each other or any external libraries.


title: Decompose Expression into Segments

text: Say I have an expression `test = 3 x1^2 - 2 x3^-3` and I would like to decompose the expression into `{3 x1^2, -(2/x3^3)}`, I can do that by using `List @@ test` on Mathematica. However, the problem I face is that when the expression is `test = x1^2`, i get `{x1, 2}` and for `test = (3 x1^2)` i get `{3, x1^2}` instead of `{x1^2}` and `{3x1^2}` respectively. The added information I have is the list of variables. For example, if `test = x1^2` I have the list of variables, which is `{x1}`. And for `test = 3 x1^2 - 2 x3^-3`, I have `{x1,x3}` Is there any other way to get what I want? Thanks


title: Mathematica TCP socket client toward Trading Platform

text: I'd like to connect _Mathematica_ with my Italian electronic trading platform. To connect I need to open a TCP socket client towards the trading platform and send a string command. The high-level description (pseudo code) is like this:               - create new tcp socket on hostname="localhost and port ="5333"     - create out channel     - create input channel          - send request in string format         "function=subscribe|item=<stockCode>|schema=ask1;bid1;last_price"          - read response: if response is like outcom=OK then wait the push update          - read push update            - close socket      But how I can do this with _Mathematica_? Using JLink I should write something like this:               socket = new Socket(TCP_address, TCP_port);     out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),     "UTF-8"));     in = new BufferedReader(new InputStreamReader(socket.getInputStream(),     "UTF-8"));     //send request to T3 .     out.println(messagge);     //Wait response      String response = in.readLine();     //[...]     //If response is outcome=OK wait push data     while(true){     String update = in.readLine();     //Thread to manage push data     }     } catch (UnknownHostException e) {     //[...]     } catch (IOException e) {     //[...]     }     //[...]      But I'd like to know if is possible to avoid java and .net !


title: How to work with lists of functions

text: I have some lists of interpolated functions and I want to know if there is an easy way to operate with them. A simplified example:               listsin = Table[FunctionInterpolation[Sin[i*x], {x, 0, 2 Pi}], {i, 1, 10}]     listlinear = Table[FunctionInterpolation[i*x, {x, 0, 2 Pi}], {i, 1, 10}]      This generates two lists of ten functions each. I want to be able to perform basic operations with these functions: sums, derivatives and products. I came up with a way that works               listsumd = Table[With[{i = i}, (listsin[[i]]'[#] + listlinear[[i]]'[#]) &], {i, 1, 10}]      But want to know if it is possible to do this without having to iterate through all the elements in the table, just by operating directly on the lists.


title: Creating a weighted, directed graph from ordered triples

text: I have a relatively large set of data that I am trying to turn into a weighted, directed graph. The data concerns the inflow of migrants based on country of origin. I currently have three columns of data in excel: a number representing country migrated to ($a_i$), a number representing country of origin ($b_i$), and the number of migrants, $n$, who have traveled from $b_i$ to $a_i$. If I turn this data into a set of ordered triples ($b_i$,$a_i$,$\sigma$) where $a_i$ and $b_i$ are as defined above, and $\sigma$ represents some sort of weight (which I will calculate based upon $n$), would it be possible to have mathematica interpret these triples as directions for constructing a graph? That is, could I somehow yield a directed graph such that each triple corresponds to an edge $b_i\rightarrow a_i$ with weight $\sigma$? Any help is appreciated.


title: Calculating the mean curvature of a surface - suggestions

text: I am attempting to calculate the mean curvature [1, 2] of a surface defined by a function of `x` and `y`. My function is rather simple:               f = 1 - 0.05(Cos[2 π x/L] + Sin[2 π x/L])Cos[2 π y/L];      So to calculate the mean curvature, this is what I do (`κ` is the mean curvature below):               L=79.1829;     f = 1 - 0.05(Cos[2 π x/L] + Sin[2 π x/L])Cos[2 π y/L];     κ=((1 + D[f,x]^2) D[f,y,y]-2 D[f,x]D[f,y]D[D[f,x],y]+       (1+D[f,y]^2)D[f,x,x])/((1 + D[f,x]^2 + D[f,y]^2)^1.5)      And then I plot it as :               (*Surface defined by f*)     Plot3D[       f,       {x, 0, L},       {y, 0, L}       ]      ![enter image description here](http://i.stack.imgur.com/yX7l9.png)                (*Plot of kappa*)      Plot3D[       κ,       {x, 0, L},       {y, 0, L}       ]      ![enter image description here](http://i.stack.imgur.com/ez4VU.png)   1. I wasn't entirely sure of whether to post this question in math.se or mathematica.se but I did so on mathematica.se since it does have a _Mathematica_ component to it.   2. Is what I am doing correct? I ask because this seems rather trivial.   3. Does anyone have any suggestion as to do this in a better way, perhaps plot it in a better way? A little background: * * * I am trying to prove quantitatively that different initial conditions created by the surface like `f` would engender different amounts of curvature for a fluid dynamics problem.


title: Use a pre-computed list instead of RandomInteger

text: I would like to replace `RandomInteger[{1, 10}, {10, 10}]` in the following code:               DynamicModule[{c = 11},        Grid[         Map[Button[ToString @ #,                     c = #,                     Background -> Dynamic[If[Mod[#, c] == 0, Green, White]],                     ImageSize -> {32, 32},                     Appearance ->  "Frameless"] &,            RandomInteger[{1, 10}, {10, 10}],           {2}],          Frame -> All,          FrameStyle -> Directive[GrayLevel[0.8], Dashed],          Spacings -> {.2, .2}]]      with a series of lists; e.g., `Transpose @ Partition[Range @ (10*10), 10]`.


title: How can I shift from one window to another window?

text: I am building a cdf application,which has multiple screens,every screen was linked to another screen. Right now I am using `CreateDialog`. Are there any other options of displaying multiple screens to users?


title: Importing 2d array of files

text: I would like to import multiple files to a 2d array. I know to get a list of files I can do               myfiles=FileNames["*.txt"]     alldata=Import/@myfiles      Is it possible to get my data files in a 2d array if, for example, my files look like               myfiles={file11.txt,file12.txt,file21.txt,file22.txt}      where the numbers in the filenames correspond to an x and y index. I have done this using for loops. Is there a more functional way?


title: No warning when extrapolating with Plot

text: One of the most annoying "features" of Mathematica is that the `Plot` family does extrapolation on `InterpolatingFunction`s without any warning. I'm sure it was discussed to hell previously, but I cannot seem to find any reference here in _Mathematica_.SE. While I know how to simply overcome the problem by defining a global variable for the domain of the interpolation, from time to time I forget to do this and then I spend days figuring out where does the numerical error originate. This can be avoided if `Plot` was to give a warning. Consider the following example. An ODE system is defined and integrated for two different time ranges:               odes = {        a'[t] == -a[t] - .2 a[t]^2 + 2. b[t],         b'[t] == a[t] + .1 a[t]^2 - 1.1 b[t], a[0] == 1, b[0] == 1     };     sol100 = First@NDSolve[odes, {a, b}, {t, 0, 100}];     sol500 = First@NDSolve[odes, {a, b}, {t, 0, 500}];      Now querying the function value for a point outside of the range gives a correct warning:               (a /. sol100)[500]      > >     InterpolatingFunction::dmval: Input value {500} lies outside >     the range of data in the interpolating function. Extrapolation will be > used. >> >   >     651.034 >   The same is not done when we use the function in `Plot`:               Show[      Plot[{a[t], b[t]} /. sol100, {t, 0, 400}, PlotStyle -> {Thick, Red}],      Plot[{a[t], b[t]} /. sol500, {t, 0, 500}, PlotStyle -> {Thick, Blue}]      ]      ![Mathematica graphics](http://i.stack.imgur.com/X7xaL.png) I've tried to force a warning, with no avail. The following example still does not drop a warning, and returns the same plot and not `"Error"`.               On[InterpolatingFunction::dmval]     Check[Plot[{a[t], b[t]} /. sol100, {t, 0, 500}], "Error",       InterpolatingFunction::dmval]      Interestingly, one can be sure that `InterpolatingFunction::dmval` is NOT turned off at all inside the `Plot` family. In the following example, `LogLinearPlot` is able to drop a warning about sampling from below the domain (that can be ignored being unrelated, see this post, also it seems to be fixed in v9), but it does not drop the same warning when sampling from **above** (> 100)!               LogLinearPlot[{a[t], b[t]} /. sol100, {t, 0.1, 500}]      > >     InterpolatingFunction::dmval: Input value {-2.30241} lies outside the >     range of data in the interpolating function. Extrapolation will be used. > >> >   It is even more disturbing to see that `Plot` checks the lower boundary but not the upper (thanks to J.M. for the comment):               Plot[{a[t], b[t]} /. sol100, {t, -1, 500}]      > >     InterpolatingFunction::dmval: Input value {-0.989765} lies outside the >     range of data in the interpolating function. Extrapolation will be used. > >> >   As Oleksandr has pointed out, it is not about lower vs. upper bound but first point vs. the rest.               Plot[{a[t], b[t]} /. sol100, {t, 101, 500}]      > >     InterpolatingFunction::dmval: Input value {101.008} lies outside the >     range of data in the interpolating function. Extrapolation will be used. > >> >   ## **Questions**   1. Why `Plot` does not give a warning when extrapolating an `InterpolatingFunction`? Is there some higher-level consideration that justifies this behaviour, or is it a higly annoying feature that is surely unexpected in most cases (maybe a bug)?   2. How can one force `Plot` to give a warning? Is there any workaround that forces InterpolatingFunction::dmval not to be attenuated inside `Plot`?  Please note that I am not interested in solutions that make sure that I use the same value for integration and for plotting (i.e. defining a global `time` variable). I want to make sure that `Plot` NEVER extrapolates without giving a warning.


title: Get subgraphs: communities of graph g

text: I have a graph `g`. I want a set of graphs `c` which holds the community subgraphs of `g`. I tried `c = Subgraph[g, FindGraphCommunities[g]]`, but it only outputs the whole graph `g`. I see in the documentation that `FindGraphCommunities` returns a list of vertices, this may be why. How do I also get the edges?


title: Semi prime numbers

text: The high school textbook I am using has the example of semi-prime numbers. They wanted students to find (by "perspiration") all the semi-prime numbers less than $50$ (for a question on set theory). A semi-prime number is the product of exactly two prime numbers (not necessarily distinct). How would I generate the first $n$ semi-prime numbers using _Mathematica_?


title: How can I plot Intensity values(Z) based on X and Y position. Data stored as 3 columns in CSV file

text: I have a CSV data file with `X` position, `Y` position and corresponding intensity as `Z`. I would like to plot it to form an image. I have an idea that list density plot is one method,but, somehow the importing of the CSV file as table and plotting is resulting in an error :               Read::readn: "Invalid real number found when reading from "test2 10 10.csv."      I am totally new to Mathematica and just learning. I don't understand why it takes so long to even import a CSV file. Thanks !


title: How to find the variance under the assumption that x follows some probability distribution

text: I am aware that we can find the expectation under the assumption that x follows some probability distribution, something like this:               Expectation[((1 - x)/x), x \[Distributed] BetaDistribution[alpha, beta]]      However, is it possible to find the variance of the above equation (1-x)/x under the same assumption that x follows a beta distribution?


title: NExpectation not up to expectations with Boole or Conditioned

text: _Context_ I am interested in computing numerically the number of extrema at a given threshold for random fields. These numbers are expectations of MultinormalDistributions. _Problem_ This integral should give the differential number of maxima of a scale invariant Gaussian random field ($\gamma=0$ i.e. white noise) at threshold zero.               NExpectation[(-(x*y) + z^2)*Boole[x*y - z^2 <= 0],      {x, z, y} \[Distributed]      MultinormalDistribution[{0, 0, 0}, {{3/8, 0, 1/8}, {0, 1/8, 0}, {1/8, 0, 3/8}}]]      Its value should be `1/4/Sqrt[3]= 0.144338` whereas Mathematica returns 0.138245 which is wrong by a factor of 5 %. Strangely enough if I split the integral in two as               NExpectation[(-(x*y) + z^2)*Boole[x + y >= 0 && x*y - z^2 <= 0],       {x, z, y} \[Distributed]       MultinormalDistribution[{0, 0, 0},{{3/8, 0, 1/8}, {0, 1/8, 0}, {1/8, 0, 3/8}}]] +     NExpectation[(-(x*y) + z^2)*Boole[x + y <= 0 && x*y - z^2 <= 0],        {x, z, y} \[Distributed]      MultinormalDistribution[{0, 0, 0}, {{3/8, 0, 1/8}, {0, 1/8, 0}, {1/8, 0, 3/8}}]]      Mathematica returns the correct answer to 5 digits. I understand integrating numerically Boole is likely to cause problems but I am nonetheless surprised by the poor result. On a related topic                NExpectation[-(x*y) + z^2 \[Conditioned] (x*y - z^2 < 0),       {x, z, y} \[Distributed]       MultinormalDistribution[{0, 0, 0}, {{3/8, 0, 1/8}, {0, 1/8, 0}, {1/8, 0, 3/8}}]]      seems to take a while before returning unevaluated (even though it should probably be the correct way to proceed?). **Questions**   1. Why is the first method doing so poorly?   2. Why is the second method failing altogether?   3. Any guidance on how to tell NExpectation to be "smart" about the Boole condition? Thanks Regards


title: Problem with hole filling using filledCurveToPolygons3D in MMA 10

text: I successfully used the `filledCurveToPolygons3D` function to create `Graphics3D` text in MMA 9 on a Windows 7 PC; see: How can I create a 3D FilledCurve object? However, when I installed MMA 10 on this very same machine and tried using this technique again, all the holes in the text are filled. I tried using the recommended changes to the RHS of `processHoles` that another user had had with MMA 9 on a Mac, but I still ended up with all the holes filled. The same problem shows up as well with the 2D function `filledCurveToPolygons`.


title: Conditional expression

text: How do I evaluate a conditional expression in order to convert the solutions that are in terms of $x$ to a new variable $c$ depending on $x$? The conventional method I have been using with eliminate doesn't work in this case, because the solution is not a simple inequality, but rather conditional.                f[x_] := x^2 + c;      g[x_] := f[f[x]];      y = Solve[g'[x] == 1, x, Reals]      output is:               {{x -> ConditionalExpression[Root[-1 + 4 c #1 + 4 #1^3 &, 1],      c > -(3/4) || c < -(3/4)]},       {x ->  ConditionalExpression[Root[-1 + 4 c #1 + 4 #1^3 &, 2],  c < -(3/4)]},       {x ->  ConditionalExpression[Root[-1 + 4 c #1 + 4 #1^3 &, 3],  c < -(3/4)]}}           Eliminate[c == -x - x^2 && x == y[1], x]


title: ErrorBars/ other way of visualising deviation in Paired Bar Charts (PBC)

text: Data:   * three categories A,B,C   * values in each category: `{median-semiIQR, sIQR (such that this value = median), sIQR (such that this value = median + sIQR)}` e.g. `{{90, 21, 21}, {57, 14, 14}, {117, 69, 69}}` What I want: Preferably, just bar indicating the median value, then an errorbar added, indicating the sIQR, but how is this done in a PBC? Else: cat. A is Red, cat. B Blue and cat. C Green. The last two values of each category have to be Blended, so that they are Pinkish, Lightblueish and LightGreenish, to indicate that these are sIQRs. In addition, I would like to display the median value for each category


title: How do I find the maximum value from the given set of data?

text: I have a set of data like `{{x1, y1},{x2, y2}, ...,{xn, yn}}`.   From this data can I find the value of `x` for which `y` is maximum.   Is it is possible using _Mathemamtica 9.0_?


title: 3D Random Walk with Periodic Boundary Conditions

text: I am working on a 3D random walk with periodic boundary conditions and have written a program that will do this for me but it is extremely slow. Does anyone have any suggestions on how I could speed this up?               Timing[      n = 1.;      T = 10000.;      boundary = 5;      initial = boundary;      step = 0.1;      RandomWalk[x_] :=        Accumulate[        Join[{Table[RandomReal[{-initial, initial}], {3}]},          RandomVariate[NormalDistribution[0, step], {x, 3}]]];       i = 1;      (Label[begin];       p[i] = RandomWalk[T + 1];       If[i == n, Goto[end]];       i = i + 1;       Goto[begin];       Label[end];);      t = 0;      (Label[begin1];       i = 1;       Label[begin2];       positionslist = p[i];       If[p[i][[t + 1, 1]] > boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{-boundary, p[i][[t + 1, 2]], p[i][[t + 1, 3]]}},             RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[p[i][[t + 1, 1]] < -boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{boundary, p[i][[t + 1, 2]], p[i][[t + 1, 3]]}},             RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[p[i][[t + 1, 2]] > boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{p[i][[t + 1, 1]], -boundary, p[i][[t + 1, 3]]}},             RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[p[i][[t + 1, 2]] < -boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{p[i][[t + 1, 1]], boundary, p[i][[t + 1, 3]]}},             RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[p[i][[t + 1, 3]] > boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{p[i][[t + 1, 1]], p[i][[t + 1, 2]], -boundary}},             RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[p[i][[t + 1, 3]] < -boundary,         p[i] = Join[Take[positionslist, t + 1],           Accumulate[           Join[{{p[i][[t + 1, 1]], p[i][[t + 1, 2]], boundary}},                 RandomVariate[             NormalDistribution[0, step], {T - t + 1, 3}]]]]];       If[i == n, Goto[end2]];       i = i + 1;       Goto[begin2];       Label[end2];       If[t == T, Goto[end1]];       t = t + 1;       Goto[begin1];       Label[end1];);]               {9.44905, Null}      I would like to do this simulation for multiple particles (at least 50) for about 100000 time steps and not have it take all day.


title: Finding the Minimum value of an interpolating function

text: I can't seem to use `FindMinValue` to find the min. value of a curve represented by an interpolating function. For instance the below code generates an interpolating function polynomial as the solution of the heat equation.               tsol = u /.        NDSolve[{D[u[t, x], t] == D[u[t, x], x, x], u[0, x] == 0,           u[t, 0] == Sin[t], u[t, 5] == 0}, u, {t, 0, 10}, {x, 0, 5}][[1]]      This plots it:               Plot3D[Evaluate[u[t, x] /. %], {t, 0, 10}, {x, 0, 5},       PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/yfXqT.png) I'd like to find the minimum point in the curve represented by this function at say, `t=10.0`, , so I try doing this:               FindMinValue[tsol, {{x, 0, 5}, {t, 0, 10}}]      Which is obviously wrong. I'd like to find the minimum value AT t=10. This didn't work either:               FindMinValue[tsol[10, x], {x, 0, 5}]      I actually have an interpolating func. which is in `x` `y` and `t` and I am quite flabbergasted. Why is the Dimensions of `tsol` 5? I thought it'd be 2 since it is only in x and t. Plot of tsol[10,x]: ![enter image description here](http://i.stack.imgur.com/YA3BV.png)


title: Force Mathematica not to reduce a fraction

text: I am interested in a function which would stop _Mathematica_ reducing fraction. If my input is `50/100`, _Mathematica_ outputs `1/2`, I want it to output `50/100`. Any nice function which does this? I need this because I want to define a recursive function with this behavior:               f[0]=50/100     f[n_]:=(Numerator[f[n-1]]+1)/(Denominator[f[n-1]]+1)      I want to obtain `f[1]=51/101`, not `f[1]=2/3`, which I get. A more complicated example:               f[0]=50/100     f[n_]:=If[Mod[n,2]==0,(Numerator[f[n-1]+1])/n,Numerator[f[n-1]/(Denominator[f[n-1]]+1)      This gets really annoying if I store 50/100 as {50,100}.


title: Can I store a DataDistribution in a database?

text: I have a `DataDistribution`               data = KernelMixtureDistribution[RandomVariate[NormalDistribution[], 10^5]]       that takes a long time to calculate because of database operations. I don't need to constantly recalculate the distribution, so I'd like to store it in a database, and recalculate it at intervals. The documentation for `SQLBinary` refers to `ExportString`, which seems focused on graphics and doesn't have a generic format. Nor does `StringTake` work on a `DataDistribution`. So, how can I store a `DataDistribution` in an SQL database? EDIT: Thank you again Andy Ross! Here's my solution in the end. creating a string version of a data distribution.               inform = kern // InputForm;     ToString[inform]      Then I save it into an SQL database with `SQLInsert`. Next, to extract it back to usable form:               ToExpression[ ToString[sqlkern] , InputForm]


title: How do you show a cone inside of a sphere?

text: I have a sphere of radius 5 and a cone (i.e. z=√(x^2+y^2)) inside of it. I can show them separately, but I'd like to show them together. I've tried a few tricks with opacity, implicit specifications, show, and range changes, but nothing is giving me a satisfying result. Really I'd like to show the "ice cream cone" shape by itself, but I'd settle for a cone under a hemisphere right now. Anyone know how I can get this done? Thanks in advance


title: Why does Integrate set the constant of integration to be one in this case?

text: Why does                Integrate[(4 x)/(2 x + 1), x]      give                1 + 2 x - Log[1 + 2 x]      Notice the extra `1`. The answer should be `2 x - Log[1 + 2 x]` plus the constant of integration. But Integrate never gives a constant of integration.                Integrate[4 x, x]      (2 x^2*)      Actually, here is the answer by Rubi:                Int[(4 x)/(2 x + 1), x]      (* 2 x - Log[1 + 2 x] *)      And by Maple ![Mathematica graphics](http://i.stack.imgur.com/iAhtu.png) and by Wolfram Alpha ![Mathematica graphics](http://i.stack.imgur.com/Y5saL.png) I restarted the kernel, restarted _Mathematica_. Same answer. Using V 9.01 on windows 7. ![Mathematica graphics](http://i.stack.imgur.com/CkMtg.png) Any idea what is going on? Is this a known feature/issue? One can of course argue that the answer is not wrong, since the constant of integration can be any value, but it is strange that it shows up here only, and with a specific value.


title: Asymptotic expansion on 3 nonlinear ordinary differential equations

text: The 3 nonlinear differential equations are as follows \begin{equation} \epsilon \frac{dc}{dt}=\alpha I + \ c (-K_F - K_D-K_N s-K_P(1-q)), \nonumber \end{equation}   \begin{equation} \frac{ds}{dt}= \lambda_b P_C \ \epsilon \ c (1-s)- \lambda_r (1-q) \ s, \nonumber \end{equation} \begin{equation} \frac{dq}{dt}= K_P (1-q) \frac{P_C}{P_Q} \ \ c - \gamma \ q, \nonumber \end{equation} I want to use asymptotic expansion on $c, s$ and $q$. And values of parameters are: $K_F = 6.7 \times 10^{-2},$   $K_N = 6.03 \times 10^{-1}$ $K_P = 2.92 \times 10^{-2}$, $K_D = 4.94 \times 10^{-2}$, $\lambda_b= 0.0087$, $I=1200$ $P_C = 3 \times 10^{11}$ $P_Q = 2.304 \times 10^{9}$ $\gamma=2.74 $ $\lambda_{b}=0.0087 $ $\lambda_{r}= 835$ $\alpha=1.14437 \times 10^{-3}$ For initial conditions: \begin{equation} c_0(0)= c(0) = 0.25 \nonumber \end{equation} \begin{equation} s_0(0)= cs(0) = 0.02 \nonumber \nonumber \end{equation} \begin{equation} q_0(0)=q(0) = 0.98 \nonumber \nonumber \end{equation} and \begin{equation} c_i(0)= 0, \ i>0\nonumber \end{equation} \begin{equation} s_i(0)= 0, \ i>0 \nonumber \nonumber \end{equation} \begin{equation} q_i(0)=0, i>0\. \nonumber \nonumber \end{equation} => i started with the expansions : \begin{equation} c= c_0+ \epsilon c_1 + \epsilon^2 c_2+......... \nonumber \end{equation} \begin{equation} s= s_0+ \epsilon s_1 + \epsilon^2 s_2+......... \nonumber \end{equation} \begin{equation} q= q_0+ \epsilon q_1 + \epsilon^2 q_2+......... \nonumber \end{equation} we are only interseted in up to fisrt power of $\epsilon$. so, we should get total 6 approximate differential equations to get answer for $\frac{dc_0}{dt}, \frac{ds_0}{dt}, \frac{dq_0}{dt}, \frac{dc_1}{dt}, \frac{ds_1}{dt}$ and $\frac{dq_1}{dt}$ but i think $\frac{dc_1}{dt}$ will disappear while expanding and equating the up to first power of $\epsilon$, do i need to go further up to $\epsilon{^2}$ because $\frac{dc_1}{dt}$ is very important to find and we need 6 approximate differetial equations in total. what can i do? please some one help me.


title: Heron's formula for area of a triangle

text: > Use the first form of Heron's formula to give a function `areah`, which > gives the area of a triangle. Test your answer on the isosceles triangle > `{{-1 ,0}, {1, 0}, {0, 1}, {-1, 0}}`. This is what I have:               areah[triangle_] :=       (lenbroke[triangle]/2 Product[lenbroke[triangle]/2 -         len (lineseg (triangle[[i]])), {i, 1, 3}])      This is what I get when I test it:               areah[{{-1, 0}, {1, 0}, {0, 1}, {-1, 0}}]      I don't know what is wrong because when I test it, it doesn't work.


title: Converting in various currencies

text: I was just playing around with _Mathematica_ converting some currencies:               UnitConvert[Quantity[1, "\[Euro]"], "ISK"]     UnitConvert[Quantity[1, "\[Euro]"], "£"]     UnitConvert[Quantity[1, "£"], "\[Euro]"]     UnitConvert[Quantity[1, "$"], "\[Euro]"]     UnitConvert[Quantity[1, "BitCoin"], "\[Euro]"]     UnitConvert[Quantity[1, "BitCoin"], "$"]      ![outputs](http://i.stack.imgur.com/xj203.png) I was surprised about the outputs #23 and #24. Why can't _Mathematica_ convert them like the rest? So I should take the factor BTC/USD: WolframAlpha says: ![enter image description here](http://i.stack.imgur.com/bq19i.png) ![enter image description here](http://i.stack.imgur.com/uQhPu.png) Why aren't BitCoin rates shown by `UnitConvert`? And btw: Is there a shortcut for the BitCoin symbol in _Mathematica_? Here is what I found out about the symbol/shortcut **EDIT and WARNING:** Do NOT copy/paste the BitCoin sign (฿) from the output!!! It's not interpreted as Bitcoins by _Mathematica_ :               Quantity[371.57, "\[Euro]/฿"]      ![enter image description here](http://i.stack.imgur.com/WKr8s.png) ![enter image description here](http://i.stack.imgur.com/DHnFr.png) _Mathematica_ gives the same symbol for BitCoin and ThaiBaht!               Quantity[1, "฿"]     Quantity[1, "ThaiBaht"]     Quantity[1, "BitCoin"]      ![enter image description here](http://i.stack.imgur.com/D0cI3.png) BUT               UnitConvert[Quantity[1, "฿"], "\[Euro]"]     UnitConvert[Quantity[1, "TahiBaht"], "\[Euro]"]     UnitConvert[Quantity[1, "BitCoin"], "\[Euro]"]      ![enter image description here](http://i.stack.imgur.com/UUDdP.png)


title: Combining the second elements of a set of ordered pairs based on their first element

text: I have a large set of ordered pairs and I am trying to add the second elements together for any group of pairs that has the same first element. For example my data looks like:               data={{1,2},{1,3},{2,3},{3,2},{3,6}}      and I want to return something like:               newdata={{1,5},{2,3},{3,8}}      I figured out how to group the data based on their first element using `GatherBy[data,{First}]`, but I'm not sure where to go from there. I feel like there is probably a much easier way than that, but it is evading me.


title: Merging lists and adding common elements

text: I have two 2D arrays where some of the x-values are identical,               L={{1,1},{2,2},{3,3}};     J={{0,1},{2,2},{4,4}};      I want to add these lists in the following way               {{0,1}, {1,1},{2,4},{3,3},{4,4}};      In other words, that y-values of the data points that have the same x are added. How can I achieve this? * * * **Please note that the arrays are not necessarily of the same length** Two arrays for test:               first = {{0.15, 0.000470185}, {0.16, 0.000521784}, {0.17, 0.000580663}, {0.18,        0.000648083}, {0.19, 0.000725569}, {0.2, 0.000814968}, {0.21,        0.000918532}, {0.22, 0.00103901}, {0.23, 0.0011798}, {0.24,        0.00134508}, {0.25, 0.00154005}, {0.26, 0.00177121}, {0.27,        0.00204667}, {0.28, 0.00237667}, {0.29, 0.00277409}, {0.3,        0.00325523}, {0.31, 0.00384059}, {0.32, 0.00455591}, {0.33,        0.00543312}, {0.34, 0.00651098}, {0.35, 0.00783476}, {0.36,        0.00945361}, {0.37, 0.0114133}, {0.38, 0.0137402}, {0.39,        0.0164132}, {0.4, 0.0193217}, {0.41, 0.0222235}, {0.42,        0.0247384}, {0.43, 0.0264243}, {0.44, 0.0269371}, {0.45,        0.0261818}, {0.46, 0.024341}, {0.47, 0.0217652}, {0.48,        0.0188176}, {0.49, 0.0157753}, {0.5, 0.0128044}, {0.51,        0.00998009}, {0.52, 0.00731676}, {0.53, 0.00479353}, {0.54,        0.00237078}, {0.55, 0}}               second = {{-0.04, -0.0000547619}, {-0.03, -0.000405238}, {-0.02, -0.00207438}, \     {-0.01, -0.00878929}, {0, -0.0154401}, {0.01, -0.0178195}, {0.02, \     -0.0180879}, {0.03, -0.0173267}, {0.04, -0.0157714}, {0.05, \     -0.014605}, {0.06, -0.0131757}, {0.07, -0.0119764}, {0.08, \     -0.010695}, {0.09, -0.00946286}, {0.1, -0.00849357}, {0.11, \     -0.00708071}, {0.12, -0.00578286}, {0.13, -0.00468214}, {0.14, \     -0.00306119}, {0.15, -0.00146214}, {0.16, 0.00061881}, {0.17,        0.00194733}, {0.18, 0.00376762}, {0.19, 0.00509833}, {0.2,        0.00625381}, {0.21, 0.00762286}, {0.22, 0.00918905}, {0.23,        0.0105964}, {0.24, 0.0118067}, {0.25, 0.0134238}, {0.26,        0.0149774}, {0.27, 0.0163519}, {0.28, 0.017469}, {0.29,        0.0167517}, {0.3, 0.0102788}, {0.31, 0.00253876}, {0.32,        0.000314333}, {0.33, 0.000038881}, {0.34, 0.0000224524}}      * * * first array is here: http://www.datafilehost.com/d/731a267e. The second array I generate from this code:               factor = 11.0;     second = Table[{(38 - i)*0.01, 0}, {i, 0, 38}] - 0.04;     tempData = (1/10000) (factor/21) {         0.41,         0.71,         5.74,         46.36,         187.70,         305.90,         319.0,         298.60,         273.50,         245.13,         215.60,         193.50,         167.80,         139.20,         114.20,         93.10,         68.80,         35.56,         11.30,         -26.70,         -55.90,         -85.50,         -105.60,         -129.30,         -155.10,         -172.80,         -195.30,         -218.70,         -240.60,         -266.70,         -288.00,         -316.4,         -330.3,         -325.4,         -281.95,         -160.50,         -37.88,         -7.4,         -1.0         };          For[i = 1, i < Length[tempData] + 1, i++,       second[[i, 2]] = tempData[[i]]];     second = second // Reverse;


title: Given a list of pairs, average the second elements of pairs whose first elements match

text: Say this is my list:               mylist={{1,4},{1,6},{1,11},{2,12},{2,14}}      I want to do an operation that looks at the first element of each pairs, and for all those that match, average their second elements, and put that "first element and averaged second elements" pair in a new list. So my final product would be:               newlist={{1,7},{2,13}}      A caveat however is that the first elements are not obvious integers like in my example. They could be any number and would not easily be iterated over as they would be in my example. I imagine I could do this with loops but I was wondering if there was a more elegant Mathematica "list-manipulation" way. Thank you!


title: Filter through list and lump data

text: I have a very large data set (around 3000) that looks like:               {{1749.08, 580.}, {1749.17, 626.}, {1749.25, 700.}, {1749.33,        557.}, {1749.42, 850.}, {1749.5, 835.}, {1749.58, 948.}, {1749.67,        663.}....      The first number is the year plus the month/12. So I want to iterate over all the list adding the second part for each year So example using data above: `For year 1749: 580+626+700+557+850+835+948+663` I know I have to use a for loop but I can't figure out the syntax. Can anyone lend a helping hand?


title: Re-arranging / selecting of a data table very slow in For loop

text: My task is quite simple; I have a table of data like               M = {{1,2}, {1,3}, {3,4}, {5,1}, {6,9}, {6,8}, {6,1}};      so the table is sorted with respect to the first entry of each tuple. What I want is basically to gather tuples with the same 'x' entry in a new one. M would look like this:               M = {{1,(2+3)/2}, {3,4}, {5,1}, {6,(9+8+1)/3}};      This can be possibly solved elegantly with some gathering and application of summation and counting, but since I'm a C speaker, I've taken the For loop as my first try:               Stringed = ConstantArray[{-1., -1.}, Dimensions[StoreFlat][[1]]]; (* this is     the array where all the data will be stored in. StoreFlat is the sorted but     "uncollected" input *)     Module[{i = 1, j = 1, k = 1, a = 1., f = 1.},       Monitor[        For[i = 1, i <= Dimensions[StoreFlat][[1]], i++, (* loop over the number of tuples *)         If[i == 1, (* first entry *)          f = StoreFlat[[1, 1]];          a = StoreFlat[[1, 2]];,          If[f == StoreFlat[[i, 1]], (* a tuple exists already with this entry *)            a += StoreFlat[[i, 2]];            k++;,            f = StoreFlat[[i, 1]]; (* this entry is larger than the former one *)            a = StoreFlat[[i, 2]];            j++; k = 1;            ];          ];         Stringed[[j]] = {f, a/k}; (* output. the second entry is divided by the number of     entries. *)         ],        ProgressIndicator@N[i/Dimensions[StoreFlat][[1]]]        ]       ];      I know that this is probably not the fastest way. But since my input is not too larger (190 000 tuples of a real, floating point value) this should do the job. Is anything wrong about my approach? On my laptop, this thing takes a lot of time (10 to 20 minutes, I guess - I cancelled it).


title: From a list of (x,y) pairs, generate a new list of (x,ymean) pairs, where ymean is the average of all y's with the same x in the original list

text: This seems like the sort of thing where _Mathematica_ can give a very simple solution. I have a list of points `{x,y}`:               {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 5}}      From this list, I want to generate a new list of pairs `{x,ymean}`, where `ymean` is the average of all `y`'s in the original list which were paired to the same value of `x`:               {{1, 3}, {2, 7/2}, {3, 5}}      What's the simplest, most elegant way to accomplish this in Mathematica?


title: Question about the matrix operation

text: I was wondering if there is an automatic way to do this kind of matrix operation. For example, for a given matrix               list = {{1, 3T}, {3, 8T}, {2, 2T}, {1, 5T}, {4, 6T}};        I want the result to be like this as shown below after the operation.               result = {{1 ,8T}, {2, 2T}, {3, 8T}, {4, 6T}}      The operation will add the terms in the second column if they have the same number in the first column for all the rows. i.e. for the first row, the second term is calculated as `3T` plus `5T`,which is the term in `list[[4,2]]`.


title: Total elements of a list that have a common first element

text: > **Possible Duplicate:**   >  List-operations only when restrictions are fulfilled (Part 1) I have a set of data like:               list = {{Tim, 45},{Mary,100},{Tim,500},{Bob,499},{Mary,50}};      I'm looking for a simple way to total the values based off of the name so that the output would look like: `{{Tim,545},{Mary,150},{Bob,499}}`


title: List-operations only when restrictions are fulfilled (Part 1)

text: Consider the following:               data={{{3542313600, 175}, {3542918400, 175}}, {{3544128000, 450},     {3544128000, 450}, {3545337600, 450}, {3545942400, 450}, {3546547200, 450}}};      whereas the first element of each `{_,_}` represent a date in absolute time, i.e. `{_,_}` corresponds to the pattern `{AbsoluteDate_,Value_}`. Now I would like to calculate the sum of all `Value_` when the corresponding `AbsoluteDate_` is equal, e.g. `{3545337600, 450}, {3545337600, 450}`-> `{3545337600, 900}`.


title: Sorting a table of vectors with weights

text: I'm trying to simplify a table, for instance               {{1, {4, 2, 0}}, {4, {2, 4, 0}}, {-2, {3, 3, 0}}, {1, {3, 0, 3}}, {-3, {0, 4, 2}}}      Here the first column is the "weight" of the corresponding vector in the second column. In the specific problem, the ordering of the entries in the vectors in the second column do not matter, so these can be sorted. I then want to gather the vectors, such that ones that are equivalent only appear once. In the process, I want to sum the weights. For instance, in the above example, the result would be               {{2, {4, 2, 0}}, {-1, {3, 3, 0}}      Any help would be greatly appreciated!


title: How can I fit a matrix function with multiple variables to given eigenvalues?

text: I have a 5x5 matrix function `H[kx]`               H[kx_]:={{T1, kx T8, -I T6, kx T9, -I kx T10},       {kx T8, T2, -I kx T11, kx T12, I kx T13},       {I T6, I kx T11, T3, -I kx T14, kx T15},       {kx T9, kx T12, I kx T14, T4, -I T7},       {I kx T10, -I kx T13, kx T15, I T7, T5}     }      with real parameters `T1` to `T15`, and I have data as follow               dat={{-0.005, -0.418971, 1.24115, 2.6321, 3.07757, 4.40013},       {-0.004, -0.418735, 1.24086, 2.63201, 3.07785, 4.40028},       {-0.003, -0.418551, 1.24063, 2.63194, 3.07806, 4.4004},       {-0.002, -0.41842, 1.24047, 2.63189, 3.07822, 4.40048},       {-0.001, -0.418342, 1.24038, 2.63185, 3.07831, 4.40053},       {0., -0.418316, 1.24034, 2.63184, 3.07834, 4.40055},       {0.001, -0.418342, 1.24038, 2.63185, 3.07831, 4.40053},       {0.002, -0.41842, 1.24047, 2.63189, 3.07822, 4.40048},       {0.003, -0.418548, 1.24063, 2.63194, 3.07807, 4.4004},       {0.004, -0.418728, 1.24085, 2.63201, 3.07785, 4.40028},       {0.005, -0.418959, 1.24114, 2.63211, 3.07758, 4.40012}     }      For each `i`, `kx=dat[[i,1]]`, and `dat[[i,2;;6]]` are the eigenvalues (from small to big) which will be fitted by `H[kx]`. The aim is to find all the parameters `T1` to `T15` which best produce the eigenvalues given by `dat` for all `kx`. How can I achieve this?


title: What is the point of Refresh if Dynamic has an UpdateInterval option?

text: I haven't found an example where I can't get rid of Refresh[]:               In[1]:= Dynamic[DateString[],UpdateInterval->1]     Out[1]= Sat 10 Nov 2012 01:36:34     In[2]:= Dynamic[Refresh[DateString[],UpdateInterval->1]]     Out[2]= Sat 10 Nov 2012 01:36:34


title: How to colorize a rectangle with a given color function?

text: I want to set color to a rectangle (in fact a line) that lies on (0,0) and (1,0), and the color function is given by $u(x,t)=t(x-x^2), 0\leq t\leq1$. Since, this $u(x,t)$ act as temperature at the point $(x,0)$ at time $t$, I want to use the colordata with "TemperatureMap", the following is what I have tried:               u[x_, t_] := t (x - x^2)     Animate[Plot[0, {x, 0, 1},       AxesOrigin -> {0, 0},       PlotRange -> {{0, 1}, {-0.02, 0.25}},       PlotStyle -> {Thick},       ColorFunction -> (ColorData["TemperatureMap"][u[#, t]]) &],     {t, 0, 1}]      I find that it must be some problem in the ColorFunction, but I can't fix it, any suggestion? * * * I have tried your code, and find it shall works as the first answer, but since my original question (not posted here) is tried to solving the following question,               f[x_] := -x^2 + x     equ = {D[u[t, x], t] == D[u[t, x], x, x],     u[0, x] == f[x],     u[t, 0] == f[0],     u[t, 1] == f[1]};     sol = NDSolve[equ, u, {t, 0, 1}, {x, 0, 1}]     HeatConda = Animate[Show[{     Plot[Evaluate[u[t, x] /. sol], {x, 0, 1},       PlotRange -> {-0.1, 0.25}, AxesOrigin -> {0, 0},       Filling -> Axis,       ColorFunction -> (ColorData["TemperatureMap"][#2] &)],     Plot[-0.04, {x, 0, 1}, PlotStyle -> {Thick},      ColorFunction ->       Function[{x, y},         ColorData["TemperatureMap"][Evaluate[u[t, x] /. sol]]]]}],      {t, 0, 0.4}]      I want to color the **bottom line** as the same as the filling color. I first tried to simplify the question to the one post here, but the solution here still can work for my (original) question, so please help me again? ![The Figure](http://i.stack.imgur.com/8AEbs.png)


title: ParametricNDSolveValue or NDSolve + fitting

text: I have been trying to find the value for the parameter `kestim` that yields the best fit of a model to some data points. `datac` has **25 data points** , but I illustrate with just a few. I tried to do the fitting after using `ParametricNDSolveValue`:               datac={{0,73},{300,605},{600,1244},{900,1874},{1200,2000},{1500,2900},{1800,3300}};          pfun = ParametricNDSolveValue[{       [MODEL]       } /. parameters,       {G,T,H,Y,U},       {t, 0, 7200}, {kestim}]               (*because variable Y is the one I am interested, I specify it in the next command*)     f[x_]:=pfun[x][[4]]               (*I evaluate `f[1.1][600]` I get the correct value of variable `Y`. I then fit it to the data.*)     fit = NonlinearModelFit[datac, f[kestim][t], {kestim}, {t}]      Yet, I get the error `Part::partw: "Part 4 of \!\(\*TagBox[RowBox[{\"ParametricFunction\" [etc etc] does not exist.>>` and the output `FittedModel[InterpolatingFunction[{{0.,7200.}},<>][t]]`. From the latter I am able to extract the value of `kestim`, although the value obtained for this parameter is not significant. I know I am not providing enough information, but I really cannot show my model here. Yet, do you think you could help me find what I am doing wrong? Thank you so much! **Edit** : What was going wrong was probably the `ReplaceAll` inside `pfun`. Now it is working. I provide a draft version of the model below:               pfun = ParametricNDSolveValue[{       G'[t] == 50 - 6*^3 T[t] G[t], G[0] == 0,       T'[t] == 73 H[t] - 11 T[t], T[0] == 25000,       H'[t] == ke (1 - T[t] - H[t]) - 73 H[t], H[0] == 0       },       {G,T,H},       {t, 0, 7200}, {ke}];               (*as per suggestion of @ruebenko*)     f[ke_?NumericQ] := pfun[ke][[3]]          f[1.1][600]     (*Out=0.0135135*)


title: Forcing a graph not to resize

text: This code:               Clear[ighamiltMol,timeList,hamiltMol,];          timeList={Abs[0.333333 E^(-I t) + 0.333333 E^(I t) + 0.166667 E^(-2 I t) +         0.166667 E^(2 I t)]^2,       Abs[0.\[VeryThinSpace]+ 0.166667 E^(-I t) - 0.166667 E^(I t) +         0.166667 E^(-2 I t) - 0.166667 E^(2 I t)]^2,       Abs[-0.166667 E^(-I t) - 0.166667 E^(I t) + 0.166667 E^(-2 I t) +         0.166667 E^(2 I t)]^2,       Abs[-0.333333 E^(-I t) + 0.333333 E^(I t) + 0.166667 E^(-2 I t) -         0.166667 E^(2 I t)]^2,       Abs[0.\[VeryThinSpace]- 0.166667 E^(-I t) - 0.166667 E^(I t) +         0.166667 E^(-2 I t) + 0.166667 E^(2 I t)]^2,       Abs[0.166667 E^(-I t) - 0.166667 E^(I t) + 0.166667 E^(-2 I t) -             0.166667 E^(2 I t)]^2}          hamiltMol={{0, 1, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 0}, {0, 0, 1,        0, 1, 0}, {0, 0, 0, 1, 0, 1}, {1, 0, 0, 0, 1, 0}}          ighamiltMol =        Dynamic@AdjacencyGraph[hamiltMol,          VertexLabels -> Placed["Name", Tooltip],          GraphStyle -> "SpringEmbedding",          VertexShapeFunction -> (Disk[#1, timeList[[#2]]] &)];          Animator[Dynamic[t], {0, 19}, .5]     ighamiltMol      Generates this animation (2 pictures shown, notice the resizing): ![Mathematica graphics](http://i.stack.imgur.com/JNRzr.png) ![Mathematica graphics](http://i.stack.imgur.com/HgYxH.png) I would like my disks' radii not to exceed 2/3 of the distance between two vertices, so that the graph needs no resizing. The same method applied to `GraphPlot[]` and `GraphPlot3D[]` also does not work, producing results like those obtained with `AdjacencyGraph[]`. I've tried setting a `DataRange->{}`, but it doesn't work either. `Rescale[]`ing didn't work. (Note that this is not a problem in a `Graphics[]` environment.) I don't know what to try next.


title: Manipulate code creates error messages when file is opened

text: When I open the file containing the following code I get a series of error messages. Once I evaluate the cell with the code the error messages disappear. What is Mathematica doing when it opens a file, or how can avoid creating this problem for myself in the future?                econmagic1[ ds_, di_, ss_, si_  ] := (       (* begin equilibrium calculation *)           A = { { 1, - 1 ds }, { 1, - ss } };       CC = Inverse[ A ].{ di, si };            Manipulate[        (* begin grid layout*)        Grid[{               (* begin first row *)          {Show[                 (* begin initial supply curve *)             Plot[ ( 1 / ss ) ( x - si ), {x, 0, Part[ CC, 1] },          PlotStyle -> { Red, Dashed },               PlotLegends -> { "Initial Supply Set"}],                 (* begin initial demand curve *)             Plot[ ( 1 / ds ) x + (  - di / ds) , {x, 0, di },           PlotStyle -> Dashed,  PlotLegends -> { "Initial Demand Set"} ],                 (* begin demand curve *)             Plot[ ( 1 / ds ) ( x - et ) + (  - di / ds) , {x, 0,           di + et},  PlotLegends -> { "Demand Set"} ],                 (* begin supply curve *)             Plot[ ( 1 / ss ) ( x - si ), {x, 0,           Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,              si }, 1 ]}, PlotStyle -> Red,          PlotLegends -> { "Supply Set"}],                 (* begin horizontal for equilibrium *)             Plot[Part[           Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et, si },           2 ],  {x, 0,           Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,              si }, 1 ]},  PlotStyle -> { Dashed, Thick } ],                 (* begin filling for consumer surplus *)             Plot[{  ( 1 / ds ) ( x - et ) + (  - di / ds),           Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,              si }, 2 ] }, {x, 0,           Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,              si }, 1 ]}, Filling -> 1 -> {2},          FillingStyle -> Directive[ Opacity[ 0.1 ], Blue ] ],                 (* begin filling for producer surplus *)             Plot[{  Part[            Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et, si },            2 ],  ( 1 / ss ) ( x - si ) }, {x, 0,           Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,              si }, 1 ] }, Filling -> 1 -> {2},          FillingStyle -> Directive[ Opacity[ 0.1 ], Red ] ],                 (* begin equilibrium point *)             ListPlot[{ {            Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,               si }, 1 ],            Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,               si }, 2 ] } }, PlotStyle -> Black,          PlotLegends -> { "Equilibrium Point" }],                 (* begin dashed lines for market equilibrium *)                  Graphics[{ Dashed,           Line[{ {              Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 1 ], 0 }, {              Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 1 ],              Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 2 ]}}] }],                 AxesOrigin -> { 0, 0 },         PlotRange -> { { 0, di + 10 }, { 0, (  - di / ds) + 10 }},           AxesLabel -> { "Quantity", "Price"}, ImageSize -> Large        ]}, (* End Show *)               (* begin second row *)          { Grid[{                  (*          second row first column *)             {"QD Price Intercept:" TraditionalForm[ - ( di + et ) / ds ],                   (* second row second column *)               "QD Quantity Intercept:" TraditionalForm[ di + et ] },                  (*          third row first column *)                 {"QS Price Intercept:" TraditionalForm[ - si / ss ],                   (* third row second column *)               "The equilibrium point is:"     TraditionalForm[ {              Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 1 ],              Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 2 ] } ] },                  (*  fourth row first column *)               {"Consumer Surplus:" TraditionalForm[(               1 / 2 ) ( (- di / ds ) -                Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{                   di + et, si }, 2 ])  Part[               Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                 si }, 1 ] ],                   (* fourth row second column *)               "Producer Surplus:" If[                     (*  Does the Supply Curve Intersect the Price Axis *)                ( - si / ss ) >= 0,                     (*  Supply Curve Intersects Price Axis *)                 TraditionalForm[ .5 (                Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{                    di + et, si }, 2 ] - ( - si / ss  ) ) (                Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{                   di + et, si }, 1 ] )],                     (* Supply Curve Does Not Intersect Price Axis *)            TraditionalForm[ 0.5  ( Part[                  Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{ di + et,                    si }, 1 ] -  si  ) (                Part[ Inverse[{ { 1, - 1 ds }, { 1, - ss } } ].{                   di + et, si }, 2 ] )]                 ] }          },        Alignment -> Left, Frame -> All, Spacings -> { 4, 1 } ]        }        }, Alignment -> Left],        { { et, 0 },  -4.5, 25 } ]        )


title: How to change coordinates of a differential operator?

text: I'm doing a basic quantum mechanics problem and am trying to learn how to do it in _Mathematica_. Any help would be much appreciated. $\vec{L} = \vec{x} \times \vec{p}$ where $\vec{x}$ has components: $\begin{align*} x &= r \sin \theta \cos \phi\\\ y &= r \sin \theta \sin \phi\\\ z &= r \cos \theta \end{align*}$ and $\vec{p}$ has components: $p_x = - i \hbar \dfrac{\partial}{\partial x}$ etc. Show that $L_z = -i \hbar \dfrac{\partial}{\partial \phi}$


title: Efficiently adding a fixed real numbered value to a set of elements in an array

text: Imagine I'm trying to add some value $r$ to each element in a very large array $L$. Take for example:               L = Table[RandomReal[{0,1}],{q,1,10^7}];     r = 0.0032;      I can effectively add $r$ to each element in $L$ by writing:               L = Table[L[[q]]+r,{q,1,Length[L]}];      This operation takes about $\approx 322$ milliseconds. However, is there a better / faster way to proceed?


title: #[[1]]//FullForm = 1?

text: I have a set of symbolic algebraic expressions that I'm trying to get some speed into. To illustrate the issue, I'll use a simple form like `{ k0 X, k1 Y, k1 Z}`, where each term is large and complicated. By random walk, I've arrived at a promising form               { r0 X, r1 Y,r1 Z}/.r0->k0 /.r1->k1      which is faster than the original, but with my particular set of expressions, it turns out that a function is faster:               {#[[1]] X, #[[2]] Y, #[[2]] Z}&@{k0, k1}      The expressions are large, making substitutions by hand time consuming and error prone, so I set out to replace the k s with a rule like               {k0->#[[1]],k1->#[[2]]}      I was surprised that this wasn't a straightforward operation, k0 being replaced by 1 instead of the intended #[[1]]. I thrashed around for a bit, eventually finding the odd (to me) result that               {#[[1]], #[[2]]}//FullForm      Gives               List[ 1, Part[Slot[1],2]]      Can anyone suggest a way of thinking in which this makes sense? Is there any place in the design for `Part[Slot[1],1]` ? I worked around it with a hack:               {#[[2]] X, #[[3]] Y, #[[3]] Z}&@{Null, k0, k1}      which works but is ugly to say nothing of embarrassing. Thanks in advance.


title: Why is NeighborhoodGraph so slow?

text: To get neighboring vertices I first tried:               gg = GridGraph[{10, 10, 10, 10}];     VertexList[NeighborhoodGraph[gg, 1, 1]] // AbsoluteTiming        > {5.539308, {1, 2, 11, 101, 1001}} But that is really slow. This is much faster and still uses the new `Graph` package:               Union[VertexInComponent[gg, 1, 1], VertexOutComponent[gg, 1, 1]] // AbsoluteTiming      > {0.000172, {1, 2, 11, 101, 1001}}' I believe that this mimics the `NeigborhoodGraph` approach above, but is still much faster than using `NeighborhoodGraph`:               VertexList[Subgraph[gg, Union[VertexInComponent[gg, 1, 1],            VertexOutComponent[gg, 1, 1]]]] // AbsoluteTiming      > {0.000306, {1, 2, 11, 101, 1001}} The last two approaches are also faster than `NeighborhoodVertices` from the `GraphUtilities` package:               Needs["GraphUtilities`"]     NeighborhoodVertices[gg, 1, 1] // AbsoluteTiming      > {0.017248, {1, 2, 11, 101, 1001}} I'm working with large graphs that I need to manipulate quickly for several interactive information visualization tools. Any tips on why NeighborhoodGraph is so slow here and how to best use the new Graph package when speed is an issue?


title: How to save a GraphicsRow output?

text: I need to save the result of GraphicsRow command as a pdf or jpg file. Something like `GraphicsRow[{plt1,plt2,plt3}] -> pdf`. On clicking on the image there is not a "Save Graphics as" option that one finds on a Plot output. In the end, I need to add arrows and annotations to the whole output and save it as a single jpg or pdf file. I can add stuff but I can't get the output saved unless I issue the command `Export["test.pdf", %]`. What am I missing?


title: Pattern matching repeated structures with named subexpression components

text: I am trying to write a function with a pattern that tests its arguments for a particular structure. But in that pattern I'd like to name a subpattern to make it easier to exract and operate on. The code below works fine:               Plant[x:Allele[_,_]..] := Involute[{x}]      But what I really want is to extract the parts of each Allele expression and pass them as lists to Involute. I tried using the definition below (expecting `a` and `b` to be Sequences of the arguments to Allele):               Plant[x:Allele[a_,b_]..] := Involute[{x}, {a}, {b}]      Unfortunately, this produces unexpected results when evaluated - specifically it only seems to work on expressions that accept a single Allele argument. When a expand the pattern I get:                In: (x:Allele[a_,b_]..)//FullForm     Out: Pattern[x, Repeated[Allele[Pattern[a, Blank[]], Pattern[b, Blank[]]]]]      which doesn't seem right. Where's the mistake?


title: Get number of combinations without "forbidden patterns"

text: I need to get the number of all combinations of binary digits in an 8-digit binary number, but minus some "forbidden" patterns like:               xxxx0xx1     x1xxx0xx     x1xxx0x0      (where x is any digit) These shouldn't be in "valid" combinations I would like to count. My numbers are much larger in fact, so I can't simply enumerate them. What should I do?