title: Visualising Special Relativity

text: Mathematica newbie learning by doing (or not so far, in this case). **Problem** : Special Relativity - consider two inertial frames $A$ & $A'$ in relative motion. At a time $t0$ as measured in $S$, draw a sphere $S'$ of radius $b$ in the hyperplane of simultaneity of $A'$ (i.e. orthogonal to $t'$), i.e. a surface that is spherical seen in $A'$ and exists only for the "moment" $t'0$. $t'0$ is simultanous with $t0$ as seen from $A$. ( _I have the Lorentz transformation matrix ready; use`c=1` for simplicity_) **Objectives** : a) visualise $S$, the image of $S'$ as seen from $A$ as a function of time in $A$, ideally with some surface patterning (e.g. lat/long grid, colour gradients, etc.) on $S'$ that will be transformed along with $S'$ so that the appearance of the surface seen from $A$ is also meaningful (shows orientation, distortion, etc.) b) determine analytically $tmin$ and $tmax$, the times at which the $S$ appears and disappears according to $A$ (see Expectatons below) **Expectation** : I _think_ $S$ becomes an ellipsoid that grows and shrinks betweem $tmin$ and $tmax$: since simultaneous events in $A'$ are not simultaneous in $A$ they must be at different times and continuity of the sphere implies a continuous temporal interval. I am not sure which is harder: doing 4D geometry in one's head or trying to do it by programming [Mathematica] Polite request for explicit code, if possible: at this stage I don't think I can be relied on to read between the lines - and if you wouldn't mind explaining how it works then I would also learn two things at once. Thanks in advance PS: It is not difficult to plot a sphere (thanks to Kuba for an nice way of doing that), the problem is producing a description (functions?) that can be both plotted and transformed so as to preserve surface features and to get the analytical answer b) above. I have looked at many Mathematic demonstrations and code, and tried too many graphics functions to list here and explain why they didn't seem to work for me - it's a completely open question: how would _you_ do it? **Code for generating the Lorentz matrix.** NB you may notice special case handling for `v = 0` because _Mma_ objected to `0/0` (and for `v>=c` returning a `0 matrix` because I don't know how to throw an error)               LorentzF[v_] := Module[{l, i, j, dim, γ},        dim = Length[v] + 1;        If[NumericQ[Norm[v]] == True  && (Norm[v] == 0  || Norm[v] >= 1),         If[Norm[v] == 0,          l = Table[KroneckerDelta[i, j], {i, 1, dim}, {j, 1, dim}],          l = Table[0, {i, 1, dim}, {j, 1, dim}]],         If[dim < 2, l = {},          l = Table[0, {i, 1, dim}, {j, 1, dim}];          l[[1, 1]] = γ;          For[i = 2, i <= dim, i++,            l[[1, i]] = l[[i, 1]] = -γ v[[i - 1]]           ];          For[i = 2, i <= dim, i++,            For[j = 2, j <= dim, j++,             l[[i, j]] =              l[[j, i]] = (γ - 1) v[[i - 1]] v[[j - 1]]/ v.v +                KroneckerDelta[i, j]            ]           ];           ]         ];        γ = 1/Sqrt[1 - v.v];        l        ];      **Bona fides** Check that `-v` is the inverse               Simplify[LorentzF[{bx, by, bz}].LorentzF[-{bx, by, bz}]]  // MatrixForm      Pick out the spatial part [NB, this is physically wrong, but I'm showing willing] creating something that can be used by `GeometricTransformation`               LorentzFSpace[{vx_, vy_, vz_}] :=  LorentzF[{vx, vy, vz}][[2 ;; 4]][[All, 2 ;; 4]]      Plot a sphere using `RegionPLot`               RegionPlot3D[x^2 + y^2 + z^2 < 1, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}]      Another attempt               Graphics3D[      GeometricTransformation[Sphere[], LorentzFSpace[{0.56, 0.56, 0.56}]], Axes -> True,       AxesLabel -> {x, y, z}, FaceGrids -> {{-1, 0, 0}, {0, 1, 0}, {0, 0, -1}} ]      But I can't "markup" `Sphere[]` or do a _proper_ hyperplane intersection because only the presentation is being changed (and it's still the wrong transform) Think about doing it by points and lines based upon a lat/long grid (which won't work for reasons given above) latdivs = # divisions of latitude to use, etc. NB, when I first entered the function below I used "=" instead of ":=" by mistake, which lead to a "Iterator does not have appropriate bounds" error on the inner iterator. I don't understand why that mistake had that effect.               sphereGrid4D[latdivs_, longdivs_, originpt_, radius_]  :=  Table[{originpt[[1]], originpt[[2]] + radius*sin[i 2 Pi/longdivs], originpt[[3]] + radius*cos[i 2 Pi/ longdivs], originpt[[4]] - radius*sin[j Pi /latdivs]}, {j, 0, longdivs}, {i, 0, latdivs}]      Kuba's contribution (on the question they suggested I delete, which I did)               frame = Chop@First@ParametricPlot3D[{Sin[u] Sin[v], Cos[u] Sin[v], Cos[v]}, {u, 0, 2 Pi}, {v, -Pi, Pi}, Axes -> None, PlotStyle -> None, PlotPoints -> 10];          Graphics3D[{frame, GeometricTransformation[frame, {{{2, 0, 0}, {0, 2, 0}, {0, 0, 2}}, {5, 5, 0}}]}]      (and I still don't understand the Chop@First@ part) **Last comment for tonight (Spanish time)** Actually, I may have solved the $tmin$, $tmax$ problem, but I'd like to _see_ the pictures to confirm! Idea: consider the sphere as define by the dot product of the vector p (I think I swapped my frames around, but it doesn't really matter) transform the vector back to the other frame and solve (my copy/paste may be screwed up and it's late, but I hope you get the idea)               v = {vx, vy, vz}; (* assign velocity components *)     sphere[p_] := Sum[p[[i]]^2, {i, 1, Length[p]}]; (* define a sphere by magnitude of p*)     p0 = {t0, 0, 0, 0};      s = Simplify[sphere[LorentzF[-v].p0]];     solns = Solve[s == b, t0]; Simplify[solns]      Getting: (sorry, don't know how to do this nicely)               {{t0 -> -(Sqrt[b]/Sqrt[-((1 + vx^2 + vy^2 + vz^2)/(-1 + vx^2 + vy^2 + vz^2))])}, {t0 -> Sqrt[b]/Sqrt[-((1 + vx^2 + vy^2 + vz^2)/(-1 + vx^2 + vy^2 + vz^2))]}}      which seemed OK (too) late last night, but now doesn't. Hence my confusions It would have been nice if I could have found a way to create a substitution `V^2=vx^2+vy^2+vz^2` but `V^2` can't be a symbol (?)


title: Converting Mathematica Greek letters from Notebook to Unicode Form in SE

