Efficiently Constructing Rank One Approximations for a Matrix using SVD

Suppose I have a $m\times n$ matrix $A$ (real for simplicity). Then `SingularValueDecomposition[A]` yields 3 matrices $U$, $\Sigma$ and $V$ such that $A = U\Sigma V^\top = u_1 \sigma_1 v_1^\top + u_2 \sigma_2 v_2^\top + \cdots$, where $U = [u_1\;\; u_2 \ldots]$ (vector = column matrix). Successive approximations for $A$ are given by the rank 1 matrices $u_1 \sigma_1 v_1^\top$, etc. I wanted to make a function to compute this but found myself doing all sorts of messy manipulations due to Mathematica's matrix structure (and/or my lack of knowledge on how to use them). Here is my tentative function. It has as input any matrix A and an optional argument n saying how many rank 1 matrices should be summed. This function is not meant to be numerically fast or anything; perhaps I would use it as a educational tool to examine different approximations of A or etc. The point is in the `Sum` function where I would like to know: is there a more efficient (or perhaps cleaner) way of doing the matrix multiplications?               RankOneApprox[A_, n_: 1] := Block[{U, Sig, V},          {U, Sig, V} = SingularValueDecomposition[A];          Sum[Sig[[i,i]] ({U[[All, i]]}\[Transpose].{V[[All, i]]}), {i, 1, n}]];


How to align rotated tick labels?

How can I align tick labels so the tick label text ends centered under the data point? Of Course it works fine with a rotation of 90 Degrees, but not with 45 or similar angles. I see an example of how to do this charts but not with Plot or ListPlot http://mathematica.stackexchange.com/a/2656/388               d = Table[n, {n, 10}];     xticks = Table[{n,      Rotate["The y value is " <> ToString[n], 45 Degree]}, {n, d}];     ListPlot[d, Frame -> True,       FrameTicks -> {{Automatic, None}, {xticks, None}}]      ![Labeled list plot](http://i.stack.imgur.com/npnsK.png)


When to make (file.nb) instead of (file.cdf)?

I started with **File > New > FreeCDF** so I can save my work in a format compatible with the CDF Player. I can use Mathematica to make new cells, evaluate input and so in the CDF file. What are the differences between using **File > New > FreeCDF** and **File > New > Notebook**? I suppose there are cases when you want to use `file.nb` instead of `file.cdf` but what are they?


Optimizing a function involving NDSolve results in error messages

