title: How Manipulating a matrix and a graphic in only one Manipulate?

text: I have to manipulate a matrix and graphics in one big Manipulate-Block. This way:               Manipulate[Matrixform[mat],Graphics3D[]]      How can I achieve that? Ok, here my Code:               Manipulate[      Graphics3D[       {        Switch[x,          "Streckung", {GraphicsComplex[streckung[a, b, c], Polygon[i]]},          "Verschiebung", {GraphicsComplex[           wuerfel[a, b, c, verschiebung, k], Polygon[i]]},          "Parallelprojektion", {GraphicsComplex[           wuerfel[a, b, c, verschiebung, k], Polygon[i]], Green, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{1, 0, 0}, {0, 1, 0}, {0, 0, 0}}], {{_, 2}, {_,                  4}, {_, 6}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3}, All]]],           Blue, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{1, 0, 0}, {0, 0, 0}, {0, 0, 1}}], {{_, 3}, {_,                  4}, {_, 7}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3},              All]]], Red, Polygon[           Transpose [             ReplacePart[              Transpose[               wuerfel[a, b, c, verschiebung,                  k].{{0, 0, 0}, {0, 1, 0}, {0, 0, 1}}], {{_, 5}, {_,                  6}, {_, 7}, {_, 8}} :> Sequence[]]][[{1, 2, 4, 3},              All]]]},          "x-Drehung", {GraphicsComplex[wdrehungx[w], Polygon[i]]},         "y-Drehung", {GraphicsComplex[wdrehungy[w], Polygon[i]]},         "z-Drehung", {GraphicsComplex[wdrehungz[w], Polygon[i]]}]},       Axes -> True, Boxed -> True,        Switch[x, "Verschiebung", PlotRange -> {{0, 5}, {0, 5}, {0, 5}},         "Parallelprojektion", PlotRange -> {{0, 5}, {0, 5}, {0, 5}}, _,         PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}]], {{a, 1, "x-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{b, 1, "y-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{c, 1, "z-Richtung"},        Switch[x, "Verschiebung", 0, "Streckung", 0, "Parallelprojektion",         0, _, -3], 3},      {{w, 0, "Winkel (in \[Degree])"}, 0, 360},      Button["Reset", a = 1; b = 1; c = 1; w = 0],      {x, {"Streckung", "Verschiebung", "Parallelprojektion", "x-Drehung",         "y-Drehung", "z-Drehung"}, ControlType -> PopupMenu},      Initialization :>        (verschiebung := {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {a, b,            c, 1}};        k := PolyhedronData["Cube", "VertexCoordinates"];        Short[i = PolyhedronData["Cube", "FaceIndices"]];        streckung[a_, b_, c_] := k.{{a, 0, 0}, {0, b, 0}, {0, 0, c}};        wuerfel[a_, b_, c_, M_, l_] :=          ReplacePart[          Transpose[            Insert[Transpose[l],              ConstantArray[1,               Map[Part[Dimensions[l], Sequence @@ #] &, {1}]],              Map[Part[Dimensions[l], Sequence @@ #] &, {2}] + 1]].M, {{_,              4}} :> Sequence[]];        wdrehungx[a_] :=          k.{{1, 0, 0}, {0, Cos[a Degree], -Sin[a Degree]}, {0,             Sin[ a Degree], Cos[a Degree]}};        wdrehungz[a_] :=          k.{{Cos[a Degree], -Sin[a Degree], 0}, {Sin[a Degree],             Cos[a Degree], 0}, {0, 0, 1}};        wdrehungy[a_] :=          k.{{Cos[a Degree], 0, -Sin[a Degree]}, {0, 1, 0}, {Sin[a Degree],             0, Cos[a Degree]}};        )      ]      ![Mathematica graphics](http://i.stack.imgur.com/8emx6.png) I have to show each transformmatrix. when you choose "streckung" for example, you should see the transformmatrix streckung with the manipulated variables a,b and c.


title: Java Heap Space Error on data insertion over SQL Server

text: I'm trying to insert 2-milliion lines into a SQL Database, and get this error: > JDBC::error: Java heap space The insert is a standart _Mathematica_ SQL statement:               conn = myConn[ip]     columns = {"Col1", "Col2", "Col3", "Col4"}     SQLInsert[conn, "MyTable", columns,data]     CloseSQLConnection[conn]      Where data is a `List`of 2-million elements (rows). The command works just fine for a smaller number of rows. I know I could break data into small chunks, but I would like to know how to solve it increasing the Java heap space.


title: Weird behaviour from ListSurfacePlot3D

text: Looking at Documentation for `ListSurfacePlot3D`, I follow the basic example presented there.               data = ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"];     ListSurfacePlot3D[data, MaxPlotPoints -> 50, Mesh -> 30, Axes -> None,       MeshFunctions -> (#1 - #2 + #3 &), MeshShading -> {None, Yellow}]      What happens is that, first of all the vertex data from Stanford Bunny is read and stored in `data`, but then running `ListSurfacePlot3D` returns no output (I was expecting a graphic object as shown in documentation). In fact after running the line with `ListSurfacePlot3D` I see that `data` is cleared from workspace (it doesn't contain any data, in fact it is not even defined anymore - changing color from black to blue). It seems that `MeshShading` is causing this problem, so the following works:               data = ExampleData[{"Geometry3D", "StanfordBunny"}, "VertexData"];     ListSurfacePlot3D[data, MaxPlotPoints -> 50, Mesh -> 30, Axes -> None,       MeshFunctions -> (#1 - #2 + #3 &)]      ![enter image description here](http://i.stack.imgur.com/V2ZEm.jpg) I face the same problem when trying other examples from documentation; ListSurfacePlot3D/Options/MeshShading So, is this a bug or am I missing something? I am using OS X 10.8.4 64 bit, and _Mathematica_ version 9.0 for Mac OS X x86 (64-bit) (January 24, 2013).


title: finding roots of an equation involving infinite series

text: Tc[κ_] := t /. Chop[       FindRoot[         1 == (4 κ^4 NSum[ 2/3 Hypergeometric1F1[3/2, 5/2, -((2 κ^2 l)/t)], {l, 1, Infinity}]                 + 2 κ^2 t (PolyLog[1, Exp[(-2 κ^2)/t]])                 + 2 t^2 (PolyLog[2, Exp[(-2 κ^2)/t]]                 + (2 κ^2)/t PolyLog[1, Exp[(-2 κ^2)/t]])),       {t, tstart}, AccuracyGoal -> 8, PrecisionGoal -> 8]      ]          tstart = 0.5; ni = 100; κmin = 0; κmax = 1;      dκ := (κmax - κmin)/(ni - 1);     dat = Chop[ Table[{κ = κmax - (i - 1) dκ, Tc[κ]}, {i, ni}] ];      ListLinePlot[dat]      _Mathematica_ cannot plot for `ni=100` points. It just keeps on running for hours, but it does produce a plot for a very small number of points, e.g. `ni=5`. How could I tackle this problem?


title: Guidelines on giving readable names to variables

text: I know that one cannot use `underscore` to a variable name, like `degree_of_The_First_Polynomial`. But for a long variable name, it is difficult to read something like `degreeOfTheFirstPolynomial`. What do you do when you need a **clear, self-explained, easy-to-read** variable name?


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

text: I have an external program saving files to some directory on my hard disc. I'd like to run a script that imports and runs a script on each file as it is added to the directory. Is there a simple way to do this using `Dynamic`? Is it necessary to use `Refresh`? For example, I'd like to be able to save a series of text files to a directory (with arbitrary names) and then print the contents in near real-time.


title: Time ColorFunction

text: I have the following data               data = {{0, 0}, {-0.0385, 0.0667}, {-0.0566, 0.1283}, {0.0966,          0.0441}, {-0.1166,          0.0038}, {-0.2046, -0.0673}, {-0.2536, -0.21}, {-0.5485, \     -0.2643}, {-0.3702, -0.1148}, {-0.4201, -0.2319}, {-0.5558, -0.2748}, \     {-0.693, -0.3272}, {-0.6276, -0.3844}, {-0.6305, -0.3448}, {-0.671, \     -0.4833}, {-0.6809, -0.3441}, {-0.7082, -0.2548}, {-0.5978, -0.3126}, \     {-0.4337, -0.3588}, {-0.2542, -0.4139}, {-0.3318, -0.3318}, {-0.4991, \     -0.2123}, {-0.4195, -0.1966}, {-0.4797, 0.0285}, {-0.2198,          0.0965}, {-0.1914, 0.1604}, {-0.0854, 0.1668}, {0.0715,          0.3025}, {0.0847, 0.3116}, {0.175, 0.3152}, {0.0123,          0.4577}, {0.0941, 0.4445}, {0.083, 0.3729}, {0.1251,          0.1414}, {0.0239, 0.3119}, {-0.0665, 0.3748}, {-0.0171,          0.4261}, {0.0781, 0.4031}, {-0.0945, 0.315}, {-0.2497,          0.3892}, {-0.285, 0.3823}, {-0.2873, 0.4343}, {-0.196,          0.4628}, {-0.2812, 0.5166}, {-0.186, 0.2917}, {-0.3101,          0.3047}, {-0.4103, 0.2439}, {-0.4335, 0.2251}, {-0.5113,          0.4149}, {-0.6487, 0.4662}, {-0.5045, 0.1807}}; which represents movement of some particle in time 0,...,50. Using `ColorFunction` is possible to get rainbow color according to axis $y$ as               ListLinePlot[data,ColorFunction->Function[{x,y},ColorData["Rainbow"][y]],PlotStyle->Thick] or axis $x$ as               ListLinePlot[data,ColorFunction->Function[{x,y},ColorData["Rainbow"][x]],PlotStyle->Thick] Is it possible to use `ColorFunction` according to time 0,...,50 and to get rainbow according to its movement in this time?


title: Equivalent of __FILE__?

text: Many languages define a special identifier whose value is the path to the source file currently being processed. (For example, in C, this is done through the `__FILE__` preprocessor macro.) Does Mathematica have anything like this (at least for `*.m` files)? (I could not find a tag that adequately represents the topic of this question (namely, something like "source file processing"); suggestions welcome.)


title: Inverse of a complicated function

text: Mathematica is struggling to find the inverse of this function f(r): `f[r_]:=ArcCos[(-1 + 4.20278 r (0.008712/r^2 + 0.475876/r - 1/(1 + r)))/Sqrt[ 1 - 10.598 r^2 (0.008712/r^2 + 0.475876/r - 1/(1 + r))]]` If I attempt to use Solve or NSolve `(N)Solve[s==f[r],r]` mathematica just hangs up. The same is true for InverseFunction[]. I was wondering if there were any strategies to find the inverse of this function, even perhaps a numerical approximation. I have many functions like this and need to find their inverses. Many thanks.


title: How to resolve a Unix symlink?

text: Does Mathematica have any function to resolve a Unix symlink (recursively, if necessary) to its real path?


title: Whether NIntegrate evaluation is multithreaded or not?

text: About MultiThread evaluation I am talking about here, see this post I am NIntegrate the function `grarm[e, 3, dimension, 1, 1, 0.005]`. There is matrix operation in function `grarm`, the `dimension` set the dim of the matrix. I give the code of `gram` in the end.( **take notice that you will have to manually change the dimension to get different`gram` with different dimension variable before integration**) OK, First I set `dimension` equals 7, and integrate the following               In:=NIntegrate[Im[grarm[e, 3, 7, 1, 1, 0.005]^2], {e, -0.3, 0},        MaxRecursion -> 200] // AbsoluteTiming          Out:={7.454151, 0.0581345}      and If I use linux command `top` to monitor the cpu situation, I see it is single threaded. See ![enter image description here](http://i.stack.imgur.com/Rjgea.png) now, I set `dimension` to 9, and integrate the following               In[55]:= NIntegrate[Im[grarm[e, 3, 9, 1, 1, 0.005]^2], {e, -0.3, 0},        MaxRecursion -> 200] // AbsoluteTiming          Out[55]= {83.592780, 0.0271489}      and If I use linux command `top` to monitor the cpu situation, I see it is multi-threaded. See ![enter image description here](http://i.stack.imgur.com/E33kD.png) And Now I force the same integration to use one thread only, integrate the following               In[56]:=      ParallelMap[       NIntegrate[         Im[grarm[e, #[[1]], 9, #[[2]], 1, 0.005]^2], {e, -0.3, 0},          MaxRecursion -> 200] &,        Tuples[{Range[3, 3], Range[1, 1]}]] // AbsoluteTiming          Out[56]= {16.575363, {0.0271489}}      Notice it is much faster, that is odd. In summary, There are two peculiar things waited to be explained   1. why dimension=7 is single thread while dimension=9 is multi-thread? Can `NIntegrate` actually naturally multi-threaded or not? Or the multi-thread is actually due to the matrix operation in the integrand(well, I personally think this is not likely)?   2. why multi-thread evaluation is much slower than single thread evaluation in the case of dimension 9? * * * In the end, the code for `grarm`.(don't forget to change the dimension, before integration)               dimension = 7;          Clear[armchairibbonmat]     armchairibbonmat[kx_, n_] :=      (       h = Table[0, {i, 1, 2 (n + 2)}, {j, 1, 2 (n + 2)}];       a[m_] := 2 m - 1;       b[m_] := 2 m;       t1 = 1;       aa = 1;       Do[        h[[b[i], a[i]]] = t1 E^(I kx aa);        h[[a[i], b[i]]] = t1 E^(-I kx aa);        h[[b[i + 1], a[i]]] = t1 E^(-I kx aa/2);        h[[b[i - 1], a[i]]] = t1 E^(-I kx aa/2);        h[[a[i - 1], b[i]]] = t1 E^(I kx aa/2);        h[[a[i + 1], b[i]]] = t1 E^(I kx aa/2);        , {i, 2, n + 1}];       h = ArrayPad[h, -2]       )          mat = Compile[{kx, n}, Evaluate@armchairibbonmat[kx, dimension]];     Clear[armchairibbonmat];     armchairibbonmat = mat;          Clear[gkarm]     gkarm[kx_?NumericQ, e_, xx_, width_, ii_, label_, \[Eta]_] :=       Inverse[(e - I \[Eta]) IdentityMatrix[2*width] -          armchairibbonmat[kx, width]][[2*(ii - 1) + label,         2*(ii - 1) + label]]          Clear[fkx]     fkx[kx_?NumericQ, xx_] := E^(I kx xx)          Clear[grarm]     grarm[e_?NumericQ, xx_, width_, ii_, label_, \[Eta]_] :=       NIntegrate[       gkarm[kx, e, xx, width, ii, label, \[Eta]]*        fkx[kx, xx], {kx, -\[Pi]/3, \[Pi]/3}, MaxRecursion -> 200]


title: List-manipulation Interpolation

text: For example, I have the following list:               AA={{0, 20000.}, {26.6, 19950.}, {53.2, 19950.}, {79.8,        19950.}, {97.1198, 18644.1}, {102.681, 16452.3}}      Another calculation results in an arbitrary value intended for the first part of the list, let's say 21.3. By interpolating linearly, this results in a value of 19960 for the second part of the list. How can I import this in Mathematica?


title: Problems with Simultaneous Equation Solving

text: Let me first explain what I am doing and then I will explain the problem that I can't figure out. I am basically trying to solve 2 equations for 2 unknowns (`a1` and `a2`) with some given definitions such as `GL1` `GL2` `GC1` and `GC2`. With the given code below, I solved the unknowns in terms of some parameters and (`C1` and `C2`). However, I want to substitute the equations of `C1` and `C2` in the solutions. I tried to put the equations first like given `GL1` `GL2` `GC1`... But I didn't get any answers then I tried to solve it without putting `C1` and `C2` and I got an answer. I now try to substitute those by using `Simplify`, but I don't get any answers again. I need some help to solve these equations. Please check my code below.               GL1 = fd a1 t Y1;     GL2 = fd a2 t Y2;     GC1 = (Y1 + Y2) (1 - fd) t p;     GC2 = (Y1 + Y2) (1 - fd) t q;          FullSimplify[       Solve[((GC1 - GL1) q / (GC2 - GL2) p) (a2/a1) - (C2/Y1)/(C2/Y2) == 0 &&          a ((GC1/(1 -    fd) - GL1/fd)/C1 + (GC2/(1 - fd) - GL2/fd)/C2) +          2 b (1 - 2 fd)/fd (1 - fd) == 0,        {a1, a2}] ]           (*     Solutions: (2 roots for a1 and a2)     {{a1 -> 1/(2 a C2 fd^2 t Y1 (p q Y1^2 - ...,       a2 -> 1/(2 a C1 fd^2 t Y2 (-p q Y1^2 + ...      },       {a1 -> 1/(2 a C2 fd^2 t Y1 (p q Y1^2 - ...,        a2 -> 1/(2 a C1 fd^2 t Y2 (-p q Y1^2 + ..}}     *)      Now as we see solutions are in terms of `C1` and `C2`, I want to substitute these two equations:                  C1 =  (1 - t (fd a1 + (1 - fd))) Y1;        C2 =  (1 - t (fd a2 + (1 - fd))) Y2;      When I substitute these equations and try to Simplify I don't get any answers, I think the kernel goes into a infinite loop. Any suggestions.


title: Use only exponents (no radicals) in output expressions

text: Radical symbols ($\sqrt{\,\,\,\,}$) are the devil. Is there any way to get mathematica to never use them, and instead express everything as an exponential? i.e. I want               In[1]:= Sqrt[x]      to give $x^{1/2}$ instead of $\sqrt{x}$.


title: How to parallelize this code

text: Here I obtained one code which should tests some zeros of the poly for various g, but sometimes I have to many cycles because of step and I need to parallelize the running on all cores. Classical ParallelDo instead the Do doesn't work. What to do further                poly=g*x^3+21*x^2-1.23*x+7.3247*g*I*x^2;                LM = {};      Do[      Lroots = x /. NSolve[(poly /. {g -> G}) == 0, x];           res = 0;      Do[      root = Lroots[[i]];      If[Im[root] >= 0,      L1 = Drop[Lroots, {i}];      res = res + 1/(Times @@ (root - L1));      ];       , {i, 1, Length[Lroots]}        ];       M = 1/((4*G^2)*res);       AppendTo[LM, M];           , {G, 0.001, 15, 0.01}      ];


title: Reassign values to symbols

text: I've got a situation where I have, say 4 symbols, `a`, `b`, `c` and `d`. This is a simplification of the issue I've been working with. Let's say I assign numeric values to these symbols:`a=1; b=2; c=3; d=4`. I now create a list: `myList:={a,b,c,d}`. I'd like to be able to say: `( # = 5 ) & /@ myList` to assign the value 5 to `a`, `b`, `c` and `d`. The code works as long as `a`-`d` are unassigned. Is there a way to do this, or am I trying to abuse the language?


title: What's wrong with this stylesheet?

text: I edited this style sheet:               Cell[StyleData["Text"], FontSize -> 20, FontWeight -> "Bold",        FontColor -> RGBColor[255, 255, 255], FontFamily -> "Courier New"]      but nothing happens. Is there anything wrong with this piece of code?


title: Customizing AxesStyle->Arrowheads

text: How do I call `AxesStyle->Arrowheads[ ]` in order to control whether or not an arrow appears on each of the four ends of the axes in a `Plot`, and if it does appear how to control the size of each one? Here's an example:               Plot[1/x^5, {x, -20, 20}, AxesStyle -> Arrowheads[{-.02, 0}],      ImagePadding -> None]      It seems `Axes->Arrowheads[.05]` makes all 4 of them appear and appear at the same size, while `Axes->Arrowheads[{-.05,.05}]` makes them appear in "pairs". But sometimes I just want the "north" and "west" axes to have arrows and nothing else.


title: How to cancel a common term from numerator and denominator?

text: What mathematica commands are needed to simplify $\frac{x+n x^m}{x(1+x)}$ to $\frac{1+n x^{m-1}}{(1+x)}$ ?               ClearAll[n , x, m];     num = n x^m + x;     den = x (x + 1);     s = num/den      ![Mathematica graphics](http://i.stack.imgur.com/pld6I.png) to verify               Reduce[s == (1 + n x^(m - 1))/(1 + x)]      ![Mathematica graphics](http://i.stack.imgur.com/bCIZv.png)


title: Can I get a trace of the complexity of a convergent sum?

text: _Motivation--- I have a glimmer of an idea that a convergent sum could be considered a self-referential number similar to a fractal. I would like to play with it for a while._ I have the following convergent sum:               NSum[((1/Pochhammer[m^2 + 1, m]) + (1/Pochhammer[m^2 + m + 1, 2 m])),       {m, 1, Infinity}, WorkingPrecision -> 50]        Is there a way to show the internals of about 4 or 5 steps?


title: Identifying the sign of an expression in an interval

text: My expression is the following: $$ \frac{(1-\alpha ) \alpha h^2 (h+2) \mu r}{(h+1) ((1-\alpha ) h+1) (\alpha h+1)}-\left(\frac{\alpha h \mu }{h+1}\right)^{\alpha } \left(\frac{(1-\alpha ) h \mu }{h+1}\right)^{1-\alpha }+\left(\frac{(1-\alpha ) h \mu }{(h+1) (\alpha h+1)}\right)^{1-\alpha } \left(\frac{\alpha h \mu }{\alpha h+1}\right)^{\alpha } $$ or given as _Mathematica_ input:               (((μ*h*α)/(1 + h*α))^α ((μ*h*(1 - α))/((1 + h*α)*(1 + h)))^(1 -α)) +      ((r*μ*h^2*α*(2 + h)*(1-α))/((1 + h*(1 - α))*(1 + h)*(1 +h*α))) -      (((μ*h*α)/(1 + h))^α ((μ*h*(1 - α))/(1 + h))^(1 -α))      and I would like to know the sign of this when : $1/2\leq α\leq 1$ and $h$,$r$ and $\mu$ are positive


title: Basic Dynamic Interface Programming that returns variables to nb functions

text: I have a dynamic module that contains some basic PopupMenu's and Buttons but also need to use the variables returned from these buttons and PopupMenu's in my nb functions outside of this DynamicModule. Here is the code:               DynamicModule[{var = 1, var2 = 3},      Dynamic[Column[Join[       {PopupMenu[pass2Fun1 = Dynamic[var], {1 -> "Return 1", 2 -> "Return 2",         3 -> "Return 3"}, ContinuousAction -> True]},       Switch[var, 1,        {Button["One", Module[{data = SystemDialogInput["FileOpen"]}, {}],         Method -> "Queued"]}, 2,         {Button["Two", Module[{data2 = SystemDialogInput["FileOpen"]}, {}],           Method -> "Queued"],           Button["Three",Module[{data3 = SystemDialogInput["FileOpen"]}, {}],           Method -> "Queued"]}, 3,         {Button["Four", Module[{data4 = SystemDialogInput["FileOpen"]}, {}],          Method -> "Queued"],       PopupMenu[pass2Fun2 = Dynamic[var2], {3 -> "choice 1", 4 -> "choice 2",          5 -> "choice 3"}, ContinuousAction -> True]}      ]]], TrackedSymbols :> {var, var2}]]      pass2Fun1 and pass2Fun2 are variables that are needed outside the Dynamic Module, and of course so are the SystemDialogInput variables. Take for example the If statement code where we can test to see if the variable pass2Fun1 ==1 To run this test place the above Dynamic Module code in a cell and check to see that the variable pass2Fun1 is filled as Global` Then run the If statement code in another cell to see if you get a good printed result.                If[pass2Fun1 == 1,      Print["This works", pass2Fun1],      Print["Broken", pass2Fun1]]      The If statement can not see the variable pass2Fun1==1 but If I print that variable it prints. If I check the context and the context path both are Global`. Now for the fun Part: In a separate cell evaluate:               pass2Fun1=1;       Then run the If statement again. Now the code runs fine. I thought we had a solution but further checking revealed this strange behavior. After trying Rojo's code below you will see that this If statement will still not complete. So in both the example code above and Rojo's solution below the result in the If statement test is the same. Rojo's code in the above function:               DynamicModule[{pass2Fun1 = 1, pass2Fun2 = 3},      Dynamic[Column[       Join[{PopupMenu[          Dynamic[pass2Fun1], {1 -> "Return 1", 2 -> "Return 2",            3 -> "Return 3"}, ContinuousAction -> True]},         Switch[pass2Fun1,          1, {Button["One",            Module[{data = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"]},          2, {Button["Two",            Module[{data2 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"],           Button["Three",            Module[{data3 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"]},          3, {Button["Four",            Module[{data4 = SystemDialogInput["FileOpen"]}, {}],            Method -> "Queued"],           PopupMenu[           Dynamic[pass2Fun2], {3 -> "choice 1", 4 -> "choice 2",             5 -> "choice 3"}, ContinuousAction -> True]}]]],        TrackedSymbols :> {pass2Fun1, pass2Fun2}]]      My question: What is the best method to get the variable data from another nb a Button or PopupMenu to the functions in a different nb? These nb functions control the generation of results based on the input data and the variables pass2Fun1 & 2 and the SystemDialogInputs. Should all the functions be called inside the DynamicModule or made Global? Even if it's made Global as in the case above, how do I make sure the variable is filled in such a way as to be useful to other functions? Thanks in advance for the help!


title: Differential equations: Solving a singular/nonlinear ODE using NDSolve

text: I am trying to numerically solve a rather horrible looking singular/nonlinear ode: `A*(y''[x]/y[x])'' +y[x]^2==1` on the interval `[0,1]`, where `A` is a small parameter `(~10^(-4))`. The boundary conditions are :               y[0]=y[1]==1     y'[0]==0     y''[1]==0.       I expand the term in parentheses and use `NDSolve`:               s = NDSolve[{10^(-4)*(y''''[x]/y[x] - 2*y'''[x]*y'[x]/(y[x]*y[x]) - (y''[x]/y[x])*                  (y''[x]/y[x]) + 2*(y''[x]*y'[x]*y'[x])/(y[x]*y[x]*y[x])) + y[x]*y[x] == 1,                   y[0] == 0, y[1] == 0, y'[0] == 0, y''[1] == 0}, y, {x, 0, 1}]      And I get the following errors: > >     Power::infy: Infinite expression 1/0.^2 encountered. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       Power::infy: Infinite expression 1/0.^2 encountered. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       Power::infy: Infinite expression 1/0.^3 encountered. >> >       General::stop: Further output of Power::infy will be suppressed during >              this calculation. >> >       ∞::indet: Indeterminate expression 0. ComplexInfinity encountered. >> >       General::stop: Further output of ∞::indet will be suppressed during >              this calculation. >> >       NDSolve::ndnum: Encountered non-numerical value for a derivative at x > == 0.`. >   I realize the solution to this function is very ill behaved near $x=0$. I was wondering whether there is a way to over come this problem? I know that, in the interior, `y[x] = -1`. Thanks a lot!


title: How to convert a system of parametric equations to a normal equation?

text: For example, I have a system of parametric equations (`R` is a constant number) :               { x == p +  R Cos[k],       y == Cos[p] +  R Sin[k],       k == ArcTan[ 1/Sin[p] ]   }      Now I am going to find the normal equation of $\; y = f(x)\;$ without other variables. (Theoretically it is possible because there are totally 4 variables and 3 equations.) How can I do this in Mathematica?


title: How to perform DialogInput operation within Button

text: Can someone clarify how to perform a `DialogInput` operation within a `Button`? I wrote some code for that but it's not working.               Button["Enter value",       DialogInput[{name = ""},        Column[{InputField[Dynamic[name], String],          Button["Hi", Dynamic[name]]}]]]      My problem is this — when I run the above code, the given text is displayed but when I click on the button, the actual operation is not being carried out.


title: K-means clustering

text: In MATLAB, there is a command `kmeans()` that divides an array into $k$ clusters and calculates the centroid of each cluster. Is there any command in _Mathematica_ to perform the same action? For example:               x = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25}}      The MATLAB `kmeans` command does this:               [b, c] = kmeans(x, 2)      It divides `x` into two clusters and calculates the centroids of these two clusters, and indicates for each element in the array which cluster it is a member of               b = {1,1,2,2,2}      and               c={{3.5000,4.5000,5.5000,6.5000,7.5000},{16.0000,17.0000,18.0000,19.0000,20.0000}}


title: What is the fastest way to maintain a large set of expressions?

text: In my algorithm I need to maintain a set (an unordered list of distinct elements) of expressions supporting two operations:   * Test an expression for membership in the set   * Adding a new expression to the set Expressions are to be compared using `SameQ`. The set can have hundreds of thousands of elements and I want it to work as fast as possible. In most programming languages I would use a hash-table or a balanced tree to implement such a set. Is there any better data structure in _Mathematica_ for this purpose than a plain `List`? Is it worth trying to manually implement a better structure?


title: Morphological Components with periodic boundary conditions

text: I would like to find the connected(with periodic boundary conditions) components in a large binary matrix. What I've tried, and it does a fair job is:               MorphologicalComponents[RandomInteger[{0, 1}, {100, 100}],CornerNeighbors -> False]      For instance:               ArrayPlot[MorphologicalComponents[RandomInteger[{0, 1}, {20, 20}], CornerNeighbors -> False], ColorFunction -> "Rainbow", ImageSize -> Large]      ![enter image description here](http://i.stack.imgur.com/edcNT.png) The only option missing here is the periodic boundary condition. `MorphologicalComponents` doesn't have a `DistanceFunction` to impose periodic boundary conditions there. The other idea I had was to give up on `MorphologicalComponents` and use `ClusteringComponents` with a complicated `DistanceFunction`, but that is just a pain in the neck. * * * ## Example: Let me give an example of what I mean by periodic boundary condition. For instance given the input:               {{1, 0, 0, 1, 1}, {0, 0, 1, 0, 0}, {1, 1, 1, 0, 1}, {0, 1, 0, 0, 0}, {1, 0, 0, 1, 0}}      I would expect to get something like:               {{1, 0, 0, 1, 1}, {0, 0, 2, 0, 0}, {2, 2, 2, 0, 2}, {0, 2, 0, 0, 0}, {1, 0, 0, 1, 0}}      As an output. The arrayplots for these two matrices are: ![enter image description here](http://i.stack.imgur.com/0Xmpq.png) ![enter image description here](http://i.stack.imgur.com/zc5Wj.png)


title: Filtering the elements of an array to split them into two categories

text: So, I am new to _Mathematica_ , and I am trying to write something that involves taking values from one array and separating them into two different arrays. My code for doing this is:               For[i = 1, i < (TruncationOrder + 1), i++,         (If[(Abs[Im[evalueb1[[1, i]]]] < 10^-14),             (If[Re[evalueb1[[1, i]]] > 0,                 ρplus[[i, i]] = evalueb1[[1, i]],                 ρminus[[i, i]] = evalueb1[[1, i]]]),              If[Im[evalueb1[[1, i]]] > 0,                 ρplus[[i, i]] = evalueb1[[1, i]],                 ρminus[[i, i]] = evalueb1[[1, i]]]])];      However, this does not give the desired results. I randomly have '1' several times in my new array. The actual values are given below: Original:                {-0.651301 - 2.44576*10^-16 I, 0.651301 + 3.73803*10^-17 I, 0.671298 - 6.68417*10^-16 I,       -0.671305 + 1.17248*10^-17 I, -0.000107956 + 0.735512 I, -0.000107956 -        0.735512 I,       9.93642*10^-6 + 0.764605 I, 9.93642*10^-6 - 0.764605 I, -0.965926 + 5.29506*10^-16 I,       0.965926 + 3.76737*10^-16 I, 0.97048 + 4.33453*10^-16 I, -0.97048 + 5.39299*10^-16 I,       0.0344992 - 1.4214 I, 0.0344992 + 1.4214 I, 0.0028631 + 1.4505 I, 0.0028631 - 1.4505 I,       -0.0626803 + 1.78014 I, -0.0626803 - 1.78014 I, -0.12443 + 1.98252 I, -0.12443 - 1.98252 I,       0.167724 - 2.24691 I, 0.167724 + 2.24691 I}      New incorrect ones: `ρplus`:                   {1, 0.651301 + 3.73803*10^-17 I, 0.671298 - 6.68417*10^-16 I, 1, -0.000107956 + 0.735512 I,          1, 9.93642*10^-6 + 0.764605 I, 1, 1, 0.965926 + 3.76737*10^-16 I,          0.97048 + 4.33453*10^-16 I}      `ρminus`:                   {-0.651301 - 2.44576*10^-16 I, 1, 1, -0.671305 + 1.17248*10^-17 I,          1, -0.000107956 - 0.735512 I, 1, 9.93642*10^-6 - 0.764605 I,          -0.965926 + 5.29506*10^-16 I, 1, 1}


title: Numerical integration involving Inverse Normal CDF

text: I'd like to evaluate the following numerical integration using _Mathematica_ $$ \ \int_0^T\int_0^\infty xe^{-0.04 s}g(x,s) dxds\ $$ where g(x,s) is a Gaussian copula function with say, marginal exponential distributions with parameter A and parameter B (i.e. X~exp(A) and S~exp(B)). In the following MMA attempt, the g(x,s) is defined by GE[Theta,A,B]. This is what I've tried so far:               GE[Theta_, A_, B_] := CopulaDistribution[{"Binormal", Theta}, {ExponentialDistribution[A],ExponentialDistribution[B]}];          Delta = 0.04; A = 0.10; B = 10; Theta = 0.9; T=5;     GExpExp[x_,s_] := PDF[GE[Theta, A, B], {x, s}]          NIntegrate[Exp[-Delta*s]*x GExpExp, {x, 0, Infinity}, {s, 0, T}]       and the following is the error I obtain: * _NIntegrate::inumr: The integrand 1.1547 E^(-10 s-0.1 x-s [Delta]+2 InverseErfc[2 \ Plus[ <<2>>]]^2-1.33333 (0.707107 InverseErfc[<<1>>]-Power[<<2>>] \ InverseErfc[<<1>>])^2)_ x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0.05`,36},{0.5`,1}}. >>* I then try to integrate the expression with respect to only one variable, in this case I chose variable x, so that I'd end up with a univariate expression (and hence I might be able to work on a simpler problem from then on)                 Integrate[Exp[-Delta*s]*GExpExp1[x, s], {x, 0, Infinity}]            (* 11.547 E^(-10.04 s + 1.33333 InverseErfc[4 - 4 E^(-10 s)]^2) *)      It seems that eventually I still have to deal with the Inverse[NormalDistribution] function, which I think is the source of this issue. I then continued with the following:                 T = 5;        Assuming[s > 0, LaplaceTransform[NIntegrate[11.547005383792516` E^(-10.04` s + 1.3333333333333337` InverseErfc[4 - 4 E^(-10 s)]^2), {s, 0, T}], s, T]]            (* NIntegrate::inumr: The integrand 11.547 E^(-10.04 s+1.33333 InverseErfc[4+Times[<<2>>]]^2) has evaluated to non-numerical values for all sampling points in the region with boundaries {{1.,2}}. >>  *)      It could be because the function does not converge, but even after reducing the limit interval from [0,T] to [2,3] (and of course changing T to 5 instead of 2) I still can't obtain a number. Does anyone know the correct syntax that I should use so that I can obtain a numerical answer eventually? Your assistance is much appreciated.


title: DateListPlot FillingStyle problem

text: In the following query, If the option `PlotStyle->{Red,Blue}` is inserted it works but `FillingStyle->{Red,Blue}` does not: The filling turns all Blue. Is this a known issue? I tried basic `ColorFunction` but could only get rainbows. Any other options? It's desirable to alternate the segments using only 2 colors (though not Red and Blue, that's just for example).               Labeled[DateListPlot[#, Joined -> True, ImageSize -> 1000,          AspectRatio -> 1/5,          Epilog -> {Inset[            Text[Style[">statigrafix<", Blue, Opacity[0.1],               FontFamily -> "Consolas", FontSize -> 14]],             Scaled[{0.15, 0.75}]]}, Frame -> {True, True, False, False},          Filling -> Bottom, GridLines -> None] &@       Split[FinancialData["^DJI", "Close", "Jan 1 1980"],         Not@(#[[2]] > 10000 && #2[[2]] <= 10000) &],      Style["Dow Jones Industial 1.1.80-6.22.12 segmented by 10k \     crossings", Gray, Opacity[0.3], FontFamily -> "Helvetica"], Bottom]


title: Accurately evaluating the hypergeometric function

text: As part of another problem, I am working to evaluate hypergeometric functions such as               Hypergeometric2F1[1, 1, n, -1]      for large $n$. I am hoping to obtain at least double-precision accuracy all the way through `n = 1600`. However, starting as low as `n = 200`, I obtain precision errors:               N[Hypergeometric2F1[1, 1, 200, -1], 17]     N::meprec: Internal precision limit      Are there ways to tell _Mathematica_ it can use as much time as it wants to compute this quantity? Or are there any other workarounds?


title: Overlapping ArrayPlot

text: I have two ArrayPlots, and I want to overlap them as it is done here. For clarity, suppose               Array1 = RandomReal[{0, 1}, {3, 2}];      Array2 = RandomReal[{0, 1}, {3, 2}];      and the first `ArrayPlot` uses `ColorFunction -> (Blend[{White,Yellow},#]&)`, and the second uses `ColorFunction -> (Blend[{White,Blue},#]&)`. I'd like to combine them in such a way I end up with an ArrayPlot with White, Yellow, Blue and Green shades. Thanks for your attention.


title: Can Mathematica propose an exact value based on an approximate one?

text: Sometimes, I use Mathematica to do some hypothesis on homeworks to make the question easier. For instance, when I have to compute big sums when $n\to\infty$ and Mathematica can't give the exact answer, I set $n$ to a very big number and I get an approached value. Is it possible with this value to get possible closed forms just like in Wolfram Alpha (which by the way runs Mathematica's kernel) ? **Example :** I have to find out the sum of all $\frac{1}{2p!}$ when $p$ goes from $0$ to $+\infty$ and let's say Mathematica doesn't directly say it's $\frac{e}{2}$, but it gives 1.66 for a big value of $n$. Is there a function which can figure out which constant is near this number ?


title: distance between each vertex of a graph and its output

text: I have a question regarding this Q&A. Let's call a vertex that is not the tail of any directed edge an _output_ of the graph. The graph below has only one output (at the far right). If I want the distance from each vertex to the output of the graph, what should I do? This one is on my graph:               matOP = {{0, 1, 0, 0, 1, 0, 1, 0}, {0, 1, 0, 0, 1, 0, 1, 0}, {0, 0, 1, 0, 1, 0, 1, 0},               {0, 0, 0, 1, 0, 0, 1, 0}, {0, 0, 0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0}};          pos = Position[matOP, 1];     edge = Subsets[Range@Length@pos, {2}];     dedge = DeleteDuplicates[        DirectedEdge @@@ (Extract[edge, #] & /@            With[{dist =               N@(EuclideanDistance[pos[[#]], pos[[#2]]] & @@@ edge)},             Flatten[Position[dist, #] & /@               DeleteDuplicates@N@Select[dist, # <= 1.5 &]]])];          Graph[dedge,        VertexCoordinates -> Rule @@@ Thread[{Range@Length@pos, pos}]]      ![enter image description here](http://i.stack.imgur.com/tOxbt.png)


title: How can you form a variable from a function and its arguments?

text: Is there a way to make the general replacement               foo[x,y,z]->fooxyz      so that I can treat the x_i as variables so that I will obtain foofgh from the following:               foo[f,g,h] /.{ foo[x,y,z]->fooxyz }      ?


title: DateListPlot input entry problem

text: I imported some data from Excel and got the following for my date and values:               {{{1986, 1, 2, 0, 0, 0.}, 25.56, ""}, {{1986, 1, 3, 0, 0, 0.}, 26., ""}      It seems that there is an extra space there. How can I remove that and make appropriate format for `DateListPlot`? Also important: what materials do I need to learn to overcome such difficulties?


title: Replace every Minus to Plus in Expression

text: Thought this is a rather simple thing, but I was not able to find a solution: I have a _polynomial_ expression like:                expr1=a^2-b+c*d      expr2=a-b      expr3=-a+b-c      and i want to replace every negative sign to Plus                expr1new=a^2+b+c*d      expr2new=a+b      expr3=a+b+c      The problem is that               FullForm[a-b]     (* Plus[a, Times[-1, b]] *)      thus I cannot use simple replacement. Do you know a simple way for that? **Update** This example does not work with simple replacements:               expr4 = (1 - I) a;     expr4 /. {-1 -> 1}     FullForm[expr4]          (* (1 - I) a     Times[Complex[1, -1], a] *)


title: Mathematica 10 fails to calculate integral that Mathematica 9 can handle

text: The following:               Mass/2  Integrate[(r^2 + Rotation^2 (2 - Cos[θ]^2))/(r^2 + Rotation^2       Cos[θ]^2)^2 Sin[θ], {r, r1, ∞}, {θ, 0, π},       Assumptions -> {r1 > 0 && Rotation >= 0}] // Simplify      returns > >     (1/(32 Rotation))Mass (-16 ArcTan[r1/Rotation] + 1/(2 r1^2)(16 π r1^2 + >     32 r1 Rotation + π Rotation^2 + 8 π r1^2 Log[r1] + >     4 ArcTan[Rotation/r1] (7 Rotation^2 - 8 r1^2 Log[r1]) - >     2 ArcTan[r1/(2 Rotation) - Rotation/(2 r1)] (Rotation^2 + 8 r1^2 > Log[r1]))) >   in _Mathematica 9.0.1_ , and > During evaluation of In[35]:= Simplify::time: Time spent on a transformation > exceeded 300.` seconds, and the transformation was aborted. Increasing the > value of TimeConstraint option may improve the result of simplification. >> > > Out[35]= 1/2 Mass Integrate[((r^2 - Rotation^2 (-2 + Cos[θ]^2)) Sin[θ])/(r^2 > + Rotation^2 Cos[θ]^2)^2, {r, r1, ∞}, {θ, 0, π}, Assumptions -> r1 > 0 && > Rotation >= 0] in _Mathematica 10.0.0_. In the latter case, it takes much longer to return, although it fails to produce the result. Is this a bug?


title: How to limit only two "0 and 1" strings for an xor implement?

text: I tried to implement some logic gates for a series of "0 & 1" strings, just like _and_ , _or_ , _nand_ , _nor_ and _not_ listed below. How could I limit _xor_ only accept a two strings list as its argument?               str2 = {"11000000", "10000001", "11111111"};          or[str : {__String}] :=        StringJoin[        MapThread[Or,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];          and[str : {__String}] :=        StringJoin[        MapThread[And,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];          nand[str : {__String}] :=        not[StringJoin[         MapThread[ And,            Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}]];          nor[str : {__String}] :=        not[StringJoin[         MapThread[ Or,            Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}]];          not[str : _String ] :=        StringJoin[         Characters[str] /. {"1" -> False, "0" -> True}  /. {False -> "0", True -> "1"}];          (* ????? *)     xor[str : {_String, _String}] :=        StringJoin[        MapThread[Xor,           Characters[str] /. {"0" -> False, "1" -> True}] /. {False -> "0", True -> "1"}];      ![enter image description here](http://i.stack.imgur.com/fSJx9.gif)


title: Collapsing summation

text: I am trying to write a command to collapse the sum of terms into an expression with summation. Something like               F_[1, j___] + F_[2, j___] + F_[3, j___] := Sum[F[i, j], {i, 1, 3}]      which is designed to to collapse the LHS, which is a function of 2 or more parameters (for example - F[i,j] or F[i,j,k] - this is the reason for the i___ in the definition) into a summation on the first variable. but I get the following error:               SetDelayed::write: "Tag Plus in F_[1,i___]+F_[2,i___]+F_[3,i___] is Protected"      It seems that I am overriding the _Plus_ definition. I don't know then how to define this properly. Thanks.


title: How to write to the cloud quickly?

text: I am wondering how to most quickly log data during cloud execution. I do not need anything fancy: all I want to do is persist certain information for later analysis, with minimal blocking for the end user. A solution that involves dumping data and then periodically cleaning it up with a `ScheduledTask` would be acceptable. All of the code will run in the cloud. The `Permissions` need to be private. For example, say I want to track which users call certain functions I have deployed. `CloudSymbol` is faster in the cloud than in Mathematica, but it is still slow.               CloudSymbol@"list1" = {};     AppendTo[CloudSymbol@"list1", $RequesterWolframUUID] // AbsoluteTiming      > {4.070239, $RequesterWolframUUID} Before we compare timings, briefly note this behavior:               CloudSymbol@"list1"      > {$RequesterWolframUUID}               CloudEvaluate[CloudSymbol@"list1"]      > {"0e2497dc-9281-48f3-8e84-14b5e2587446"}               CloudSymbol@"list1"      > {$RequesterWolframUUID} Returning to timings,               CloudEvaluate[AppendTo[CloudSymbol@"list1",$RequesterWolframUUID]//AbsoluteTiming]       //AbsoluteTiming      > {2.866184, {1.723062, > {0e2497dc-9281-48f3-8e84-14b5e2587446,0e2497dc-9281-48f3-8e84-14b5e2587446}}} It is worth pointing out that the assignment in the cloud caused `$RequesterWolframUUID` to be resolved at that time. Compare this result to the behavior above.               CloudSymbol@"list1"      > {0e2497dc-9281-48f3-8e84-14b5e2587446,0e2497dc-9281-48f3-8e84-14b5e2587446} `URLFetch` is marginally faster than `CloudEvaluate`.               logUser=CloudDeploy@APIFunction[{},AppendTo[CloudSymbol@"list1",$RequesterWolframUUID]&];     URLFetch@logUser // AbsoluteTiming      > {2.500356,{"0e2497dc-9281-48f3-8e84-14b5e2587446", > "0e2497dc-9281-48f3-8e84-14b5e2587446", > "0e2497dc-9281-48f3-8e84-14b5e2587446"} However, this doesn't work when running in the cloud.               CloudEvaluate[URLFetch@logUser // AbsoluteTiming] // AbsoluteTiming      > (* errors, because the page was a login prompt *) I tried `CloudEvaluate`-ing `CloudConnect` first, with no luck. Also, `URLFetch` and `URLFetchAsynchronous` are inconsistent.               URLFetchAsynchronous[logUser,#&]      > > URLFetchAsynchronous[CloudObject["https://www.wolframcloud.com/objects/b2305e35-a643-4a52-a94d-575e0019b0d2"],#1&]               URLFetchAsynchronous[URLBuild@logUser,#&]      > > AsynchronousTaskObject["https://www.wolframcloud.com/objects/b2305e35-a643-4a52-a94d-575e0019b0d2", > 5, 15817848933037716543] But even putting the syntax aside, handling the `"data"` event revealed that `URLFetchAsynchronous` is getting the login prompt, as in the cloud, so the function was not evaluated. Lastly, the documentation says `PutAppend` has been updated to work with cloud objects, but I don't know how to use it.               list2 = CloudPut[$RequesterWolframUUID, "list2"];     $RequesterWolframUUID >>> list2 (* fast, no errors *)     CloudGet@"list2"      > $RequesterWolframUUID               PutAppend[$RequesterWolframUUID, URLBuild@list2]      > OpenAppend::noopen: Cannot open > https://www.wolframcloud.com/objects/user-0e2497dc-9281-48f3-8e84-14b5e2587446/list2. Ideas?


title: How can I change the position of my plot legends?

text: As the title indicates, I want to change the current position of the legends in a combined plot. The _Mathematica_ code I used is               dataRG00 = {{2.5, 15.15}, {2.75, 13.73}, {3, 12.64}, {3.25,      11.56}, {3.5, 10.68}, {3.75, 9.65}, {4, 9.31}, {4.25, 9.27}, {4.5,      8.88}, {4.75, 8.21}, {5, 8.0}};     dataRG11 = {{2.5, 2.07}, {2.75, 3.0}, {3, 3.84}, {3.25, 4.58}, {3.5,      5.56}, {3.75, 6.32}, {4, 6.73}, {4.25, 7.10}, {4.5, 7.06}, {4.75,      7.07}, {5, 7.29}};     dataRG21 = {{2.5, 20.56}, {2.75, 19.50}, {3, 18.51}, {3.25,      17.51}, {3.5, 16.52}, {3.75, 15.63}, {4, 14.75}, {4.25,      13.85}, {4.5, 13.00}, {4.75, 12.26}, {5, 11.6}};     dataRG32 = {{2.5, 5.24}, {2.75, 5.14}, {3, 5.00}, {3.25, 4.51}, {3.5,      4.25}, {3.75, 3.62}, {4, 2.56}, {4.25, 1.66}, {4.5, 1.42}, {4.75,      1.29}, {5, 1.25}};     dataRG43 = {{2.5, 10.31}, {2.75, 10.41}, {3, 10.56}, {3.25,      10.46}, {3.5, 10.25}, {3.75, 10.33}, {4, 10.67}, {4.25,      10.23}, {4.5, 9.21}, {4.75, 9.60}, {5, 10.5}};     dataRG85 = {{2.5, 4.62}, {2.75, 4.64}, {3, 4.72}, {3.25, 4.67}, {3.5,      4.46}, {3.75, 4.49}, {4, 4.37}, {4.25, 4.22}, {4.5, 4.25}, {4.75,      4.06}, {5, 3.8}};     dataRG99 = {{2.5, 1.05}, {2.75, 0.77}, {3, 0.66}, {3.25, 0.74}, {3.5,      0.86}, {3.75, 0.81}, {4, 0.90}, {4.25, 0.76}, {4.5, 0.90}, {4.75,      0.90}, {5, 1.08}};     dataCH = {{2.5, 41.0}, {2.75, 42.81}, {3, 44.05}, {3.25, 45.96}, {3.5,      47.42}, {3.75, 49.18}, {4, 50.68}, {4.25, 52.90}, {4.5,      55.27}, {4.75, 56.60}, {5, 56.48}};          col = {Darker[Green], Red, Blue, Yellow, Orange, Cyan, Magenta,      Darker[Gray]};     ley = {"Box", "1:1 linear", "2:1 boxlet", "3:2 boxlet", "4:3 boxlet",      "8:5 boxlet", "Other resonances", "Chaotic"};     plrange = {{2.4, 5.1}, {-2, 60}};          legendPlot[xl_List] :=      ListPlot[xl, Frame -> True,      PlotStyle -> Table[{Thickness[0.003], col[[i]]}, {i, 1, 8}],      Joined -> True, PlotMarkers -> {Automatic, 15},      FrameLabel -> {"α", "Percentage %"},      FrameStyle -> Directive[FontSize -> 17, FontFamily -> "Helvetica"],      PlotRange -> plrange, Axes -> False, ImageSize -> 600,      Epilog ->       Inset[Grid[      MapIndexed[{Graphics[{col[[First[#2]]],            Inset[Style[{\[FilledCircle], \[FilledSquare], \      \[FilledDiamond], \[FilledUpTriangle], \[FilledDownTriangle], \      \[EmptyCircle], \[EmptySquare], \[EmptyDiamond]}[[First[#2]]], 15]],            Thickness[0.08], Line[{{0, 0}, {1, 0}}]},           AspectRatio -> 0.5, ImageSize -> 20],          Style[ley[[First[#2]]], Bold, FontSize -> 10,           FontFamily -> "Helvetica"]} &, xl]],      Offset[{-2, -2}, Scaled[{1, 1}]], {Right, Top}]]          P0 = legendPlot[{dataRG00, dataRG11, dataRG21, dataRG32, dataRG43,      dataRG85, dataRG99, dataCH}]      which produces the following plot ![enter image description here](http://i.stack.imgur.com/ybPtx.jpg) Obviously, the position of the legends is wrong since they overlap part of the plot. What I want, is to move the legends outside the frame of the plot and particularly at the right hand side of it and adjust it at the middle of the y range. I "played" a lot with `Offset` and `Scaled` but I without success. Any ideas?


title: Removing a ProgessIndicator when no longer needed

text: I have a progress indicator in my _Mathematica_ notebook that I update as various calculations are performed:               indicator = ProgressIndicator[Dynamic[progress]];      I would like to figure out how to remove the indicator when the calculations are complete or in the case above when               progress == 1      I’ve looked through the documentation and can’t seem to find a good way to do this.


title: Differentiating a Dot Product

text: I apologize if this type of question has been asked before, but a preliminary search turned up nothing. I would like to differentiate dot products. For example, consider taking a derivative with respect to the $i$-th component of $P$ in the dot product $P \cdot X$. How do I teach Mathematica that is given by $\frac{\partial (P\cdot X)}{\partial P_i} = \frac{\partial }{\partial P_i}(P_a X^a) = \delta^i_a X^a = X^i$ ? Ideally, I would like to implement/generalize this rule to dot products of vectors in special relativity where the dot product is given by $a \cdot b = \eta_{\mu\nu} a^\mu b^\nu$. Thanks!


title: How can I factor my trigonometric equation?

text: The equation $$3\sin^2 x - 3\cos x -6\sin x + 2\sin 2x + 3=0$$ has a solution $x = 0$. That means it has a factor of $\cos x - 1$. I tried to write the given equation has the form $$(\cos x - 1)P(x)=0.$$ I am looking for the factor $P(x)$. How can I get _Mathematica_ to find it?


title: Why don't I see all the grid lines in my combined contour plots?

text: I am trying to display four continuous functions, but when I try to combine them withe a single `Show`, I can't see the second vertical line. I suppose the problem is with the `GridLines`. The code is:               j = -1;     a2 = 3.968342707518218;     a1 = 3.275794729726671;     NalfaF = -0.749964;     alfaF1 = 0.749964;     mu = 10^-3;     Ntot = NalfaF*mu;     tot1 = alfaF1*mu;     alfaF2 = 1.54553;     tot2 = alfaF2*mu;     k =       Show[ContourPlot[(Sqrt[(16 tot1 y)/3 (1 + tot1/(27 y^3))] - (            2 tot1)/(9 j y)) (x - 0.95 a1) == 0.002, {x, -10, 10}, {y,          0, .3}, PlotRange -> {{2.50, 4.5}, {0., 0.3}},         ContourShading -> None, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["2:1", {a1 + 0.1, 0.01}],           Black, Point[{a1, 0.}]}, GridLines -> {{a1}, {}}],       ContourPlot[(-Sqrt[(16 tot1*y)/3 (1 + tot1/(27 y^3))] - (2 tot1)/(            9 j y)) (x - 1.17 a1) == 0.004, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         GridLines -> {{a1}, {}}, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["2:1", {a1 + 0.1, 0.01}],           Black, Point[{a1, 0.}]}],        ContourPlot[(Sqrt[(16 tot2 y)/3 (1 + tot2/(27 y^3))] - (2 tot2)/(            9 j y)) (x - 0.95 a2) == 0.002, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["3:2", {a2 + 0.1, 0.01}],           Black, Point[{a2, 0.}]}, GridLines -> {{a2}, {}}],       ContourPlot[(-Sqrt[(16 tot2*y)/3 (1 + tot2/(27 y^3))] - (2 tot2)/(            9 j y)) (x - 1.1 a2) == 0.004, {x, -10, 10}, {y, 0, .3},         PlotRange -> {{2.50, 4.5}, {0., 0.3}}, ContourShading -> None,         GridLines -> {{a2}, {}}, PlotPoints -> 100,         Epilog -> {AbsolutePointSize[8], Text["3:2", {a2 + 0.1, 0.01}],           Black, Point[{a2, 0.}]}]]      How can I make sure both vertical lines show?


title: What is the inverse of CoefficientList?

text: I have numbers in vector notation. I need to get polynomial notation from them. My numbers are `{0, 1, 23, 5, 15, 0, 0, 0}`. I want to get x + 23x^2 + 5x^3 + 15x^4 from this list. How can I get that polynomial?


title: Can one optimize AutomaticNumbering feature?

text: If one wants to use the automatic numbering feature of Mathematica, he has to make tags for cells of the type he wants to be referenced to. Then, as soon as he needs to make a reference to the tagged cell, he goes to Menu/Insert/Automatic Numbering. This brings up the dialog "Create Automatic Numbering Object". There one finds three fields: one is entitled "Counter", the two others enable one to select the tag of the cell to be numbered. In the field "Counter" one finds a number of cell types, and one MUST select the type he needs. In some StyleSheets, such as JournalArticle, the number of cell types is really impressive. In this case the stage of choosing the cell type from the Counter field of the "Create Automatic Numbering Object" dialog considerably brakes the writing process and becomes a head ache. I heavily use the JournalArticle StyleSheet along with the automatic numeration. However, I only make numeration and refer to two types of Cells: (i) DisplayFormulaNumbered and (ii) Figure. Here comes my question: Is it possible to customize the "Create Automatic Numbering Object" dialog such, that only two types of cells: (i) DisplayFormulaNumbered and (ii) Figure would show up there? (my data PC WindowsXP, Mathematica 9.0.1.0)


title: Manipulate for probability distribution with multiple parameters, kernel smoothing

text: I'm looking to use the `Manipulate` command to take a distribution with multiple parameters (e.g., mean and sigma for the normal), generate some variates, then plot the density with kernel smoothing. Ideally I'd like to have sliders for all parameters, the number of variates used, and the bandwidth for smoothing. Here's what I've got:               Manipulate[       Plot[         SmoothKernelDistribution[RandomVariate[NormalDistribution[μ, σ], numbVars], bw],         {x, -5, 5}],       {μ, -1, 1},       {σ, 0, 5},       {numVars, 10, 1000, 10},       {bw, .1, 5}]      But it looks like I'm not indicating things correctly, getting errors for the `RandomVariate` parameters and for `SmoothKernelDistribution` and perhaps others that are supressed.


title: How do I generate a set of n-tuples containing integral solutions to a linear equation provided certain constraints?

text: Let $m,k,p$ be fixed positive integers. I want to create a table of k-tuples $(x_1,x_2,\ldots,x_k)$ comprised of solutions in positive integers to the equation below: $$x_1+x_2+\cdots+x_k=m\quad\text{where }1\leq{}x_1,x_2,\ldots,x_k\leq{}p$$ For example, if I set $m=16,k=3$, and $p=6$. How can I make mathematica generate the set (table) of integer triples $(x_1,x_2,x_3)$ such that $$x_1+x_2+x_3=16$$ where $1\leq{}x_1,x_2,x_3\leq{}6$. Also, how would I seperately generate a table of positive integral triples $(x_1,x_2,x_3)$ for which $$x_1+x_2+x_3\geq{}16 \quad \text{and } 1\leq{}x_1,x_2,x_3\leq{}6.$$


title: Why does Installing small caps fonts in OS X cause notebook Text cells to use that font?

text: I installed Adobe Type 1 Times Roman SC (small caps) and Times Roman Bold SC fonts on my Mac OS X system. Now every old or newly-created `Text` style cell in every Mathematica notebook appears in small caps! This is with the `Default.nb` style sheet. Why? And how to fix. Uninstalling the two fonts did cure the problem, but it makes no sense to me that this should have happened. Note that the Options Inspector shows the font settings for the `Text` style as being Times, 12, Plain.


title: Why does Mathematica choose the second function definition?

text: While working on a solution to this question I've come across a case where I simply don't understand Mathematica's behaviour. I've got the following definitions:               PatternImplies[(x:(Verbatim[Blank]                       |Verbatim[BlankSequence]                       |Verbatim[BlankNullSequence]))[h_],x[]]:=True          (*CatchAll rule*)     PatternImplies[_,_]:=Maybe;      Now I try this:               PatternImplies[_Integer,_]     (*     ==> Maybe     *)      I would have expected `True`. My first thought was that I probably got the pattern wrong, so I tested:               MatchQ[PatternImplies[_Integer,_],            PatternImplies[(x:(Verbatim[Blank]                              |Verbatim[BlankSequence]                              |Verbatim[BlankNullSequence]))[h_],x[]]]     (*     ==> True     *)      In other words, the pattern matches. Moreover, looking at `Downvalues` I see that the special rule is indeed stored before the catch-all rule. So why does Mathematica chose the second definition (and more importantly, what can I do about it?)


title: How can I completely ban usage of some functions in output and mandate use of others?

text: For example, I hate that Mathematica uses `Pochhammer` symbol in outputs and prefer all the expressions in `Gamma` function. How can I ban usage of `Pochhammer`? I also want all outputs to use `HurwitzZeta` rather than `Zeta`. In another instance I want the results to use my own variant of Polygamma function (modified). How can I mandate its usage when possible?


title: What default theoretical distribution does Mathematica use in PearsonChiSquareTest?

text: I used Mathematica's function PearsonChiSquareTest to test whether the data were drawn from a normal distribution. As in the reference, I expected Mathematica to compare the result to a normal distribution, by running: `PearsonChiSquareTest[data]`. As I wanted to extract the test statistics from properties, I was "forced" to name the distribution I wanted to compare it to, namely the normal distribution: `PearsonChiSquareTest[data, NormalDistribution[],"PValue"]`.   What is surprising is that the _PValue_ for the first case is _different_ from the second case where I use the Normal Distribution explicitly. Anyone knows what's the difference here?               data = RandomVariate[NormalDistribution[], 10^4];          PearsonChiSquareTest[data]          (*     ==> 0.3248593157     *)          PearsonChiSquareTest[data, NormalDistribution[]]          (*     ==> 0.4704917701     *)


title: How can I create facetted histograms?

text: I love _Mathematica_ , and I would love to be able to use it for all of my data analysis tasks, but there is one type of analysis which I find almost trivial in R, and I have no idea how to approach in _Mathematica_. Say I have a CSV file containing a few hundred thousand people's ranked preferences for items, in a format like this:               Gender,X29234,X30310,X28908,...     Male,1,2,3,...     Female,1,3,2,...     ...      (in this case the female liked item X28908 more than item X30310) 10000 rows of sample data can be found here. I want to plot histograms of the ranks each gender assigned to each item. In R I can use `reshape2` and `ggplot2` to do something like this:               library(reshape2)     library(ggplot2)     merged_data <- read.csv("merged_data.csv")     melted = melt(merged_data, id=1)     ggplot(melted)      + geom_histogram(aes(x=value,y = ..density..,fill=factor(Gender)),binwidth=1, position="identity",alpha=.5)      + facet_wrap(~variable)      + theme(legend.position="bottom")      + scale_fill_discrete(name="Gender: ")      to get a nice graph like this: ![histograms](http://i.stack.imgur.com/qeR0z.jpg) The key thing for me here are that the individual plots all end up having the same axis bounds, even though the bounds of the data in each plot aren't the same, which makes comparisons really easy. How would I go about doing something like this in _Mathematica_ so I can get rid of R in my workflow? **Edit:** I should clarify that this example with Gender is to simplify the problem to something easier to explain, and I'm looking for a solution which is as automatic as possible: doesn't involve enumerating in the source the possible values of the Gender field, doesn't involve hard-coding in the source the bounds of the plot etc. ggplot2 does all of these out of the box, so I'm looking for a reusable approach to do something similar.


title: Table with some editable cells

text: I have a table: ![Table I want to be editable](http://i.stack.imgur.com/nbukd.jpg) I want it to be editable only where the zeros appear. I read this post Generating an editable table that can be used as input because it's almost exactly what I want, but I couln't figure out how to keep uneditable the first column AND the first row. I don't show the modifications I did because they wouldn't shed any light.


title: point-wise transform of `Plot`

text: Suppose I have the following plot:               Plot[(1 - p2)^2/(p2^2 + (1 - p2)^2), {p2, 0, 1}, AxesLabel -> {"p2", "p1"}]      ![enter image description here](http://i.stack.imgur.com/a8nky.png) Now I want to do a point-wise transform to every point $(p2,p1)$ on the line (making a new plot) using: $ p1 \rightarrow \dfrac{p1-\gamma}{1-\gamma}\quad p2\rightarrow\dfrac{p2-\gamma}{1-\gamma} $ In other words, I want to move every point on the line $(p2,p1)$ to a new location $\left(\dfrac{p2-\gamma}{1-\gamma},\dfrac{p1-\gamma}{1-\gamma}\right)$. How should I achieve that?


title: Starting NDSolve from intermediate time step?

text: I always wondered if I could start NDSolve from an intermediate time step. What I mean is, in the code sample below, if I were to run my solution from `tmin=0` to `tmax=2` and then I realize that my solution hasn't converged yet, could I just change my `tmin` to `2` and then proceed with a larger `tmax` (in this case the solution coverges [attains steady state in this example] at `tmax=5`). This is because very often I solve 4th order Nonlinear PDEs with NDSolve, some of which take over 70-80 minutes to complete (as I run them for long times of a million time steps or so) and then I realize that the solution hasn't converged yet. So can I just, as in my presumed working example, change my `tmin` to my `tmax` from the previous run and change my `tmax` to a larger run?               tmin = 0;     tmax = 5;     sol = 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, tmin, tmax}, {x, 0, 5}];     Plot3D[Evaluate[u[t, x] /. sol], {t, tmin, tmax}, {x, 0, 5},       PlotRange -> All]


title: Random variables with transformed discrete distributions cannot be applied to Probability[] function?

text: I have two discrete uniform distributions over same support:               Dx = DiscreteUniformDistribution[{-8, 8}];       Dy = DiscreteUniformDistribution[{-8, 8}];      I use random variables X $\sim$ Dx, Y $\sim$ Dy to model condition in some if- else clause in C code. For example,               if (3 * x + 1 > y) {        ...      }      So, I model this condition by random event 3*X + 1 > Y. Then probability I look for is:               Probability[       x > y,        {Distributed[x, TransformedDistribution[3 * x + 1, Distributed[x, Dx]]],        Distributed[y, Dy]}     ]      Unfortunately, Mathematica produces nothing. As for me, this is very strange behavior because Mathematica also cannot compute mean for the product distribution of {X, Y}. Maybe, this problem is caused by different support of X and Y. How can I compute this probability?


title: Mathematica Compiled Functions - additional functions

text: Mathematica supports an exact list of compilable functions: They are listed here: List of compilable functions. However, I would need to add the following functions: ToExpression, StringFreeQ, StringReplace, BinaryRead and BinaryWrite... Is it possible? I know that BinaryRead and BinaryWrite have simple C++ equivalents but how can I add this functionality to the Compile function? Furthermore, Compile only accepts Integer, Floats and Lists and Nested Lists as input. Can it be modified to accept Strings? Could reimplementing the Compile Function work?


title: ContourPlot and Colorfunction

text: I have the following code:               ContourPlot[     (2.7` (-3.8099999999999996` + 7.24` x - 3.24` x^2 + 3.62` y - 6.48` x y + 6.48` x^2 y))/     ( 11.43` - 6.48` x + 3.24` x^2 - 3.24` y + 6.48` x y) -      ( 3 (-(-1 + x)^2 + (1 + 2 (-1 + x) x) y))/( 3 + (-2 + x) x + (-1 + 2 x) y) ,      {x, 0.5, 1}, {y, 0, 0.5},      ContourStyle -> {Black, Thick}, Contours -> {0},       ColorFunction ->      (If[#1 > 0, Directive[Lighter[Lighter[Lighter[Yellow]]]], White] &)]      which gives me ![enter image description here](http://i.stack.imgur.com/bba1Z.png) But my color function should color the area above the black line white while color area below the black line yellow. However, if I use the colorfunction `Rainbow`, then it will give me the correct coloring result: ![enter image description here](http://i.stack.imgur.com/qapTk.png) What should I do to make my 1st color function behave as expected?


title: Conditioning on group of functions

text: I have two sets of functions which I want to implement them in a single function with an option indicating which set of functions should be used. Suppose that I have two lists like:(updated example)               b = {-1, 1, 0, 2}}     u = {{1, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 1, 1}, {0, 1, 1, 0}, {1, 0, 1,     1}, {0, 1, 0, 1}, {1, 0, 1, 0}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1,     0, 0}}      and I have this function:                AbEst[b0_, u0_, method_] :=       Module[{t, b = b0, u = u0, l, a, pos, theta, dif, se},       t = Table[i, {i, -4, 4, .01}];       L[b_, t_, u_] :=         Product[p[b[[i]], t]^u[[i]]*(1 - p[b[[i]], t])^(1 - u[[i]]), {i,           1, Length[u]}];       p[b_, t_] := 1/(1 + Exp[-1.7*(t - b)]);       l = L[b, t, #] & /@ u;       a = PDF[NormalDistribution[0, 1], t];       pos = Table[a, {Dimensions[u][[1]]}]*l;       Which[method == "ML",        theta =          t[[Position[l[[#]], Max[l[[#]]]][[1, 1]] & /@            Range[Dimensions[u][[1]]]]],        method == "MAP",        theta =          t[[Position[pos[[#]], Max[pos[[#]]]][[1, 1]] & /@            Range[Dimensions[u][[1]]]]],        method == "EAP",        theta = pos.t/Total[Transpose[pos]]];       dif = (Table[t, {Dimensions[u][[1]]}] -            Partition[Flatten[Table[theta, {Length[t]}]], Length[t]])^2;       Which[method == "ML",        se = Sqrt[Total[Transpose[l*dif]]/Total[Transpose[l]]],        method == "MAP",        se = Sqrt[Total[Transpose[pos*dif]]/Total[Transpose[pos]]],        method == "EAP",        se = Sqrt[Total[Transpose[pos*dif]]/Total[Transpose[pos]]]];       Return[Transpose[{theta, se}]]]      Now it returns `{theta,se}` for given `method`. I want to change it such that it returns theta by default (i.e. without computing `se`) and computes and returns `{theta,se}` if it was requested. 1) How can I do that? 2) How can I re-write more efficient function in which fits my purpose?


title: Labelling Curves Using ListLogLinearPlot within DynamicModule (So Close)

text: I currently have a large number of time-series datasets in the form where the name and time-series transposed data, so I have a list of lists of names for datasets and their time-dependant data. The _end goal_ is to graph a plot which **I already have as I want it by itself,** only with a **legend** that is, with other graphics, **finished as well.** Within this expression for `myPlot` I am able to generate the labels I need via inserting an `Epilog` expression, producing `SetAttributes[tt, Listable] tt[name_ -> data_] := Tooltip[data, name]` _(Just for manipulation)_ (1) `myPlot = ListLogLinearPlot[#, Epilog -> Table[Inset[Framed[DisplayForm[names[[i]]], RoundingRadius -> 5, Background -> White], {5.5, 25}], {i, len}]]` (2) `myPlot /@ tt[thirds@ruleData] // Column` which together yield a plot with unmovable labels for each dataset ((2) actually yields the plots with or without Epilog / labels, as specified by (1), whereas (1) alone unsquelched yields itself back in text-only output). But I am unable to combine these expressions with `DynamicModule` as another post on the Stack Forums suggests. http://stackoverflow.com/questions/7221315/how-do-i-label-different-curves-in- mathematica However, on top of a dummy graphic (table "pos" rather than plot) **I can get`DynamicModule` to have movable labels:** `DynamicModule[{pos = Table[{names[[i]]}, {i, len}]}, LocatorPane[Dynamic[pos], Appearance -> Table[Framed[Text@TraditionalForm[names[[i]]], RoundingRadius -> 5,Background -> White], {i, len}]]]` So, I would think the only problem then is figuring out how to "insert" the `myPlot` function(s) into `DynamicModule`. I am almost certain the presence of the `#` in my `ListLogLinearPlot` function is the culprit. I need to combine these expressions labels are movable ON the graph just as they are on the dummy table. Thank you again, I deeply appreciate any resposnes.


title: Importing or reading data in binary format 212

text: I have a binary data file in format 212, and I want to import the file into _Mathematica_. How do I read or import binary format 212? I almost have no direct experience of working with any binary format. I would appreciate your help. Here is the link to the data file: physionet.org/physiobank/database/mitdb/100.dat The specification of the format is "Each sample is represented by a 12-bit two’s complement amplitude. The first sample is obtained from the 12 least significant bits of the first byte pair (stored least significant byte first). The second sample is formed from the 4 remaining bits of the first byte pair (which are the 4 high bits of the 12-bit sample) and the next byte (which contains the remaining 8 bits of the second sample). The process is repeated for each successive pair of samples." From the following link: http://www.physionet.org/physiotools/wag/signal-5.htm#sect9


title: Multiple screens support for slideshows

text: I really like using Mathematica for building slideshows/presentations. But is mirroring the only way to see the content both on the laptop's screen and on the projector? When using screen mirroring, the projector display is blurry because the resolution doesn't match. When not using screen mirroring, having to constantly switch back and forth between the screen, the audience and the keyboard is really not convenient. Is there a better way to use Mathematica on multiple screens?


title: Why can't I change the style of a cell repeatedly?

text: I ran into this when I was working with an example from the Help Pages of V9. `Cells` is a new function added in V9. The following appears to work the first time it is evaluated in a notebook with `nb` assigned to some appropriate value, say, `EvaluationNotebook[]`.               Scan[(CurrentValue[#, StyleNames] = "Title") &, Cells[nb, CellStyle -> "Section"]]      However, if I try again to change the cells affected by the first evaluation to another style or back to the original style, nothing changes. Neither this               Scan[(CurrentValue[#, StyleNames] = "Text") &, Cells[nb, CellStyle -> "Title"]]       nor this               Scan[(CurrentValue[#, StyleNames] = "Section") &, Cells[nb, CellStyle -> "Title"]]        has any effect. For other `CurrenValue` targets such as `FontSize`, it's easy to change the value repeatedly.                Scan[(CurrentValue[#, FontSize] = 100) &,  Cells[nb, CellStyle -> "Section"]]      Scan[(CurrentValue[#, FontSize] = 30) &,  Cells[nb, CellStyle -> "Section"]]


title: Mark selected sub-lists in the list they were selected from

text: I've got this simple problem with two lists. I select some items from a list, but I want to visualize the difference between the previous list and the list that I create with `Select`. For instance:               a = {{7, 0, 0, 2}, {0, 0, 2, 5}, {10, 4, 8, 7}, {7, 1, 9, 2}, {1, 3, 6, 7},           {6, 9, 2, 9}, {2, 0, 7, 1}, {2, 5, 1, 1}, {9, 6, 4, 0}, {9, 9, 2, 8}};     b = Select[a, #[[4]] > 5 &];      I want a list that compare the two lists in this manner               results =        {{7, 0, 0, "-"}, {0, 0, 2, "-"}, {10, 4, 8, 7}, {7, 1, 9, "-"}, {1, 3, 6, 7},         {6, 9, 2, 9}, {2, 0, 7, "-"}, {2, 5, 1, "-"}, {9, 6, 4, "-"}, {9, 9, 2, 8}};


title: How to make Mathematica returns the exact expression I typed

text: I'm using _Mathematica_ to compare some constants. Before playing around with those constants, I would like to check that I didn't make any mistake in typing them. So my question is the following: "What is the command that return the expression I typed?" Just to be clear. The expression               4*Sum[Log[Gamma[k]], {k, 3, IntegerPart[n] + 2*(n - IntegerPart[n])}]      returns: ![enter image description here](http://i.stack.imgur.com/RvG3h.png) And that is what I want. On the other hand, the expression               Sum[(2*n - 2*m - 1)*Log[n*(m + 1)], {m, 0, IntegerPart[n] - 1}]      returns: ![enter image description here](http://i.stack.imgur.com/962bs.png) and that is what I want to avoid!


title: Evaluate code to some point

text: How can I evaluate my code, up to some point? I don't want to evaluate all of my code always. I have to use `Shift` \- `Enter` for every line from the first cell up to the point I want to be, and it's not easy when you have a lot of code.


title: Mismatch between numerical and analytic evaluation of an integral

text: I evaluated the following integral               NIntegrate[Sqrt[r] Abs[Cos[(k + 1/2) Pi r]], {r, 0, 1}]      getting as a result 0.413232 for `k=1` Then I evaluated the same integral as               Assuming[k ∈ Integers && k ⩾ 0,       Integrate[ 1/Sqrt[2] Sqrt[r (1 + Cos[2 (k + 1/2) Pi r])], {r, 0, 1}]]      and then I evaluated the result               -((4 (-1 + FresnelS[1]))/((1 + 2 k)^(3/2) π))      for `k=1` and I get the following result 0.137646. I am checking this result because I am mainly interested in               Integrate[ 1/Sqrt[2] Sqrt[r (1 + Cos[2 (k + 1/2) Pi r])], {r, R, 1}]      as a function of `R`. Where is my error?


title: Simplify expressions that contain full derivatives

text: The best way to show what I want is by giving an example: How to go from               Exp[-a[x, y]] (g[x, y]*Derivative[1, 0][f][x, y])/h[x, y] +      Exp[-a[x, y]] (f[x, y]*Derivative[1, 0][g][x, y])/h[x, y] -      Exp[-a[x, y]] (f[x, y]*g[x, y]*Derivative[1, 0][h][x, y])/h[x, y]^2      to               Exp[-a[x, y]] D[f[x, y]*g[x, y]/h[x, y], x]      If the Exp were not there, i.e. the expression is a full derivative, then integrating would work 1               expr = With[{anti =      Integrate[(g[x, y]*Derivative[1, 0][f][x, y])/     h[x, y] + (f[x, y]*Derivative[1, 0][g][x, y])/     h[x, y] - (f[x, y]*g[x, y]*Derivative[1, 0][h][x, y])/h[x, y]^2,     x]}, HoldForm[D[anti, x]]]


title: Antialiasing option behaves weird (polygon edges visible in ContourPlot)

text: When I set the `Antialiasing` option in `Style`, I get the followings:               plot = ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400];     Grid@{{        Style[plot, Antialiasing -> Automatic],        Style[plot, Antialiasing -> True],        Style[plot, Antialiasing -> False]        }}      ![Mathematica graphics](http://i.stack.imgur.com/D0gb9.png) For `Antialiasing -> Automatic`, everything is fine. Though `Antialiasing -> True` reveals polygon edges while still maintaining antialias on contourlines, frames, etc. `Antialiasing -> False` gives a plot where nothing is antialiased and polygon edges are not visible. There is this thing written in the documentation for `[Antialiasing][1]`: > With the default setting Antialiasing -> Automatic, choices are made to > optimize appearance on each type of computer system. I would not say this is an optimal appearance. Can anyone tell me the logic/algorithm behind `Automatic` in this case?


title: Cannot calculate an integral

text: I am new to _Mathematica_. So I just run a basic procedure but _Mathematica_ didn't calculate this integral. Maybe it is too complicated to be done.               Integrate[(a E^(I g x - 1/2 (d + a ArcSinh[(-c + x)/b])^2))/(b Sqrt[ 2 π]                Sqrt[1 + (-c + x)^2/b^2]), {x, -∞, ∞}]      $a,b,c,d$ and $g$ are constants. Could you suggest what I should do?


title: Inconsistent GraphicsRow behaviour

text: During the debugging of my previous question (somewhat related), I encountered this strange behaviour: when the global option `Antialiasing` is set to `True` in **Option Inspector** , the following code gives **non-antialiased** plots (observe e.g. frames):               GraphicsRow@{       ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400],       ListDensityPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Mesh -> False,         ImageSize -> 400]       }      ![Mathematica graphics](http://i.stack.imgur.com/oLQ1F.png) The next input is from the same notebook, same session, the only difference is that `GraphicsRow` only contains one plot object. Result is **antialiased** (visible polygon edges are of no concern here, see other post).               GraphicsRow@{ListContourPlot[        Table[Sin[i + j^2], {i, 0, 2, 0.05}, {j, 1.2, 2, 0.05}],         ColorFunction -> ColorData["AvocadoColors"], Contours -> 10,         Mesh -> False, ImageSize -> 400], ""}      ![Mathematica graphics](http://i.stack.imgur.com/s8BjO.png) **Question** Is it a bug of `GraphicsRow`?


title: Using GraphHighlight interactively

text: I want to build a small GUI, where the user can select either a single edge or a single node of a graph. I got to this point:               selection = {};          Dynamic[Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3,         3 \[UndirectedEdge] 1},       PlotLabel -> selection,       VertexShapeFunction -> (EventHandler[           Disk[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),       EdgeShapeFunction -> (EventHandler[           Arrow[#1, .1], {"MouseClicked" :> (selection = {#2})}] &),       GraphHighlight -> selection,       GraphHighlightStyle -> "Thick",       ImageSize -> 200       ]]      Which gives the following (note that I already highlighted an edge by clicking on it for clarity): ![Mathematica graphics](http://i.stack.imgur.com/wPDjG.png) Now if I try to click on one of the **nodes** , the dynamic visualization breaks, giving back the unevaluated result: ![Mathematica graphics](http://i.stack.imgur.com/oN3i1.png) Note, that the `GraphHighlight` and `PlotLabel` options correctly registered the click, as the selected node is on their right hand sides. Any idea what the difference is in this context between edges and nodes? The two clicking functionality are meant to be identical.


title: Are later versions of the Front-End compatible with older Kernels?

text: At my graduate school, all of the clusters still use version-6, and I only have version-7 and version-8 installed on my computer. I would like to use those machines remotely. Are either of the versions I have compatible with the version-6 kernel?


title: Speeding up NDSolve for system of differential equations

text: I am wondering if there is a way to speed up this function that solves a system of ordinary differential equations with NDSolve? Thus far I've tried specifying a few different methods such as LSODA, BDF, StiffnessSwitching; however, none of these has significantly affected the execution time. Is it possible to use Compile here?               Atotal = 100.;      Btotal = 100.;      Ctotal = 100.;      Rtotal = 100.;      input = Table[i, {i, 0.5, 6.5, 1.0}];     runs = Table[i, {i, 1, 6}];     simtime = 60*{15., 30.};           chiscore[input_Real, runs_Integer, simtime_Real, k1_Real,       k1m_Real, k2_Real, k2m_Real, a_Real, k3_Real, k3m_Real,        k4_Real, k4m_Real, k5_Real, k5m_Real, k6_Real, k6m_Real,       kn_Real, kc_Real, k8_Real, k8m_Real, k9_Real, k9m_Real,       k10_Real, k11_Real, negoff_, Atotal_Real, Btotal_Real,       Ctotal_, Rtotal_Real] :=       Block[{soln, t, A, B, Cin, Cout, R},          soln = NDSolve[             {               Derivative[1][A][t] == (((k1*input)/(1 + negoff*(R[t]/k10)))*               (Atotal - A[t]))/(k1m + (Atotal - A[t])) - (k2*A[t])/(k2m + A[t]),               Derivative[1][B][t] == (k3*A[t]*(Btotal - B[t]))/               (k3m + (Btotal - B[t])) - ((k4 + k11*R[t])*B[t])/(k4m + B[t]),               Derivative[1][Cin][t] == ((k5*B[t] + a*Cin[t])*(Ctotal - Cin[t] - Cout[t]))/               (k5m + (Ctotal - Cin[t] - Cout[t])) - (k6*Cin[t])/(k6m + Cin[t])               - kn*Cin[t] + kc*Cout[t],                Derivative[1][Cout][t] == kn*Cin[t] - kc*Cout[t],               Derivative[1][R][t] == (k8*Cout[t]*(Rtotal - R[t]))/               (k8m + (Rtotal - R[t])) - (k9*R[t])/(k9m + R[t]),             A[0] == 0.,             B[0] == 0.,              Cin[0] == 0.,             Cout[0] == 0.,             R[0] == 0.            },           {A, B, Cin, Cout, R},           {t, 0., simtime}][[1]]        ]          Table[chiscore[input[[i]], runs[[i]], simtime[[2]], 4.0, 0.0043,       0.0713, 0.039, .02, 1.561, 0.502, 0.0752, 0.000284, 1.48658,       0.0575, 0.746837, 0.442668, 0.182, 0.00176, 0.0375, 2.73359,       0.000685, 0.0567, 0.1735, 0.0367, 1.0, Atotal, Btotal, Ctotal,      Rtotal][[1]],     {i, 1, 5}]; // Timing


title: Can mathematica rearrange an equation and solve/plot it?

text: Suppose we have this equation: $$ sin(x+y+z) = x^2y - wz$$ I want mathematica to plot contours of $x$ with axes of $y$ against $z$ in the limit $w \rightarrow 1$, tried this code but didn't work.               a = Reduce[ Sin(x+y+z) == x^2y - wz, x]     a /. w -> 1     ContourPlot[a, {y, 0, 1}, {z, 0, 1}]      I tried a different method here, using Solve, but didn't work either:               ContourPlot [x /. Solve[Sin(x+y+z) = x^2y - z, x], {z,0,1}, {y,0,1} ]


title: How can I convert x^2 to x*x?

text: When I try the following code:               a b^2 c /. b c -> e      _Mathematica_ gives me: > >     a b^2 c >   but what I want is: > >     a b e >   The `FullForm` of `a b^2 c` is `Times[a, Power[b, 2], c]`, so it can not match the pattern `b c`. the problem above is a simplified version of my practical one as below: * * * The practical problem which comes to me is:               dat = {Subscript[n, c] Subscript[n, d] Subscript[v, c] Subscript[v, d],Subscript[n, d] Subscript[p, c] Subscript[v, c] Subscript[v, d],I Subscript[h, d] Subscript[n, d] Subscript[p, d] Subscript[v, d],I Subscript[h, d] Subsuperscript[n, d, 2] Subscript[v, d],Subscript[n, c] Subscript[p, d] Subscript[v, c] Subscript[v, d],Subscript[p, c] Subscript[p, d] Subscript[v, c] Subscript[v, d],I Subscript[h, d] Subsuperscript[p, d, 2] Subscript[v, d],I Subscript[h, d] Subscript[n, d] Subscript[p, d] Subscript[v, d],I Subscript[h, c] Subscript[n, c] Subscript[p, c] Subscript[v, c],I Subscript[h, c] Subsuperscript[p, c, 2] Subscript[v, c],-Subscript[h, c] Subscript[h, d] Subscript[p, c] Subscript[p, d],-Subscript[h, c] Subscript[h, d] Subscript[n, d] Subscript[p, c],I Subscript[h, c] Subsuperscript[n, c, 2] Subscript[v, c],I Subscript[h, c] Subscript[n, c] Subscript[p, c] Subscript[v, c],-Subscript[h, c] Subscript[h, d] Subscript[n, c] Subscript[p, d],-Subscript[h, c] Subscript[h, d] Subscript[n, c] Subscript[n, d]}          rules = {Subscript[h, c] Subscript[p, c]->I Subscript[h, e] Subscript[n, e]+Subscript[h, f] Subscript[p, f],Subscript[h, c] Subscript[n, c]->Subscript[h, f] Subscript[n, f]+I Subscript[h, e] Subscript[p, e],Subscript[p, c] Subscript[v, c]->I Subscript[n, e] Subscript[v, e]+Subscript[p, f] Subscript[v, f],Subscript[n, c] Subscript[v, c]->I Subscript[p, e] Subscript[v, e]+Subscript[n, f] Subscript[v, f],Subscript[h, d] Subscript[p, d]->I Subscript[h, f] Subscript[n, f]+Subscript[h, e] Subscript[p, e],Subscript[h, d] Subscript[n, d]->Subscript[h, e] Subscript[n, e]+I Subscript[h, f] Subscript[p, f],Subscript[p, d] Subscript[v, d]->Subscript[p, e] Subscript[v, e]+I Subscript[n, f] Subscript[v, f],Subscript[n, d] Subscript[v, d]->Subscript[n, e] Subscript[v, e]+I Subscript[p, f] Subscript[v, f]}          dat//.rules      some elements of the `dat` can't be matched by `rules` and `ReplaceRepeated`.


title: Width-dependent MatrixForm

text: When writing fractions, Mathematica has a quite intelligent behaviour: If the fraction gets too long to fit on the width of the notebook, it is automatically replaced by `/`. However, by default nothing like this happens for matrices given in `MatrixForm`. Therefore my question is: Is it possible to write a `DecayingMatrixForm` which shows as `MatrixForm` if the matrix fits into the notebook's width, but switches to showing the list when the notebook is resized to be more narrow? If that is not possible, is it at least possible to have that decision dependent on the current notebook width when first displaying the matrix? Note that the solution should work correctly also if `MatrixForm` is used _inside_ an expression, as in `Table[MatrixForm[Table[f[i,j],{i,1,n},{j,1,n}]],{n,1,20}]`.


title: Take a list with the amounts of the random samples from another list while holding the index

text: I have a list called `cant` with some amounts of samples to take from the list `community` as follows:               cant = {5, 1, 2, 3, 4};     community = {{1, 2, 3, 4, 5, 6}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3, 4, 5, 6}};       I'm trying to find a better way to do this task:               where = {};     Table[AppendTo[where,       Table[Flatten[{RandomSample[community[[i]], 1], i}], {cant[[         i]]}]];, {i, Length[community]}];      The result is:               where      {{{3, 1}, {2, 1}, {3, 1}, {4, 1}, {4, 1}}, {{1, 2}}, {{3, 3}, {3, 3}}, {{1, 4}, {3, 4}, {1, 4}}, {{4, 5}, {1, 5}, {3, 5}, {1, 5}}}      Because with               where[[1]]     {{3, 1}, {2, 1}, {3, 1}, {4, 1}, {4, 1}}      The 5 samples in the first item (3, 2, 3, 4, and 4) have the index of community 1. I read about Reap and Sow, but really I couldn't understand how to implement this. Any idea of how to make this faster because I'm working with large communities and sampling thousands? I appreciate your help,


title: Using a ListDensityPlot to map color onto a ListPlot3D graph

text: I have a 3 column list of data points. The first two columns correspond to x and y coordinates, with data points creating a surface in the z direction from column 3. This gives me a nice wavy surface. I have a separate file of corresponding error values (chi) which amounts to a similar 3 columns: same x and y coordinates with chi values for each point in my data file. With this file, I've created a very nice (read: adequate) density plot, to show in 2 dimensions, via shading, the variation of chi across the parameter space. What I'd LIKE to do, is then use this 2D representation to shade the 3D plot, sort of like a "hot" and "cold" graph so I can visualize where the errors tend to be highest and lowest, while easily associating them with my data. Any ideas? Much appreciated! Edit: Adding code and plots for clarity.               `ListDensityPlot[gchi[[All, {1, 2, 3}]],ColorFunction -> "DarkRainbow"]`      ![Density Plot - Chi Values](http://i.stack.imgur.com/2oj71.png) These are the colors I'd like plotted on the following 3D plot (of different values). The colors vary by value from blue(low) to red(high).               `ListPlot3D[{gband[[All, {1, 2, 3}]]}, PlotRange -> Full, Mesh -> 6,ColorFunction -> Function[{gchix, gchiy, gchiz}, Hue[gchiz]]]`       ![3D Parameter graph](http://i.stack.imgur.com/0P0jP.png) This is the graph of "found" values for the functions I'm fitting. They're over the same space (x,y) coords as the density plot above, and here, the z components represent data points. I'd like to color this 3D graph by a projection of the 2D density plot (of different values z, same values x,y) onto the rendered surface. Arbitrary color scheme, I just want it to vary by a separate function determined by a separate list of values.


title: TrackedSymbols affected by CurrentValue. Another problem with SetDelayed(:=)+OwnVales in Initialization

text: It is MWE, only a `Disk[]` that should print `"Click"` when clicked. Also `"date... updating"` should be printed on the first evaluation and on each update of variable `enabled`. (which is **constant** in this MWE) In the `Column` there is another `Dynamic` object which shows current `MousePosition`. And this element is responsible for printing (flooding) `"date... updating"` even though `enabled` is not changing.               DynamicModule[{enabled = True, pos},      Column[{             Dynamic[Print[DateString[] <> " updating"];                     EventHandler[Graphics@Disk[], {"MouseClicked" :> Print["Click"]}],                     TrackedSymbols :> {enabled}]             ,             Dynamic[pos]             }]      , Initialization :> (pos := MousePosition["Graphics"])]      ![enter image description here](http://i.stack.imgur.com/sUOS5.png) I think I don't understand this and IMO it is not expected or desired behaviour. When one put another `Print` next to `Graphics` you will see that it is in face whole `Graphics` updating. **So the question is** : If it's not a bug (I missed something) then how to recreate this MWE so it behaves correctly. * * * I think it may be (but not necessarily) related to Why does a heavy background slow LocatorPane from updating, even if only the locators are Dynamic? p.s. `Dynamic[Refresh[..., TrackedSymbols:>{enabled}]]` behaves the same way. * * * **Edit** so at the end it seems to be more related to Button evaluation inside DynamicModule


title: Dealing with nested options

text: OptionValue allows for recent versions of Mathematica (I think as from 7) to easily access optional parameters if they are explicitely given to a function or their default values otherwise. For big functions using options of options can be useful but we don't have in such cases something like OptionValue in order to access them. We must resort to using Replace in order to use them. See for example the option "LegendGridOptions" in the answer of Jens to the question Creating legends for plots with multiple lines?               "LegendGridOptions" -> {Alignment -> Left, Spacings -> {.4, .1}}}      Has someone already tried to do something like OptionValue for sub-options ?


title: I'm trying to filter a date range by day of month and day of week - what am I doing wrong?

text: I am trying to generate a list of dates that match two criteria: they have to all be the first of the month, and they have to be a particular day of the week, Sunday in my case. The code I have written is this: `Select[DayRange[{1901, 1, 1}, {2000, 12, 31}], DayName[#] == Sunday && # == {_, _, 1} &]` I.e. I want to `Select` only those days in between the `DayRange` 1 january 1901 and 31 December 2000 that match the criteria of being a `Sunday` as well as (`&&`) being the first of the month (`{_, _, 1}`). However, this function just outputs an empty list. I'm still new to Mathematica, but in as far as I can see everything here should work fine. What am I doing wrong?


title: Bordermatrix from LaTeX

text: How would I create an output similar to the result produced by this LaTeX code:               M = \bordermatrix{~ & x & y \cr                       A & 1 & 0 \cr                       B & 0 & 1 \cr}      which when compiled, looks like ![enter image description here](http://i.stack.imgur.com/MJLX9.png)


title: Mathematica Application in Real Life

text: As an 'user'-level in _Mathematica_ , I mainly use built-in _Mathematica_ function and benefit _Mathematica_ as a mathematical tool-box for my specific scientific problem. My level is not yet programmer-level. The magic of _Mathematica_ is that there are endless level of skill to improve. It is hardly to evaluate a C-programmer by viewing his code. But for _Mathematica_ , be viewing the code, the level could be evaluated. Normally, when skilled level increases, the length of code decreases. Based on the idea of Leonid Shifrin and the level in online game, I myself auto evaluate my skill.   * Level 0 - Level 20: Beginner-Users who uses mainly built-in functions.    * Level 20 - Level 40: Intermediate, mix some long procedural programming and functional style   * Level 40 - Level 60: Expert, low-level system understanding Although I have " _Mathematica_ **_Advanced_** Foundation Level" certification, I think my level is Beginner - Pre-Intermediate about level 18- to level 22. I can not understand the Expert level, for example One-Line Code Competition. As we can see here, Expert level codes program in just 'one line'. :) ![enter image description here](http://i.stack.imgur.com/2mPTV.png) My question is, could you please introduce the use of Mathematica as a real- life application? It is not a question of technique, but a question of idea, imagination. Your applications could open my eye of the use of Mathematica in your real-life. I also see "User Stories" on _Wolfram_ site, but almost of them are scientific, industrial applications. In my case, as an researcher-lecturer at University, I intend to use Mathematica in my teaching. Correct the copies take me a lot of time. So my project is:   * Use _Mathematica_ to auto generate MCQ (Multiple Choice Question) question based on my question data base.   * Scan students answers as an image file.   * Use _Mathematica_ to generate the note by image manipulating on these scanned copies. (The optical reader in my university is really expensive, and not available for everyone). So coding my own _Mathematica_ code is optimal way. Ideas, projects of the use of _Mathematica_ in real life are welcome !


title: Keyboard Shortcut several Keys

text: I would like to set up a system (or define a keyboard shortcut) so when you type the following > sum I have the following print at the current selection.               NotebookWrite[      InputNotebook[],      ToBoxes[Unevaluated@Sum[Placeholder[ ], {t, 1, n}]],      Placeholder]      This only works partially works b/c it removes focus.               x = Input[""]


title: Produce {f[x],g[y],h[z]} in as many ways as possible

text: I have two lists of equal lengths but for my task I will use 3-element lists , namely `{x,y,z}` and `{f,g,h}`. The first contains variables and the second functions. I want to produce `{f[x],g[y],h[z]}` with input the above lists in as many ways as possible. Until now I have devised the following ones:               Inner[#1[#2]&,{f,g,h},{x,y,z},List]      and               MapThread[#1[#2]&,{{f,g,h},{x,y,z}}]      As pointed out , there is a very similar thread at wolfram's community. If I come up with more solutions I will add them here. **Update** I am updating with the one-liners. In _Wolfram's Community_ forum there are also solutions changing Attributes or using Append but I will omit them here.               MapThread[#1[#2]&,{{f,g,h},{x,y,z}}]          Inner[#1[#2]&,{f,g,h},{x,y,z},List]          Diagonal[Through/@Distribute[{f,g,h}[{x,y,z}],List]          MapThread[Compose,{{f,g,h},{x,y,z}}]      `Apply[List,{f,g,h}.{x,y,z}/.Times->(Operate[##1,0]&)]` and `Apply[List,{f,g,h}.{x,y,z}/.Times->(#1[#2]&)]` work only because f,g,h are before x,y,z in alphabetical order as very well pointed out by @andre                Apply[Compose,Thread[{{f,g,h},{x,y,z}}],{1}]           (#1[[1]][#1[[2]]]&)/@Transpose[{{f,g,h},{x,y,z}}]


title: From iterative to functional

text: How to write this small piece in a functional way (ie. without state variables)?:               test[oldJ_List, newJ_List] := Total[Abs[oldJ - newJ]] > 1;     relax[j_List, x_?NumericQ] := Mean[Nearest[j, x, 4]];          j = Range[100]; (* any numeric list *)     j1 = j/2; (*some initial value for the While[] test to return True*)          While[test[j1, j],      j1 = j;       (j[[#]] = relax[j, j[[#]]]) & /@ Range@Length@j]


title: Binning sequential sets of elements together in a list

text: Given a list of the form:               {{1,2,3,4,5},{6,7,8,9,10},{11,12},{13,14,15,16},{17,18,19,20,21,22,23},{24},{25,26},{27},{4}}      How can I bin each sequential set of N elements of the list together? For example, if N = 3, we would transform the above list into:               {{1,2,3,4,5,6,7,8,9,10,11,12},{13,14,15,16,17,18,19,20,21,22,23,24},{25,26,27,4}}      Of length 3.


title: CommunityGraphPlot doesn't size

text: When I need to plot a 'large' graph with CommunityGraphPlot the output is always sized at the Mathematica default value. The Graph object itself can be resized with ImageSize option. However that doesn't work with Mathematica 9.0.0. The only option is to enlarge the plot by clicking the image and pull it to the wanted size. Then you can export this graph to PDF and print it. Is there a alternative way?               g = RandomGraph[{200, 300}, VertexLabels -> "Name",ImagePadding -> 20, ImageSize -> Scaled[0.5]]      ![enter image description here](http://i.stack.imgur.com/fPbDj.png)               CommunityGraphPlot[g]      ![enter image description here](http://i.stack.imgur.com/wol4q.png) **UPDATE:** I just found out that the CommunityGraphPlot generated can be double clicked and then you can freely drag the vertexes etc while keeping the connections! Can't do that with Graph object by default.


title: Pattern issues weird warning

text: Take for example               head[b_[PatternSequence[_, _]]] := 9      I know this example serves no purpose as is. It also happens in useful examples such as               head[b_[_, arg : PatternSequence[_, _]]] := {arg, b}      The definition is made propely, but it issues the message > `Pattern::patvar:` First element in pattern `Pattern[1,_]` is not a valid > pattern name. >> A simpler example of the problem, suggested by @celtschk in comments               b_[PatternSequence[_, _]] :> 0      and               b_[PatternSequence[]] :> 0      Particularly interesting is an example @OleksandrR found, in which the mysterious numbering of patterns becomes more evident               (p : {a_, b_, c_})[PatternSequence[]] -> Null      > `Pattern::patvar:` "First element in pattern > `Pattern[4,{Pattern[1,_],Pattern[2,_],Pattern[3,_]}]` is not a valid pattern > name."


title: Higher order SVD

text: Does anyone know how to do a higher order SVD in Mathematica ? A good reference seems to be here http://www.sandia.gov/~tgkolda/pubs/pubfiles/SAND2007-6702.pdf but I don't understand their formalism yet, maybe someone has already some experience with this in Mathematica and this could speed up the understanding. Thanks Another interesting reference is here ftp://ftp.cs.sjtu.edu.cn:990/zhang- lq/Papers/TensorFactorization/2004icpr_tensorRepresentaion_Wang.pdf