text: Related : > How to "Copy as Unicode" from a Notebook?               Plot[\[Alpha], {\[Alpha], 0, 8}]          cellExpression          (*     Cell[BoxData[RowBox[{Plot,[,RowBox[{\[Alpha],,,RowBox[{{,RowBox[{\[Alpha],,,0,,,8}],}}]}],     ]}]],Input,CellChangeTimes->{3.58068*10^9,{3.58068*10^9,3.58068*10^9}}]     *)          CellExpression2InputText[cellExpression_] := First[FrontEndExecute[     FrontEnd`ExportPacket[cellExpression, "InputText"]]]          CellExpression2InputText[cellExpression]          (*     Plot[\[Alpha], {\[Alpha], 0, 8}]     *)          CellExpression2InputText[cellExpression] // CopyToClipboard          Paste[]          Plot[\[Alpha], {\[Alpha], 0, 8}]      when copy the result above to SE, the [Alpha] was not shown in Unicode Form. And I failed in my usage involved with `CellExpression2InputText` Mr.Wizard's method, this is good to copy directly from input cell.               SetAttributes[copyUnicode, HoldFirst]     copyUnicode[expr_, form_: InputForm] :=     Run["clip <", Export["$Clipboard.temp", ToString[Unevaluated @ expr, form],     "Text", CharacterEncoding -> "Unicode"]];      ### case 1               CellExpression2InputText[cellExpression] // copyUnicode          Paste[]      PasteResult（not good）               CellExpression2InputText[cellExpression]      ### case 2               ToExpression[CellExpression2InputText[cellExpression], InputForm, HoldForm] // copyUnicode          Paste[]      still not good ## question * * * So question is clear: How to convert `CellExpression` to string/clipboard with greek letters in Unicode Form when copy to SE without laborious work by hand.               \[Alpha] ==> to α


title: Find all roots in the interval of nonlinear equation

text: I am struggling on how to find all the roots of `1+1/2^x+1/3^x==0` which lie in a given of real and imaginary interval. `Solve` does not work, and `FindRoot` only returns one root. Is there a better way to get as many roots as possible? Thank you so much for your help.


title: How to generate a picture like this?

text: How to generate a picture like this? I'd like the surface of the manifold to randomly distort. ![](http://25.media.tumblr.com/tumblr_mdq7e6M88N1qc0s10o1_r1_500.gif)


title: Factor out invariant code from Plot

text: Given a simple Gaussian kernel               UnscaledKernel[a_, b_, sigma_] :=       Exp[-(((a - b)/sigma).((a - b)/sigma))/2]      and un-normalized smoothing function               Smooth[valCountLst_, val_, sigma_] :=        Sum[valCountLst[[i]][[2]]*         UnscaledKernel[{valCountLst[[i]][[1]]}, {val}, sigma], {i, 1,          Length[valCountLst]}];      and a normalization constant so that the integral on the defined domain is 1:               ScalingFactor[valCountLst_, sigma_, lower_, upper_] :=       Integrate[       Smooth[valCountLst, everyVal, sigma], {everyVal, lower, upper}]      From this unsmoothed data (that is, 1000 items at value 0 and 10 items at value 1):               testList = {{0, 1000}, {1, 10}};      **I'm plotting smoothed (un-normalized) data takes 0.024 seconds:**               Plot[N[Log[Smooth[testList, x, 0.2]]], {x, 0, 1.0}] // Timing      (output is `{0.024, THEFIGURE}`). **When plotting the smoothed, normalized data, it takes much longer, 13.09 seconds:**               Plot[N[Log[         Smooth[testList, x, 0.2]/ScalingFactor[testList, 0.2]]], {x, 0,         1.0}] // Timing      **This seems strange since the scaling factor takes only 0.044 seconds to compute.** My conclusion is that Mathematica is computing the scaling factor _for every point, even though it does not depend on the point value x_. **Is there a way to help Mathematica compute this expression once and factor it out (or memoize it)?** Thanks a lot.


title: Get DownValues that do not involve patterns?

text: Say I have a function with a few definitions that also implements memoization:               f[x_] := f[x] = x^2     f[x_, y_] := f[x, y] = x^2 + y^2      I then apply the function to some data:               f /@ {1, 2, 3}     f @@@ {{1, 2}, {3, 4}}      Now the function will have a bunch of `DownValues` both for the stored results and for the pattern based definitions. Is there some easy way to retrieve only all the stored result, leaving out the pattern based definitions?


title: Will Mathematica install and run on Raspberry Pi computer?

text: My club is considering buying a Raspberry Pi computer for tinkering. Can Mathematica be installed on and ran from it?


title: How can I change the style of every newly opened notebook?

text: I'd like to make _Mathematica_ open a new notebook using the Natural Color template (under the Creative category) by default. Is that possible? If so, how?


title: What is wrong about Abs[x]-a? Is it a bug?

text: ![enter image description here](http://i.stack.imgur.com/LtKtT.png) Why is the `Out[74]` not `{1 - a, {x -> -1}}`?                Maximize[{Sqrt[x^2] - a, -1 <= x <= 1}, x]      > >     {1 - a, {x -> -1}} >


title: Best way to create symmetric matrices

text: From time to time I need to generate symmetric matrices with relatively expensive cost of element evaluation. Most frequently these are Gram matrices where elements are $L_2$ dot products. Here are two ways of efficient implementation which come to mind: memoization and direct procedural generation.               ClearAll[el, elmem];     el[i_, j_] := Integrate[ChebyshevT[i, x] ChebyshevT[j, x], {x, -1, 1}];     elmem[i_, j_] := elmem[j, i] = el[i, j];          n = 30;     ClearSystemCache[];     a1 = Table[el[i, j], {i, n}, {j, n}]; // Timing     ClearSystemCache[];     a2 = Table[elmem[i, j], {i, n}, {j, n}]; // Timing     ClearSystemCache[];     (a3 = ConstantArray[0, {n, n}];       Do[a3[[i, j]] = a3[[j, i]] = el[i, j], {i, n}, {j, i}];) // Timing     a1 == a2 == a3      * * *               {34.75, Null}          {18.235, Null}          {18.172, Null}          True      Here `a1` is a redundant version for comparison, `a2` is using memoization, `a3` is a procedural-style one which I don't really like but it beats the built-in function here. The results are quite good but I wonder **if there are more elegant ways of generating symmetric matrices?** * * * **SUMMARY (UPDATED)** Thanks to all participants for their contributions. Now it's time to benchmark. Here is the compilation of all proposed methods with minor modifications.               array[n_, f_] := Array[f, {n, n}];     arraymem[n_, f_] :=        Block[{mem}, mem[i_, j_] := mem[j, j] = f[i, j]; Array[mem, {n, n}]];     proc[n_, f_] := Block[{res},       res = ConstantArray[0, {n, n}];        Do[res[[i, j]] = res[[j, i]] = f[i, j], {i, n}, {j, i}];       res       ]          acl[size_, fn_] :=        Module[{rtmp}, rtmp = Table[fn[i, j], {i, 1, size}, {j, 1, i}];        MapThread[Join, {rtmp, Rest /@ Flatten[rtmp, {{2}, {1}}]}]];          RM1[n_, f_] :=        SparseArray[{{i_, j_} :> f[i, j] /; i >= j, {i_, j_} :> f[j, i]}, n];     RM2[n_, f_] :=        Table[{{i, j} -> #, {j, i} -> #} &@f[i, j], {i, n}, {j, i}] //          Flatten // SparseArray;          MrWizard1[n_, f_] :=        Join[#, Rest /@ #~Flatten~{2}, 2] &@Table[i~f~j, {i, n}, {j, i}];     MrWizard2[n_, f_] := Max@##~f~Min@## &~Array~{n, n};          MrWizard3[n_, f_] := Block[{f1, f2},       f1 = LowerTriangularize[#, -1] + Transpose@LowerTriangularize[#] &@          ConstantArray[Range@#, #] &;       f2 = {#, Reverse[(Length@# + 1) - #, {1, 2}]} &;       f @@ f2@f1@n       ]               whuber[n_Integer, f_] /; n >= 1 :=        Module[{data, m, indexes},         data = Flatten[Table[f[i, j], {i, n}, {j, i, n}], 1];        m = Binomial[n + 1, 2] + 1;        indexes =          Table[m + Abs[j - i] - Binomial[n + 2 - Min[i, j], 2], {i, n}, {j,            n}];        Part[data, #] & /@ indexes];          JM[n_Integer, f_, ori_Integer: 1] :=        Module[{tri = Table[f[i, j], {i, ori, n + ori - 1}, {j, ori, i}]},         Fold[ArrayFlatten[{{#1, Transpose[{Most[#2]}]}, {{Most[#2]},              Last[#2]}}] &, {First[tri]}, Rest[tri]]];          generators = {array, arraymem, proc, acl, RM1, RM2, MrWizard1,         MrWizard2, MrWizard3, whuber, JM};      The first three procedures are mine, all other are named after their authors. Let's start from cheap `f` and (relatively) large dimensions.               fun = Cos[#1 #2] &;     ns = Range[100, 500, 50]     data = Table[ClearSystemCache[]; Timing[gen[n, fun]] // First,        {n, ns}, {gen, generators}];      Here is a logarithmic diagram for this test:               << PlotLegends`          ListLogPlot[data // Transpose, PlotRange -> All, Joined -> True,       PlotMarkers -> {Automatic, Medium}, DataRange -> {Min@ns, Max@ns},       PlotLegend -> generators, LegendPosition -> {1, -0.5},       LegendSize -> {.5, 1}, ImageSize -> 600, Ticks -> {ns, Automatic},       Frame -> True, FrameLabel -> {"n", "time"}]      ![enter image description here](http://i.stack.imgur.com/n2W49.png) Now let's make `f` numeric:               fun = Cos[N@#1 #2] &;      The result is quite surprising: ![enter image description here](http://i.stack.imgur.com/rlhDC.png) As you may guess, the missed quantities are machine zeroes. The last experiment is old: it doesn't include fresh `MrWizard3` and RM's codes are with `//Normal`. It takes "expensive" `f` from above and tolerant `n`:               fun = Integrate[ChebyshevT[#1 , x] ChebyshevT[#2, x], {x, -1, 1}] &;     ns = Range[10, 30, 5]      The result is ![enter image description here](http://i.stack.imgur.com/UOJDZ.png) As we see, all methods which do not recompute the elements twice behave identically.


title: How to symbolically differentiate an infinite series without evaluating the series itself

text: I'm dealing with finite sums of infinite series. Each of the infinite series possesses a different starting index, i.e. each of the series begins at n = 0, n = 1, or n = 2. As a result, it's important to keep track of the indices for each of the series. In addition, Mathematica cannot evaluate the series, because it's too complicated and undesirable for what's to be accomplished. I've only written the series in this manner to allow for efficient symbolic manipulation. The problem is that Mathematica takes a long time "trying" to evaluate each of the series. I've tried Hold, HoldAll, Unevaluated, and HoldForm. HoldForm seems like the correct choice, but there's a problem. Although I don't want to evaluate the series themselves, I'd still like to be able to perform operations on the series, such as differentiation. So, does anyone know of a way to differentiate a series without evaluating the series itself? I'm new to Mathematica, so the answer might be simple. Thanks for your time.


title: How can I make a barchart?

text: I want to mimic the below image type using Mathematica's `BarChart3D` function. For this purpose I wrote the following code but it isn't working. ![enter image description here](http://i.stack.imgur.com/P1SIa.png)               BarChart3D[{1, 2, 3},        ImageSize->{550,250},LabelingFunction -> Above,         ChartLabels -> Placed[barChartLabels, Below], BarSpacing -> 1,         ChartStyle -> Green,         ChartElements -> (Graphics3D[{Purple, Glow[Purple], EdgeForm[Purple],                           Cuboid[]}, Boxed -> False]),         LabelStyle -> {Directive[Bold, 15], Directive[Bold, 15]}     ]


title: Write and Read to StreamPosition

text: One OutputStream and one InputStream are opened on the same file:               atmp = OpenAppend["tmp"];       Write[atmp, "a"];       Write[atmp, "b"];       Write[atmp, "cde"];       rtmp = OpenRead["tmp"];       Read[rtmp];       Write[atmp, "ABC"];       ReadList[rtmp]        > >     {"b", "cde"}   >   What happend to ABC?               Read[rtmp]       EndOfFile       FilePrint["tmp"]        > >     "a" >     "b" >     "cde" >     "ABC" >   * * * OK.   One after the other, close one, open the other.   But still skeptical.   Shouldn't I be able to set the StreamPosition now?               atmp = OpenAppend["tmp"];       Write[atmp, "a"];       Write[atmp, "bc"];       Write[atmp, "def"];       StreamPosition[atmp];       Close[atmp];       rtmp = OpenRead["tmp"];       Read[rtmp];       ReadList[rtmp];       StreamPosition[rtmp];       SetStreamPosition[rtmp, 1];       Read[rtmp];       FilePrint["tmp"];       Close[rtmp];       DeleteFile["tmp"];       Streams[];


title: Copy and pasted graphics are fuzzy

text: I have a function that creates a 2D line with filling to the axis. When I copy this graphic into word it is very fuzzy, so much so that the numbers and text are almost unreadable, not to mention the aesthetic problem. When I take away the filling, the graphic can be copy and pasted into word as normal. the code used is:               Show[       Plot[d[x], {x, 0, 5}, PlotRange -> {-0.003, 0.003}],        ListLinePlot[residualsdata, PlotStyle -> Black, Filling -> Axis,          FillingStyle -> Directive[Opacity[0.5], Green]]]      The graphic without the filling is gotten by:               Show[       Plot[d[x], {x, 0, 5}, PlotRange -> {-0.003, 0.003}],        ListLinePlot[residualsdata, PlotStyle -> Black]]      Does anybody know the cause of this problem and/or how to fix it?


title: Combining two pure functions

text: How to get from the following intermediate result to the final one with just one pure function?               data = {"2894;Hot Pink;53:09:44;1449714",         "17456;Dark Cyan;19:06:42;6929227", "5147;Lime;54:11:55;5247632"};         from = 2; to = 3; delim = ";"; nr = to - from + 1;            inter = StringSplit[#, delim][[from ;; to]] & /@ data       {{"Hot Pink", "53:09:44"}, {"Dark Cyan", "19:06:42"}, {"Lime", "54:11:55"}}            final = {{"Hot Pink;53:09:44"}, {"Dark Cyan;19:06:42"}, {"Lime;54:11:55"}}


title: Placing package in existing Utilities` context has odd paraellelization effect

text: I noticed this in V.10 but possibly it was in effect in V.9. I have a package which in simplified form looks like:-               BeginPackage["Utilities`DataHandling`"];     f;     Begin["`Private`"];     f[data_List] := Module[{samples, selectFrom},         selectFrom[]:=($KernelID->data);          DistributeDefinitions[selectFrom];          samples = ParallelTable[$KernelID->Apply[Hold,{"CTUDH",$Context, Context[selectFrom], selectFrom[]}], {10}, Method -> "CoarsestGrained"];         samples         ];     End[];     EndPackage[];      The actual package is much bigger and performed a useful function, the payload in ParallelTable here is to illustrate the problem. When f is executed, the local symbol **selectFrom** is given a definition and distributed to all sub-kernels. Except that its not (when the package is loaded via Needs). So far as the sub- kernels are concerned the symbol **selectFrom** has no definition so the call **selectFrom** results in **Utilities`DataHandling`Private`selectFromXXX** [] - the _Hold_ prevents this from evaluating in the master kernel on return. Try f[{1,2,3}]. Changing the package name to MyUtilities`DataHandling` or indeed anything else resolves this and **selectFrom** is correctly defined in all the sub-kernels. This only took a day or so to work out *sigh*. What is special about the (admittedly Built-in) context Utilities? How does it mess up _DistributeDefintions_?


title: LinearSolve failing to find solution to system of linear equations of 64 variables

text: I've got a 64x64 Matrix `L` for which I want to find the solution to the matrix equation `L . x == rho`. L is defined as `L[a, b, c, d, e, f]` with assumptions `Element[{a, b, c, d, e, f}, Reals]`. As long as I put specific numbers in `L`, e.g. `L[1, 1, 1, 1, 1, 1]`, `LinearSolve[L, rho]` (with `rho` something like `rho = {1, 0, 0, ..., 0}`) finds the solution within a fraction of a second. But when making even one argument symbolic, say `L[a, 1, 1, 1, 1, 1]`, `LinearSolve` finds no solution (with `rho` as defined above): > LinearSolve::nosol: Linear equation encountered that has no solution. But there is a solution, at least all values of `a` I tried manually. And `a` is only added linearly in only some of the components of `L`. And even `Det[L]` is nonzero, so there should be a solution. I assume I'm doing something pretty wrong. Can anyone help me? Edit: Here is a sample matrix L[a,b,c,d,e,f] with fewer dimensions(5x5) where LinearSolve works(probably not the best sample because the big L matrix is more or less spare and this example doesn't look so):               L[a,b,c,d,e,f]={{1, 0, 0, 0, 0}, {0, (0. + 2. I) c, -((I dSin[f])/Sqrt[3]), -((I d Cos[f])/Sqrt[3]), 0},     {(I d Cos[f])/Sqrt[3], -((I d Sin[f])/Sqrt[3]), -11.565 - (0. + 1. I) a +(0. + 0.666667 I) c, 0, -(1/2) I e Sin[f]},     {-((I d Sin[f])/Sqrt[3]), -((I d Cos[f])/Sqrt[3]), 0, -11.565 - (0. + 1. I) a + (0. + 1.33333 I) c, 0},     {0, 0, -(1/2) I e Sin[f], 0, -0.2 - (0. + 1. I) a + (0. + 1. I) b - (0. + 0.2 I) c}}      i is no variable but the imaginary unit


title: Collecting roots of different equations and create a list

text: I solve two equations and have two solutions one by each equation. I want to create list of these roots. Could anyone please help me? Appreciate it. m02R150 = FindRoot[P1 == 0, {E1, 0.07, 0.1}] m01R150 = FindRoot[P1 == 0, {E1, 0.19, 0.2}] {E1 -> 0.0992422} {E1 -> 0.195237} What I want is to create a list: Lm0R150 = {0.0992422, 0.195237}


title: Split Lingustic(IPA) at Words Unique Sounds

text: How might I split a word at each IPA of each unique sound. For example               {"pray", "wade"}     (* {{"p","r","ˈeɪ"}, {"w","ˈeɪ","d"}} *)      ssch answered a question here showing how to add the IPA form to WordData. After adding such values I determined that ideally I am looking to separate the values in between each IPA sound(this probably isn't the correct terminology). An example would be the following `"pray"` and `{"p","r","ˈeɪ"}`. `"wade"` would return `{"w","ˈeɪ","d"}` Ideally a list of each unique IPA sound could be useful something like `{"b", "d", "dʒ", "f", "g", "h"....` So how might I get a list of Mathemametica's IPA sounds such that I can split a word's IPA form at each unique IPA sound?


title: How can I only draw outer common tangent to two circles?

text: I have code worked for drawing common tangent lines to two circles(http://en.wikipedia.org/wiki/Tangent_lines_to_circles), now I want to delete the inner common tangent lines, how?               Manipulate[Block[{t1, t2, v1, v2, pts},       t1 = {xm, ym};       t2 = {xn, yn};       {v1, v2} = p;       pts = {t1, t2} /. NSolve[{(t2 - v2).(t2 - t1) == 0, (t1 - v1).(t2 - t1) == 0,          (t1 - v1).(t1 - v1) == r1^2, (t2 - v2).(t2 - v2) == r2^2}, {xm, ym, xn, yn}, Reals];       If[pts == {t1, t2}, pts = {}];       Graphics[{Circle[p[[1]], r1], Circle[p[[2]], r2], Line[pts]},         PlotRange -> 6, Frame -> 1]       ], {{p, {{-3, 1}, {3, 0}}}, Locator}, {{r1, 1}, 1, 3}, {{r2, 2}, 1,        3}]      ![enter image description here](http://i.stack.imgur.com/e5Yov.png)


title: Interacting with 3D Graphics, for export

text: Are there any export formats which preserve the ability to interact with 3D Graphics? (In particular, the ability to rotate.) EDIT: I've found this question: How to make a 3D plot auto-rotate? which produces an object with head DynamicModule. Can I export as an animated gif or QuickTime movie?


title: Truncating out higher order polynomials in series of fractions

text: I have taken sequential partial derivatives of a two variable polynomial fraction, resulting in a very long series of polynomials of form:               C*x^i*y^j/(some product series of (1-x^k*y)^n)      What I wish to do is a series of basic truncations. First, I eliminate all polynomials that have `x^i*y^j` with `i` or `j > 4` in the numerator. I keep looking over the documentation and StackExchange and cannot find anything that works for me. I am open to suggestions. Edit: Thus far, I have merely sorted the long series, and picked out the valid fractions starting from the bottom. What is the solution that uses Mathematica functions?


title: Counting 'False' values at the ends of a list

text: I have table like this:               t = {False, False, False, 4.5, 6.789, 1.23, 0.98, False, False}      and I want to know how many False values I have at the beginning and at the end of the table. I made:               size = Length[t]     t = Cases[t,Except[False]];     size2 = Length[t]     diff = size - size2      But this counts number of all `'False'` values inside the table. But I want to know how many is at the beginning and how many at the end (so i my example I have: 3 at the beginning and 2 at the end). How can I solve that?


title: Unset while running recursion

text: I am trying to run a recursive definition while at the same time clearing previously found values, so my memory is not completely consumed. I found this: How to clear parts of a memoized function? But it does not seem to be what I am looking for. I want to clear memorized values, while the recursion is running. I thought I could do something like this:               Block[{$IterationLimit = $RecursionLimit = ∞},f [m_]:= f [m] = f [m-1]+f [m-2]          f[0]=0          f[1]=1          If [m - 3 > 0, Unset[f[m-3]]]      But it does not work. I realize I could just use `Fibonacci[n]`, but I am doing this to try to learn _Mathematica_ not to study the Fibonacci sequence. Thank you for any help!


title: Speeding up this fractal-generating code

text: I used the code below (which is a sample from this gist containing more similar code) in my answer to my own question about Mandelbrot-like sets for functions other than the simple quadratic on Math.SE to generate this image: ![graphic](http://i.stack.imgur.com/pL8nx.png)               cosineEscapeTime =       Compile[{{c, _Complex}},        Block[{z = c, n = 2, escapeRadius = 10 \[Pi], maxIterations = 100},         While[And[Abs[z] <= escapeRadius, n < maxIterations],          z = Cos[z] + c; n++]; n]]          Block[{center = {0.5527, 0.9435}, radius = 0.1},       DensityPlot[       cosineEscapeTime[x + I y], {x, center[[1]] - radius,         center[[1]] + radius}, {y, center[[2]] - radius,         center[[2]] + radius}, PlotPoints -> 250, AspectRatio -> 1,        ColorFunction -> "TemperatureMap"]]      What could I do to improve the speed/time-efficiency of this code? Is there any reasonable way to parallelize it? (I'm running Mathematica 8 on an 8-core machine.) * * * _**edit_** Thanks all for the help so far. I wanted to post an update with what I'm seeing based on the answers so far and see if I get any further refinements before I accept an answer. Without going to hand-written C code and/or OpenCL/CUDA stuff, the best so far seems to be to use `cosineEscapeTime` as defined above, but replace the `Block[...DensityPlot[]]` with:               Block[{center = {0.5527, 0.9435}, radius = 0.1, n = 500},      Graphics[       Raster[Rescale@         ParallelTable[          cosineEscapeTime[x + I y],           {y, center[[2]] - radius, center[[2]] + radius, 2 radius/(n - 1)},            {x, center[[1]] - radius, center[[1]] + radius, 2 radius/(n - 1)}],         ColorFunction -> "TemperatureMap"], ImageSize -> n]      ]      Probably in large part because it parallelizes over my 8 cores, this runs in a little under 1 second versus about 27 seconds for my original code (based on `AbsoluteTiming[]`).


title: How to visualize the voting choices in the moderator elections?

text: I'm trying to use Mathematica to create some visual representations of the votes cast in the recent Mathematica-StackExchange moderator elections. (Not the vote-counting system itself, OpenSTV, but rather the choices people made.) This is what I've got so far, but I'm stuck on how to represent the data visually, not knowing much about charting. According to this Meta post, the results can be downloaded in text form from this page. It looks to be a plain text file (with oddball Unicode characters):               data = Import[      "http://mathematica.stackexchange.com/election/download-result/1", "Table", CharacterEncoding -> "UTF8"]          (*     {{6, 3}, {1, 1, 2, 3, 0}, {1, 2, 4, 3, 0}, {1, 1, 4, 2, 0}, {1, 3, 1, 5, 0},      .... {"Verbeia"}, {"Mr.Wizard"}, {"F'x"}, {"Eiyrioü von Kauyf"}, {"Mathematica Moderator Election 2012"}}     *)      Although I couldn't find a guide to the format, it looks reasonable to assume that the initial {6,3} is the number of candidates and the number of vacancies, that the strings at the end before the election name are the candidates names, and that the lists starting with 1 and ending with 0 are the individual votes. So:               votes = Cases[data, {1, a_, b_, c_, 0} -> {a, b, c}]      gives the votes:               (*     {{1, 2, 3}, {2, 4, 3}, ... {1, 3, 5}}     *)      which I suppose can be turned into something more readable by picking up the names from the end of the list:               votes1 = votes /.       Table[        n -> First@data[[Rescale[n, {1, 6}, {-7, -2}]]],       {n, 1, 6}]      to give something like this:               (*     {{"R.M.", "J.M", "Verbeia"}, {"J.M", "Mr.Wizard", "Verbeia"},       {"R.M.", "Mr.Wizard", "J.M"}, {"Verbeia", "R.M.", "F'x"},       {"Mr.Wizard", "J.M", "Verbeia"}, {"J.M", "R.M.", "Mr.Wizard"} ...     *)      So now I'd like to make this data accessible visually, using charts or graphs. (Or, as the online help says, "produce compelling dynamic visualizations".) How could I do this?


title: How can we create Randolph diagrams in Mathematica?

text: I have become fascinated with Randolph Diagrams and was wondering how we would create the diagrams from logical sequences using _Mathematica_? It looks like it would be a combination of logic and graphing. I have no idea where to start. I need some suggestions to get me going. **Edit** Randolph's paper on JStor


title: Where to download the MathWorld package?

text: I was trying to run some notebook I downloaded from MathWorld, but lots of them need               << MathWorld`Curves`      I tried to google it , only to find this, but the link links to nothing but a blank page. so where do I find these packages?


title: Accurately distort graphics

text: I would like to accurately distort this plot of $\sin(x^{1/2})$ (and others like it) so that the wavelengths are evened out (ie - "inverse-square root" it). ![enter image description here](http://i.stack.imgur.com/d7oRl.gif) I should like to do the same to "de-log" plots too. I have no idea where to start though.


title: FullSimplify yielding different results in mathematica 8 and 9

text: I have been experiencing some problems running a certain mathematica file in version 9. I've tracked the problem to a particular sum that I perform. Running the same code in version 8 and 9 I get two different results for this sum. If I then ask mathematica whether the two sums are identical mathematica 8 says that they are whereas mathematica 9 says that they are not. So: I run the same code in version 8 and 9 and get a different result, if I compare the results version 8 says that they are the same, version 9 says that they are not. Why would this happen? A bug? Comparison attached below.               Chop@FullSimplify[       1.9999999999999996` x0^4 + 3.9999999999999987` x0^2 x1^2 +        2.` x1^4 + 0.3333333333333333` x1^2 x2^2 + (0.857142857142857` x0^2 -        0.699854212223765` x0 x1 + 0.14285714285714285` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396075` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095236` x0^2 + 0.11664236870396079` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396089` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.523809523809524` x0^2 +  0.11664236870396096` x0 x1 + 0.5873015873015872` x1^2) x2^2 +        (0.5238095238095236` x0^2 + 0.11664236870396066` x0 x1 + 0.5873015873015873` x1^2) x2^2 +        (0.5238095238095237` x0^2 + 0.11664236870396083` x0 x1 + 0.5873015873015874` x1^2) x2^2 +        1.9999999999999996` x2^4 ==        1.9999999999999996` x0^4 + 2.` x1^4 + 4.` x1^2 x2^2 + 1.9999999999999996` x2^4 +        6 x0^2 (0.5238095238095236` x1^2 + 0.5238095238095236` x2^2) +        x0^2 (0.857142857142857` x1^2 + 0.857142857142857` x2^2) +         x0 (1.166423687039609` x1^3 - 0.6998542122237649` x1 x2^2) +        2 x0 (-0.19440394783993475` x1^3 + 0.11664236870396069` x1 x2^2) +        x0 (-0.1944039478399347` x1^3 + 0.11664236870396072` x1 x2^2) +        x0 (-0.1944039478399347` x1^3 + 0.11664236870396077` x1 x2^2) +        2 x0 (-0.1944039478399347` x1^3 + 0.11664236870396083` x1 x2^2)]      Cheers, David


title: Replace an expression with a slightly tricky LHS transformation

text: I would like to make the substitution `x^(11*y) -> r` in the following equation               x^(11 *y^z) - 1       to end up with:               r^(y^(z - 1)) - 1      How can I do this in _Mathematica_?


title: Why is EigenValues returning Root expressions?

text: This is the code I have:               ϵs = -13.6;     ϵso = -29.1;     ϵp = -14.1;     ssσ = -7.20;     spσ = 9.46;          θ = ((π - β)/2);          Hmatrix0[θ_] =      {       {ϵs, 0, ssσ, Cos[θ]*spσ, -Sin[θ]*spσ, 0},        {0, ϵs, ssσ, -Cos[θ]*spσ, -Sin[θ]*spσ, 0},        {ssσ, ssσ, ϵso, 0, 0, 0},        {Cos[θ]*spσ, -Cos[θ]*spσ, 0, ϵp, 0, 0},        {-Sin[θ]*spσ, -Sin[θ]*spσ, 0, 0, ϵp, 0},        {0, 0, 0, 0, 0, ϵp}     }          Eigenvalues[Hmatrix0[θ]]      This is a sample of one of the eigenvalues: > Root[(38319.6 + 0. I) - 130827. Cos[β] - 116527. Cos[2 β] + (120228. - > 9278.49 Cos[β] - 4004.37 Cos[2 β]) #1 + (29612. + 9.09495*10^-13 Cos[β]) > #1^2 + 2480.29 #1^3 + 84.5 #1^4 + 1. #1^5 &, 1] I wish to plot the eigenvalues as a function of beta as it ranges from $\frac{\pi}{2}$ to $\pi$ but I don't know what those hashes are and putting `N[hmatrix0[`$\beta$`]]` doesn't work.


title: Function won't compile. Is there a workaround?

text: Here's a simplified form of a function I would like to compile, but it produces errors               DataType = Compile[{{Inputdata, _Real, 1}}, Module[{CIEL, CIEa, CIEb},         dim = Dimensions@Inputdata;         If[dim[[1]] > 3,          {CIEL, CIEa, CIEb} = Inputdata             ]         ],        CompilationTarget -> "C"        ];      The error _Mathematica_ produces is: > Compile::extscalar: `dim=Dimensions[Inputdata]` cannot be compiled and will > be evaluated externally. The result is assumed to be of type Void. >> Is there a workaround to allow these types of functions to compile for conditionals that depend on the dimensions of a list?


title: Merging (combining) tables of graph relationships (2-mode to 1-mode network)

text: I have some data of corporate board members in Australia in excel format here (Dropbox public link). It is the data behind this graph. The first worksheet is of all the vertexes (directors and companies with a unique ID for each, and a market capitalisation to use for weighting the size of vertexes in displayed graphs). The second worksheet is the relationship between companies and directors (edges). The edges table looks a bit like this               {{"Source", "Target"}, {"BHP BILLITON",        "Mr Alberto Calderon"}, {"BHP BILLITON",        "Mr Andrew Mackenzie"}, {"BHP BILLITON",        "Mr Brendan Harris"}, {"BHP BILLITON",        "Mr Carlos Cordeiro"}, {"BHP BILLITON",        "Ms Carolyn Hewson"}, {"BHP BILLITON",        "Mr David Crawford, AO"}, {"BHP BILLITON",        "Mr Graham Kerr"}, {"BHP BILLITON",        "Mr Jac Nasser, AO"}, {"BHP BILLITON",        "Dr John Buchanan"}, {"BHP BILLITON",        "Dr John Schubert, AO"}, {"BHP BILLITON",        "Ms Karen Wood"}, {"BHP BILLITON",        "Mr Keith Rumble"}, {"BHP BILLITON", "Mr Lindsay Maxsted"}...       What I ultimately want is a graph of that eliminates the companies, with undirected edges between only directors who are on boards together.                   ASXdata =            Import["https://dl.dropbox.com/u/3997716/ASXdata.xls"];         ASXvertexes = Take[ASXdata[[2]]];         ASXedges = Take[ASXdata[[1]]];     graphFunc = Function[{u, v}, v \[UndirectedEdge] u];     twoMode = graphFunc @@@ ASXvertexes;     twoModeGraph = Graph[twoMode, ImageSize -> 500]      The above code gets me the below 2-mode graph (includes company and director vertexes). ![enter image description here](http://i.stack.imgur.com/tZjm2.png) Somehow I want a function that assigns all the possible undirected edges between the directors that have the same company in the first column. I should then see a graph that looks a bit like the below snippet (my previous function can turn it into an undirected graph).               {{Mr ALberto Calderon,Mr Andrew Mackenzie},{Mr Alberto Calderon, Mr Brendan Harris}...      Obviously the graph will be much bigger because of all the extra edges required - eg. for the 21 directors in BHP there will now be 210 edges between them, instead of the previous 21 between the company and each director. Ideally I could also create a network for just companies, with edges where they share a common board member. I literally have no idea how to even start, but assume I could apply whatever function someone can come up with to the columns in reverse for this.               {{BHP BILLITON, ASCIANO},{ANZ,TELSTRA}...      I guess the other main question, since I intend to be doing this sort of stuff quite a bit, is whether I first map the unique numerical vertex IDs from the first worksheet in the spreadsheet before doing these type of operations and before working with the resulting graph (measuring centrality, components, clusters, paths etc). **UPDATE** I have been able to divide the edges list by company. I figured that I would take the director name list for each company that comes from this, them make a complete graph of each, then combine them. However CompleteGraph doesn't seem to like the list input                  ASXvertexes = Take[ASXdata[[1]]];     ASXedges = Take[ASXdata[[2]]];     tASXedges = Transpose[ASXedges];     graphFunc = Function[{u, v}, v \[UndirectedEdge] u];     twoMode = graphFunc @@@ ASXedges;     twoModeGraph = Graph[twoMode, ImageSize -> 500];     compnames = Union[Transpose[ASXedges][[1]]];     directornames = Union[Transpose[ASXedges][[2]]];          t = Split[Rest@tASXedges[[1, All]]];          match = Table[       Cases[ASXedges, {n_, __} /; n == compnames[[b]]], {b, 1,         Length[compnames]}]     c1 = Flatten[Take[Flatten[Take[match, 1], 1], All, -1]]     CompleteGraph[c1]      Which gives as output               CompleteGraph[{"Mr Bill Bartlett", "Mr Rod De Aboitiz",        "Mr Malcolm G Irving", "Mr John M Thame", "Dr Frank M Wolf",        "Mr David Bastian", "Mr Ellis Varejes", "Mrs Myra Salkinder",        "Mr Neil Summerfield"}]      **UPDATE 2** With a bit of help from @kguler I can assign unique IDs to the names, and do a bit of sorting. But for some reason the Graph function won't accept what I give it (it looks like a reasonably constructed graph to me). I get the error message "Graph::supp : Mixed graphs and multi graphs are not supported>>" I've had this problem before, but I though the filtering of Union, DeleteCases etc would have done it. Here's the current code               ASXdata =        Import["https://dl.dropbox.com/u/3997716/ASXdata.xls"];     ASXvertexes = Take[ASXdata[[1]]];     ASXedges = Drop[Take[ASXdata[[2]]], 1];     graphFunc = Function[{u, v}, v \[UndirectedEdge] u];     compnames = Union[Transpose[ASXedges][[1]]];     directornames = Union[Transpose[ASXedges][[2]]];     edges = ArrayComponents[ASXedges];     blist = Flatten[Take[edges, All, 1]];          match = Table[Cases[edges, {n_, __} /; n == b], {b, blist}];     directorgroups =        Union[Table[Part[match, i, All, 2], {i, 1, Length[match]}]];          example =      Sort[       Flatten[        Table[         DeleteCases[          Union[           Tuples[directorgroups[[i]]            , 2],           SameTest -> (First[#1] == Last[#2] &)]          , _List?(Equal @@ # &)]         , {i, 1, Length[directorgroups]}]        , 1]       ]          testdirectorgraph = graphFunc @@@ example;     Graph[testdirectorgraph]      Many thanks again.


title: RSolve fails on a two-equation non-linear system

text: I have a system of just two recurrence equations, I need to solve them and so I use `RSolve`:               RSolve[{H[n + 1] == (1 + (7 h[n])/10) H[n],              h[n + 1] == 1 - (1 + (7 h[n])/10) H[n]},             {H[n], h[n]}, n]       But this just returns my code, without any errors: > >     RSolve[{H[1 + n] == (1 + (7 h[n])/10) H[n], >             h[1 + n] == 1 - (1 + (7 h[n])/10) H[n]}, >            {H[n], h[n]}, n] >   Where am I going wrong? Why am I not even seeing any errors? Additional Info:   * I am modelling the frequency of two variants, H and h, through discrete time (n)   * Total frequency in the population: h + H = 1   * The two variant's frequencies depend on each other as you can see in the above code


title: Substituting a function in the output

text: I have to calculate the derivatives of the function `K` defined in the code:               << VectorAnalysis`     K = δ[t]*Exp[-(r/L)]/r;     SetCoordinates[Cartesian[x, y, z]];          r = Sqrt[(x - x0)^2 + (y - y0)^2 + (z - z0)^2];     Hes = D[K, {{x, y, z}, 2}];     der = Grad[K];     FullSimplify[der[[1]]]     FullSimplify[Hes[[1, 2]]]     FullSimplify[Hes[[1, 1]]]      This is part the output just for `FullSimplify[der[[1]]]`: > >     -((E^(-(Sqrt[(x - x0)^2 + (y - y0)^2 + (z - z0)^2]/ L)) (x - x0) (L + >         Sqrt[(x - x0)^2 + (y - y0)^2 + (z - z0)^2]) δ[t])/( L ((x - x0)^2 + > (y - y0)^2 + >       (z - z0)^2)^(3/2))) >   I would like the function `K` to appear in the result instead of that "mess": is it possible to do it?


title: Is it possible for me to explicitly specify a point list for SpatialGraphDistribution?

text: The function `RandomGraph[SpatialGraphDistribution[n, r]]` generates a random geometric graph over $[0,1]^2$ where vertices are connected if they are within a distance $r$ of one-another. How would I explicitly specify a list of points for generating a random geometric graph using this function? Specifically, I need to enforce a minimum threshold distance between points. Clarification: My point list is going to come from a Random Sequential Adsorption (RSA) simulation of circles on a plane. So I mean that no two points should be closer than some minimum threshold distance set by the radius of the circles being deposited, not that two points shouldn't share an edge if they are closer than the threshold distance.


title: Reducing mesh details while exporting to vector format SVG

text: I am trying to export a simple cuboid into .SVG format. In the output file, the cuboid is finely meshed, which increases the file size. How to remove this detailed mesh?                Export[FileNameJoin[{NotebookDirectory[], "trial.svg"}], Graphics3D[Cuboid[]]]      ![enter image description here](http://i.stack.imgur.com/UHBws.png)


title: Evaluate integral of a series

text: I want to evaluate this integral, but it won't work. Does anyone knows why?               Remove["Global`*"]          dm = (M/(2 π a)) a ;          i[ϵ_] = 1/(a Sqrt[1 - 2 (ϵ) Cos[θ] + (ϵ)^2]);     i1[ϵ_] = Series[i[ϵ], {ϵ, 0, 1}];     invertdist[r_] = i1[a/r];          ϕ[r_] = -Integrate[G dm invertdist[r], {θ, 0, 2  π}]


title: SplicedDistribution - different definition across Mathematica 9?

text: I am having troubles with my notebook. I succesfully defined Asymmetric Laplace Distribution at school using `SplicedDistribution` function, and _Mathematica_ was able to compute (about 30sec) `Mean`, `Variance`, `Skewness` and `Kurtosis`.   Now, I am at home and _Mathematica_ can compute only `Mean`?! I am running _Mathematica 9.0.1.0 Student Edition_. Where is the problem during switching machines? I can make upload of notebook if needed. ![SplicedDistribution problem](http://i.stack.imgur.com/BHUqR.png)               AsymmetricLaplaceDistribution[ θ_, τ_, κ_] =        SplicedDistribution[{ κ, 1/κ},{ -∞, θ, ∞},{ LaplaceDistribution[ θ, τ κ],                                                   LaplaceDistribution[ θ, τ/κ]}];      and then               ALD = AsymmetricLaplaceDistribution[ θ, τ, κ];      and after               { Mean[ALD], Variance[ALD], Skewness[ALD], Kurtosis[ALD]}      yields (but only @ school computers? why?)               { θ + τ/κ - κ τ, ((1 + κ^4) τ^2)/κ^2,       -(( 2 (-1 + κ^6) τ^3)/(κ^3 (((1 + κ^4) τ^2)/κ^2)^(3/2))),       (9 + 6 κ^4 + 9 κ^8)/(1 + κ^4)^2}      **Edit** : I just find `Moment[ dist, r]` works fine up to `r = 10` what I tested. But still, `Variance` does not.


title: How to distribute PermutationProduct over the sum

text: Assuming I have two elements of the permutation group algebra $a_1$, $a_2$ such that $a_i=\sum_{p\in S_n}\alpha_pp$, I want to define a linear product $\odot$ that distributes over the sum and pulls out scalars: $a_1\odot a_2=\sum_{p\in S_n}\sum_{q\in S_n}\alpha_p\alpha_qp\odot q$, where $p\odot q\equiv PermutationProduct[p,q]$. If I try for example               Distribute[PermutationProduct[Cycles[{{}}] + Cycles[{{1, 2}}], Cycles[{{}}] - Cycles[{{1, 2}}]]}      The result is               Cycles[{}] +PermutationProduct[Cycles[{{1, 2}}],(-Cycles[{{1, 2}}])]      but I'm not sure how to make it take "constants" outside the product.


title: Inconsistent behavior of Assuming[] in combination with Simplify[]

text: The following integral gives the correct result               Assuming[{n, m} \[Element] Integers,      Integrate[     2/W Sin[(n Pi z)/W] D[Sin[(m Pi z)/W], {z}], {z, 0, W}] //      Simplify]          (2 (-1+(-1)^(m+n)) m n)/((m^2-n^2) W)      However, the following expression returns `0`, which is, i.g., wrong (for `m=n=1` this should give `1`)               Assuming[{n, m} \[Element] Integers,      Integrate[2/W Sin[(n Pi z)/W] D[Sin[(m Pi z)/W], {z, 0}], {z, 0, W}]//     Simplify]      Edit: To make the disaster clearer:               Assuming[{m, n} \[Element] Integers,      Integrate[2 Sin[n \[Pi] z] Sin[m \[Pi] z], {z, 0, 1}]//Simplify]      returns 0!


title: Conjugating symbolic expression

text: I am trying to conjugate a symbolic expression, and I have explicitly stated the real terms. However, I simply can't get it to work:               Conjugate[      ComplexExpand[       I Cos[z] Sin[y] + Sin[z] +         A (Cos[z] - I Sin[y] Sin[z]), {z \[Element] Reals,         A \[Element] Reals, y \[Element] Reals}]]      What am I doing wrong here?


title: Importing RSS to Notebook: How to get images instead of long ugly links?

text: This question on importing news headlines via a RSS feed reminded me of an old question I've been meaning to ask. Past attempts at finding a use for Mathematica's RSS to Notebook capabilities were frustrated by the fact that images within a given post always get parsed as a long ugly link to the image, rather than importing the image itself. Consider the following blog:               NotebookPut[Import["http://gregmankiw.blogspot.com/feeds/posts/default?alt=rss", "RSS"]];      Scrolling down to one of the posts containing an simple image (along with a tiny snipped of text that correctly hyperlinks to a WSJ article), one often sees something like: ![enter image description here](http://i.stack.imgur.com/6o3ce.png) **Request 1:** Instead of the messy html text---that is a working hyperlink to the actual image---I'd rather see an actual image. Many posts also contain embedded video clips for sites like YouTube, etc. Instead of seeing an messy link, as in: ![enter image description here](http://i.stack.imgur.com/aL2W3.png) **Request 2:** Can you instead display a static video image (and make that image a hyperlink to the actual YouTube video---and feel free to strip out the tracking crap...)? I realize this may require some knowledge of how YouTube embedded links actually work. Dunno if it's easy, or even possible, to request a static 'placeholder' image from YouTube.


title: Differentiating space curves

text: I'm trying to do some very basic differential geometry of space curves. For example, a space curve $\gamma:\mathbb R\to\mathbb R^3$ has unit tangent and normal vectors given by $$t(s)=\frac{\gamma'(s)}{\lVert\gamma'(s)\rVert},\\\ n(s)=\frac{t'(s)}{\lVert t'(s)\rVert}.$$ I want to define functions that would compute the tangent and normal vectors of an arbitrary curve at any $s$. I tried it in a higher-order functional style, like in say Haskell:               norm[x_] := Sqrt[x.x]     tangent[γ_] := Function[s, γ'[s]/norm[γ'[s]]]     normal[γ_] := Function[s, tangent[γ]'[s]/norm[tangent[γ]'[s]]]      (I need to define my own `norm` because Mathematica doesn't like to differentiate `Norm`.) Unfortunately, this doesn't work. Let `γ[s_] := {Cos[s], Sin[s], 0}` be our test curve, a circle. Then `normal[γ][1] // N` does not return a vector, but instead a bizarre expression involving the dot product of `1.` and a vector. I have no idea how to begin figuring out what's going on. I can do it in a less elegant way as               tangent[γ_, s_] := γ'[s]/norm[γ'[s]]     normal[γ_, s_] := D[tangent[γ, ss], ss]/norm[D[tangent[γ, ss], ss]] /. ss -> s      but this requires the use of a dummy variable and the not-so-pretty `D[tangent[γ, ss], ss]` construction. Why does my original implementation not work, and is there a simple way to fix it?


title: Faster way to compute the distance from a point to a surface in 3D

text: I am trying to compute the shortest distance between a point and a triangle in 3D               distance[point_, {p1_, p2_, p3_}] := Module[{p, s, t, sol},       p = s*p1 + (1 - s)*(t*p2 + (1 - t)*p3);       MinValue[{(point - p).(point - p),        0 <= s <= 1, 0 <= t <= 1}, {s, t}]];      but it seems to be quite slow, is there any way to make it faster?


title: Numerically solving a PDE with dependance on a fixed grid point

text: I am trying to solve partial differential equations of the type $y^{(1,0)}(t,x) = f(y^{(0,1)}(t,x), y(t,x_0))$ where $x_0$ is a fixed point. For example, when pluging this into Mathematica :               NDSolve[{D[y[t, x], t] == D[y[t, x], x] + y[t, 1], y[0, x] == Cos[x]}, y, {x, 0, 2}, {t, 0, 2}]      I get the error message               NDSolve::delpde: Delay partial differential equations are not currently supported by NDSolve. >>      The problem is cured by replacing `y[t, 1]` by `y[t, x] DiscreteDelta[x-1]` ; however I do not find this trick very elegant. Do you know of a better way to circumvent this problem?


title: Why is my compiled function slower than a regular function?

text: I have the following functions:               Block[{n, diag},      snake`diag[n_] = Ceiling[1/2 (-1 + Sqrt[1 + 8 n])];      snake`alongdiag[n_, diag_] = {0, diag + 1} + (n - diag (diag - 1)/2) {1, -1};      snake[n_] = snake`alongdiag[n, snake`diag[n]];]     (*A003986 on OEIS, http://oeis.org/A003986*)     A003986[n_] := BitOr @@ (snake[n] - {1, 1})     A003986c =       Compile[{{n, _Integer}}, A003986[n], CompilationTarget -> "C",        RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed"]      The functions seem very "compilable" in that they're just numerical computations. However, the compiled function performs as badly or worse:               Table[{x, A003986 /@ Range@(10^x); // Timing // First,           A003986c[Range@(10^x)]; // Timing // First}, {x, 5}]~       Prepend~{"Func", "ME", "Comp"} // TableForm      ![enter image description here](http://i.stack.imgur.com/MmQLV.png) Fine - perhaps the function does "too little" and the overhead from running the C code is costing too much. But then altering my code to fix that doesn't help things:               A003986l =        Compile[{{n, _Integer}}, A003986 /@ Range[n],          CompilationTarget -> "C", RuntimeOptions -> "Speed"];     Table[{x, A003986 /@ Range@(10^x); // Timing // First,           A003986l[(10^x)]; // Timing // First}, {x, 5}]~       Prepend~{"Func", "ME", "Comp"} // TableForm      ![enter image description here](http://i.stack.imgur.com/iaKNG.png) Both functions are approximately linear, so everything seems to be working as expected in an algorithmic regard, but this is very slow for a couple of formulas and `BitOr`! What is going wrong?


title: Visualizing vectors

text: How to visualize a set of vectors with 3 coordinates $(x,y,z)$, e.g.,$(1,1,1), (1,-1,-1),(-1,1,-1),(-1,-1,1)$? In fact there are many of them. I try the function "Graphic3D" with the following code               Graphics3D[{Arrow[{{0, 0, 0}, {1, 1, 1}}], Arrow[{{0, 0, 0}, {1, -1, -1}}]},      {Arrow[{{0, 0, 0}, {-1, 1, -1}}], Arrow[{{0, 0, 0}, {1, -1, -1}}]},     Axes -> True, Boxed -> True]      However, it seems it can only give me the first two vectors in the plot. How can I visualize all of them at the same time? And is there any other way to visualize them? ![enter image description here](http://i.stack.imgur.com/L0Bb1.jpg)


title: Symbolic Definite Integration

text: How do I perform               Integrate[Sin[x]^2/(z^2 + R^2 - 2 zRCos[x])^(3/2), {x, 0, Pi}]      where `z` and `R` are constants. I would like if possible the result in terms of `z` and `R`.


title: Parallelize[Mapindexed[]], level={-1}? Sal Mangano's 《Cookbook》

text: It is easy to **Parallelize[]** Map[] & MapIndexed[], as having been shown in MMA9 Help for ParallelMap[] and Parallelize[]. For MapIndexed[], the default **levelspec** is {1}. However there are many cases when we need mapping to deeper levels such as {-1}, for example with image data (2D array). I have tried Parallelize[] and found it FAILED and switched to **sequential evaluation** whenever **levelspec** is explicitly specified, actually even when **levelspec={1}** ! ![enter image description here](http://i.stack.imgur.com/qlBlE.png) In page 652 of Sal Mangano's _Mathematica Cookbook_, he seems to have written functions which   1. use Parallelize[] on MapIndexed[]   2. able to specify **levelSpec** ![enter image description here](http://i.stack.imgur.com/LIkHH.png) I don't know how he achieved that, and his example was not detailed enough to see the intended effect. I actually suspect that: with the default levelspec={1}, Parallelize[] could conveniently distribute the elements on the first level of the list across different kernels (like **breadth-first search** on level 1, using a **queue** in C); however if we need to go deeper with MapIndexed[]'s **depth-first** (see help) search, then the parallel implementation would be very difficult. So is it true that **Parallelize[Mapindexed[]]** only works with default/implicit levelSpec={1}, not others? Is Mr. Sal Mangano on this forum? Could he also comment?


title: Wrapping a data selection in Mathematica

text: I was wondering what would be the most efficient way to add brackets to given elements in my data set in order to change it's form from {{a,b},{c,d}} to {{{a},b},{{c},d}}. I took a look through a few questions within the exchange database but couldn't find an answer which would output data in that form. I found an example for strings here, however,the output is a string which I can't manipulate as data (if that makes any sense). My example data is as follows:               List = {{0.343051, 48.3831}, {0.331855, 81.4873}, {0.323979, 101.01}, {0.317126, 108.65}, {0.310429, 106.103}, {0.303265, 95.0686}, {0.294876, 77.2432}, {0.283812, 54.3249}, {0.265673, 28.0113}, {0., 0.00176955}, {-0.265673, 28.0113}, {-0.283812, 54.3249}, {-0.294876, 77.2433}, {-0.303265, 95.0686}, {-0.310429, 106.103}, {-0.317126, 108.65}, {-0.323979, 101.01}, {-0.331855, 81.4882}, {-0.343051, 48.3836}}      (I'm not looking for it to be done for a specific dataset of just this size, but rather for the more general case initially suggested) My current method looks a bit like this:               Transpose@{Partition[List[[All,1]],1],List[[All,2]]}      where I separate the list into two and use partition to wrap all the first elements of list in a set of brackets and then transpose. As the list size increases the timing becomes a bit too nonsensical. Could someone suggest a faster method please or possibly direct me to the answer? Thanks in advance


title: Minimize failing on a polynomial

text: Calling:               Minimize[{-0.4877 - 0.1190 r^2 - 0.1885 r^4 + 2.9703 z - 0.5531 z^2,               0 <= z <= 3.5 ∧ 0 <= r <= 1.75}, {r, z}]      returns `{1.00051, {r -> 1.75, z -> 3.5}}`, when it's obvious that simply setting `r` and `z` to `0` yields `-0.4877`. Is this an issue of numerical instability? Is there anything that can be done about it?


title: Fast Spherical Linear Interpolation of list of quaternions

text: An accurate way to interpolate between two quaternions is to use Spherical Linear Interpolation (Slerp) because it preserves the unit length, whereas straightforward linear interpolation does not, as shown by this example:               Clear[slerp];     slerp[q1_, q2_, f_] := Module[{omega},       omega = ArcCos[Dot[Normalize@q1, Normalize@q2]]];       If[PossibleZeroQ[omega],          q1,         (Sin[(1 - f) omega] q1 + Sin[f omega] q2)/Sin[omega]       ]     ]          q1 = {1,0,0,0};     q2 = {0,1,0,0};     q3 = {0,0,1,0};          (* Linear interpolation using Interpolation *)     qint = Interpolation[{{0,q1},{1,q2}},InterpolationOrder->1];          Plot[{Norm@qint[t], Norm@slerp[{1, 0, 0, 0}, {0, 1, 0, 0}, t]}, {t, 0, 1},        AxesLabel -> {"time", "length"}, PlotRange -> {0.7, 1.01},        PlotStyle -> {Automatic, Dashed},        Epilog -> {Text["Linear Interpolation", {0.5, 0.75}],        Text["Spherical Linear Interpolation", {0.5, 0.98}]}     ]      ![Mathematica graphics](http://i.stack.imgur.com/SkKgL.png) What's nice thing about `Interpolation`, however, is that it is easy to give it a list of vectors to get an interpolating function valid over the specified range, and it works fast:               Interpolation[{{0,q1},{1,q2},{2,q3}},InterpolationOrder->1]      > InterpolatingFunction[{{0,2}},<>] How can I create something like an `InterpolatingFunction` that preserves the unit-length property? This is what I came up with, but it seems kludgy and it is very slow (this code does not check input bounds):               Clear[slerpInterpolation];      slerpInterpolation[q_List] := Function[{t},        Module[{times, quaternions, pos, u, dt},         times = q[[All, 1]];         quaternions = q[[All, 2]];         pos = Last@Flatten@Position[t - times, x_ /; x >= 0];         dt = times[[pos + 1]] - times[[pos]];         u = (t - times[[pos]])/dt;         slerp[quaternions[[pos]], quaternions[[pos + 1]], u]       ]     ]      It is too slow in practice, giving about 10 evaluations per second on my laptop. Compare that with regular interpolation:               qlist = Transpose[{Range[100000] - 1, Normalize /@ RandomReal[{-1, 1}, {100000, 4}]}];     sint = slerpInterpolation[qlist];     lint = Interpolation[qlist, InterpolationOrder -> 1];          AbsoluteTiming[Do[sint[541.236], {10}]][[1]]/10      > 0.0967707               AbsoluteTiming[Do[lint[541.236], {10000}]][[1]]/10000      > 7.2522*10^-6


title: How to write a UTF-8 file?

text: s = OpenWrite[ofile, CharacterEncoding -> "UTF8"]     Export[s, "∂f/∂t"]     Close[s]      did not successfully write `∂` into the file. Instead, it writes the `InputForm`. How to let it write `∂`?


title: FindRoot inside Table

text: **(MWE at the end of the post)** I need to solve a non-linear equation $f(y;x_1,x_2,..,x_5)$ in one variable $y$ and then compute 4 new output expressions, for over 60 different initial parameter inputs of $x_i$. The 4 output variables which are as follows: $g_m(y,x_1,..,x_5) \; \forall m$ The main equation will solve for the variable $y(i)$: $f(y(i),x_1(i),x_2(i),...,x_5(i))=0 \; \forall \; i \in \\{1,60\\}$ Now my $f(y(i),x_1(i),x_2(i),...,x_5(i))=A1(y,x_1,..,x_5)*y^{k_1} + B1(y,x_1,..,x_5)*y^{k_2}-c1(x_1,..,x_5)$ I define variables               A1=A1(y,x1,..,x5);     B1=B1(y,x1,..,x5);     c1=c1(x1,..,x5);      g1=g1(y,x1,..,x5);     g2=g2(y,x1,..,x5);     g3=g3(y,x1,..,x5);     g4=g4(x1,..,x5);      I have data for $x_1(i),..,x_5(i)$ in a CSV file that I Import and Table straight into the variable names making them into lists.               datatemp = Import["C:\\Documents\\2012U26G0.csv"];     j = Dimensions[datatemp][[1]]     kk=2     x1 = Table[datatemp[[i, 3]], {i, kk, j}]     x2 = Table[datatemp[[i, 4]], {i, kk, j}]     x3 = Table[datatemp[[i, 5]], {i, kk, j}]     x4 = Table[datatemp[[i, 6]], {i, kk, j}]     x5 = Table[datatemp[[i, 7]], {i, kk, j}]      I think this automatically makes my earlier defined formulae for $A1$,$B1$ and $g_m$ into a list of formulae with the only unknown being $y$ and it makes $c1$ into a list of constants since $c1$ was only dependent on $x_i$. Now, what I would like to be able to do is the following. Give some initial search point for my FindRoot for $i=1$               sol={1,1,1,1,120}      As you will see in a second, I only care about               sol[[5]]      Due to continuity, the roots move monotonically with $i$ so once I find one root, I can get a sense of where to look for the next one so I substitute the previous solution into the search for the next one. Also, in one shot I compute the 4 output variables I need. So when the Table is run, in one shot I have all the output data I want.               outputdata=Table[sol={g1,g2,g3,g4,y} /. FindRoot[ A1[[i]]*(y[[i]])^(k1) + B1[[i]]*(y[[i]])^(k2)==c[[i]] , {y, sol[[5]]+10, sol[[5]], sol[[5]]+20}], {i,1, 60}]      This process worked for a charm for little while but for a certain parameter space (by parameter I don't mean the $x_i$ I used earlier but a host of $\gamma$s and$\beta$s in my equations that I have suppressed so far), it has started giving me errors, 1/0 infinity type stuff, because of some assignment issues. Is there a clean and correct/good way to do this? I wanna be able to import a ton of data, Table my findroot to compute a whole bunch of data and Export it real fast. Please please please help! _**MWE_**               f = y^(3.1276)*(A1) + y^(-0.5875)*(B1) + (c1)^2;     A1 = x1/y + x2*y + 3*x3;     B1 = x1*x3 + 1/(y*x2);     c1 = x1^3 + x2^5 - x3;     g1 = y^(x1) - x3*x2;     g2 = x1/y;      Imported Data Below:               x1 = {89, 88, 87}     x2 = {0.048334203`, 0.048515211`, 0.048707816`}     x3 = {-19486.2273`, -19742.04035`, -20016.22863`}      When I do this, I can see what the curves look like:                Plot[Table[y^(3.1276)*(A1[[i]]) + y^(-0.5875)*(B1[[i]]) + (c1[[i]])^2, {i, 1,       3}], {y, 150, 180}]      ![enter image description here](http://i.stack.imgur.com/EBvBq.jpg) This is what I want to do. To be able to Table a whole bunch of output in one shot:               dataoutput=Table[{g1[[i]], g2[[i]], y} /. FindRoot[y^(3.1276)*(A1[[i]]) +      y^(-0.5875)*(B1[[i]]) + (c1[[i]])^2, {y, 165, 150, 170}], {i, 1,      3}]      This is the result that I get, with some errors about accuracygoal and precisiongoal.               {{1623.03, -6.88842*10^19, 167.181}, {1530.37, -5.38632*10^19,       163.049}, {1431., -4.18019*10^19, 158.952}}      My MWE is working, just like my actual problem worked for a certain parameter space but now I am running into trouble. Is there a good way to Import a ton of Data, Table my FindRoot and generate a ton of output using Table and then Export my results? Thanks.


title: Contexts after Cell Grouping

text: I'm trying to separate my document into cell groups, each with their own context (much like the style of code isolation described by the answer here: Localizing variables within a Manipulate), but the I can't get the grouped cells to share a context, even though Notebook's Default Context is set as "Unique to each cell group." I have a simple example. The linked notebook appears as a single cell group (when I look at the grouping bars along the right side of the window), but multiple calls of `Print[$Context]` yield different results. It seems like, once a cell has been created, it's context doesn't change even if I adjust the grouping. What is going on in the simple example I posted, and is there a way to fix these weird context differences/prevent them from happening? Thanks!


title: How to populate a table using a rule replacement

text:
I am trying to populate the rows and columns of a table by using a rule replacment. To generate a table that looks like this ![enter image description here](http://i.stack.imgur.com/asCQa.jpg) For example Sc would be row 1, column 1. An example of a record looks like this                rawData = Import["H:\\allresults.json"]               record = {19, 60, "Ag", "Ag", "19Ag@60Ag_npo: -186.503305 by solar
 \     19Ag@60Ag_bnp: -180.812004 by solar
 O_sng:-8.032213 by \     marco
", "-1.675194475", "Binding Energy", "solar"}      Then I extract the relevant entries with some functions (there is probably a more elegant way to to do this)               getRow[resultVector_] := resultVector[[3]];     getColumn[resultVector_] := resultVector[[4]];     getResult[resultVector_] := resultVector[[5]];     getResultType[resultVector_] := resultVector[[7]];      For example               getRow[record]      gives               Out[41] = Ag      I have a list of replacemnt rules               elementList = {"Sc" -> 1, "Ti" -> 2, "V" -> 3, "Cr" -> 4, "Mn" -> 5,        "Fe" -> 6, "Co" -> 7, "Ni" -> 8, "Cu" -> 9, "Zn" -> 10, "Y" -> 11,        "Zr" -> 12, "Nb" -> 13, "Mo" -> 14, "Tc" -> 15, "Ru" -> 16,        "Rh" -> 17, "Pd" -> 18, "Ag" -> 19, "Cd" -> 20, "Lu" -> 21,        "Hf" -> 22, "Ta" -> 23, "W" -> 24, "Re" -> 25, "Os" -> 26,        "Ir" -> 27, "Pt" -> 28, "Au" -> 29, "Hg" -> 30}      I would like to build a table where the location in the table gets identified, and the corresponding result gets put into that location of the table. For example Ag, Ag (row, column) should put "-1.675194475" in location (19,19) (row, column) of a table. Is there a better way to do this than with replacement rules? * * * Update: Here is my current implementation to see all my data:               elementList = {"Sc" -> 1, "Ti" -> 2, "V" -> 3, "Cr" -> 4, "Mn" -> 5,       "Fe" -> 6, "Co" -> 7, "Ni" -> 8, "Cu" -> 9, "Zn" -> 10, "Y" -> 11,        "Zr" -> 12, "Nb" -> 13, "Mo" -> 14, "Tc" -> 15, "Ru" -> 16,        "Rh" -> 17, "Pd" -> 18, "Ag" -> 19, "Cd" -> 20, "Lu" -> 21,        "Hf" -> 22, "Ta" -> 23, "W" -> 24, "Re" -> 25, "Os" -> 26,        "Ir" -> 27, "Pt" -> 28, "Au" -> 29, "Hg" -> 30};      I create lists of data for different particle sizes and energy types               data = Import["H:\\allresults.json"];     atoms32 = Select[data, StringCases[#[[1]], "32"] != {} &];     atoms79 = Select[data, StringCases[#[[1]], "60"] != {} &];     atoms32Binding =        Select[atoms32, StringCases[#[[1]], "Binding"] != {} &];     atoms32Cohesive =        Select[atoms32, StringCases[#[[1]], "Cohesive"] != {} &] ;     atoms79Binding =        Select[atoms79, StringCases[#[[1]], "Binding"] != {} &];     atoms79Cohesive =        Select[atoms79, StringCases[#[[1]], "Cohesive"] != {} &];     mat = Outer[List, elements, elements];      Is there a more elegant way to do this? I intend to do more energy calculations of different types in the future (vacancy formation energy etc). Is it possible to write it such that the data is automatically partitioned out into lists for each size and type?               rules79Binding =        Cases[atoms79Binding, {__, "M1" -> e1_, "M2" -> e2_, __,           "result" -> val_, __} :> {e1, e2} ->           ToExpression@val, \[Infinity]];     rules79Cohesive =        Cases[atoms79Cohesive, {__, "M1" -> e1_, "M2" -> e2_, __,           "result" -> val_, __} :> {e1, e2} ->           ToExpression@val, \[Infinity]];     rules32Binding =        Cases[atoms32Binding, {__, "M1" -> e1_, "M2" -> e2_, __,           "result" -> val_, __} :> {e1, e2} ->           ToExpression@val, \[Infinity]];     rules32Cohesive =        Cases[atoms32Cohesive, {__, "M1" -> e1_, "M2" -> e2_, __,           "result" -> val_, __} :> {e1, e2} ->           ToExpression@val, \[Infinity]];       This also suffers from exactly the same repetitive line with the only thing that changes between the lines is the list. Finally I plot all the data               ArrayPlot[mat /. rules79Binding /. {_, _} -> 0,       ColorFunction -> (Blend[{Blue, Red}, #] &),       ColorRules -> {0 -> White}, Mesh -> True, Frame -> True,       FrameTicks -> ({#, #} &@Transpose@{Range@Length@elements, elements}),       PlotRangePadding -> None, ImageSize -> 500,       PlotLabel -> "19M1@60M2 Binding Energy"]     ArrayPlot[mat /. rules79Cohesive /. {_, _} -> 0,       ColorFunction -> (Blend[{Blue, Red}, #] &),       ColorRules -> {0 -> White}, Mesh -> True, Frame -> True,       FrameTicks -> ({#, #} &@Transpose@{Range@Length@elements, elements}),       PlotRangePadding -> None, ImageSize -> 500,       PlotLabel -> "19M1@60M2 Cohesive Energy"]     ArrayPlot[mat /. rules32Binding /. {_, _} -> 0,       ColorFunction -> (Blend[{Blue, Red}, #] &),       ColorRules -> {0 -> White}, Mesh -> True, Frame -> True,       FrameTicks -> ({#, #} &@Transpose@{Range@Length@elements, elements}),       PlotRangePadding -> None, ImageSize -> 500,       PlotLabel -> "6M1@32M2 Binding Energy"]     ArrayPlot[mat /. rules32Cohesive /. {_, _} -> 0,       ColorFunction -> (Blend[{Blue, Red}, #] &),       ColorRules -> {0 -> White}, Mesh -> True, Frame -> True,       FrameTicks -> ({#, #} &@Transpose@{Range@Length@elements, elements}),       PlotRangePadding -> None, ImageSize -> 500,       PlotLabel -> "6M1@32M2 Cohesive Energy"]      I have not put pictures up of each plot so that I do not make the post too long. Also, How can I map specific numerical values over color gradients. For example, for the binding energies, {-1,-2} blends through green. {-2,-3} blends through yellow {-3,-5}, blends through orange, {-5, -10} blends through red, and {-10, infinity} is black.


title: How to replace plus sign by comma

text: I want to replace plus by comma and the order of numbers in the list should be in increasing order. Example:               a1 + a10 + a11 + a13 + a2 + a27 + a28      In this expression, I want to replace plus sign by comma and delete "a". To get a list of numbers and the order should be               {1,2,10,11,13,27,28}      I have tried this, but it's not convenient...               StringReplace["a1 + a 10 + a 11 + a 13 + a2 + a27 + a28" , "+ a" -> ","]


title: Why don't I get numeric values from this Solve?

text: Solve[ a^2 + b^2 == c^2 && a < 100 && b < 100 && c < 100, {a, b, c}, Integers]      gives me this result > >     {{c -> ConditionalExpression[-Sqrt[ a^2 + b^2], >              ((a | b | c) ∈ Integers &&  Sqrt[10000 - a^2] - b > 0  && -99 > <= a <= -1) || >              ((a | b | c) ∈ Integers &&  Sqrt[10000 - a^2] - b > 0  &&   1 > <= a <= 99) || >              ((a | b | c) ∈ Integers &&  Sqrt[10000 - a^2] + b <= 0 && -99 > <= a <= -1) || >              ((a | b | c) ∈ Integers &&  Sqrt[10000 - a^2] + b <= 0 &&   1 > <= a <= 99) || >                   ...           ] },   ...  } >   where I would expect something like > >     {{x -> 3, y -> 4, z -> 5}, {x -> 4, y -> 3, z -> 5}, {x -> 5, y -> 12, z > -> 13},...} >   What am I doing wrong?


title: Extracting the coordinate of a particular point of interest from a ListPlot

text: Is there a way to obtain the coordinate of a point of interest in a `ListPlot`? As an example, I have a list containing many sets of 2D coordinates and the plot drawn is discontinuous at one point (the first derivative is not continuous and the gradient increases suddenly). Can I extract the location of that point interactively? Otherwise, I have to search through the list of data myself to determine the change of gradient, which defeats the whole purpose of drawing a plot. Also, using the Get Coordinates function from the right click menu does not give very accurate results.


title: Associating symbol pages with symbols (Workbench)

text: Normally when you have symbol Abc, WorkBench creates a symbol page named _Abc_. Then when you make a build, type Abc and then press the F1 key, you are sent to the Abc symbol page. Suppose however that you want to type a string , say _xyz_ , but on pressing F1 you want to go to symbol page Abc or, at least, be given Abc page among the search results. Is this possible? I think it might be. For example, type the exclamation mark (!) and then F1. You are given the choice between the _Factorial_ , _Not_ and _Run_ pages. How were these associations made? In other words: is it possible to intercept the F1 action? Or somehow indicate for a symbol page which search strings are appropriate? Or use some other hack to obtain this effect?


title: Attaching a legend to BallAndStick picture

text: I am looking for a way to add a legend showing the identity of various atoms (with different colours) to this picture. Any Clues?               Import["ExampleData/1PPT.pdb", "Rendering" -> "BallAndStick"]      ![enter image description here](http://i.stack.imgur.com/FSFoH.png)


title: How to create a Table of Tables with indexed variables

text: I want to use concise code to generate a table of values that list the addition of a set of vectors. What I am looking for is essentially a Table of Tables. I will show here the kind of lists I want, which I am able to generate individually. First, let's define a set of say 6 vectors (an ordered pair):               H = Table[{Cos[n*Pi/3], Sin[n*Pi/3]}, {n, 0, 5, 1}];      This will be our first Table. Next, I want to get all vectors that result from adding any two vectors in H together:               H2 = Table[H[[i1]] + H[[i2]], {i1, 1, 6, 1}, {i2, 1, 6, 1}];      Now we create another Table, but this time with all vectors that result from choosing three vectors from the set H and adding them together:               H3 = Table[H[[i1]] + H[[i2]] + H[[i3]], {i1, 1, 6, 1}, {i2, 1, 6, 1}, {i3, 1, 6, 1}];      Suppose we were to continue creating tables like this with arbitrarily many sums of this type. How can I create one single Table that would combine them all? I am aware that I can use some function like Append to join them all together after each one has been generated, but I am looking for something more efficient that can be done a single cell. I have something in mind along the following lines (note that this is not properly functioning code, but I am writing it for illustrative purposes). It would be nice to be able to generalize these Tables using something like this, where I've attempted to index the variables (incorrectly?):               H[N_] =      Table[     Sum[ H[[i_j]] , {j, 1, N, 1}],     {i_1, 1, 6, 1}, {i_2, 1, 6, 1}, ... {i_N, 1, 6, 1}] ;      Then I could create a single table with say 10 iterations using:               Table[ H[N],{N,1,10,1}]      Unfortunately, I am unable to index variables in this way because Mathematica tells me the variable names are "Protected". How can I get around this?


title: How to order legend in Show?

text: I've asked this question in Wolfram community and have not received a response. I am wondering why when I use `Show` to combine 6 plots, the plot legend does not show in order? The order should be 150, 250, 350, 450, 550, 650. However when I step through `Show` adding one plot at a time, I notice that _Mathematica_ does something weird with the order of the legend, and in the end the order is 650, 150, 250, 350, 450, 550. How can I get the order of the Legend or Show to be correct, such that there is a logical sequence of the label? I have attached some code below to show what's happening:                data = {          {0., 23.1628, 15., 12., 5., 2., .75, 0.0},          {0., 53.611, 100., 83.27448, 40., 33., 25., 10.0},          {0., 71.7055, 100., 79, 72.996, 30.76314, 17., 15.},          {0., 71.92428, 100., 100, 83.35182, 41.09816, 35., 10.0},          {0., 75.87498, 100., 100., 88.65755, 87.0691, 34.27131, 20.},          {0., 100., 100., 100., 88.65755, 87.0691, 80.4311, 39.40}          } // TableForm;          time = {0., 120., 300., 600., 900., 1200., 1500., 1800.};          activity = Table[Transpose[{time, data[[1, i]]}], {i, 1, 6}];          tickSpecs = {{{0, "0"}, {120, "2"}, {300, "5"}, {600, "10"}, {900,          "15"}, {1200, "20"}, {1500, "25"}, {1800, "30"}}, Automatic};          label = {"150 ", "250 ", "350 ", "450 ", "550 ", "650 "};     colors = {Black, Red, Orange, Green, Blue, Purple, Magenta};               Plots = Table[          ListPlot[activity[[i]],              PlotRange -> All,              PlotStyle -> {Darker[colors[[i]]], Dashing[{0.05}], Thick,           AbsolutePointSize[12]},         Joined -> True,         Mesh -> All,         Ticks -> {Automatic, None},         FrameTicks -> tickSpecs,         Frame -> {Left, Bottom},         FrameStyle -> Thick,         Axes -> False,         LabelStyle -> {FontSize -> 20, FormatType -> Bold},         ImageSize -> 450,         PlotLegends ->          LineLegend[{label[[i]]},           LabelStyle -> Directive[Bold, 15],           LegendMarkerSize -> Automatic]],     {i, 1, 6}];          Show[Plots]


title: RegionPlot giving an "invalid comparison" error

text: I am trying to use `RegionPlot` in _Mathematica_ and I am stuck because I am getting an invalid comparison error. I am trying to evaluate the following code:                   Manipulate[      RegionPlot[{(         X Log[((-8 + X (8 + γ) + Sqrt[              64 - 128 X + X^2 (64 + γ^2)]) (-8 (-1 + X) y0 +               X z0 (-8 + 8 X - X γ + Sqrt[                 64 - 128 X + X^2 (64 + γ^2)])))/((8 -               X (8 + γ) + Sqrt[              64 - 128 X + X^2 (64 + γ^2)]) (8 (-1 + X) y0 +               X z0 (8 + X (-8 + γ) + Sqrt[                 64 - 128 X + X^2 (64 + γ^2)])))])/Sqrt[         64 - 128 X + X^2 (64 + γ^2)] >          0, ((-8 + X (8 + γ) + Sqrt[            64 (-1 + X)^2 + X^2 γ^2])^2 (-8 (-1 + X) y0 +             X z0 (-8 - X (-8 + γ) + Sqrt[               64 (-1 + X)^2 + X^2 γ^2])))/((8 - X (8 + γ) +             Sqrt[64 - 128 X + X^2 (64 + γ^2)])^2 (8 (-1 + X) y0 +             X z0 (8 + X (-8 + γ) + Sqrt[               64 (-1 + X)^2 + X^2 γ^2]))) >          Exp[-(8 - 8/X + γ)*(           X Log[((-8 + X (8 + γ) + Sqrt[                64 - 128 X + X^2 (64 + γ^2)]) (-8 (-1 + X) y0 +                 X z0 (-8 + 8 X - X γ + Sqrt[                   64 - 128 X + X^2 (64 + γ^2)])))/((8 -                 X (8 + γ) + Sqrt[                64 - 128 X + X^2 (64 + γ^2)]) (8 (-1 + X) y0 +                 X z0 (8 + X (-8 + γ) + Sqrt[                   64 - 128 X + X^2 (64 + γ^2)])))])/Sqrt[           64 - 128 X + X^2 (64 + γ^2)]]}, {z0, -(1 - X^-1),         2*(1 - X^-1)}, {y0, -(X - 1), 2*(X - 1)}, Frame -> True,        FrameTicks -> Automatic, BaseStyle -> {FontSize -> 30},        PlotStyle -> {Directive[Orange, Opacity[0.4]],          Directive[Green, Opacity[0.4]], Directive[Blue, Opacity[0.4]]},        Evaluated -> True], {X, 1.01, 10, Appearance -> "Open"}, {γ,        0.1, 100, Appearance -> "Open"}]          I want to evaluate the second inequality only if the first equality is satisfied, or something like that, so the code will evaluate without producing an error message.


title: Finding similar expressions in list

text: I have a function that returns to me lists of expressions, like:               I (a^2 + b^2) (* 1 *)     a (I b + e)   (* 2 *)     b (I a + d)   (* 3 *)     b (I a + f)   (* 4 *)     a b           (* 5 *)     a (I b + f)   (* 6 *)     I (b^2 + c^2) (* 7 *)      The expressions can become arbitrary complex. Now I want a function that returns to me that expression 2,3,4,6 as well as 1,7 are similar, because one can just rename the variables. I have absolutly no idea how to solve this problem, and would be very happy for any hint in the right direction. **Update on _similarity-criterion_** Similar means:                a -> b, c, d, e, f, ... zzzz, SomeVar1, ...      (If it is simpler, for the moment one can assume that the list of variables can be only a,b,c,d,...,z = 26 lowercase letters). It must not transform the structure of the equation, for instance:                a (I b + e)      Here, _a_ cannot become _b_ or _e_ , _b_ cannot become _a_ or _e_ , _e_ cannot become _a_ or _b_ , i.e. all of them must be different. All terms a, b, c, d are simple variables, and cannot become Sin[a], Tan[b], 1/c, ... Examples:   * `a (I b + e)`, `b (I a + d)`, `b (I a + f)`, `a (I b + f)` are all similar   * `a^2 + b` and `a + b^2` are similar   * `a (c + d) + b (c + e)` and `a (c + d) + b (e + f)` are not similar because `c` is repeated in the first one but not the second one


title: DateListPlot with two time list adding 2 labels, and setting the color of the label and lines in plot

text: This command will produce a chart with two lines on it.               DateListPlot[{CapReg, Equity},  Joined -> True ]      What I would like to do is add a label above the chart "CapReg" in red, and a label below the chart "Equity" in blue. Then I would like to have the color of the `CapReg` line be red, and the line for `Equity` be blue. Any ideas? Many thanks in advance.


title: In lambda calculus, can the parameter of abstraction be a non-variable lambda expression?

text: In short, my main confusion is between the two concept `variable` and `lambda expression`: I am reading this reference here: > The syntax of (pure) lambda expressions is defined as follows: > >   1. A variable is a lambda expression (we will use single, lower-case > letters for variables). >   2. If M and N are lambda expressions, then so are each of the following: > > a) (M)   >  b) λid.M   >  c) MN > > > > We can express the rules given above that define the language of lambda > expressions using a context-free grammar: exp → ID | ( exp ) | λ ID . exp // > abstraction | exp exp // application From rule #1 and the context-free grammar, I think the author means that `ID` refers to `variable`, and `variable ∈ lambda expression`. But I am not sure whether `lambda expression ∈ variable`. Question:   May I know whether I can use a "complex" expressions (e.g. a non-variable lambda expression) as `id` in `λid.M`? Intuitively, I interpret `variable` represented by an ID with a single letter, but I could not find reference to support my conjecture. (or in other words, how is `variable` defined in lambda calculus, if this is not too broad a question?)


title: How to do symbolic definite integral without copy and paste the intermediate results?

text: I am do a symbolic definite integral, I am doing it like this:               Integrate[1/Sqrt[(ϵ + u)^2 + Δ^2], ϵ] // FullSimplify      It gives an output:               Log[u + ϵ + Sqrt[Δ^2 + (u + ϵ)^2]]      then I **copy** this output and define a function respect to the integrate variable:               F2[ϵ_] := Log[u + ϵ + Sqrt[Δ^2 + (u + ϵ)^2]]      Finally I can substitute the upper and lower limit to `F2` and obtain my results:               F2[ξ - u] - F2[m]      I don't like the **manually** copy step. So how do you do this **automatically**?


title: Mathematica does not export Turkish characters in a Graphics expression

text: When I export the following `Graphics` expression as a _PDF_ (or _EPS_ ) file, the _Turkish_ characters _ü_ and _ç_ do not appear.               Graphics[Text[Style["Türkçe", 72, Background -> White], {0, 0}]]       Is it possible to fix this? Here is how it looks in _PDF_ file.   ![1](http://s2.postimage.org/qyd9be995/turkce.jpg)


title: Unexpected behavior of PasteButton

text: Assume the following very complex palette:               CreatePalette[       PasteButton[FontColor -> RGBColor[1, 0, 0]]     ];      Its purpose is to insert a `FontColor` rule. It works like expected in a notebook but I plan to use it inside raw cell expressions. Please try the following two examples. Paste the following code into a notebook               NotebookWrite[      SelectedNotebook[],      Cell[Cell["abc", "Text"]]      ]      You get a text cell saying "abc". Now go with the cursor anywhere between the "abc" and press `Ctrl+Shift+E` (this is _Cell->Show Expression_ ) to see the underlying cell data. Go directly in front of the last closing bracket, make a comma and press the palette-button. You should get               Cell[BoxData[      FormBox["abc", Text]],FontColor->RGBColor[1,0,0]]      Pressing `Ctrl+Shift+E` again and the text is red. Works like a charm. Now try the following cell with the same approach:               NotebookWrite[      SelectedNotebook[],      Cell[StyleData["StandardForm"]]      ]      Here I get (Linux 64, Mma 8.0.4)               Cell[StyleData["StandardForm"],       RowBox[{"FontColor", "->", RowBox[{"RGBColor", "[",        RowBox[{"1", ",", "0", ",", "0"}], "]"}]}]     ]      which is not what I expected and which does not work. **Question:** Can anyone explain me what's going on here? Is the `PasteButton` aware of the context? **Background:** The background is, that I have created a palette which I want to use to adjust style-sheet definitions. That was, when I stumbled over this behaviour. **Fix:** One possible way to fix this is to use `NotebookWrite` directly instead of the `PasteButton`. Disadvantage of this approach is, that the expression can no longer be inserted into a normal notebook, because there you have to insert cell-expression.


title: Making a Mathematica package manager?

text: I'd like to get a serious discussion started about a package manager. This has come up elsewhere, and many people have implemented their own solutions. It would be nice to have a standardized way to deploy and distribute Mathematica code to anyone. I also imagine we could distribute other content this way. For example, one thing I think would be nice, if there were interest, would be to collate information from this site and serve it as a package that includes tools and supplemental documentation. Please share your ideas on how we can achieve this.


title: How to extrude a 3D image from a binary 2D image

text: I'm trying to extrude a nice 3D form from the 2D binary image below using the code posted, but I haven't had any luck in figuring out the error that's keeping `GraphicsComplex` from running. The end result should be the 3D points and a plot. Any help would certainly be appreciated! ![my 2D binary Image](http://i.stack.imgur.com/UWO6k.png)                 pts= ImageData[testimage];       twoD = Rescale[Table[Thread[{pts[[i]], pts[[i]]}], {i, 1, Length[pts]}]];           extrude[pts_, h_] := Module[{vb, vt, len = Length[pts], nh, shape},      If[! NumericQ[h], nh = 0., nh = N@h];      vb = Table[{pts[[i, 1]], pts[[i, 2]], 0}, {i, len}];      vt = Table[{pts[[i, 1]], pts[[i, 2]], nh}, {i, len}];      shape =        GraphicsComplex[        Join[vb, vt], {Polygon[Range[len]],          Polygon[Append[           Table[{i, i + 1, len + i + 1, len + i}, {i, len - 1}], {len, 1,          len + 1, 2 len}]], Polygon[Range[len + 1, 2 len]]}]      ]


title: How do I find all the possible events that work with EventHandler?

text: The `EventHandler` documentation, More Information section, lists 5 mouse events:               "MouseClicked" "MouseDown" "MouseDragged" "MouseMoved" "MouseUp"      There is at least one other mouse event that can be used that is not listed in this documentation: `"MouseEntered"` How can I find out all the possible arguments that can be used as events for `EventHandler`? **Edit** Also in this answer we learn of an undocumented option `HandleShiftReturn` which works as a "name" with `MenuCommand`. From the documentation: {"MenuCommand","name"} menu command with specified name chosen How do we find out all the possible "names"? **Edit #2 19th June** I got a reply from tech support. They state that "MouseEntered" and "MouseExited" in the GUI Kit are different from the ones in `EventHandler` and the ones in `EventHandler` are not yet ready for public use hence not documented. I didn't get an answer to my request for a full list of events for `EventHandler` (that are public). **Edit #3 30th June** Contacted tech support again after this question. Tech support advise that there is no (documented) way to use the shift, option, control, and function keys with `EventHandler`. Further they said there is no way to use key combinations with `EventHandler`. Still no closer to getting a complete list of events.


title: How to efficiently import videos

text: I need to do frame-by-frame analysis of videos. I can import the video files I need, but each file is too large to import at once. I can use the `Import[fn, "Frames",{n}]` command to import images one-by-one, but this takes a long time once `n` gets large. For example, the first frame it takes 0.14 sec, but the 200th frame takes 2.2 sec. Mathematica seems to be reading from the start of the file each time I do this. Obviously, this will not work. Is there some way to speed this up. E.g. using streams? Or tricking Mathematica to use `ImageCapture` to get images from a video file instead of a webcam? Thanks


title: setting real parameters in Hamiltonian matrix

text: The following Matrix represents my Hamiltonian.               m = {{ B/2 - d - j/2 + a, (Sqrt[2]*j)/2, M}, {(Sqrt[2]*j)/2, B/2 + a, 0}, {M, 0, (-3*B)/2 - d + j/2 + a}      How can I define the variables used in matrix such that the Mathematica assumes as they are real. because with this matrix, mathematica gives complex eigenvalues but my eigenvalues are supposed to be real.


title: Is there a way to find out who is importing a package?

text: After calling some functions, if I look into `$ContextPath`, I can see that `JLink`` is in there. Is there a way to find out what sequence of functions calls (like a stack-trace) imported a particular package? Something like `FuncA` called `FuncB` which called `FuncD` which executed `Needs["JLink`"]`


title: How to optimally solve and generalize this Conway's Game of Life puzzle

text: I tried solving this using mma. I am aware of this command - **Cellular automata**. But i don't want to use that coz then there is no challenge. So below is how i did it and my question is can this be done with fewer lines of code (without resorting to _CellularAutomaton_ ). Also i wanted to generalize it to any initial condition. > I am representing the grid shown in the puzzle as a (n $\times$ m) matrix > such that all the live cells are represented by _1_ and the dead ones by > _0_. Also in this particular case we have $n = 26$ and $m = 27$. Then i > manually made a list of the initial condition given in the question. Here > each pair represents the $(ij)^{th}$ element having live cells.   > > >   * _[as a side note - can this process be automated - i mean finding this > list from that image given for the intial grid by some image processing]_ >               list = {{2, 6}, {2, 13}, {3, 23}, {3, 25}, {4, 3}, {4, 10},            {4, 9}, {4, 18}, {5, 18}, {5, 2}, {8, 11}, {8, 12},             {10, 10}, {10, 12}, {11, 11}, {12, 18}, {13, 2}, {14, 2}, {13,               23}, {14, 8}, {14, 23}, {16, 24}, {17, 25}, {18, 24},               {18, 18}, {18, 17}, {19, 12}, {20, 12}, {20, 3}, {20, 4}, {22,              24}, {23, 23}, {22, 17}, {23, 18}};      > The matrix $A_{n \times m}$ now contains the elements _1_ and _0_ > corresponding to the live and dead cells receptively.   >  $f^{ij}_{0}$ contains the $(ij)^{th}$ element of $A_{n \times m}$                 A[n_, m_] := SparseArray[# -> 1 & /@ list, {n, m}, 0]           Table[f[0][i, j] = A[26, 27][[i, j]], {i, 1, 26}, {j, 1, 27}];      > The recursive function which gives the next generation is:-               f[k_][i_, j_] := f[k][i, j] = Module[{n = 26, m = 27, neg},            findNeighbours[i, j] := Module[{},          f[k - 1][#[[1]], #[[2]]] & /@ {{i - 1, j - 1}, {i - 1,             j}, {i - 1, j + 1}, {i, j - 1}, {i, j + 1}, {i + 1,               j - 1}, {i + 1, j}, {i + 1, j + 1}}];             neg = Cases[findNeighbours[i, j], _Integer];              (* Apply the rules to the ij th element*)         Which[f[k - 1][i, j] == 1,               Which[Count[neg, 1] < 2,                val = 0, (Count[neg, 1] === 2 || Count[neg, 1] === 3), val = 1,                 Count[neg, 1] > 3, val = 0],                 f[k - 1][i, j] == 0,                 Which[Count[neg, 1] === 3, val = 1, True, val = 0]]                 ]      > Finally we can plot the results to see the answer which is 3 if the starting > generation is called $1^{st}$ generation.                  genaration[0] =           ArrayPlot[         Table[f[0][i, j] = A[26, 27][[i, j]], {i, 1, 26}, {j, 1, 27}], Mesh -> True];                  genaration[n_] :=           ArrayPlot[Table[f[n][i, j], {i, 1, 26}, {j, 1, 27}], Mesh -> True]            res = ListAnimate[genaration[#] & /@ Range[0, 3],               AnimationRate -> 0.5]      ![](http://i.stack.imgur.com/mgrZo.gif)


title: How to substitute the following conditions into an expression?

text: I have an expression: $p=a\;b\; x + b^2\; y + a\;c\; z$. I want to substitute $a\;b=1$, $b^2 = 2$ and $a\;c = 4$ to obtain $p = x + 2y + 4z$.   How can I tell _Mathematica_ to do that? I dont know how to start.


title: Choosing the units for plotting

text: I´m new to using units in Mathematica. I have read other similar posts about this issue but I haven´t found an answer so far. My problem is simple: I want to plot a certain function with a certain unit. In my case, I want a graphic in Angle - mm. I have this function depending on a.               f[a_]:=(1 - Cos[0.017 a])*(Quantity[45.2,"Millimeters"]) +      (Quantity[145.`, "Millimeters"])*(1-Sqrt[1 - 0.097 Sin[0.017 a]^2])      When I plot it using               Plot[Evaluate[f[a]], {a, 0, 720}]      I get a results which is 1/1000 times the correct one (which should be in mm), so I assume that it is being shown in m. But in general, there is no way to know in which unit the graphic is being shown. Or is there a way to do this? Thank you for the help.


title: Why does initialization slow down manipulate in this case?

text: I'm trying to manipulate a plot of function with some parameters. The function is a long expression, so I tried to put it inside the Initialization options of `Manipulate`. However, once I did that, the performance is really bad, compared to one that have the function explicitly written out. Here is a simplified version: Here is the original one:               Manipulate[      DensityPlot[       Re[( C10 Exp[I 2 τ] )/(0.1 - I (ω - C10/10)) + (          C10 Exp[I 4 τ] )/(0.1 - I (ω - C10/10)) + (          C10 Exp[I 8 τ] )/(0.1 - I (ω - C10/10))], {τ,         0, π}, {ω, -0.5, 0.5}, PlotRange -> All,        PlotPoints -> 60],      {{C10, 0.5}, 0.1, 1.}]      and here is the one with definition inside `Initialization` option:               Manipulate[      DensityPlot[       f[ω, τ, C10], {τ, 0, π}, {ω, -0.5, 0.5},        PlotRange -> All, PlotPoints -> 60],      {{C10, 0.5}, 0.1, 1.},       Initialization :> {f[ω_, τ_, C10_] :=          Re[( C10 Exp[I 2 τ] )/(0.1 - I (ω - C10/10)) + (            C10 Exp[I 4 τ] )/(0.1 - I (ω - C10/10)) + (            C10 Exp[I 8 τ] )/(0.1 - I (ω - C10/10))]}]      Here is the screenshot for comparison: ![enter image description here](http://i.stack.imgur.com/ApDeZ.gif) ![enter image description here](http://i.stack.imgur.com/0Rjk1.gif) They original one seems much faster than the later one. Why does this happen and how to solve it?


title: Where is the unit after a calculation?

text: I was playing with some of the new features, and when I type e.g.               Quantity[10, "ml"] + Quantity[250 - 100, "ml"]      I get               160 mL      as expected. But when I want to solve the following equation               Solve[Quantity[x, "ml"] Quantity[5, "mol"] + Quantity[250 - x, "ml"] Quantity[7, "mol"] ==     Quantity[250, "ml"] Quantity[6, "mol"], x]      I get               {{x -> 125}}      without any unit. But x actually is in mL. So I'm wondering what I am getting wrong, i.e. why don't I get mL here? thanks!


title: Close programmatically all cell groups in Mathematica?

text: Is it possible to collapse all cell groups in the current notebook? I tried               nb = SelectedNotebook[];     SelectionMove[nb, Before, CellGroup]     FrontEndTokenExecute["OpenCloseGroup"]      but nothing changes.


title: Is DateString supposed to be truncating seconds?

text: If I configure `DateString` to format dates as ISO dates with               $DateStringFormat := {"Year", "-", "Month", "-", "Day", "T", ":",            "Hour", ":", "Minute", ":", "SecondExact",            If[$TimeZone == 0, "Z", "UTC" <> ToString[$TimeZone]]}      I get truncated seconds, rather than rounded seconds               {2012, 10, 12, 21, 32, 22.5359} // DateString     2012-10-12T:21:32:22.535UTC-5.      This seems wrong. The result should either be               2012-10-12T:21:32:22.5359UTC-5.      or               2012-10-12T:21:32:22.536UTC-5.      Is it a bug, or am I misunderstanding `"SecondExact"` or `DateString`?


title: Can I plot a Parametric and Cartesian functions on same grid?

text: I am trying to make a simulation of an airfoil in Mathematica. The final coordinates of the airfoil are parametric, but some of the other things like chord line are f(x) functions. Is there any way that I can plot a normal function and a parametric function on the same graph? Thank you.