I want to minimize a function `f` with `NMinimize` but an error occurs that says:               f[l_] := (       kk = NDSolve[{y'[x] == 2*x + 3, y[l] == 0}, y, {x, 0, l}];       out = Evaluate[y[0] /. kk];       out[[1]])          NMinimize[{f[t], 0 <= t <= 10}, f, t]      > During evaluation of In[18]:= NDSolve::ndsv: Cannot find starting value for > the variable y. >> > > During evaluation of In[18]:= ReplaceAll::reps: > {NDSolve[{(y^[Prime])[x]==3+2 x,y[{t}]==0},y,{x,0,{t}}]} is neither a list > of replacement rules nor a valid dispatch table, and so cannot be used for > replacing. >> > > During evaluation of In[18]:= NMinimize::argrx: NMinimize called with 3 > arguments; 2 arguments are expected. >> >   >   >     Out[18]= NMinimize[{y[0], 0 <= t <= 10}, f, t] >   How can I fix the function `f` to avoid this problem?


Indices and variable definitions in Mathematica

Does anyone know how I can do this in Mathematica? Just an example.. Defining indices and variables (defined over indices), "mapping" variables and indices:               index i {NewYork,LosAngeles,Chicago}     Subindex j {NewYork,LosAngeles}     Index k {a,b,c}          variable costs = costs(i,k)     variable size = size(i)     variable biggest = biggest (j,k)      After that, I can start my calculations..               costs(i,k)=...      What about the notation package? Does it help? Thanks!!


Passing a variable messages list to Quiet

I'm trying to build a Verbose option into some code but I'm having trouble passing to a `Quiet` statement a variable list of which messages I want to suppress. My naïve try is code along the lines of               f[x_] := Module[{messageList},       messageList = {Power::infy};       Quiet[1/x, messageList]       ]     f[0]      The idea would then be to build an option `Verbose` which controls whether the assignment `messageList = {Power::infy}` is made, or whether that variable is set to `{}`, which will let the message through. However, even this bare-bones code is not working, and it returns messages of the sort               Quiet::anmlist: Argument 2 of Quiet[1/0,messageList$1303]           should be All, None, a message name, or a list of message names. >>      (though obviously the number after `messageList$` changes every time). * * * ### Edit It seems, from a discussion in the comments, that two things are important (though I don't understand why). First of all, not all error messages are treated equally (as shown e.g. by running `Evaluate[{Power::infy, FindRoot::lstol}]`) so to give a better example, here is one with the error I'm interested in, `FindRoot::lstol`:               g[a_] := Module[{verbose = True, messageList},       If[verbose,        messageList = {},        messageList = {FindRoot::lstol}        ];       Quiet[        FindRoot[x^2 + x + a, {x, 3}]        , messageList]       ]     g[1]      It is also important to me to be able to control, from within the function (and eventually with an `OptionsPattern[]` that contains `Verbose->True` or `False`) whether the message list that gets passed is `{}` or a nontrivial one. I'm not picky about how it gets there (i.e. `messageList = If[verbose, {}, {FindRoot::lstol}];` would serve just fine) but it does need to have at least that level of logic built in. * * * What is the correct way to do this?


Flipping x-tick-labels on custom plot

I'm slightly new to the world of Mathematica, so I can't assess the difficulty of my request, but anyhow, this is my question: I have 2 datasets that I want to plot with two y axes, and a reversed x axis. (as to 'why do you want a reversed x-axis': the time parameter is in thousand years before present, which decreases in value as time moves forward, such that 0 is the present day) The data is the following:               area = {{0, 443.387}, {1, 443.387}, {2, 443.387}, {3, 443.387}, {4,       443.387}, {5, 444.06}, {6, 445.406}, {7, 446.751}, {8, 447.424}, {9,      698.385}, {10, 718.57}, {11, 734.044}, {12, 772.395}, {13,       822.856}, {14, 878.7}, {15, 5933.58}, {16, 6837.85}, {17,       7254.32}, {18, 7362.65}, {19, 7458.86}, {20, 7540.94}, {21,       7621.01}}                    ;     distance = {{0, 10.3807}, {1, 10.3807}, {2, 10.3807}, {3, 10.3807}, {4,       10.0923}, {5, 10.0923}, {6, 10.0923}, {7, 10.0923}, {8,       10.0923}, {9, 9.69003}, {10, 9.65897}, {11, 9.65897}, {12,       9.35579}, {13, 8.94344}, {14, 8.22982}, {15, 7.4932}, {16,       6.66484}, {17, 5.21611}, {18, 5.21611}, {19, 4.47083}, {20,       3.94395}, {21, 3.72562}}     ;      I made a YY-plot code using this code: http://mathematica.stackexchange.com/a/647/11219, which produces: ![YY_plot-example](http://i.stack.imgur.com/wI5og.png) And then reversed the original data using the code as found here: http://mathematica.stackexchange.com/a/5717/11219, which should reverse both the data and the axis ticks. ![enter image description here](http://i.stack.imgur.com/4Ddi2.png) As I hope you can see: the data is transformed correctly, the labels on the x-axis are not. So in combining the two codes I found, I broke the Ticks on the x-axis. Is it possible to fix this? Even a manual setting of the labels is fine with me, all my plots have the same data range from 21--0. The current code is:               TwoAxisListLinePlot[{f_, g_}] :=       Module[{fgraph, ggraph, frange, grange, fticks,         gticks}, {fgraph, ggraph} =         MapIndexed[         ListLinePlot[#, Axes -> True, PlotStyle -> ColorData[1][#2[[1]]],            Mesh -> Full,           Ticks -> ({Transpose[({#[[1]],                      Reverse@#[[2]], #[[3]], #[[4]]} &@                   Transpose[Sort@#[[1, 2, 1]]])], #[[1, 2, 2]]} &@              AbsoluteOptions[ListLinePlot@#1, Ticks])           ] &, {f, g}]; {frange, grange} =         Last[PlotRange /. AbsoluteOptions[#, PlotRange]] & /@ {fgraph, ggraph};       fticks =         Last[Ticks /.            AbsoluteOptions[fgraph,             Ticks]] /. _RGBColor | _GrayLevel | _Hue :> ColorData[1][1];       gticks = (MapAt[Function[r, Rescale[r, grange, frange]], #, {1}] & /@            Last[Ticks /.              AbsoluteOptions[ggraph,               Ticks]]) /. _RGBColor | _GrayLevel | _Hue -> ColorData[1][2];       Show[fgraph,         ggraph /.          Graphics[graph_, s___] :>           Graphics[           GeometricTransformation[graph,             RescalingTransform[{{0, 1}, grange}, {{0, 1}, frange}]], s],         Axes -> False, Frame -> True,         FrameStyle -> {ColorData[1] /@ {1, 2}, {Automatic, Automatic}},         FrameLabel -> {"Years before present [ka]", "Area [km\.b2]", "",           "Isolation [km]"},        FrameTicks -> {{fticks, gticks}, {Automatic, Automatic}}]]      And then run as               k1 = Transpose@({Reverse[#[[1]]], #[[2]]} &@Transpose@area);     k2 = Transpose@({Reverse[#[[1]]], #[[2]]} &@Transpose@distance);     TwoAxisListLinePlot[{k1, k2}]


Determinant of a random matrix consisting of integers

I am trying to implement a function that finds the determinant of a random matrix consisting of integers. This is the code I have written so far, but I am stuck. Suggestions ? I want to find a solution without Det[M].               M := RandomInteger[{-10, 10}, {8, 8}]          det[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] := Module[{i, d},     If[N == 2,     Drop[Mi, {1, 1}, {1, 1}][[1, 1]]*Drop[Mi, {1, 1}, {1, 1}][[2, 2]] -      Drop[Mi, {1, 1}, {1, 1}][[1, 2]]*      Drop[Mi, {1, 1}, {1, 1}][[2, 1]],      For[i = 1, i <= Length[M], i++,      d = d + (-1)^(1 + i) *M[[1, i]]*        Minors[Drop[M, {1, 1}, {i, i}],            Length[Drop[M, {1, 1}, {i, i}]]][[1]][[1]]]];      Return[d, Module]]     det1[Mi_ /; Dimensions[Mi][[1]] == Dimensions[Mi][[2]]] :=      Module[{det1},     det1 = Sum[     If[det1 == 1,       Break[], (-1)^(1 + j) *Mi[[1, j]]*det1[Drop[Mi, {1}, {j}]]], {j,       1, Length[Mi]}]; Return[det1 // MatrixForm, Module]]     det1[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] :=     Module[{i, d = M},     For[i = 1, i <= Length[d], i++,     If[Length[M] == 1, Goto[end]      If[Length[M] == 2,        d = Drop[d, {1}, {1}][[1, 1]]*Drop[d, {1}, {1}][[2, 2]] -          Drop[d, {1}, {1}][[1, 2]]*Drop[d, {1}, {1}][[2, 1]];        Goto[end], d = d + (-1)^(1 + i) *d[[1, i]]*Drop[d, {1}, {i}]];     Label[end]; Return[d, Module]]]]     det1[M_ /; Dimensions[M][[1]] == Dimensions[M][[2]]] :=     Module[{i, d = M},     For[i = 1, i <= Length[d], i++,      Switch[d, 1, Goto[end], 2,      d = Drop[d, {1}, {1}][[1, 1]]*Drop[d, {1}, {1}][[2, 2]] -        Drop[d, {1}, {1}][[1, 2]]*Drop[d, {1}, {1}][[2, 1]];      Goto[end], _,     d = d + (-1)^(1 + i) *d[[1, i]]*Drop[d, {1}, {i}]];      Label[end]; Return[d, Module]]]     Return[Determinant[Mi]]


Saving data inside a notebook so that I don't have to run it again?

Piggybacking on this, I am somehow not fully convinced that I can't save data generated by a calculation in a mathematica file so that when I re-launch said file, I wouldn't have to run my calculations again. I ask because I use `NDSolve` for 4th order non linear PDEs and sometimes I need to run it for really large times (in excess of a few hours, yes that sounds crazy but I am just trying to get results for a fluid dynamics problem here and I am not all that interested in being a computer scientist to reduce run times). So after reading the linked article, I did this for an example problem:               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, 0, 10}, {x, 0, 5}]          DumpSave["pde0.mx", sol]      Then I quit mathematica and relaunch it and load `pde0.mx` with `Get`               Get["pde0.mx"]      And when I plot,               Plot3D[Evaluate[u[t, x] /. sol], {t, 0, 10}, {x, 0, 5},       PlotRange -> All]      Voila, I get the plot as if I had run the simulation. So.. did I run the simulation again by invoking `sol` through `Get` or was my kernel state saved?


How to check if a 2D point is in a polygon?

Background: I use code from An Efficient Test For A Point To Be In A Convex Polygon Wolfram Demonstration to check if a point ( mouse pointer ) is in a ( convex ) polygon. Clearly this code fails for non-convex polygons. **Question: I am looking for an efficient routine to check if a 2D-point is in a polygon.**


How to judge if a point is in the interior of a closed curve or not?

For example:               pts = {{0, 1}, {-(Sqrt[3]/2), -(1/2)}, {Sqrt[3]/2, -(1/2)}};     trig=JoinedCurve[Line[pts], CurveClosed -> True];      Then `trig` is a closed triangle. If I have a point `p={a,b}`, how can I judge if `p` is in the interior of the triangle `trig`?


How to calculate the analytical result of this singular integral?

I'm trying to solve this integral: $I(a,b)=\displaystyle{\int_1^{\infty }\dfrac{e^{-ax}}{\sqrt{x^2-1} (1+x\sqrt{1-b^2}) (x-1/\sqrt{1-b^2})} \, dx} \,\, \,\,(a \;\textrm{real>0} \, , 0<b<1)$ by varying b from 0 to 1. Mathematica didn't calculate this integral. Maybe it is too complicated to be done. In Mathematica input form:               Integrate[Exp[-a x]/(Sqrt[x^2 - 1](1+x Sqrt[1-b^2])(x-(1/Sqrt[1-b^2]))), {x,1,Infinity}]      If I simply enter that into Mathematica, it instantly returns the same expression. How do I go about this? Is there any tricks that can be applied? Is there a way to get the a symbolic result? Thank's.


Is it possible to change the fontsize when printing a notebook in the working enviroment?

I want to print a notebook that owns syntax color,I use the Szabolcs's method               SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Working"]      Then I can achieve a PDF file shown as below: ![Working Enviroment](http://i.stack.imgur.com/CoA15.png) However,when I change the `PrintingStyleEnvironment to "Printout"`               SetOptions[$FrontEndSession, PrintingStyleEnvironment -> "Printout"]      ![Printout Enviroment](http://i.stack.imgur.com/3tM4q.png) I feel the fontsize in the `Working Enviroment` is more large than `Printout Enviroment`. So my question is: **How to make the fontsize in`Working Enviroment` be same with `Printout Enviroment`.** **I feel the fontsize in`Printout Enviroment` is very suitable.**


Breaking up data and finding independence

Suppose I have the list with elements (either 1 or 4 as the last digit) as follows:               data=     {{42, 49.11, 1}, {41, 49.32, 4}, {41, 48.21, 4}, {41, 53.08, 1}, {39,        46.22, 1}, {39, 47.06, 1}, {47, 48.87, 4}, {41, 49.64, 1}, {41,        48.44, 1}, {42, 49.98, 4}, {39, 49.04, 1}, {46, 48.73, 1}, {49,        48.33, 4}, {39, 50.95, 1}, {42, 46.05, 4}, {49, 52.52, 1}, {49,        48.81, 1}, {49, 50.75, 4}, {47, 52.39, 1}, {41, 52.56, 1}, {40,        56.01, 4}, {46, 52.77, 4}, {43, 52.81, 1}, {39, 50.37, 1}, {40,        52.38, 1}, {49, 51.31, 4}, {48, 54.26, 4}, {40, 53.3, 4}, {42,        50.62, 4}, {48, 49.66, 4}, {43, 51.39, 4}, {41, 59.23, 4}, {41,        49.07, 4}, {40, 51.43, 4}, {39, 54.47, 4}, {49, 50.4, 4}, {48,        51.04, 1}, {46, 47.95, 1}, {45, 50.52, 4}, {44, 53.18, 1}}      How do I break it into two sets with the same last digit, such that               data1={{42, 49.11, 1},  {41, 53.08, 1}, {39,        46.22, 1}, {39, 47.06, 1}, {41, 49.64, 1}, {41,        48.44, 1}, {39, 49.04, 1}, {46, 48.73, 1}, {39, 50.95, 1},       {49, 52.52, 1}, {49, 48.81, 1}...}      and               data2={{41, 49.32, 4}, {41, 48.21, 4}, {47, 48.87, 4},{42, 49.98, 4}, {49,        48.33, 4},  {42, 46.05, 4}, {49, 50.75, 4},  {40,   56.01, 4}, {46, 52.77, 4}..}      How do I test whether these two data sets are linearly independent?


Why does this simple program leak memory?

I have a simple Mathematica program which writes some plots to image files for later conversion into a movie. Unfortunately, the program leaks so much memory that it quickly exhausts all 12G of RAM on my machine. The only way out is to quit the kernel(s). I can't see why this program shouldn't use a bounded amount of memory. I've read through Debugging memory leaks which unfortunately hasn't helped - the only "heavy" symbol is 'data', whose size is fixed. I don't see what's growing! Note that the same problem occurs regardless of whether the loop is Map or Do, Parallel- or not. The problem also occurs in both Mathematica 8 and 9, both under Linux. Help?               (* number of frames *)     n = 1000;     (* just some bogus data *)     makeData[_] := Table[{{x, y} = RandomReal[{-3, 3}, {2}], {y, -x}}, {200}];     data = Array[makeData, n];     (* Export the frames *)     ParallelMap[       Export[         "movie-" <> IntegerString[#, 10, 4] <> ".png",         ListVectorPlot[data[[#]]]] &,       Range[1, n]];      **Edit** :   Some more information: after running this code (the non-parallel version), I checked the memory usage of the processes involved. The percentages are out of 12GB, so both the frontend and the kernel are consuming quite a bit of memory, while PNG.exe is almost nonexistent.                 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                 24575 gredner   20   0  4400  740  588 S    0  0.0   0:00.00 Mathematica             24646 gredner   20   0 3029m 2.3g  22m S    0 20.5   1:43.02 Mathematica             24655 gredner   20   0 3384m 1.6g  14m S    0 13.7   3:31.47 MathKernel              24984 gredner   20   0  387m 7364 2464 S    0  0.1   0:20.92 PNG.exe


PolynomialRemainder memory

This calculation makes the kernel crash because it needs so much memory. Thoughts on how to get around this?               PolynomialRemainder[1+x^267910657,1+x+x^20+x^32, x, Modulus->2]


Complex infinities in an Euler-Lagrange equation

I now wish to solve for $L(t)$ and $H(t)$ some ugly Lagrangian (in the code below) in configuration space, respectively the length and the height of a system. I tried running the code below, with the boundary conditions $ L(0)=\frac{2}{3},L(10)=1, H(0)=0,H(10)=1$               << VariationalMethods`     lagr = EulerEquations[(L'[t]^2 + H'[t]^2)/2 +      1/L[t]^8 (0.939047619047619 L[t]^8 +         H[t]^3 L[          t]^2 (0.008947123427519658 - 0.3461214643843182 L[t]^2 +            6.463704237990063 L[t]^4 - 112.66974752093684 L[t]^6 -            61.714285714285715 L[t]^7) +         H[t]^4 (0.0004134154745845219 - 0.017673330227199326 L[t]^2 +            0.34184835988574624 L[t]^4 - 4.255936946824733 L[t]^6 +            55.63938149182066 L[t]^8 + 27.08994708994709 L[t]^9) +         H[t]^2 L[          t]^4 (0.05911127889691029 +            L[t]^2 (-2.2077672911653297 +               L[t] (2.1333333333333333 +                  L[t] (57.725858297763935 +                     36.888888888888886 L[t]))))), {L[t], H[t]}, t];     sln = NDSolve[{lagr, L[0] == 1, L[10] == 2/3, H[0] == 1,      H[10] == 0}, {L[t], H[t]}, {t, 0, 10}]      only to get some nonsensical error messages:               Power::infy: "Infinite expression 1/0.^6 encountered."     Infinity::indet: "Indeterminate expression -338.009+ComplexInfinity+ComplexInfinity+ComplexInfinity encountered."     NDSolve::ndnum: Encountered non-numerical value for a derivative at t == 0.`.       In my mind, these messages would appear because there are complex-valued terms as well as having a point where $L = 0$, while, in fact, all coefficients are real and I would expect the solution never to cross $L=0$. However, I can't pin down what's the problem with the third message error... Perhaps I might have misunderstood the equation...


Have I found a big difference between using the short form and the long form of a pure function?

By referring to the _Mathematica_ documentation, I learned to use `##2` to represent all the arguments but the first one. This is a brief way to represent a pattern matching all arguments but the first one. However, how can I do the same thing in the long `Function[args. body]` form? For example, `{##2}& @@ f[x1, x2, x3, x4]` will give `{x2, x3, x4}`. Unfortunately, `Function[{u1, u2}, {u2}] @@ f[x1, x2, x3, x4]` only gives `{x2}`. I think this occurs because the long form does not interally contain pattern matching functionality, although I find this hard to believe. So my question is whether the long form really ignores the functionality of pattern matching? In general, are these two pure function forms identical in every aspect? That is, is the short form is just a shortcut for the long form?


NVCC running CUDA in Mathematica 9.01 CudaCCompiler[] fails

This is an old thread that received no responce but like to post again. Anyone here using Mathematica and CUDA? I have not been able to have Mathemartica detect teh CUDA able C compiler. CUDACCompiler[] returns empty. I have tried the following and no results get teh following error               CreateLibrary::target: Target system specification "TargetSystemID" -> Windows-x86-64 is not available for NVIDIA CUDA Compiler installation C:\Users\jecalderon\AppData\Roaming\Mathematica\Paclets\Repository\CUDAResources-Win64-9.0.2.0\CUDAToolkit\bin\. >>


Notation for numerical solutions to differential equations

Can somebody explain this notation to me? Using _Mathematica_ 's first example in the `NDSolve` documentation:               s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]      The output is:               {{y -> InterpolatingFunction[{{0.,30.}}, <>]}}      What do all the curly brackets and the angle signs indicate? Why is there no indication of dependence on `x`? I'm also curious why you have to use this result in what I consider to be an awkward way:               Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All]      as opposed to simply:               Plot[s, {x, 0, 30}, PlotRange -> All]


Eliminate several variables between five Conic_section equations

I want to eliminate `x1, x2, y1, y2` between these 5 equations. I tried               Eliminate[{x1^2/a^2 + y1^2/b^2 == 1, x2^2/a^2 + y2^2/b^2 == 1,        x1 x2 + y1 y2 == 0, y2/(x2 - c) == y1/(x1 - c) == k}, {x1, x2, y1, y2}]      Mathematica takes a long time, I couldn't even wait for it to finish.Can you recommend an efficient method? **Updated:** http://en.wikipedia.org/wiki/Proportionality_(mathematics)               ForAll[{a, b}, b d != 0 && b^2 != d^2,       Equivalent[a/b == c/d,        a/b == c/d == (a - c)/(b - d) == (a + c)/(b + d)]]     Resolve[%]     (*True*)            k^2 /. Solve[          Eliminate[{x1^2/a^2 + y1^2/b^2 == 1, x2^2/a^2 + y2^2/b^2 == 1,           x1 x2 + y1 y2 == 0, y2/(x2 - c) == (y1 - y2)/(x1 - x2) == k}, {x1, x2, y1, y2}],         k] // DeleteDuplicates//Tr          (* (a^2 b^2)/(-a^2 b^2 + a^2 c^2 + b^2 c^2) *)


Slideshow mode: how to cycle slides automatically?

I'm doing a slideshow for an informative conference, so I need a slideshow running in background on some monitors. My question is: is there any way to make _Mathematica_ to cycle slides automatically? `Manipulate`, `Animate` and `SlideView` have the "Play" button by which one can set the speed. I'd need something similar for the slideshow. Any idea is welcome, also those which require the editing of notebook code.


Solving stochastic master equation

Can someone help please me in solving the following stochastic master equation for the density matrix $\rho$? ![enter image description here](http://i.stack.imgur.com/59yTx.png) where $\rho$ is the density matrix, $\sigma_i$ are the pauli matrices, $dt$ is the time, $dW$ shows the Wiener increment and ![enter image description here](http://i.stack.imgur.com/Jp1DK.png) The other parameters are constants and $[a,b]$ shows commutator of the operator $a$ and $b$


How to find monotonically increasing intervals of a function

I tried this code, but not working               Clear[f];     f[x_] := x^3 - 3 x + 2;     ForAll[{x1, x2}, x1 < x2, f[x1] < f[x2]]     Reduce[%, {x1, x2}, Reals]      I expected the result is `x<=-1 || x>=1`


How do we solve third order nonlinear differential equation f’’’+ff’-f’2-Re2 f’=0 f(0)=0,f'(0)=1,f(Infinity)=0 From the OP's comment: > >     ic1 = 0; ic2 = 0; ic3 = 1 a = 0.0; >     sol = NDSolve[{y'''[x] + y[x] y'[x] - y'[x]^2 - a^2 y'[x] == 0, >       y[0] == ic1, y'[Infinity] == ic3, y'[0] == ic2}, y[x], PlotRange]; >     Plot[y[x] /. sol, {x, 0, finish}]. >   > > I have used this code to solve using mathematica but i didnt get it


Only String Keys supported in Dataset's Association Query?

Given data:               titanic = ExampleData[{"Dataset", "Titanic"}]      This Association Query works:               titanic[All, <| "newKey" -> "age"|>]      But numeric or Symbol Keys,               titanic[All, <| 1 -> "age"|>]     titanic[All, <| newKey -> "age"|>]      fail with error: `Missing[KeyAbsent]`. Known issue? Numeric keys are especially conveninent for multiple, parametrized queries. Currently, that requires the workaround `KeyMap[ToString]` and later back `ToExpression`.


Is it possible to embed the Mathematica editor?

Is it possible to embed a Mathematica window into a .NET application? I mean not just the interop, but actually making the notebook editor window part of a .NET form. Is this possible?


How to define a function $f(x)$ such that $f(1.5)=1.5$, $f(1.)=1$, $f(0.)=0$, etc.? Namely, if $x$ is an integer with a decimal point, $f(x)$ returns the integer only, otherwise returns $x$. This will be useful in the labels of the following plots.               Table[Block[{a = aa}, Show[Plot[x^a, {x, 0, 1}, PlotLabel -> Style[Row@{"a", "=", aa}, 15]]]], {aa, 0, 2, 0.5}]


How can I get an exponent vector from monomials?

I am trying to get an exponent vector from a list of monomials. I am using the `CoefficientRules` command; however, it is returning a list that includes the coefficients of the monomial. I don't need the coefficient and need to remove it before I can use the exponent vector, however I am finding this quite difficult.               poly = x^2 + 2 x*y + y^2;     monomialList = MonomialList[poly];     alpha = CoefficientRules[monomialList]          {{{2, 0} -> 1}, {{1, 1} -> 2}, {{0, 2} -> 1}}      Is there a way to remove the -> and the value that follows it, or a better way to generate the exponent vector?


What is the correct way to plot a dynamically generated list of functions?

For example, I want to generate a list of random waves and plot them. Then I wrote               f:=Random[Real]     h:=Floor[f*20]      And then               Manipulate[Plot[Table[f Sin[h x + h t], {n, 0, 5}], {x, -5, 5}, PlotRange -> {-2, 2}], {t, 0, 10}]      But it turned out a mess. I tried to fix it with               a = Table[f Sin[ h x + h t], {n, 0, 5}]     Manipulate[Plot[a, {x, -5, 5}], {t, 0, 10}]      But no graph was generated. Finally I tried               a = Table[f Sin[ h x + h t], {n, 0, 5}]     Manipulate[Plot[a /. t -> b, {x, -5, 5}], {b, 0, 10}]      This time the graph was correct. But there are still 2 problems:   1. All functions are in the same color.   2. It lags a lot when I tried to manipulate t. These problems don't exist if you write by hand the list inside plot. So what is the correct way to solve these problems and get the desired output?


johansen test error in code

### Cross-posted at the Wolfram community forum I have found this code on a forum, apparently it worked in a previous version of mathematica. Now when I run it, it keeps running for ages. I am not able to find the error.                ewa = FinancialData["NYSE:EWA", {{2006, 4, 4}, {2012, 4, 9}}, "Value"];      ewc = FinancialData["NYSE:EWC", {{2006, 4, 4}, {2012, 4, 9}}, "Value"];      data = Transpose@{ewa, ewc};      johansenProcedure[levels_?MatrixQ, p_Integer] /;      (Dimensions[levels][[ 1]] > (Dimensions[levels][[2]] + p)) :=      With[{N = Dimensions[levels][[1]], T = Dimensions[levels][[2]],      diff = Rest[levels - RotateLeft[levels]], ypt = Drop[levels, -p]},      Module[{x, r0t, rpt, s00, sop, cc, λ, vλ, logλ},     x = Join @@ (Drop[RotateLeft[diff, #], p - 1] & /@ Range[p]);     With[{q = Inverse[Transpose[x].x], y0t = Drop[diff, p - 1]},     r0t = y0t - x.q.Transpose[x].y0t; rpt = ypt - x.q.Transpose[x].ypt; s00 = (Transpose[r0t].r0t)/T; s0p = (Transpose[r0t].rpt)/T;     cc = Inverse[CholeskyDecomposition[(Transpose[rpt].rpt)/T]];     {λ, vλ} = Eigensystem[(cc.Transpose[s0p].Inverse[s00].s0p.Transpose[cc])];     logλ = Log[1 - λ];     {Reverse[-T* FoldList[Plus, First[logλ], Rest[logλ]]],     Reverse[-T logλ], Join[Reverse[Transpose[Transpose[cc].vλ]], s00, s0p]} ]]];          johansenProcedure[data, 10]      This is the error code               Dot::dotsh: Tensors {<<1>>} and {{0.38,0.42},{-0.21,-0.27},{0.03,0.13},{0.,-0.03},<<44>>,      {0.04,0.02},{-0.56,-0.63},<<1455>>} have incompatible shapes. Dot::dotsh: Tensors {<<1>>} and {{0.38,0.42},{-0.21,-0.27},{0.03,0.13},{0.,-0.03},<<44>>,{0.04,0.02},{-0.56,-0.63},<<1455>>} have incompatible shapes.      On guy suggested that this line was broken:               r0t = y0t - x.q.Transpose[x].y0t;      rpt = ypt - x.q.Transpose[x].ypt;       I have spent ages but are not able to figure out what to do, could someone give it a try?


Processing and storing a graph with a large number of vertices s.t. k-hop neighborhoods are efficiently retrievable

I have an unweighted, undirected graph $G$ with $(v_1, ..., v_N) \in V$ vertices, where each vertex in the lattice represents a string of some length ($\leq 200$ characters), and I need to construct $G$ from an unordered list of edges between vertices (i.e. a list saying that vertex $v_i$ is connected to vertex $v_j$ for some $i \neq j$). Here, $||V||$ is very large, on order $10^{9}$ to $10^{12}$ or so, but the degree of each vertex $v_i$ is bounded by some small integer value s.t. the maximum vertex degree is $\Delta G\approx 16$. What is a good way to store or process $G$ in Mathematica (some sort of suffix tree or hash table?) s.t. I can efficiently retrieve a list of vertices in the $k$-hop neighborhood of some vertex $v_i$? By $k$-hop neighborhood, I mean the set of vertices that can be reached from $v_i$ by traveling along at most $k$ edges. * * * To provide an example, I might start with a list of vertices corresponding to unique binary strings: $v_1 = 10101011110...$ $v_2 = 01110100101...$ ... $v_N = 00000011110...$ And an unordered list of (undirected) edges between vertices: $v_{36544} \to v_{3}$ $v_{740943} \to v_{92034}$ $v_{36544} \to v_{674}$ ... Is there a nice / efficient way to process the about lists in Mathematica s.t. I can retrieve the set of nearest-neighbors for, say, $v_{36544}$, which includes $(v_{3}, v_{674}, ...)$? The naive way to proceed is to simply specify a graph structure as: Graph[{...}], but is this efficient for very large instances of $G$? * * * Update - OK, some data. Intel Xeon CPU (X5690) 3.47 GHz 64 bit system (No attempt at parallelization) Lookup time for the $k=1$ hop neighborhood of an arbitrary vertex (using NeighborhoodGraph[G]): G = 10 x 10 integer lattice: 27.4 milliseconds G = 50 x 50 integer lattice: 0.765 seconds G = 100 x 100 integer lattice: 3.08 seconds The scaling appears exactly linear with graph size: http://www.wolframalpha.com/input/?i=%7B0.0274%2C+10%5E2%7D%2C%7B0.765%2C2500%7D%2C%7B3.08%2C100%5E2%7D This is awful, especially considering that Mathematica can draw a spring minimized graph in relatively short order for the 100 x 100 integer lattice.


Generate a Random Polygon

Does some package exist with a function that takes a parameter $n$ and generates a random 2D $n$-sided **simple polygon** (convex or non-convex), possibly within a certain bounding box? It does not suffice to simply generate $n$ random points as I would have to figure out how to connect the points in a non-intersecting manner. I am sure there are algorithms to solve this particular problem, but I would much rather use a **ready-made function** that would be guaranteed to work, rather than code my own function and introduce more bugs. I am trying to generate a large number of "random" test cases for my algorithm that is supposed to work for all polygons.


NDSolve for a large system of coupled (complex valued) ODEs

The system under consideration here is a generalization of the one I discussed in this problem. Qualitatively, I am trying to solve a system of coupled nonlinear (up to order 4 in the dep variables) ODEs which can take on complex values. The governing equation for the $n-th$ ODE is of the form: $\sum_{k=-M}^M (Q_{nk}+Q_{kn}) \ddot{a}_k -\sum_{\ell=-M}^M\sum_{k=-M}^M S_n(\ell,k) \dot{a}_{\ell} \dot{a}_k + U_n = 0 $ where $Q_{nk}=\frac{1}{2}\sum_{j=1}^MP_{jn}P_{(-j)k}$, with $P_{mn}=\frac{\sqrt{|m|}}{|n|}(a_{m-n}-\frac{a_ma_{-n}}{2})$, (and the contsraints that $a_{m-n}=0$ for $|m-n|>M$ and $a_{m-n}=0$ when $Sign(m-n)=Sign(n)$), $S_n(\ell,k)=\left(\frac{\partial Q_{k\ell}}{\partial a_n}-\frac{\partial Q_{n\ell}}{\partial a_k}-\frac{\partial Q_{\ell n}}{\partial a_{k}}\right)$ and $U_n = \frac{\partial V}{\partial a_n}$ where $V = \frac{1}{8}\left(\sum_{n=1}^M\frac{a_na_{-n}}{n}\right)^2 +\frac{1}{2}\sum_{n=1}^M\frac{a_na_{-n}}{n^2} -\frac{1}{2} \left(\sum_{n=1}^M\frac{a_na_{-n}}{n})\right)\left(\sum_{n=1}^M\frac{a_na_{-n}}{n}\right) + \sum_{i+j+k=0,(i,j,k)\neq 0}\frac{a_ia_ja_k}{4ij}$ and $M$ is the highest mode under consideration. In the limit of small $a_i$, these governing equations reduce to a system of harmonic oscillators of the form $\ddot{a}_i=-ia_i$, so I've been exploring the solutions with initial conditions that should reproduce this and give solutions of the form $a_n(t)= e^{int}$. When I set this system up in Mathematica, I can find coherent solutions for the $M=1,M=2$ cases. However, for $M=3$ the integration takes a very long time (so far more than 6 hours) so something is awry. The bottleneck seems to be occurring at the NDSolve portion of the code, as I think I've executed all HoldAll's that could be causing time issues. For the simpler system linked above (where all coefficients are real) I was able to integrate the $M=50$ cases in about 1 hour, so I'm trying to see why NDSolve would be taking longer in this case. I note that in that case the system was "treated as a system of differential-algebraic equations". The equations in this example are not treated as DAE, since this complicates finding appropriate ICs and I experience a "mconly" error. This could be one reason for large discrepancies in run time. Finally, there is a relationship between the coefficients such that $a_{-k} =a^*_k$ which I have not exploited and could potentially cut the number of dependent variables in half. Any insights into getting larger M cases to integrate, or why this is taking so long in its current state, would be greatly appreciated. Thanks, Nick               M = 3; (*Number of modes*)     cond1[r_, s_] := If[Sign[s] == Sign[r - s], 0, 1];     cond2[r_, s_] := If[Abs[r - s] > M, 0, 1];      F[n_] := If[n == 0, 1, Abs[n]];     a[0][t_] := 1;     P[m_, k_, t_] :=      Sqrt[F[m]]/     F[k]*(cond1[m, k]*cond2[m, k]*a[m - k][t] -       1/2*a[m][t]*a[-k][t]) ;       Q[k_, l_, t_] = 1/4*Sum[P[m, k, t]*P[-m, l, t], {m, 1, M}];     q[m_, k_, n_, t_] :=      Sqrt[F[m]]/     F[k]*(cond1[m, k]*cond2[m, k]* Boole[m - k == n] -       a[m][t]/2*Boole[-k == n] - a[-k][t]/2*Boole[m == n]);     SQ[k_, l_, n_, t_] :=      1/4*Sum[P[-m, l, t]*q[m, k, n, t] + P[m, k, t]*q[-m, l, n, t], {m,       1, M}];     SS[k_, l_, n_, t_] := (SQ[k, l, n, t] - SQ[n, l, k, t] - SQ[l, n, k, t]);     Fu[a_, b_, c_] := If[a + b + c == 0, 1, 0];      Fu2[a_] := If[a == 0, 0, 1];     V[t_] := Evaluate[     1/2*(Sum[-a[n][t]*a[-n][t]/(2*n), {n, 1, M}]^2 +        2*Sum[a[n][t] a[-n][t]/(4*n^2), {n, 1, M}] +        Sum[-a[n][t]*a[-n][t]/(2 n), {n, 1, M}]*        Sum[a[n][t] a[-n][t]/n, {n, 1, M}] +        Sum[Fu[n, m, o]*Fu2[n]*Fu2[m]*a[n][t]*a[m][t]*a[o][t]*         Abs[o]/(4 Abs[F[n]*F[m]*F[o]]), {n, -M, M}, {m, -M,          M}, {o, -M, M}])];      U[n_, t_] := Evaluate[D[V[t], a[n][t]]];      Gov[n_, t_] :=      Sum[a[l]''[t]*(Q[n, l, t] + Q[l, n, t]), {l, -M, M}] -      Sum[SS[k, l, n, t] a[k]'[t] a[l]'[t], {k, -M, M}, {l, -M, M}] +      U[n, t];     ao = 0.01;     eqns2 = {     Evaluate[Gov[-3, t] == 0],     Evaluate[Gov[-2, t] == 0],      Evaluate[Gov[-1, t] == 0],     Evaluate[Gov[1, t] == 0],      Evaluate[Gov[2, t] == 0],      Evaluate[Gov[3, t] == 0],     a[1][0] == a[-1][0] == ao,      a[1]'[0] == I*ao, a[-1]'[0] == -I*ao,      a[2][0] == a[-2][0] == ao^2,      a[2]'[0] == ao^2*I*2,      a[-2]'[0] == -ao^2*I*2 ,      a[3][0] == a[-3][0] == ao^3,      a[3]'[0] == 3*I*ao^3,     a[-3]'[0]==-3*I*ao^3     };     MMode = NDSolve[     eqns2, {a[-3][t],a[-2][t], a[-1][t], a[1][t], a[2][t], a[3][t]}, {t, 0, 10}, Method ->      {"EquationSimplification" -> "Solve"}]


The best method of constructing a product of consecutive terms

I am new to _Mathematica_ , I am searching for a way to create an expression with a sequence of terms such as:               (x-1)/x  (x-2)/x  (x-3)/x  (x-4)/x … (x-n)/x


How can I create input fields based on the user's choice from a popup menu?

I'm trying to create an interface with _Mathematica_. However, I need some instructions concerning the code below. This is about 10% of what I have in mind, but first I need to know how can I create `ns` `InputField`s after `ns` is defined by the user making a choice from the popup menu.               ns : number of station     sf : sound frequency     ws : width of window      * * *               CreateWindow[       DialogNotebook[       {         TextCell["Number of Stations: "],         PopupMenu[Dynamic[ns], Range[2, 8]],              TextCell["Sound Frequency (kHz): "],         InputField[Dynamic[sf], String, FieldSize -> 7],              TextCell["Window Size (ms): "],         InputField[Dynamic[ws], String, FieldSize -> 7],              TextCell["Calculation Start relative to the Window (ms): "],         InputField[Dynamic[cs], String, FieldSize -> 7],              ChoiceButtons[{DialogReturn[{retNS = ns, retSF = sf, retWS = ws, retCS = cs}]}]       },       WindowTitle -> "Fluvial Acoustic Tomography Configuration"]];


List all possible elements of a set

I have this two sets: $A = \\{\emptyset, \\{\emptyset\\}, \\{\\{\emptyset\\}, \emptyset\\}\\}$ $B = \\{\\{x, \\{x, y\\}\\} | x \in A, y \in A\\}$ Now I want to list all possible elements that are in $B$. How do I do this?


Convert a string to hex number?

How can I convert a string containing a hex number such as `"6b"` to a hex digit that _mathematica_ can use to do math with? I have tried using `ToExpression["6b"]` but that just give me another string. Note: Java's `BigInteger`class can construct hex integers from strings. Is there something like this in _mathematica_?


How to solve a non-linear equation?

I am trying to solve the following non-linear equation: $\frac{i e^{-x^2} \sqrt{\pi } x}{K^2}+\left(-0.131251-0.0379031 x^2-0.0151154 x^4-0.0100462 x^6+0.5 \left(0.00273859 +0.0400003 K^2\right) x^8+(0. +0.0000362178 i) x^9+0.5 \left(\text{6.72230790401107$\grave{ }$*${}^{\wedge}$-6}+0.000122761 K^2\right) x^{10}+(0. +\text{7.371834962565406$\grave{ }$*${}^{\wedge}$-8} i) x^{11}+0.5 \left(\text{3.049800199384706$\grave{ }$*${}^{\wedge}$-9}+\text{7.195529551699709$\grave{ }$*${}^{\wedge}$-8} K^2\right) x^{12}+(0. +\text{3.611964212904051$\grave{ }$*${}^{\wedge}$-11} i) x^{13}+0.5 \left(-\text{1.2612171276659422$\grave{ }$*${}^{\wedge}$-12}-\text{1.7472476684229308$\grave{ }$*${}^{\wedge}$-11} K^2\right) x^{14}+\text{2.7423509229173302$\grave{ }$*${}^{\wedge}$-15} K^2 x^{16}\right)/\left(0.0200001 K^2 x^8+0.0000613803 K^2 x^{10}+\text{3.5977647758498545$\grave{ }$*${}^{\wedge}$-8} K^2 x^{12}-\text{8.736238342114654$\grave{ }$*${}^{\wedge}$-12} K^2 x^{14}+\text{2.7423509229173302$\grave{ }$*${}^{\wedge}$-15} K^2 x^{16}\right)$ Here's the _Mathematica_ code I used:               Solve[(I E^-x^2 Sqrt[\[Pi]] x)/         k^2 + (-0.13125090233975123 - 0.037903065816010294 x^2 -            0.015115427229185784 x^4 - 0.010046171350985062 x^6 +            0.5 (0.0027385850487922922 +               0.04000027499878133 k^2) x^8 + (0. +               0.000036217780642055754 I) x^9 +            0.5 (6.72230790401107*10^-6 +               0.00012276053475132815 k^2) x^10 + (0. +               7.371834962565406*10^-8 I) x^11 +            0.5 (3.049800199384706*10^-9 +               7.195529551699709*10^-8 k^2) x^12 + (0. +               3.611964212904051*10^-11 I) x^13 +            0.5 (-1.2612171276659422*10^-12 -               1.7472476684229308*10^-11 k^2) x^14 +            2.7423509229173302*10^-15 k^2 x^16)/(0.020000137499390665 k^2 x^8 +               0.00006138026737566407 k^2 x^10 +            3.5977647758498545*10^-8 k^2 x^12 -            8.736238342114654*10^-12 k^2 x^14 +            2.7423509229173302*10^-15 k^2 x^16) == 0, x]      where x is a complex variable and k is a real one. I get this error message: > > Solve::nsmet : This system cannot be solved with the methods available to > Solve. >> Please, I need to find x in terms of k and plot the output x versus k. How can I use _Mathematica_ techniques to solve this equation?


Creating cross-version compatible documentation with Workbench

Wolfram Workbench allows you to create documentation for your own packages that is similar to the build-in documentation center. Integrating this type of documentation with the documentation center is possible starting from _Mathematica_ 6, and hence I would like to create packages whose documentation nicely integrates with _Mathematica_ 6, 7, 8, and 9. However, Workbench doesn't support this out of the box. Its documentation tools seem to be a spin-off from WRI own tools to create version-specific documentation, so it is no wonder creating cross-version compatible docs in Workbench is nearly impossible. So far, I've identified the following obstacles to creating cross-version compatible docs:   1. Documentation indices built with _Mathematica_ <= 8 are not compatible with _Mathematica_ 9, so docs built with <= 8 are not searchable in 9. See this workaround.   2. Documentation pages built with a given version of _Mathematica_ always give the " _This notebook was created in a more recent version of Mathematica_ " dialog warning in older versions. See this workaround.   3. The `PacletInfo.m` syntax has changed with _Mathematica_ 9; it now requires a `"Kernel"` extension. This chokes the _Mathematica_ 6 PacletManager, ruling out docs simultaneously compatible with 6 and 9. See this workaround.   4. Workbench 2 can only properly build docs with _Mathematica_ 7 or 8. _Mathematica_ 6 returns malformed notebooks (see this workaround by Simon Rochester), and 9 freezes halfway the build process for large packages.   5. Docs build with lower version look pretty bad on _Mathematica_ 9\. See this partial workaround. Points 2 and 5 are by no means deal-breakers, but 1 in combination with 4 certainly is. I've managed to find work-arounds for most of these issues, which I've posted below. If someone has identified similar issues or has better workarounds, I'm all ears!


Convergence and value of a complex power series

I've done a little math and I got the following power series expansion of $\log z$ about $z_0=-2+i$. $$\log z=\log(-2+i)+\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n(-2+i)^n}[z-(-2+i)]^n$$ I've shown that the series converges on $|z-(-2+i)|<\sqrt5$ but I think it only agrees with $\log z$ on $|z-(-2+i)|<1$. I have:               f = Function[z, Log[-2 + I] +            Sum[(-1)^(n + 1)*(z - (-2 + I))^n/(n*(-2 + I)^n), {n, 1, Infinity}]]      The evaluation               f[-2 + I/2]      produces > log(-2 + I) + log(9/10 + I/5) I'm wondering if there is an easy way to force this to a logarithm of a single number. I'm also wondering if someone has a suggestion on how to explore the convergence on the two regions defined above.


Errors importing UTF8 file to mathematica

I'm trying to import this file:               Import["https://dl.dropboxusercontent.com/u/35192406/jarlaxxe_tweets.\     csv", CharacterEncoding -> "UTF8"]      But I am getting errors like:               $CharacterEncoding::utf8: The byte sequence {240} could not be interpreted as a character in the UTF-8 character encoding. >>      Any idea why? And any solution?


Could a package be composed of references?

Could a package be composed of references (e.g. usage messages)? Do the code for an induvidual function implemented in a package has to be physically in that package file where it is referenced (i.e. externalized)? Or can the actual function code be referenced in one package and located somewhere in another notebook?


How do I use Map for a function with two arguments?

I'm a newbie who tries to be a good boy, and use `Map` instead of writing out a list of functions. I have a table I want to `Map` onto:               ratios = Table[10^(n/10), {n, 0, 10}]        and a function               rp[x_, r_] := 1000 x (r + 1)/(r + x)      which I want to `Plot` for the 11 ratios, for `x in [0, 1]`:               Plot[Map[rp, ratios], {x, 0, 1}]      This doesn't work, and I can guess why: `rp` requires two arguments, and MMA probably doesn't know which one is the ratio. And `x` also doesn't appear as a parameter. How do I fix this?


Map w/ multiple arguments

> **Possible Duplicate:**   >  How do I use Map for a function with two arguments? If I have a function:               F[x_,y_,z_]:=x*y*z      and I want to call it with several different x values using `Map` (and y and z fixed), is there a way to do that with a one-liner? That is, for these x values               xVals = {1,2,3,4}      I want to somehow get:               {F[1,10,100], F[2,10,100], F[3,10,100],F[4,10,100]}      If I can do it with Map, it would be great, because I have many cores and want to speed this up with the parallelized Map.


Using Map with functions that take a parameter

I have a list               l={{0, 0, 0, 3}, {0, 0, 0, 3}, {0, 0, 1, 2}}      And I would like to obtain the number of zeros in each sublist:               NZ=Table[Count[l[[i]], 0], {i, Length[l]}]      which will return the list: `{3,3,2}` . Is there a way to use `Map` to accomplish this more cleanly? What I would like to do is write something like: `Map[Count, l]` which will of course fail because `Count` needs a pattern to count.


How to explain the behavior of Rule inside these functions

I'm trying to define a function that takes an expression and spits out a pure function involving a replacement rule of that function's variable. An example would be a function `f` such that `f[x^2]` returns `x^2 /. x -> # &` (let's just stick with single-variable function for simplicity's sake). I have written 2 functions, both aim to do just that. Now, their pure function outputs do work when applied to something else (see last input of block code), but they themselves don't display in the form that I'd like:               (* 1 *)         Clear[f1]     f1[expr_] := Module[{var},       var = First@Variables[expr];       expr /. var -> # &]          f1[x^2]     (* x^2 /. var$77097 -> #1 & *)               (* 2 *)     Clear[f2]     f2[expr_] := expr /. First@Variables[expr] -> # &          f2[x^2]     (* x^2 /. First[Variables[x^2]] -> #1 & *)               {f1[x^2][3], f2[x^2][3]}     (* {9, 9} *)      It seems like `Rule` holds the evaluation of the left hand side, which I don't really know why. Adding `Evaluate` to the left hand side did not help. I tried reading the documentation for `Rule` but couldn't find any relevant information on this behavior. One of its attributes is `SequenceHold`. Could that be a contribution? Also, if anyone could help me understand the result I got for each of those modules I'd really appreciate it. I'm very fuzzy on evaluation order inside `Rule` and `Module`. Lastly, how can I build such a function mentioned in the beginning of my question?


Complicated output from simple Eigenvalues problem

I have code that uses Eigenvalues on matrices of various sizes. But the output of what should be a very simple problem, namely finding the eigenvalue of a 1x1 matrix, is overly complicated.               Eigenvalues[{{1-(0.2494562342391921 Exp[-2(-0.2+x)^2]+0.769722872465748 Exp[-2x^2])/(1-x^2)}}]      returns               (3.28871*10^-17 E^(-2 (-0.2+x)^2-2 x^2) (2.3405*10^16 E^(2 (-0.2+x)^2)+7.58524*10^15 E^(2 x^2)-3.04071*10^16 E^(2 (-0.2+x)^2+2 x^2)+3.04071*10^16 E^(2 (-0.2+x)^2+2 x^2) x^2))/(-1.+x^2)      Where did those 10^-17 and 10^16 terms come from? Why can't it just give me               1-(0.2494562342391921 Exp[-2(-0.2+x)^2]+0.769722872465748 Exp[-2x^2])/(1-x^2)      ?


Trying to generate a list of data to plot a graph with error bars. Need help creating the looping function

This is the sets of data I want to put into a form which will allow me to plot error bars from the min and max data.               avg = {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,0.621}, {60, 0.453}}     min = {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}}     max = {{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}}      This following code worked with n=1, creating one point on the graph. How do I make it loop to n=Length[avg] to plot all the points?               errmin = min[[n]] - avg[[n, 2]]     errmax = max[[n]] - avg[[n, 2]]     err = Flatten[{errmin, errmax}]     data = {{avg[[n]], ErrorBar[err]}}          ylabel = "Voltage (V \[PlusMinus] 0.05)"     xlabel = "Blade Angle (\[Degree] \[PlusMinus] 3)"     title = "Preliminary - Altering Blade Angle"     Needs["ErrorBarPlots`"]     ErrorListPlot[data, Joined -> True, InterpolationOrder -> 2,       Mesh -> Full, PlotMarkers -> Automatic,       AxesLabel -> {xlabel, ylabel}, GridLines -> Automatic,       GridLinesStyle -> Dotted, PlotLabel -> Style[title, Bold],       LabelStyle -> (FontFamily -> "Helvetica")]      I should point out I'm new to Mathematica today so please don't be too technical.


How can a function with an embedded function be compiled?

Compile fun continues today, and I'm trying to get the function below to compile. First the function:               NewC[ymax_, xmax_] := Block[{x1, a2, a0, b0, a1, b1, c1, b2, c2, a3, b3, c3, C0, xb = 0, xe = 100, ve},       a3 = (xmax + ymax - 100)/(2*(xe - xmax)*(xe - xmax));       x1 = (200 - xmax - 2*ymax + 2*a3*xe*(xe - xmax))/(2*a3*(xe - xmax) + 1);       a2 = -(2*a3*(xe - x1) + 1)/(2*(x1 - xmax));       b2 = -2*a2*xmax;       b3 = -1 - 2*a3*xe;       a0 = -(xb + ymax)/((xmax - xb)*(xmax - xb));       b0 = -2*a0*xmax;       C0 = ymax + a0*xmax*xmax;       a1 = (100 - xe - ymax)/((xe - xmax)*(xe - xmax));       b1 = -2*a1*xmax;       c1 = ymax + a1*xmax*xmax;       c2 = ymax + a2*xmax*xmax;       c3 = a3*xe*xe + 100;       ve2[ym_, tnlr_] := If[ym <= ((100 - xmax) + (100 - xe))/2,       If[tnlr <= xmax, a0*tnlr*tnlr + b0*tnlr + xb, a1*tnlr*tnlr + b1*tnlr + c1],       If[tnlr <= x1, a2*tnlr*tnlr + b2*tnlr + c2, a3*tnlr*tnlr + b3*tnlr + c3]];       ve = Chop[Map[ve2[ymax, #[[1]]] &, $range] // N]      ]      So pretty straight forward, except for the embedded function. So I externalize the important parts and global variable, but have no idea how to handle the embedded function. Here's what I tried:               NewC = With[{$range = $range, xb = 0, xe = 100},        Compile[{{ymax, _Real, 1}, {xmax, _Real, 1}},         Block[{x1, a2, a0, b0, a1, b1, c1, b2, c2, a3, b3, c3, C0, ve,ve2},        a3 = (xmax + ymax - 100)/(2*(xe - xmax)*(xe - xmax));         x1 = (200 - xmax - 2*ymax +           2*a3*xe*(xe - xmax))/(2*a3*(xe - xmax) + 1);        a2 = -(2*a3*(xe - x1) + 1)/(2*(x1 - xmax));        b2 = -2*a2*xmax;        b3 = -1 - 2*a3*xe;        a0 = -(xb + ymax)/((xmax - xb)*(xmax - xb));        b0 = -2*a0*xmax;        C0 = ymax + a0*xmax*xmax;        a1 = (100 - xe - ymax)/((xe - xmax)*(xe - xmax));        b1 = -2*a1*xmax;        c1 = ymax + a1*xmax*xmax;        c2 = ymax + a2*xmax*xmax;        c3 = a3*xe*xe + 100;        ve2[ym_, tnlr_] := If[ym <= ((100 - xmax) + (100 - xe))/2,          If[tnlr <= xmax, a0*tnlr*tnlr + b0*tnlr + xb, a1*tnlr*tnlr + b1*tnlr + c1],          If[tnlr <= x1, a2*tnlr*tnlr + b2*tnlr + c2,a3*tnlr*tnlr + b3*tnlr + c3]];        ve = Chop[Map[ve2[ymax, #[[1]]] &, $range] // N]        ],       CompilationTarget -> "C"]];      Certainly not the winning ticket. So are there principles to follow when this type of function must be modified? Thanks!


Detection of horizontal lines in an image

Ok I'm trying to detect horizontal lines in an image. But the problem is that the line is quite obscure. So I'm not sure if it is even possible to extract that. I tried many different filters, but nothing seems promising. The image is shown below: ![enter image description here](http://i.stack.imgur.com/ZObmf.jpg) And the horizontal lines of interest are shown in the second picture: ![enter image description here](http://i.stack.imgur.com/GrDFA.jpg)


Importing strings in Mathematica

This is my first post so apologies if any obvious mistakes. I'm trying to work on a data containing names (in quotes) in _Mathematica_. The data is already saved on my system under `names.txt`. I would like to be able to sort these names in alphabetical order but I can't seem to do anything with it in _Mathematica_. None of the commands seem to be working and the file itself is not recognized as a string. I'm sure I'm making an obvious mistake in my code but would greatly appreciate any help. Here's my code below: Original file (reduced version-original file has more than 1000 names): "MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL","RUTH","SHARON"               data1 = {Import["/Users/Joeblogs/Documents/mathematica/names.txt","string"]}      the output looks like:               {"JOHN", "DAVID", "VIVIAN", "ROBERT"}      How do I sort these in alphabetical order? Thanks for your help.


SpeechNavigation option. What is it for?

Could somebody please explain what is the use for `SpeechNavigation` option found in the option inspector?


Use single ListPlot for multiple sets of data (on separate graphs)

This is the code I have working for a single set of data. Is there a way I can structure this to have multiple sets of data?               title = "Preliminary - Altering Blade Angle";     ylabel = "Voltage (V ± 0.05)";     xlabel = "Blade Angle (° ± 3)";     avg = {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,          0.621}, {60, 0.453}};     min = {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}};     max = {{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}};          data = MapThread[{#1,           ErrorBar[{#2[[1]] - #1[[2]], #3[[1]] - #1[[2]]}]} &, {avg, min,          max}];          Needs["ErrorBarPlots`"];     ErrorListPlot[data, Joined -> True, InterpolationOrder -> 2,       Mesh -> Full, PlotMarkers -> Automatic,       AxesLabel -> {xlabel, ylabel}, GridLines -> Automatic,       GridLinesStyle -> Dotted, PlotLabel -> Style[title, Bold],       LabelStyle -> (FontFamily -> "Helvetica"), PlotRange -> All,       ImageSize -> 600]      Maybe I could do something like this:               Needs["ErrorBarPlots`"];     title = {{"Preliminary - Altering Blade Angle"}, {"experiment 2"}};     ylabel = {{"Voltage (V ± 0.05)"}, {"ylabel 2"}};     xlabel = {{"Blade Angle (° ± 3)"}, {"xlabel 2"}};     avg = {        {{10, 0.662}, {20, 0.96}, {30, 0.916}, {40, 0.787}, {50,           0.621}, {60, 0.453}},             {{5, 0}, {10, 0.564`}, {15, 0.795`}, {20, 0.903`}, {25,           0.933`}, {30, 0.908`}, {35, 0.844}}        };     min = {        {{0.55`}, {0.91`}, {0.85`}, {0.72`}, {0.58`}, {0.42`}},        {{0}, {0.52`}, {0.74`}, {0.78`}, {0.8`}, {0.84`}, {0.78}}        };     max = {{{0.76`}, {1.02`}, {0.99`}, {0.85`}, {0.68`}, {0.51`}},        {{0}, {0.6`}, {0.84`}, {0.98`}, {1.06`}, {0.97`}, {0.92}}        };      for the first part? I'm not sure how to structure the second part.


Embed Code Into Image

I often export images(plots, matrix, arrays, etc..) from mathematica which I end up putting in word documents or uploading to the web. The problem is that I often lose the original code and I am left only with the image representing the original output. I was thinking/considering of using one of the libraries discusses here http://stackoverflow.com/questions/3335220/embed-text-into-png but was wondering what the Mathematica community new of any functionality built into Mathematica allowing to embed text(the code) into the image. ### Compatibility Table For Answers **Edit:** For documentation purposes this is the code I personally use. It varies slightly from the other answers because it embeds that data into the images pixels.


Paste letter grades B+ , C-, A, B into notebook and not get B+C-AB

I have worked for two days to find a way through this problem. I am porting my student grade records into _Mathematica_ from spreadsheets, or sometimes from my college web sites, or sometimes from my word processor. I have many different source formats as you see, but I find I can always get the data into the format where it will paste into a word processor in one or the other format sketched in my subject line above. I can deal with the _Mathematica_ end of the project once the grades are in the form `List["B+", "C-", "A", "B"]` \-- from there convert them into gpa's, points, sums, averages, whatever -- but I have not been able to operate on the data Pasted into _Mathematica_ because the pluses and minuses are interpreted as parts of incomplete expressions, which blocks execution of string functions. To get the data in, I need to use use the Windows Copy command, then Paste into _Mathematica_. The source can easily be one of the two character formats shown just below. (Or see my subject line.) But unfortunately the grades often have pluses and minuses, especially B+ or C+. But if I paste the following example straight into List in an Input cell, it is interpreted as an incomplete expression:               List[D+, F , C-, F, A-, B, A, A- ,D-, B-, C-, B, D-, D, B, D, A+, B, D, B+, F, C-, F, C+, D-, D+, B]      The same thing happens if I paste the same information in this way:               List[D + F C - F A - B A A - D - B - C - B D - D B D A + B D B + F C - F C + D - D + B]      So I need a "container" to paste into, which will eliminate white spaces, attach any pluses or minuses to the preceding character, and interpret each letter grade as a string as here: `List["B+", "C-", "A", "B"]` (By the way the only letters which appear are ABCDFWI, if that permits simplification, and the only non-letters are + and -). I feel kinda dumb asking about this, but Strings in _Mathematica_ are so crazy I'm just not there yet.


Explicit asterisk or @ sign in string patterns

What string pattern will match an explicit asterisk (*) or at-sign (@)? The obvious example, `StringMatchQ["*", "\*"]`, returns `False`. I can't find any mention of escaping them in string patterns, only in `RegularExpressions`, and that was in the advanced tutorial.


Importing and manipulating data in HDF format

I have two matrices A1 and A2 in HDF format. I use the following code to import them.               A1 = Import[       "http://www.math.mtu.edu/~struther/Courses/4610/Data/A1.hdf", "Data"];`      When I type `Dimensions[A1]` I get the output > >     {1, 12, 10} >   Now, I want to do the Singular Value Decomposition on `A1` and reconstruct it from the output matrices. I can do the SVD, but when I check the original and reconstructed matrix by inputting `A1 - U.W.Transpose[V]`, I get a shape not matching error. Also, when I see `A1` in `MatrixForm`, I see a matrix with each column as a separate vector(column matrix) inside the big matrix.               {U, W, V} = SingularValueDecomposition[A1];     Norm[A11 - U.W.Transpose[V], 2]               Here's a screenshot of A1 in MatrixForm      ![enter image description here](http://i.stack.imgur.com/tdgs1.png) I can't figure out why there are separate columns inside the matrix. Also there are 10 rows and 12 columns, but `Dimensions[A1]` outputs > >     {1, 12, 10} >   Any help would be greatly appreciated.


Categorical Distribution

Suppose I want to do calculations with a random variable $X$ that has a simple categorical distribution (a.k.a generalised Bernoulli distribution or discrete distribution). I was expecting to be able to work with a distribution "symbolically". That is, I was expecting that there would be a function like `CategoricalDistribution`, that we could use like this.               distX = CategoricalDistribution[{1/3, 1/2, 1/6}];      But no distributions in tutorial/DiscreteDistributions looked like they were suitable. An example of how the distribution would be used would be               {Probability[x == 0, x \[Distributed] dist],      Probability[x == 1, x \[Distributed] dist],      Probability[x == 2, x \[Distributed] dist]}      would output > >     {1/3, 1/2, 1/6} >   In this particular case, we can do a workaround, by doing               dist = TransformedDistribution[       x1 + x2, {x1 \[Distributed] BernoulliDistribution[1/2],         x2 \[Distributed] BernoulliDistribution[1/3]}]      Unfortunately, this is not always possible, even with only 3 possible outcomes. For example, we cannot simulate `CategoricalDistribution[{1/2, 0, 1/2}]` like this, as we cannot have independent Bernoulli random variables that behave like this. I was hoping the categorical distribution might be a special case of another distribution. Especially the `MultinomialDistribution` with 1 as its first argument looks useful, but I cannot transform that distribution into a distribution that gives an integer. Again it seems like I am missing a function like `CategoricalDistribution` to do so. To give an example               Position[RandomVariate@MultinomialDistribution[1, {1/2, 0, 1/2}],        1][[1, 1]]      "has the right distribution", but unfortunately I cannot use `Position` inside `TransformedDistribution`. I am aware of functions like `RandomChoice`, but really I only want to do manipulations on distributions. Does anybody know how to do this?


How do I expand StirlingS2[n, 10] in terms of elementary functions?

I know that it is possible to expand `StirlingS2[n, 10]` in terms of elementary functions of `n`. I tried `FunctionExpand` but it returned unevaluated:               In[1]:= FunctionExpand[StirlingS2[n, 10]]     Out[1]= StirlingS2[n, 10]      Is there a way to do this in _Mathematica_?


Is the TCPIP link type compressed?

Since I'm already piping a _MathLink_ connection in a ssh tunnel (connect back is a pain!), I wonder if it makes sense to compress the data in the stream (`ssh -C`). As with any optimization matter, one should measure, but unfortunately it seems there's no way to get statistics out of `ssh` on the connection so I cannot just test and measure the gain or loss. My question is then, is it known whether this _MathLink_ type is already compressed?


Plotting a list in real time

I would like to use Mathematica for a presentation and have a list plotted in front of my audience, one coordinate at a time. How would I go about plotting a list progressively in real-time, ie the coordinates {1,y1} first, then one second after the coordinates {2,y2}, etc... ? Something with Manipulate so that I could switch on and off this option would be nice, but I don't see any function in the documentation that would let me plot lists in real time.


Standard message definition construct

Why are the messages almost always defined like this (at least in packages):               If[Not@ValueQ[function::usage], function::usage = "Usage message"]      and not just like this?               function::usage = "Usage message";      Is this some sort of safety measure in case of double loading of the package?   I also notice that error messages, coming after usage messages, are usually defined the second way.   I cannot imagine a reason why I would do that.   Are there situations when someone would like to import a package, redefine some usage messages and be sure they are not reset in case of reloading of the package?


Font size in PlotLegends, using Table to generate the list in the legend

I am currently trying to get to graph with several functions as below. My problem is that I cannot change the font size in the legend (authomatically generated numbers by "Table" function). This code below is the best what I can get. Does anyone know how to insure that also automatically generated numbers have font size of 16 (or any). ## Thanks!               <<PlotLegends`     Plot[       Evaluate[(g (-1+q)^2 (a+b+g (1-q ) s)^2)/((a+b+g-g p q)^3)                   /.{q->4/5,p->1/4,a->0.1,g->500,s->Range[0.1,3,0.4]}       ],       {b,0,100},       AxesLabel->{b,F},       PlotLabel->Style["q = 4/5, p = 1/4",FontSize->14],       PlotStyle->Directive[Thick],       PlotLegend->Table[Row[{Style["s = ",Bold,Italic,FontSize-> 16],i}],{i,0.1,3,0.4}],       LabelStyle->Directive[Italic,FontFamily->"Helvetica",FontSize->12],       LegendPosition->{0.5,-0.8}     ]


How to pass a list of arguments into HoldAll

I have a list of arguments (which in reality is lengthy):               arguments = {a, b, c}     arguments2 = {a_, b_, c_}     f[Sequence@@arguments2] := a + b + c      _Note_ : It seems awkward to define two lists here, there should be a better way to do this. And I want to numerically integrate a function of those arguments:               int[Sequence@@arguments2] := NIntegrate[f[Sequence@@arguments], {x, 0, 1}]      This does not work because of the `HoldAll` property of `NIntegrate`. Is there a way to do this correctly?


Reading RData files without RLink

I am using Mathematica 8. I would like to read some RData files which I have received. I do not currently have an installation of R on the machine with Mathematica.


Correct use of ListInterpolation

I have a small problem with `ListInterpolation`. I want to use `ListInterpolation` to postprocess result of a numerical simulation. Therefore, I give the function (2D) and its first and second derivatives to `ListInterpolation`. When I do so, it works with the method "Hermite". But if I switch to "Spline", I receive the warning, that the method "Spline" could not be used because "the data could not be coerced to machine real numbers".               A = ListInterpolation[data, {sigAxis, muAxis}, Method -> "Spline", InterpolationOrder -> 5];      > ListInterpolation::mspl: The Spline method could not be used because the > data could not be coerced to machine real numbers. I want to use "Spline" because I want to have accurate derivatives. I checked the _Mathematica_ manual and googled to learn what I have to do to ensure that the data can be coerced to machine real numbers. Unfortunately without any sucess at all. Could anyone give me some pointers?


Labeling individual curves in Mathematica

I need to create a plot for export and inclusion in a report. Is there a better way to label curves than `PlotLegends`? From what I've read and my personal experience, `PlotLegends` is pretty bad. Is there a better package for legends, or, ideally, a simply way to place small text next to each curve?


Legends in combined Plot and ListPlot

I have a set of data               plotgamma6 = {{0.1, 14/15}, {0.2, 17/20}, {0.3, 11/15}, {0.4,      43/60}, {0.5, 2/3}, {0.6, 13/20}, {0.7, 7/12}, {0.8, 17/30}, {0.9,      17/30}, {1., 31/60}, {1.1, 31/60}, {1.2, 7/15}, {1.3,      7/15}, {1.4, 9/20}, {1.5, 9/20}, {1.6, 9/20}, {1.7, 13/30}, {1.8,      5/12}, {1.9, 2/5}, {2., 2/5}, {2.1, 2/5}, {2.2, 23/60}, {2.3,      23/60}, {2.4, 11/30}, {2.5, 11/30}, {2.6, 11/30}, {2.7,      7/20}, {2.8, 1/3}, {2.9, 1/3}, {3., 1/3}, {3.1, 1/3}, {3.2,      1/3}, {3.3, 19/60}, {3.4, 19/60}, {3.5, 19/60}, {3.6, 3/10}, {3.7,      3/10}, {3.8, 4/15}, {3.9, 1/4}, {4., 7/30}, {4.1, 13/60}, {4.2,      13/60}, {4.3, 13/60}, {4.4, 13/60}, {4.5, 13/60}, {4.6,      13/60}, {4.7, 13/60}, {4.8, 13/60}, {4.9, 13/60}, {5., 13/60}};     plotgamma10 = {{0.1, 93/100}, {0.2, 89/100}, {0.3, 83/100}, {0.4,          81/100}, {0.5, 37/50}, {0.6, 18/25}, {0.7, 17/25}, {0.8,          16/25}, {0.9, 61/100}, {1., 59/100}, {1.1, 14/25}, {1.2,          14/25}, {1.3, 13/25}, {1.4, 13/25}, {1.5, 49/100}, {1.6,          23/50}, {1.7, 23/50}, {1.8, 9/20}, {1.9, 9/20}, {2.,          43/100}, {2.1, 43/100}, {2.2, 21/50}, {2.3, 41/100}, {2.4,          2/5}, {2.5, 19/50}, {2.6, 37/100}, {2.7, 9/25}, {2.8, 7/20}, {2.9,          17/50}, {3., 33/100}, {3.1, 29/100}, {3.2, 29/100}, {3.3,          29/100}, {3.4, 27/100}, {3.5, 13/50}, {3.6, 6/25}, {3.7,          6/25}, {3.8, 6/25}, {3.9, 6/25}, {4., 6/25}, {4.1, 21/100}, {4.2,          1/5}, {4.3, 1/5}, {4.4, 19/100}, {4.5, 9/50}, {4.6, 9/50}, {4.7,          4/25}, {4.8, 4/25}, {4.9, 4/25}, {5., 4/25}};      which I plot using ListPlot               Needs["PlotLegends`"]     a = ListPlot[{plotgamma6, plotgamma10}, AxesOrigin -> {0, 0},       PlotRange -> {{0, 5}, {0, 1}}, AxesLabel -> {"gamma", "quantity"},       PlotStyle -> PointSize[0.02], PlotLegend -> {"N=6", "N=10",},       LegendPosition -> {1.1, -0.4}, Joined -> {True, True},       PlotMarkers -> Automatic]      Now, I also want to plot a function which needs to be compared with the above data, i.e.,                   f[z_] := Exp[-z/2] BesselI[0, z/2];         b = Plot[-2 f'[z], {z, 0, 5}, PlotLegend -> "Theory",        LegendPosition -> {1.1, -0.4}]      Now, I want to combine these two plots into one, so I use               Show[a,b]      However, this gives a messed up plot! If I remove the plot legends from both the plots, then the combined plot looks reasonable though. But I really want to retain the plot legends. How would you combine these two plots? It doesn't matter to me how you plot these data, i.e., if you use `Show` or some other function. Please note that my question is closely related to How to show legend in a combined plot of many lists, However, that question wasn't answered fully either. Thanks! dbm368


Labels for each curve on a multi-curve plot using an efficient method(without writing a large code)

I have a question on plot labeling in _Mathematica_. I have               y = 4 x / L + 2      where               L = {10, 20, 30, 40}      I want to draw a graph of y vs. x. When I evaluate               Plot[y, {x, 0, 100},         ImageSize -> Scaled[1.0],        PlotLabel ->  Style["y vs X ", FontSize -> 18]]      I get four different lines in the same plot. I want to know how to label each line with its relevant L value; e.g., "l = 10" for the corresponding line. Could anyone please tell me how to do this?


How to add labels to a graph

This should be an easy question but since few examples are given for `ShowLegend` and I am a new user, I got stuck after many attempts. I plot three graphs which are seperately defined as `t1`, `t2`, `t3`. In each graphs there are one or two curves (Original codes to yield the graphs are complicated and not important). Then I present them in one graph, coding               graph1 = Show[t1, t2, t3, PlotRange->All]      Now I would like to add texts for identification for each curve in the graph1, in a form like                 --- x=2       ___ x=3       ''' x=4      Since the graph1 has already been plotted, `PlotLegend` may not work. I used `ShowLegend` but don't know how to establish the codes. Many thanks in advance.


Handling ± in a set of equations

First let me post the question that I am doing: ![enter image description here](http://i.stack.imgur.com/aaayQ.png) You see for wave equation y2, there is a `±` sign. I know how to do `+` or `-` at one time. Of course, I can use copy, paste and do each case separately; yet, I don't think that would be smart. I am wondering is there a way to include the both `Animation` in two graphs? (Simple and efficient code) The way I approach this problem is that first I define A1 as a constant, whose value is 1. Then I can vary the ratio of A2 versus A1. I would like apply `Animate` to variable `A2` and `δk`, because in the problem we are asked to `Animate` different amplitude ratio and phase difference. Here is my code for the `+` case:               Remove["Global`*"]          k2 = k1 + δk;          y1[x_, t_] = A1 Sin[k1 (x - v t)];     y2[x_, t_, A2_, δk_] = A2 Sin[k2 (x + v t)];          yr[x_, t_, A2_, δk_] = y1[x, t] + y2[x, t, A2, δk];          k1 = 2 π;     A1 = 1;     v = 1;          xmax = 10;     tmax = 30;     range = {{0, xmax}, {-4, 9}};          pix1[t_] := Plot[y1[x, t] + 4, {x, 0, xmax}, PlotStyle -> Red]          pix2[t_, A2_, δk_] := Plot[y2[x, t, A2, δk] + 4, {x, 0, xmax}, PlotStyle -> Blue]          pixr[t_, A2_, δk_] := Plot[yr[x, t, A2, δk], {x, 0, xmax}, PlotStyle ->Black]          plot[t_, A2_, δk_] :=        Show[{pix1[t], pix2[t, A2, δk], pixr[t, A2,δk]}, PlotRange -> range, AxesLabel -> {x, y}]          Animate[plot[t, A2, δk], {t, 0, tmax}, {A2, 1, 4, 1}, {δk, π/8, π, π/8}]


Series expansion using an exponential basis

I am currently trying to Laplace invert an expression with the following pattern $$ \frac{s \alpha \text{Cosh}[s(L-x)]+\beta \text{Sinh}[s(L-x)]}{s(\gamma \text{Cosh}[sL]+s \delta \text{Sinh}[sL])} $$ where $s$ is the complex variable and $x\in[0,L]$ a real variable; all other parameters are real constants. One path I foresee in achieving the inversion is by expressing the denominator in the form of a power series of exponential terms, as these correspond to shifts in the time domain. For instance, this approach can successfully be applied to $$ \frac{1}{s(1+\mathrm{e}^{-s})}=\frac{1}{s}\sum_{n=0}^{\infty}(-1)^n\mathrm{e}^{-ns} $$ which upon inversion yields a train of Heaviside functions $$ \mathcal{L}^{-1}\left(\frac{1}{s(1+\mathrm{e}^{-s})}\right)=\sum_{n=0}^{\infty}(-1)^n H(t-n) $$ Therefore, my question is, using Mathematica, how can I transform $(\gamma \text{Cosh}[sL]+s\delta\text{Sinh}[sL])^{-1}$ into a series of exponential functions; that is, $$ \frac{1}{\gamma \text{Cosh}[sL]+s\delta\text{Sinh}[sL]} = \sum_{n=0}^\infty a_n(s) \mathrm{e}^{-n sL} $$ Any help will be appreciated.


How can I add a column into a existing Dataset?

I'm very excited about the brand new `Dataset` function. I have played with it in Wolfram Cloud, and haven't figured out how can I add a new column into an existing `Dataset`. Here is an example:               data={<|"col1"->1,"col2"->2|>,<|"col1"->3,"col2"->4|>,<|"col1"->5,"col2"->6|>};     ds=Dataset[data]      Now I can play with `ds` columns. For example, I can easily make calculations between columns using their names like:               ds[All, (#col1+#col2&)]      > {3, 7, 11} Another way is:               ds[All, <|"col3"-> (#col1+#col2&)|>]      > <|col3->3,col3->7,col3->11|> Now, how can I update `ds`, to append the brand new calculated column as "col3"? I tried:               Join[ds,ds[All, <|"col3"-> (#col1+#col2&)|>],2]      without success. It would be magic if I could just do something like:               ds[All, "col3"]=ds[All, (#col1+#col2&)]      But it does not work either.


Find intersection points with V10

My question departs from this one: Find intersection of pairs of straight lines but now I want to find the points with the new V10 `Region`-functions.               lines =      {{Line[{{243.8`, 77.`}, {467.4`, 12.`}}], Line[{{356.8`, 32.`}, {363.2`, 120.`}}]},       {Line[{{291.8`, 130.`}, {476.`, 210.5`}}], Line[{{346.`, 245.`}, {393.8`, 158.`}}]},       {Line[{{103.2`, 327.`}, {245.2`, 110.5`}}], Line[{{163.8`, 211.5`}, {230.2`, 250.`}}]},       {Line[{{47.4`, 343.`}, {87.4`, 108.5`}}], Line[{{54.6`, 225.`}, {139.6`, 220.`}}]},       {Line[{{371.`, 506.5`}, {384.6`, 277.`}}], Line[{{366.`, 394.5`}, {451.8`, 372.`}}]},       {Line[{{264.6`, 525.5`}, {353.8`, 294.5`}}], Line[{{241.`, 398.`}, {321.`, 411.5`}}]},       {Line[{{113.2`, 484.5`}, {296.`, 304.5`}}], Line[{{163.2`, 347.`}, {213.2`, 406.5`}}]},       {Line[{{459.6`, 604.5`}, {320.2`, 466.5`}}], Line[{{332.4`, 596.5`}, {402.4`, 528.5`}}]},       {Line[{{288.2`, 630.5`}, {199.6`, 446.5`}}], Line[{{176.`, 585.5`}, {256.`, 530.5`}}]},       {Line[{{138.8`, 615.5`}, {81.8`, 410.`}}], Line[{{38.2`, 553.`}, {122.4`, 507.`}}]},       {Line[{{232.4`, 795.`}, {461.8`, 727.`}}], Line[{{345.2`, 774.5`}, {345.2`, 688.`}}]},       {Line[{{27.4`, 671.5`}, {206.8`, 763.5`}}], Line[{{104.6`, 728.`}, {161.8`, 647.`}}]}};      This function finds the points but is horribly slow:               (points = Point /@ RegionCentroid /@ DiscretizeRegion /@ RegionUnion @@@ lines); //        Timing // First      > 1.591210               Graphics[{lines, {Red, PointSize@0.02, points}}, Frame -> True]      ![enter image description here](http://i.stack.imgur.com/b7Vei.jpg) The next function finds the same points in less time (0.28 seconds), but is ugly and probably not general enough.               points = Cases[Show[DiscretizeRegion /@ RegionIntersection @@@ lines],        {a_Real, b_Real} :> Point[{a, b}], Infinity];      I hope somebody can suggest a fast and terse V10-method to find intersection points in 2 dimensions


Solving the magic backyard puzzle with MMA

I was trying to solve this puzzle using mma ![Mathematica graphics](http://i.stack.imgur.com/4Lidi.png) It looks like the generalization of the magic square. Anyway here my attempt:- There are four columns $(x,y,z,w)$ and nine rowa which are denoted by the array index. First i define the variables which have zero values               x[1] = 0; x[2] = 0; x[3] = 0; x[9] = 0; w[1] = 0;      Then the equation equating all the columns               c[1] = Sum[x[i], {i, 4, 8}];     c[2] = Sum[y[i], {i, 1, 9}];     c[3] = Sum[z[i], {i, 1, 9}];     c[4] = Sum[w[i], {i, 2, 9}];          col = Equal @@ Thread[Array[c, 4]]      Next for the rows               r[n_] := x[n] + y[n] + z[n] + w[n];     row = Equal @@ Thread[Array[r, 9]]      Here we can give some upper bound for the solutions.               all = Join[Array[x, 5, {4, 8}], Array[y, 9], Array[z, 9], Array[w, 9]];     And @@ Thread[0 <= all <= 100]      For distinct solutions:               allne = Unequal @@      Thread[Join[Array[x, 5, {4, 8}], Array[y, 9], Array[z, 9],      Array[w, 8, {2, 9}]]]      List of all variables               allvar = Join[     Join[Array[x, 5, {4, 8}], Array[y, 9], Array[z, 9],      Array[w, 8, {2, 9}]]]      Finally when I use FindInstance it just keeps running(its been 2hr now).               FindInstance[{col && row && And @@ Thread[0 <= all <= 100] &&       allne}, allvar, Integers]      So my question is why is FindInstance so slow even after putting bounds on integer solutions.Also can this be done by any other method. I also tried the simplest $3 \times 3$ magic square               FindInstance[     a + b + c == d + e + f == g + h + i == a + d + g == b + e + h ==      c + f + i && a != b != c != d != e != f != g != h != i, {a, b, c,      d, e, f, g, h, i}, Integers]      This also kept on running. Do you think that i just need to wait for the output because for these kind of sums mma will take that long?


How to syntax check that all instance of symbol must be contained in Subscript[]

I have a function `f[expr]` that is only allowed to take an expression `expr` that is a polynomial in `Subscript[x,_]`. By this, I mean that `expr` can be a sum/difference of terms (up to other multiplicative symbols) in $x_{\text{symb}}$, and symb can be any symbol (in Atomic form). The symbol $x$ cannot stand by itself, and it cannot appear inside other functions. Allowed form is: `expr = Subscript[x,i] Subscript[x,j] + b Subscript[x, k] Subscript[y, a] - 3 a Subscript[x,m]` (= $x_ix_j + b\, x_k y_a - 3\, a\, x_m$), But not   1. `expr = a Sqrt[Subscript[x,i]] + Subscript[x,j]` (Cannot be inside another function)   2. `expr = a Sqrt[Subscript[x,i]]` (same problem as 1.)   3. `expr = x + b Subscript[x,i]` (cannot be outside `Subscript`)   4. `expr = x` (same problem as 3.)   5. `expr = Subscript[x,i,j]` ($x$ cannot not have two indices)   6. `expr = $Subscript[y,x]$`. ($x$ cannot occur as an index) So, inside the body of `f`, I tried to do something like               Cases[expr, f_[x, y___] :> If[f =!= Subscript, Return[$Failed], "Pass"], Infinity]      But this misses the possibility that `x` is standing alone, outside of `Subscript`. Is there an economic way for checking if `expr` satisfies this property?


coding simple structures, potential problems (multithreading) and how to solve them

This post contains two parts. In the first part I will explain what I am trying to do. In the second part I will explain what I fear. My questions are about these fears. Are they justified and if yes how to deal with the problem? Part 1: I am developing a simple phraser package "structures`" to define structures (objects) that one can operate on. The package is to be used like this               Needs["structures`"];     beginStructure[];     defineField[f1,f2,f3];     defineMethod[        constructor[arg1_,arg2_]:=(THIS=newObject;THIS@f1=arg1;THIS@f2=THIS@f1+arg2)     ];     defineMethod[        instanceMethod[arg1_,arg2_]:=(THIS@f1=arg1;THIS@f2=arg2)     ];     ...     endStructure[];      I want to avoid this               Needs["structures`"];     beginStructure[];     ref = defineField[f1,f2,f3];     defineMethod[ref,        constructor[arg1_,arg2_]:=(THIS=newObject;THIS@f1=arg1;THIS@f2=THIS@f1+arg2)     ];     defineMethod[ref,        instanceMethod[arg1_,arg2_]:=(THIS@f1=arg1;THIS@f2=arg2)     ];     ...     endStructure[ref];      The coding of the data structure should be as automatic as possible, thus the information flow between the define... methods is done in the background. They leave traces of what they do. I want to avoid passing things explicitly around (like with the ref version). Essentially, what the functions defineMethod and defineFields do is that they operate on the body (the code) that is provided to them and they arrange things in the background. While doing that they leave traces of what they do so that all the methods (defineMethod, defineFields) can work in synergy (have to be called in the right order etc). Part 2: What worries me is multithreading (I know nothing about it, I have never used it). I would like to code all this in a safe way. I see a potential problem if the package is used in a parallel fashion, i.e. two instances of the package are run at the same time. Then it might happen that the following is effectively being executed               ...     beginStructure[];     ...     beginStructyure[];     ...     defineMethod[...];     endStructure[];      which is a disaster, since the defineMethod does not know which environment it should operate within, or depends on. (beginStructure should prepare the stage for other calls). The question: I would like to know: are my fears justified? Is it possible that such a situation occurs that the package is beingn run at the same time, in the same kernel? If not, why is it not possible? If yes, how to prevent it? I could have asked: How to make sure that a piece of code is never excecuted in parallel?, but that would be missleading. The environment is everything here.


How to assign Subscript[C, i] to a Sum?

What I want to show is:               Plot3D[       Sum[1000*Subscript[C, i]^2/(1000*Subscript[C, i] - 600)^r, {i, 1, k}],       {k, 1, 30}, {r, 0.1, 1.5}]      And, I want the list of `Subscript[C, i]` to be the elements of the subsets:               Select[Subsets[Range[30], {k}], Total[#] == 30 &]      For example, if `k = 2`, the results of               Select[Subsets[Range[30], {2}], Total[#] == 30 &]      is               {{1, 29}, {2, 28}, {3, 27}, {4, 26}, {5, 25}, {6, 24}, {7, 23}, {8,        22}, {9, 21}, {10, 20}, {11, 19}, {12, 18}, {13, 17}, {14, 16}}      Further, I want to assign `{1, 29}` to C1 and C2 of Sum firstly, and then assign `{2, 28}` to C1 and C2 of Sum secondly, etc. As a result, I will be able to get the graphic I want by `Plot3D`!


Find missing values in time series and fill them with Na

I have this list               list = {{1, 3}, {3, 7}};      representing a time series from t = 1 to t = 4. How would I go about filling the missing values so that my list looks like this in the end:               list = {{1, 3}, {2,Na}, {3, 7}, {4,Na}};      Of course, the length of my list and position of missing values might vary so I need a general function to do this, not just               Insert[list,{2,Na},2]


Why is Solve returning an empty list?

I evaluate               Solve[{-((2 (4 θ0 + θ1))/σ^2) - (2 (4 θ0 + θ2))/σ^2,             -((4 θ0 + θ1)/(2 σ^2)), -((4 θ0 + θ2)/(2 σ^2)),            -(2/σ) + (4 θ0 + θ1)^2/(2 σ^3)             + (4 θ0 + θ2)^2/(2 σ^3)} == {0, 0, 0, 0} && σ > 0,            { θ0, θ1, θ2, σ}]      and `Solve` returns `{}`. Why? Should it be able to solve the equation?


PDE Boundary Conditions

I am solving a PDE using Mathematica and I would like to know how to implement the condition that the two-variable function `y[t,s]` is zero whenever `t=s`. I tried the obvious:               u[t,t]==0      or               u[s,s]==0      but Mathematica gives me the following output:               The arguments should be ordered consistently      To be more specific, I am solving the following PDE:               NDSolve[{p3D[t, s]*D[y[t, s], t, t] - v3D[t, s]*(q^2)*y[t, s] -      r3D[t, s]*D[y[t, s], t] == 0, y[t, 0] == ysol[t], y[1, 1] == 0,      y[0, s] == 0}, y, {t, 0, 1.}, {s, 0, 1}]      Where p3D,v3D,r3D and ysol[t] are known functions. I need to include the condition I mentioned inside the NDSolve. Can I do that?


How to extract and assign output of Free-Form input to a variable?

Selecting a Free-Form input cell with the mouse I can query something like:               convert 1 atm to pascals      and get as a result               101\[ThinSpace]325\[ThickSpace]Pa (pascals)      I can take that number and manually enter it into a variable (I can't cut and paste it since the space turns the cut and pasted value into (101)(325)). Is there a way to just extract the numeric portion of the result and assign it to a variable?


Are there rules of thumb for knowing when RandomVariate is more efficient than RandomReal?

Please consider the following: From a fresh Mathematica kernel, `RandomVariate` is more efficient for `NormalDistribution` but `RandomReal` is for uniformly distributed noise.               RandomReal[NormalDistribution[0, 1], 100]; // Timing      > `{0.00535, Null}`               RandomVariate[NormalDistribution[0, 1], 100]; // Timing      > `{0.000069, Null}`               RandomReal[{0, 1}, 100]; // Timing      > `{0.00004, Null}`               RandomVariate[UniformDistribution[], 100]; // Timing      > `{0.005236, Null}` But if I re-evaluate, I get `Timing` results that are much more similar:               RandomReal[NormalDistribution[0, 1], 100]; // Timing      > `{0.000051, Null}`               RandomVariate[NormalDistribution[0, 1], 100]; // Timing      > `{0.000052, Null}`               RandomReal[{0, 1}, 100]; // Timing      > `{0.00003, Null}`               RandomVariate[UniformDistribution[], 100]; // Timing      > `{0.000058, Null}` Does caching the distribution definition really matter that much? Obviously `RandomVariate` has the advantage that it can generate data from mixed (not only fully continuous or fully discrete) distributions. So it is more general. But if one is generating random numbers from standard distributions like the normal or the Poisson, **is there any advantage – performance or otherwise – to using`RandomVariate` instead of `RandomReal` or `RandomInteger`?**


How to include Mathematica animation in a PowerPoint presentation?

**Note: Cross-posted atWolfram Community** I want to include a Mathematica animation in PowerPoint presentation. My code is:               poskus = Manipulate[       Graphics3D[        Dynamic@{{GrayLevel[.3], Line[space[[1 ;; t]]]}, {Blue,            PointSize[.015], Point[space[[t]]]},}, Axes -> True,         AxesStyle -> Directive[FontSize -> 20, FontFamily -> "Helvetica"],         AxesLabel -> {"x [nm]", "y [nm]", "z [nm]"},         BoxRatios -> {1, 1, 1}, ImageSize -> 700,         BoxStyle -> Directive[Dashed, Thick],         PlotRange -> {{-2620, 1600}, {-1700, 1450}, {-3500, 350}},         SphericalRegion -> True],        Row[{Control[{t, 1, Length[data], 1, Animator, ImageSize -> Small,            AnimationRunning -> False, AnimationRate -> 50,            AnimationRepetitions -> 1}], Spacer[10],          Dynamic["time = " <> ToString[data[[t, 1]]]]}], FrameMargins -> 0]      I want to place the animation into the PowerPoint slide so that the first frame is shown. Then I want to start it by mouse click. It should stop in the end position and wait for my next mouse click (for next slide). How can I achieve it? The best I could get was when exporting to swf. But the problem is that it runs immediately after I reach the slide. And it doesn't stop at the end, but it goes in reverse direction and then forward ... It is also very fast. And my computer becomes slow. The file size (test.swf) is 146 KB. Some things I would like to know:   * How to export without the sliders showing   * which format best to use   * how to influence the frame rate, length and direction of the animation   * how to most conveniently integrate the animation into PowerPoint **Edit** Sample of my data: first column is time multiplied by a factor, the others are coordinates.               data={{0.146, -160.582, 125.712, 20.1735}, {0.288, -192.582, 182.712,        58.1735}, {0.431, -207.582, 237.712, 201.174}, {0.576, -250.582,        134.712, 162.174}, {0.723, -234.582, 226.712,        292.174}, {0.877, -259.582, 236.712, 175.174}, {1.02, -303.582,        241.712, 61.1735}, {1.16, -362.582, 282.712,        17.1735}, {1.3, -448.582, 268.712, 114.174}, {1.45, -309.582,        188.712, 87.1735}, {1.58, -275.582, 193.712,        31.1735}, {1.73, -142.582, 182.712, -67.8265}, {1.88, -296.582,        257.712, -41.8265}, {2.02, -412.582,        307.712, -80.8265}, {2.16, -389.582,        366.712, -119.826}, {2.31, -337.582,        402.712, -273.826}, {2.46, -470.582,        499.712, -179.826}, {2.6, -432.582,        546.712, -208.826}, {2.76, -386.582,        539.712, -339.826}, {2.9, -467.582,        429.712, -377.826}, {3.05, -479.582,        462.712, -338.826}, {3.18, -514.582,        383.712, -239.826}, {3.32, -592.582,        279.712, -169.826}, {3.46, -574.582,        313.712, -134.826}, {3.61, -575.582,        262.712, -198.826}, {3.74, -542.582,        269.712, -241.826}, {3.89, -570.582,        201.712, -179.826}, {4.04, -637.582,        156.712, -128.826}, {4.19, -784.582, 155.712,        30.1735}, {4.33, -837.582, 212.712, 31.1735}, {4.48, -750.582,        144.712, -121.826}, {4.62, -858.582, 110.712,        58.1735}, {4.76, -880.582, 41.7125, -70.8265}, {4.89, -884.582,        117.712, -171.826}, {5.04, -874.582,        56.7125, -209.826}, {5.2, -924.582, -11.2875, -228.826}, {5.35, \     -896.582, -38.2875, -270.826}, {5.5, -869.582, -44.2875, -317.826}, \     {5.64, -915.582, -132.288, -221.826}, {5.8, -971.582, -51.2875, \     -349.826}, {5.94, -992.582, -95.2875, -377.826}, {6.08, -1060.58, \     -5.2875, -266.826}, {6.23, -1054.58,        3.7125, -431.826}, {6.38, -1099.58,        31.7125, -505.826}, {6.53, -1211.58,        85.7125, -477.826}, {6.68, -1203.58,        108.712, -508.826}, {6.83, -1001.58,        67.7125, -649.826}, {6.98, -1051.58, -1.2875, -675.826}}


What is the complete list of valid Front End Tokens? Preferably, by version number.


Solve in terms of specific variables

As part of my physics homework (which I do not need the answer for, as I did it by hand, and got the correct $$\frac{m_1 g-m_2 g \sin(\theta)}{-m_1-m_2}$$ as the answer) I would have liked to have solved the following system of equations as shown (i.e. put $a_1$ as `Subscript[a,1]` and not `a1` or something similar. The equations that I wanted to solve were:   1. `Subscript[m, 2] Subscript[a, 2 x] == T - Subscript[m, 2] g Sin[\[Theta]]`   2. `Subscript[m, 1] Subscript[a, 1 y] == T - Subscript[m, 1] g`   3. `Subscript[a, 2 x] == -Subscript[a, 1 y]` I tried the following, and was given `{}` as the answer (which is clearly false): `Solve[Subscript[m, 2] Subscript[a, 2 x] == T - Subscript[m, 2] g Sin[\[Theta]] && Subscript[m, 1] Subscript[a, 1 y] == T - Subscript[m, 1] g && Subscript[a, 2 x] == -Subscript[a, 1 y], Subscript[a, 1 y]]` It seems that there at least two problems with the equations that I am asking it to solve.   1. I do not think that it is treating $a_{1y}$ as a variable. When I typed a in the part of solve that asks for the variables that I am solving for, all terms that have `a` in them light up as blue, but when I enter the subscript, it loses that highlighting.   2. It would seem (at least to me) that a perfectly valid answer to `Solve` would be $-a_{2x}$ but that would be a useless answer, as I want the answer in terms of $m_1 , m_2 , g, \theta$ and not in terms of other "compound variables" **Note:** When I tried a "subscript-less" version (`Solve[m2 a2x == T - m2 g Sin[\[Theta]] && m1 a1y == T - m1 g && a2x == -a1y, a1y]` I still got `{}` as the answer. Using Mathematica 8. What is going on, and how can I enter the equations normally, and solve for them in terms of specific variables?


Third argument of Compile

In his last comment on this answer, halirutan shows an example in which the third argument of `Compile` does not have any effect. The example is as follows.               cfu = Compile[{}, Module[{y = {}}, AppendTo[y, 1]], {{y, _Integer, 1}}];     cfu[]      Outputs > >     {1.} >   rather than `{1}` Does anybody know an example where using the third optional argument of `Compile` does have an effect?


Plot graphs with direction and numbered in Mathematica

I would like to write a code in _Mathematica_ such that it shows the direction with numbers on points. I wrote this code which does not do this. I want just to complete this code with two options I told. Any Idea. thanks.               ListPolarPlot[{Table[{2^n, 1}, {n, 1, 6}]}, Joined -> True,PlotStyle -> {Blue, Red, Green, Yellow, Gray}, Mesh -> All, MeshStyle -> Red]      ![enter image description here](http://i.stack.imgur.com/OEtml.jpg)


Transform an expression into a graph that can be plotted with TreeGraph (not TreeForm)

I would like to plot an expression (like `TreeForm` does), but using the new `TreeGraph` functionality. `TreeGraph` takes as input a set of edges (of the form `a -> b`), so it seems that to solve the problem it is necessary to turn an expression into a set of edges. For example `Sin[Plus[a, b]]` would need to be transformed into: `{Sin -> Plus, Plus -> a, Plus -> b}`. How can this transformation be done for any _Mathematica_ expression? Thanks!


Detect a graphic primitive inside a Graphic

Please excuse me if that question is too basic but I couldn't find anything in the documentation or on here. If you consider the following `Graphic` I would like to know how to detect which primitive is being clicked,               Graphics[{Disk[#, 0.5]} & /@ {{0, 0}, {1, 0}}]      ![enter image description here](http://i.stack.imgur.com/06rIn.png) and for example change the color of the clicked `Disk`, change its radius or get the coordinates of its center or anything related to its geometry. I am aware that `EventHandler` is my friend but as the questions states, I have no clue how to detect which primitive is being clicked (except by using `Mouseposition` and compare it to the centers). I am also aware that my question is somehow poorly researched but I feel like I'm blocking on a basic notion.


Elegant way to do series expansion around x+$\epsilon$

Suppose I have a function $p(x+\epsilon,y-\epsilon,t)$, and I want to expand it around $(x,y)$ like $$ p(x+\epsilon,y-\epsilon,t)=p(x,y,t)+\dfrac{\partial p}{\partial x}\epsilon+\dfrac{\partial p}{\partial y}(-\epsilon)+\cdots $$ A naive way to do it is               Series[p[x+e,y-e,t],{x+e,x,1},{y-e,y,1}]      which will result in the following error message:               General::ivar: "e+x is not a valid variable."     ....      Right now I do the expansion in the following clumsy way:               Replace[     Normal@Series[p[x, y, t], {x, a, 1}, {y, b, 1}],      {x - a -> \[Epsilon], y - b -> -\[Epsilon]},      Infinity]      /. {a -> x, b -> y}      **Question** : Is there an elegant way to do it? In the end, I want to expand $p(x,y,t)$ in $$ -(x+z)p(x,y,t)+(x+\epsilon)p(x+\epsilon,y-\epsilon,t)+(1-x-y+\epsilon)p(x,y-\epsilon,t) $$ and keep only the $\epsilon$ terms.


How can I forecast time series data with cellular automata?

I have a time series data, for example               data = FinancialData["JK:ADRO", "July 16 2012"]      Can I use `CellularAutomaton` to forecast some period of data? How would I go about doing that?