title: Any hidden keyboard shortcut for RightTeeArrow?

text: The Basic Math Assistant palette does not show a keyboard shortcut for RightTeeArrow. Is there some hidden key combination that results in the output? (Just hoping to be able to avoid having to reach for the mouse and move over.)


title: How to find the vertices of a regular tetrahedron? a dodecahedron?

text: My question is: how to find the coordinates of the vertices of regular tetrahedron and dodecahedron? I tried to find the coordinates of the vertices of a regular tetrahedron as the solutions of a certain polynomial system in $8$ variables, notating the vertices of a tetrahedron $S(0,0,1)$, $A(0,yA,zA)$, $B(xB,yB,zB)$, and $C(xC,yC,zC)$:               Reduce[     yA^2 + zA^2 == 1 &&     xB^2 + yB^2 + zB^2 == 1 &&      xC^2 + yC^2 + zC^2 == 1 &&      yA^2 + (zA - 1)^2 == xB^2 + yB^2 + (zB - 1)^2 &&      yA^2 + (zA - 1)^2 == xC^2 + yC^2 + (zC - 1)^2 &&      xB^2 + (yB - yA)^2 + (zB - zA)^2 ==                      xC^2 + (yC - yA)^2 + (zC - zA)^2 &&      xB^2 + (yB - yA)^2 + (zB - zA)^2 ==                      (xC - xB)^2 + (yC -yB)^2 + (zC - zB)^2 &&      xB^2 + (yB - yA)^2 + (zB - zA)^2 ==                       yA^2 + (zA - 1)^2,             {xB, xC, yA, yB, yC, zA, zB, zC}, Reals]      However, that code is spinning for hours without any output. A new idea is required. P.S. 12.12.13. The answer done with Maple can be seen at http://mapleprimes.com/questions/200438-Around-Plato-And-Kepler-Again. Because nothing but trigonometry is used, I am pretty sure all that is possible in _Mathematica_.


title: Linearity of a function in Mathematica

text: I have a function which has something like `myFunc[q,a state[c,d]]` `a` could be anything, and I want to tell _Mathematica_ that this part of the function is linear, so that the coefficient of `state[c,d]` can be taken outside so that it achieves this result `a myFunc[q,state[c,d]]` Can this be done? Why is this important? I'm doing simulations on quantum mechanics, and operators have to be linear with respect to numbers, and this is important to make calculations easier.


title: Hiding the Code in .CDF File

text: I downloaded the source code of a demonstration and modified it. Then saved it as a CDF file. When I re-opened this file (in _Mathematica_ or _CDF Player_ ), all of the code can be seen. How can I hide the code so that only the manipulation panel be shown? I want it to be seen just as the demonstrations on the website demonstration.wolfram.com. I searched this site but found no solution to my problem. By the way, I use _Mathematica_ 8.0.


title: How to solve a stiff nonlinear second-order ode?

text: I want to solve a nonlinear second order ODE as an initial value problem (IVP). Unfortunately, for certain values of first derivative at starting point I get a stiff-problem. I tried to overtake this issue looking at _Mathematica_ help, but those advices don't work in my case. My equation is the following: $$ \gamma(\lambda) \lambda_{zz} + \beta(\lambda) \lambda_z^2 + \tau(\lambda) = T_M $$ where $$ \varphi(\lambda) = a_0 + a_1 \lambda^2 + a_2 \lambda^2 + a_3 \lambda^3 + a_4 \lambda^4 \\\ \tau(\lambda) = \varphi'(\lambda) \\\ \gamma(\lambda) = - \frac{h_0^2}{12} \frac{\tau(\lambda)}{\lambda^5} \\\ \beta(\lambda)=\frac{1}{2} \gamma'(\lambda) $$               H0 = 1;     par = {            a0 -> 2.0377638272727268,            a1 ->  -7.105521894545453,            a2 -> 9.234000147272726,            a3 -> -5.302489919999999,            a4 -> 1.136247839999999           };          φ[λ_] := a0 + a1 λ + a2 λ^2 + a3 λ^3 + a4 λ^4 /. par;     τ[λ_] := φ'[λ];     γ[λ_] := -(H0^2/12) τ[λ]/λ^5;     β[λ_] := 1/2 γ'[λ];          TM = 0.0059225557575715015;          Eq = γ[λ[x]] D[λ[x], {x,2}] + β[λ[x]] D[λ[x],x]^2 + τ[λ[x]];          xL = 0;     xR = 1;          ym = 1.1666666666666892;     yp = 1;          SYSf = Flatten[NDSolve[{                     Eq == TM,                     λ[0] == ym,                     λ'[0] == yp                    }, λ[x], {x, xL, xR}]                   ]      $ym$ is the value of function in $x = 0$, and $yp$ the first derivative. If I set $yp = 2$ I get the following error: > NDSolve::ndsz: At x == -0.311892, step size is effectively zero; singularity > or stiff system suspected. >> NDSolve::ndsz: At x == 0.37944200653091864`, > step size is effectively zero; singularity or stiff system suspected. >> So I tried some advices written in the help:               Needs["DifferentialEquations`NDSolveProblems`"];     Needs["DifferentialEquations`NDSolveUtilities`"];          SYSf2 = Flatten[NDSolve[            {Eq == TM,             λ[0] == ym,             λ'[0] == yp},             λ[x], {x, xL, xR}, Method -> "StiffnessSwitching"]            ]      or               SYSf3 = Flatten[NDSolve[          {Eq == TM,           λ[0] == ym,           λ'[0] == yp},           λ[x], {x, xL, xR},            Method -> {"StiffnessSwitching", Method -> {"ExplicitRungeKutta", Automatic}}]          ]      but with no success. What can I do in order to set $yp \ge 2$? Petrus **\--- EDIT ---** I changed function definitions using SetDelay operator (:=).


title: Symbolic linear algebra

text: I would like to know how I can ask _Mathematica_ to expand (and simplify) such an expression : $$ (\alpha A + \beta B)^\top (\alpha A + \beta B) $$ where $\alpha,\beta$ are two real numbers and $A,B$ are vectors in $\mathbb{R}^{n}$. $A^\top$ denotes the transpose of $A$. I assume I must tell _Mathematica_ that $A$ and $B$ are vectors. Here is what I have tried :               $Assumptions = (A | B) [Element] Vectors[n];         $Assumptions = (a | b) [Element] Reals;     TensorExpand[ Transpose[a*A + b*B].(a*A + b*B) ]      and the output is :               a A.Transpose[a A + b B, {2, 1}] + b B.Transpose[a A + b B, {2, 1}]      Which is not what I expected since I would like the output to be : $$ \alpha^{2} A^\top A + 2 \alpha \beta A^\top B + \beta^{2} B^\top B $$


title: Performing matrix multiplications with a list

text: I have a question in regards to `PseudoInverse`. I have $A$, an $n\times 2$ matrix, and when I want to compute $(A^T A)^{-1}A$, by using `PseudoInverse`, _Mathematica_ is able to give me an answer for this. However If I want to compute $(A^T A)^{-1}$, I am not able to. Here are the data:               goog = FinancialData["goog", {2012}]; yahoo = FinancialData["yhoo", {2012}];     A = Transpose[{yahoo[[1 ;;, 2]], constant}] (*Where constant is a list of value 1(Intercept)*)     kik = PseudoInverse[A]\[Transpose]*goog[[1 ;;, 2]]     Total[kik[[1 ;;, 1]]] (*gives me the coefficient*)     and Total[kik[[1 ;;, 2]]] (*gives me the intercept.*)      Now I often get mathematical equations which is written as $c^Tc$, lets say that $c$ is a vector list, but _Mathematica_ always gives an error. where c=RandomReal[100, 100] And if we look at the data given here as x, if I want to compute $(xx^T)^{-1}$, how is this done? I am struggling with the understanding of matrices and I therefore need a good understanding of how _Mathematica_ deals with these situations, I am also very sure that this would benefit other _Mathematica_ users, based on the fact that the other students taking the same class as I, are struggling with exactly the same thing in _Mathematica_.


title: Understanding the computation of IntensityCentroid?

text: If I have an image `img`, and I ask `ComponentMeasurements` to return `"IntensityValues"` for the image:               m=MorphologicalComponents[Binarize[img]];     ivalues=ComponentMeasurements[{m,img},"IntensityData"];      How can I replicate the output of `ComponentMeasurements[{m,img},"IntensityCentroid"]`? The challenge I'm having is understanding how to interpret a calculated intensity centroid from `"IntensityValues"` in the context of larger image with the overlayed morphological component? Is it flipped or rotated? It would be fantastic to see an example going from the raw `"IntensityValues"` data to the output of `ComponentMeasurements[{m,img},"IntensityCentroid"]` for the same morphological component.


title: Mathematica with a Touchpad

text: I'm trying to make it so that you do not need to rely on keyboard presses to manipulate a 3D graphic. I've done some searching, but I can't find a way to make it so that Mathematica will recognize something else as equivalent to a Shift or Ctrl press. Anyone have any ideas on how I could make a 3D Graphic fairly interactive with only a touchpad? (Pinch-to-Zoom, Two-Finger Panning, etc.)? Thanks in advance. By the way, I'm running a Logitech T651 on a Mac (I am using the Mac- compatible touchpad). The Pinch feature on the touchpad currently causes all of Mathematica to be magnified, including any interfaces or lines of code. Not sure if this helps.


title: How to combine a set of Plots, including self-drawn Inset/Lines/Circles?

text: I have a set of 9 plots which should be combined into one plot. Each of these plots contains a `ListContourPlot`, some circles, lines and an `Inset` containing again a circle, some arrows and some text: ![enter image description here](http://i.stack.imgur.com/Ptfsx.png) I already tried to use Levelscheme mentioned in this Question: http://stackoverflow.com/questions/5818888/how-to-make-a-grid-of-plots-with-a- single-pair-of-framelabels In my first attempts with a dummy `ContourPlot` function it worked pretty fine, but as I tried to use it with my plots it got totally confused: ![enter image description here](http://i.stack.imgur.com/kEchx.png) I think the custom drawn lines/circles are the problem. I used pretty much the same code shown in the thread above:               Get["LevelScheme`"]          Figure[{Multipanel[{{0, 1}, {0, 1}}, {3, 3},     (*XFrameLabels->Text["x [mm]"],     YFrameLabels->Text["y [mm]"],*)     BufferB -> 3,     BufferL -> 3,     TickFontSize -> 18,     FontSize -> 18,     FontFamily -> "FrontPage",     XGapSizes -> 0,(*Abstände zwischen Plots*)     YGapSizes -> 0,     ExtendRange -> 0.05,(*erhöht Raum innerhalb des Frames*)     PanelLetterCorner -> {0.98, 1},     ShowTickLabelsExterior -> {True, True, False, False},     ShowPanelLetter -> False     ],          FigurePanel[{1, 1}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[1, 1]]],     FigurePanel[{1, 2}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[1, 2]]],     FigurePanel[{1, 3}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[1, 3]]],     FigurePanel[{2, 1},      PlotRange -> {{-range, range}, {-range, range}}, LabL -> Text["y [mm]"]],     RawGraphics[fullAngle[[2, 1]]],     FigurePanel[{2, 2}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[2, 2]]],     FigurePanel[{2, 3}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[2, 3]]],     FigurePanel[{3, 1}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[3, 1]]],     FigurePanel[{3, 2},       PlotRange -> {{-range, range}, {-range, range}}, LabB -> Text["x [mm]"]],     RawGraphics[fullAngle[[3, 2]]],     FigurePanel[{3, 3}, PlotRange -> {{-range, range}, {-range, range}}],     RawGraphics[fullAngle[[3, 3]]]          },     PlotRange -> {{-0.08, 1.01}, {-0.15, 1.01}},     ImageSize -> 600     ]      In a second attempt I found this thread: Do I have to code each case of this Grid full of plots separately? Also the posted function in Jens' answer works mostly pretty well. The only point is, that it also gets confused by the `Inset`-s in my graphs; the result looks like: ![enter image description here](http://i.stack.imgur.com/rzhaQ.png) So my questions are: Is it possible to use Levelscheme with my existing graphs, without modifying/redrawing them? Or is it possible to alter Jens' algorithm to make it fit to my insets? Or: any other suggestion, that lets me create the desired set of graphs. EDIT 1: you can easily reproduce the graph with the following code:                AngleInset[\[Alpha]_] := Show[Graphics[{Thick, Circle[]}],       Graphics[{ { Black, Thick, Arrowheads[Large],        Arrow[{{0, 0}, {1.1, 0}}]}, {Black, Thick, Arrowheads[Large],        Arrow[{{0, 0}, {0, 1.1}}] }}],      Graphics[{Thick, Circle[{0, 0}, 0.5, {0, (-\[Alpha] Degree)}]}],      Graphics[{Red, Thick, Arrowheads[Large],       Arrow[{{0, 0}, {Cos[-\[Alpha] Degree], Sin[-\[Alpha] Degree]}}]}],      Graphics[      Style[Text[       ToString[-\[Alpha] ] <> "\[Degree]", {0, -0.5}, {0, 0} ], 24]],      Frame -> True,      FrameTicks -> False      ];          ContourPlot[Sin[x]²+Cos[y]^2, {x, 0, 2 Pi}, {y,0,2Pi},     Epilog ->      Inset[AngleInset[90], {Right, Top}, {Right, Top}, 6,      Background -> White]]


title: NDSolve: ProcessEquations and Reinitialize with Piecewise functions

text: I am having trouble with using NDSolve`Reinitialize when the system consists of a pieceise function. If we define the ODE system                simplesys = {r'[t] ==      Piecewise[{{1, 0 <= t <= 10}, {0, 10 <= t <= 20}}, 0], r[0] == 0};      and process the equations with               state = First@NDSolve`ProcessEquations[simplesys, r, t]      this works perfectly fine. However, when I try to reinitilize the ODE system with a new initial condition               newstate = NDSolve`Reinitialize[state, {r[0] == 2}]      this fails with the message               NDSolve`Reinitialize::ntcs: Cannot solve constraint equations for initial conditions.      This is due to the piecewise function in the system, I haven't got this problem for other types of systems, it only occurs when I have piecewise function. How can I solve this issue?


title: More efficient way of generating list of occurrence counts?

text: Given a list, e.g., `target = {a, b, c, b, c, d, c, d, e, f, a, h, g}`, I want to generate a list containing the occurrence count of the corresponding element of the target list, e.g., `{1, 1, 1, 2, 2, 1, 3, 2, 1, 1, 2, 1, 1}` for the example target. Target elements can be pretty much anything: atoms, sublists, etc. I'm using `result = Module[{c}, c[_] = 0; ++c[#] & /@ #] &[target]` which works fine, but wonder if the wizards have a more efficient way. Update: Came up with this while 'cigar thinking':               result = Module[{ordarg, ord},          ordarg[[ord]] =            Flatten[Range /@ (Tally[ordarg = #[[ord = Ordering[#]]]][[All, 2]])];          ordarg] &[target];      On numeric/symbol/etc. items, this clobbers my original method by orders of magnitude with large lists. It is also 2-3+ times faster even then the most excellent compiled example provided below by L.S. Interestingly, my original method is faster than this or the compiled version for string/character data. (L.S./M.W. et al, perhaps you can illuminate this?) This is plenty fast for my needs, though I'm still of course interested in the real masters' ideas.


title: Map and Scan ignore HoldFirst

text: I am trying to write a simple function that takes a list of data and outputs it to a file. I'd like the name of the file to be the same as the variable that holds the list. It seems that giving a function the attribute HoldFirst solves this problem. For example:               a = 1;          ClearAll[printName];     SetAttributes[printName, HoldFirst];     printName[var_] := ToString@Unevaluated@var      When called, this returns               In: printName@a     Out: "a"      as expected. However, things get murkier when I try to Map this function over a list. For example:               In: a = 1;         b = 2;         c = 3;              l1 = {a, b, c};              printName /@ l1          Out: {"1", "2", "3"}      For some reason Map seems to ignore the attribute HoldFirst. Is there a reason for this? The closest I see in the documentation to an answer is this: "Map always effectively constructs a complete new expression and then evaluates it." But, I don't think this is the problem, because I see similar behaviour with Scan. Any insight would be appreciated. Thanks.


title: Correct fourier scaling and high-resolution frequency identification

text: I have a dataset of amplitude versus time $(t,A(t))$ and I need to extract the dominant frequency and amplitude, and also get the amplitude at one other specific frequency. My data looks like this:               data = {{-9.75, 13.76}, {-9.5, 14.352}, {-9.25, 15.66}, {-9.,  16.506}, {-8.75, 17.768}, {-8.5, 17.218}, {-8.25, 15.794}, {-8.,  13.18}, {-7.75, 11.58}, {-7.5, 10.524}, {-7.25, 8.428}, {-7., 6.544}, {-6.75, 4.408}, {-6.5, 2.586}, {-6.25,   0.274}, {-6., -2.194}, {-5.75, -4.982}, {-5.5, -6.224}, {-5.25, -9.698}, {-5., -12.22}, {-4.75, -13.986}, {-4.5, -15.372}, {-4.25, -15.1}, {-4., -15.47}, {-3.75, -14.088}, {-3.5, -13.388}, {-3.25, -12.424}, {-3., -12.506}, {-2.75, -11.83}, {-2.5, -9.886}, {-2.25, -8.066}, {-2., -7.434}, {-1.75, -5.23}, {-1.5, -2.418}, {-1.25,   0.252}, {-1., 2.726}, {-0.75, 5.184}, {-0.5, 7.668}, {-0.25,  8.684}, {0., 9.7}, {0.25, 11.866}, {0.5, 13.534}, {0.75, 15.05}, {1., 17.512}, {1.25, 17.99}, {1.5, 16.84}, {1.75,  15.154}, {2., 12.682}, {2.25, 10.358}, {2.5, 9.314}, {2.75, 9.07}, {3., 7.866}, {3.25, 5.244}, {3.5, 2.27}, {3.75, -0.564}, {4., -2.012}, {4.25, -3.078}, {4.5, -5.484},  {4.75, -8.834}, {5., -11.234}, {5.25, -13.162}, {5.5, -15.11}, {5.75,  -16.684}, {6., -16.588}, {6.25, -14.99}, {6.5, -14.336}, {6.75, -12.956}, {7., -12.44}, {7.25, -11.72}, {7.5, -10.854}, {7.75, -8.384}, {8., -6.082}, {8.25, -3.848}, {8.5, -1.772}, {8.75, 0.552}, {9., 3.186}, {9.25, 5.154}, {9.5, 6.976}, {9.75, 8.602}, {10., 9.042}}      And I would like to define a function that takes in account the $x$ scaling for proper scaling of the spectrum. The scaling has been discussed in other questions. But there are some issued that are stopping me. What I have is (mainly copied from here) :               xyF[d_] := Block[{n, t, y, dt, ft, fy},       n = Length[d];       t = d[[All, 1]];       y = d[[All, 2]];       dt = Tally[Differences[t]][[1, 1]];       fy = Abs@Fourier[y];       ft = RotateRight[Range[-n/2, n/2 - 1]/(n dt), n/2];       Sort[Transpose[{ft, fy}], (#1[[1]] < #2[[1]]) &]       ]      My questions are:   * What is the scaling if the number of points `n` is odd instead of even?   * How do I obtain a high-resolution estimation of the dominant frequency?   * How do I get the intensity of a frequency not explicitly given? (Other than interpolating, given that close to the peak that interpolation may be poor.)


title: Using Mathematica to help obtain correct analytic formula for logarithm integration

text: I need to program into my Mathematica code the analytic form for the result of the integral: $$I(a,b)=\int ^1 _0 dx \frac{\ln(x-a)}{x-b}$$ that is valid for all complex $a$ and $b$ (but $\text{Im } b\neq0)$. Following the steps that I posted in this math SE question, I arrived at $$\begin{aligned}I(a,b)&=\text{Li}_2\Big(\frac{-1+a}{a-b}\Big)-\text{Li}_2\Big(\frac{a}{a-b}\Big)\\\ &\qquad+\ln\Big(1+\frac{1-a}{a-b}\Big)\ln(1-a)-\ln\Big(1-\frac{a}{a-b}\Big)\ln(-a)\,.\end{aligned}$$ But this is only valid for a subset of $a$ and $b$ since I haven't paid attention to how the logarithmic cut of the integrand may be crossed by the integration contour. Indeed comparing the numerically integrated result with the analytic one I derived, there is a **wedge** in the complex $a$ plane (for fixed $b$) for which my formula is wrong:               (*Numerical integration and analytic formula*)     fnum[a_, b_] /; Im[a] != 0 := NIntegrate[Log[x - a]/(x - b), {x, 0, 1}];          fanal[a_, b_] = PolyLog[2, (-1 + a)/(a - b)] - PolyLog[2, a/(a - b)] +         Log[1 + (1 - a)/(a - b)] Log[1 - a] - Log[1 - a/(a - b)] Log[-a];      Now compare:               GraphicsRow[      {Plot3D[Im[fnum[x + I y, .4 + 2 I]], {x, -5, 5}, {y, -5, 5}],       Plot3D[Im[fanal[x + I y, .4 + 2 I]], {x, -5, 5}, {y, -5, 5}]}     ]      ![enter image description here](http://i.stack.imgur.com/5nuau.png) I have checked that the difference between `fnum` and `fanal` is indeed zero except inside the **wedge**. I'm desperately trying to get the analytic formula correct for all $a$ and $b$, but as evidenced by the math SE question I posted, my mathematical skills are simply not strong enough. I know that I must add/subtract $i\pi$ from the logarithms to select the right branch. But I don't know exactly what the conditions on $a$ and $b$ are. Is it possible for _Mathematica_ to help me out (basically picking up slack) in obtaining the more general analytic formula that is valid for _all_ complex values of $a$ and $b$, including inside the **wedge**?


title: Computing a sum

text: I'm trying to make Mathematica compute this sum:               Sum[(-1)^k (n - k)^2 Binomial[2 n, k], {k, 0, n}]      As is, I get an awful formula:               Sum[(-1)^k (n - k)^2 Binomial[2 n, k], {k, 0, n}] // FullSimplify      ![enter image description here](http://i.stack.imgur.com/mdKPV.png) Using Maxima, I get the (almost correct) result `0`, with `nusum((-1)^k*(n-k)^2*binomial(2*n,k),k,0,n);`. But for `n=1`, the result is `1`, so Maxima is a bit too aggressive here: ![enter image description here](http://i.stack.imgur.com/Ae1zR.png) So I try to add assumptions to Mathematica:               Sum[(-1)^k (n - k)^2 Binomial[2 n, k], {k, 0, n},        Assumptions -> Element[n, Integers] && n > 1] // FullSimplify     Refine[%, Element[n, Integers] && n > 1]      ![enter image description here](http://i.stack.imgur.com/xvqJ1.png) It's much better, but there is an obvious simplification, and I don't know how to make Mathematica "see" it. An hypergeometric series with a negative integer parameter is a polynomial, and here it's especially simple. `FunctionExpand` does not work either. However, we have really a `Hypergeometric2F1`, and if I write it explicitly, the simplification is possible:               -2 n Hypergeometric2F1[2, 1 - 2 n, 1, 1]     Refine[%, Element[n, Integers] && n > 1]      ![enter image description here](http://i.stack.imgur.com/P6T1U.png) Is there a way to make this a bit more automatic?


title: PDE problem with initial and boundary conditions

text: I'm new to mathematica and I don't know what I do wrong, I have written the following PDE problem, with both initial and boundary (four in total)               eq = D[u[x, t], t, t] + D[u[x, t], t] - 2*D[u[x, t], x, x] == 0     bc = {u[0, t] == 0, u[2*Pi, t] == 0, u[x, 0] == 0, Derivative[0, 1][u][x, 0] == sin (2*x)}          DSolve[{eq, bc}, u[x,t], {t, x}]      I need it to solve the PDE, but it doesn't even try to make a solution... what to do. I hope you can help me


title: Evaluation of a Variable Coefficient PDE

text: I am trying to render the solution of the following partial differential equation: $$ u = u(x,y)~;\quad \frac1{x^{2/3}}\partial_xu \+ x^3\partial_yu \+ \partial_y^2u \+ \partial_x^3u = 0 $$ However, the kernel seems to not produce anything. I checked documentation for different ways of inputting in the equation, but nothing helps. I even tried the sample problems directly from the documentation and those still had no explicit solution. I also quit the local kernel and repeated the process twice. I used something of the following:               eqn2 = D[u[x, y], {x, 3}] + D[u[x, y], {y, 2}] + x^3 D[u[x, y], y] +      1/x^(2/3) D[u[x, y], {x, 1}] == 0;          DSolve[eqn2, u, {x, y}]      Any ideas of what is going on?


title: Transform Piecewise[] into sum of indicators

text: I'm interested in transforming a piecewise defined function into a sum of indicator functions, ultimately with the aim to be better able to integrate them. As an example I would like to transform the function               f = Piecewise[{{x, 3*x > y && x < 2*y}, {y, 2*x > y && x < 3*y}}, 0]      into               x Boole[3 x > y && x < 2 y] + y Boole[x >= 2 y && x < 3 y].      For this specific example, this could be achieved by               f[[1,1,1]]Boole[f[[1,1,2]]] + f[[1,2,1]]Boole[f[[1,2,2]] && !f[[1,1,2]]]      but I don't know how to efficiently generalize this to functions with more than two cases, in particular how to ensure that the term corresponding to the $n$th case contains the negated conditions of the first $n-1$ cases. In a second step, assuming that the conditions of the piecewise function are linear inequalities, I would like to decompose each Boole[] into a sum of Boole[]'s of disjoint intervals for, say, the variable $x$. In my example above this would mean               Boole[3 x > y && x < 2 y] == Boole[y/3 < x < y/2]     Boole[x >= 2 y && x < 3 y] == Boole[2y < x < 3y]      This is maybe a trivial example, but in more complex situations one will have to deal with more than one disjoint interval. In non-Mathematica notation I'd like a decomposition of the form $$ f(x) = \sum_i f_i(x) \sum_j\mathbf{1}_{\left\\{x_{i,j}^{\min}<x<x_{i,j}^\max\right\\}}(x). $$ where the $f_i$ are given by `f[[1,All,1]]`.


title: Long waiting time for computing a summation

text: It takes a long time to compute the summation below, and I'd like to know if there are alternative ways   to compute things faster. When replacing $15$ by $\infty$, then I should get $3^{1/3}$. I need Mathematica solution   not mathematical solutions (since here I can handle things on my own).               Clear[b, k]     b[0] := 1;     b[k_] := b[k - 1] + 1/(b[k - 1]^2 + b[k - 1] + 1)     N[1/(15)^(1/3) Sum[1/(b[k]^2 + b[k] + 1), {k, 0, 15}]]


title: How would I improve this Karaoke machine code?

text: I was looking at a large collection of Import/Export user suggestions the other day and it dawned on me that we finally have MIDI import in Mathematica 9, which is rather interesting since MIDI supports karaoke text events, which can be run in Mathematica with scheduled tasks. So I wrote a simple code for a Karaoke machine function, which plays a given MIDI karaoke file and highlights the text that needs to be sung at the same time.               $DisplayEvents = {      {0.0, {Red, FontSize -> 18}},       {0.5, {Orange, FontSize -> 18}},       {1.0, {Gray, FontSize -> 18}}};          TextEvents[file_] := Module[{events},      events = Cases[Import[file, "Metadata"], {time_, "TextEvent" -> text_}, 2];      events = Select[events, Not[StringMatchQ[#[[2, 2]], "\\@*"]] &];      Map[{#[[1]], StringReplace[#[[2, 2]], {"\\" -> "\n\n", "/" -> "\n"}]} &,        events]];          ScheduleTextEvents[events_] := Module[{},      Outer[With[{e = #1, d = #2},       RunScheduledTask[        Unevaluated[displayEvent[e] = Last[d]], {Max[0.0, First[e] + First[d]]}]] &,       events, $DisplayEvents, 1]]          Cleanup[] := { Cell[MakeBoxes@Row[{      Button["Stop Music", Sound`StopMIDI[]; RemoveScheduledTask /@ ScheduledTasks[]],       Button["Close Notebook", NotebookClose[EvaluationNotebook[]]]}]]}          KaraokeMachine[file_] := Module[{lyrics, song, events},      song = Import[file];      events = TextEvents[file];      Map[(displayEvent[#] = {White, FontSize -> 18}) &, events];      CreateDocument[ ExpressionCell[       With[{t = events},        Dynamic[Row[With[{x = #}, Style[x[[2]], displayEvent[x]]] & /@ t]]],        "Output", ShowCellBracket -> False], Background -> Black,        WindowElements -> {"VerticalScrollBar"},        Deployed -> True, DockedCells->Cleanup[]];      EmitSound[song];      ScheduleTextEvents[events];     ]      Which can then be called by giving it a karaoke file (for example this song by Frank Sinatra):               KaraokeMachine[ "myway.kar"]      My question mostly revolves about ideas on how I can improve on this (code improvements as well as suggestions on how to implement features, like fading in/out text). (Note: Mathematica uses the Jlink/Java MIDI implementation on MacOSX, which means that you may run into this issue on newer versions of MacOSX. I haven't been able to find a solution for this yet).


title: How can I type-check the arguments of a Mathematica function?

text: (For educational purposes) I defined the following functions: Translation (in $\mathbb{R}^2$):               trM[vec_] := {{1, 0, vec[[1]]}, {0, 1, vec[[2]]}, {0, 0, 1}}      Rotation (in $\mathbb{R}^2$):               rotM[angle_] := {{Cos[angle], -Sin[angle], 0}, {Sin[angle], Cos[angle], 0}, {0, 0, 1}}      Rotation around a point (in $\mathbb{R}^2$):               rotM[pt_, angle_] := trM[pt].rotM[angle].trM[-pt]      So far so good, now I want a function:               rotM[angle_, n_] :=        {{Cos[n angle], -Sin[n angle], 0}, {Sin[n angle], Cos[n angle], 0}, {0, 0, 1}}      Now                rotM[angle_, n_]       and               rotM[pt_, angle_]       share — in _Mathematica_ — the same signature, which breaks the polymorphism I intended to use, which then leads to the following question. **How can I type-check the arguments of a _Mathematica_ function to enforce polymorphism?**


title: Replicability of RandomVariate within a function?

text: I have a rather basic question but can't figure out a foolproof answer. In the following code, I build a function which returns the mean difference between successive elements of a vector created from `j` random variates from an exponential distribution:               fun2[j_] :=          Module[{x = RandomVariate[ExponentialDistribution[1/25], j]},          Mean[Table[Abs[x[[i + 1]] - x[[i]]], {i, Length[x] - 1}]]]      Will the use of the `x` call to `RandomVariate` create an immutable object, i.e. so that `x[[i + 1]]` and `x[[i]]` reference the same instance of the distribution? Thanks a lot for any help.


title: Parallelizing Numerical Integration in Mathematica

text: I have an ugly, six dimensional function that I need to integrate numerically. It works, but it currently take twelve hours to complete the calculation. Is there any good way to parallelize the calculation to run across multiple cores? The best I've managed to come up with is:               Sum[         ParallelTable[             NIntegrate[calc[a,b,c,d,e,f],                        {a,-1,1},                        {b,-1,1},                        {c,-1,1},                        {d,-1,1},                        {e,-1,1},                        {f,-1+i/4,-1+(i+1)/4}],         {i,0,7}]]      **EDIT:** The value for calc is given below:               calc[a,b,c,d,e,f] = (1.97531*10^15 (3. Q Cos[(3 Q)/20000] -           20000. Sin[(3 Q)/20000])^2)/(1.58025*10^24 + 6.32099*10^16 Q^2 +         Q^6 + (-1.58025*10^24 + 7.90123*10^15 Q^2 - 3.55556*10^8 Q^4) Cos[(          3 Q)/10000] + (-4.74074*10^20 Q - 2.96296*10^12 Q^3) Sin[(3 Q)/          10000])*         UnitStep[5/2 - a]^2 UnitStep[5/2 + a]^2 UnitStep[5 - b]^2 UnitStep[           5 + b]^2 UnitStep[5 - a - 1944 c] UnitStep[5 + a + 1944 c] UnitStep[           5 - b - 1944 d] UnitStep[5 + b + 1944 d] UnitStep[           40 + a - 1600 e] UnitStep[40 - a + 1600 e] UnitStep[           45/2 + b - 1600 f] UnitStep[45/2 - b + 1600 f] /. Q-> (8000000 \[Pi] Sin[               1/2 ArcCos[                 1/2 Sqrt[Cos[2 c] + Cos[2 d]] Sqrt[Cos[2 e] + Cos[2 f]] +                   Sin[c] Sin[e] + Sin[d] Sin[f]]])      There are two immediate things to note. First, there's a removable singularity at (c==e && d==f). I've also tried using a piecewise function to plug this discontinuity, but it doesn't seem to have a significant effect on the speed. One other thought that has come to mind is using the UnitSteps to directly find the range of integration. I hadn't done that before mostly out of laziness and the understanding that Mathematica automatically breaks up piecewise functions for integration, anyway.


title: How could we define a function recursively?

text: Let us first consider the constructon of the following simple iteration               Clear["Global`*"]     p[z_] := z^3 - 1;     beta = -Sign[p'[z]];     theIterationFunction = z - p[z]/(p'[z] + beta p[z]) // FullSimplify      which results in the following correct iteration function $$theIterationFunction=z+\frac{-1+z^3}{-3 z^2+\left(-1+z^3\right) \text{Sign}[z]^2}.$$ Now by choosing any value for $z$, the output would be simply given in Mathematica 8, _since the computation of $\text{Sign}[z]$ has been done automatically_. My problem is in a similar but more complicated iteration. Please consider the following               Clear["Global`*"]     p[z_] := z^3 - 1;     w = z + beta  p[z]; FD = (p[w] - p[z])/(w - z);     theIterationFunction2 = z - p[z]/FD // FullSimplify      which yeilds in $$theIterationFunction2=z-\frac{\text{beta} \left(-1+z^3\right)^2}{-z^3+\left(z+\text{beta} \left(-1+z^3\right)\right)^3}.$$ In fact, here $beta$, must be calculate by the formula $beta=\frac{-p[z]+p[z+\text{beta} p[z]]}{\text{beta} p[z]}$. That is, there is a self-defined formula for $beta$, which itself depends on $beta$. Thus, we must choose a starting value for $beta$, such as $beta=0.1$ at the beggining, but after that, each time theIterationFunction2 must calculate a new value based on its formula. For example, at the very beggining, we set $beta=0.1$ and $z=2.$, and the output will be a new value for $beta$ (NEEDLESS TO BE SHOWN) and my aimed value $y$. Now, if I give $y$, the last value of $beta$ which is saved in the memory must be used to produce a new value for $beta$ and my aimed new value $yy$. The process must be go on in this way. Hence, altogether I must define a function recursively with a pre-assumed starting value for $beta$, while I am un-able to do so! I will be thankful if anyone could help me to define such a function recursively.


title: Why do my results show small deviations from expected values?

text: Table[StringForm["p=`1`", i], {i, 0.05, 0.5, 0.05}]     (*         {p=0.05`, p=0.1`, p=0.15000000000000002`, p=0.2`, p=0.25`, p=0. 30000000000000004`,         p=0.35000000000000003`, p=0.4`, p=0.45`, p=0.5`}     *)      Why do the results show small deviations from the expected numbers `{..., 0.15, ..., 0.30, ...}`?


title: Optimizing repeated function calls

text: Easiest way to keep my library nice, is to naively call some functions many times with same parameters. Doing so prevents from zoo of (library-)global variables and complicated initialisation functions. I would expect Mathematica to optimise somehow functions calls with same parameters, but it does not appear to do that. Fallowing example is ran on Mathematica 9:               rands = Array[Random[] &, {2500, 2500}];     Timing[Inverse[rands];]     Timing[Inverse[rands];]     Timing[Inverse[rands];]     Timing[Inverse[rands];]      Output:               {0.687500, Null}     {0.687500, Null}     {0.687500, Null}     {0.687500, Null}      Is there a way to make Mathematica optimise revaluation with same parameters? What kind of nice workaround would you recommend? **EDIT** As I learned, the keyword I needed was _memoization_. I found this post very useful. Thanks!


title: Mathematica vs Sigmaplot (Non LinearModelFit)

text: I asked a question in a previous post that was closed because "The title of the question is not correct and the issue here is too trivial to help anyone later". NonLinearModelFit It's possible because I'm not so smart in _Mathematica_. But in this period I've tried a lot of alternative solutions. Recall my problem                data={{220., 542.821}, {225., 531.898}, {230., 521.391}, {235.,       510.596}, {240., 499.603}, {245., 488.585}, {250., 479.002}, {255.,       468.574}}      func= a0*Exp[a1 t + a2 t^2]      nlm = NonlinearModelFit[data, func , {a0, a1, a2}, t]      which gives the result:               FittelModel = 0.      Some answers told me that it is not an exponential, but linear problem. But this problem is a physical problem that comes out from a lot of papers that describes this phenomenum as having exponential behavior. So also if my question was trivial, I've continued to solve it. I read a lot of posts, and I tried this solution in _Mathematica_ , using `NMinimize` and not `NonLiNearModelFit`.               f[a0_, a1_, a2_][t_] := a0*Exp[a1*t + a2*t^2 ];     error[a0_, a1_, a2_][x_, y_] := (f[a0, a1, a2]@x - y);     errorSum[a0_, a1_, a2_] = Total[(error[a0, a1, a2] @@@ data)];     bestFitVals =      NMinimize[{errorSum[a0, a1,      a2], {600 < a0 < 1500&& -0.01 < a1 < 0 && -0.0000001 < a2 < 0}}(*,     Thread[0<{a0,a1,a2}]*), {a0, a1, a2}, Method -> "SimulatedAnnealing"]     soln[x_] = f[a0, a1, a2]@x /. bestFitVals[[2]]     limits = Flatten@{x, Through[{Min, Max}@data[[All, 1]]]};     Show@{Plot[soln@x, Evaluate@limits, PlotRange -> All],      ListPlot[data, PlotStyle -> Red]}      I tried all the methods available to `NMinimize`, changing starting values or removing them, but no choice works. So finally a collegue suggested that I try another software package: SigmaPlot. I said him that _Mathematica_ is superior, but Sigmaplot gives me an exponential solution, with these coefficients               a0 = 1072.637060511283     a1 = -2.128998307513597e-3     a2 = -4.390602833555603e-6.      and with residuals that are very low. I tried with another set of data, but the solution is the same: _Mathematica_ is not be able to regress or minimize and Sigmaplot is able to. I hope my question is not trivial, but I hope more that someone can solve my question: is Sigmaplot superior of _Mathematica_ , or is it the case that I'm not applying _Mathematica_ properly to my problem?


title: What are the scoping rules for function parameters shadowing System` symbols?

text: Here are some very contrived code snippets, highly unlikely to appear in real code, but still I am curious why they behave like this:               Function[List, {1, 2, 3}][Hold]     (* Hold[1, 2, 3] *)          Function[Function, Function[Slot[1]]][Hold]     (* Hold[#1] *)          Function[Slot, Function[Slot[1]]][Hold]     (* Hold[1] & *)          Function[Function, Function[x, 1]][Hold]     (* Function[x, 1] *) (* Why not Hold[x, 1]? *)          {Function[Null, Null][1]}     (* {Null} *) (* Why not {1}? *)      I think I understand the first 3 cases.   Could you please explain the last 2 results?


title: Problem displaying eps exported histograms in Word 2010

text: I am having problems displaying histograms exported as .eps in Word 2010. I don't have problems though displaying them in a specialized .eps viewer. (Postsript viewer from Rampant logic) I am writing histograms because there were no problems in exporting or displaying any other plot type.               plot = Histogram[RandomVariate[NormalDistribution[0, 1], 200]]     Export["plot.eps", plot]      ![Mathematica graphics](http://i.stack.imgur.com/bWH6X.png) Could it be that .eps files for histograms are corrupted? I did not find a way to attach the .eps file, so I hope that I am not the only person with this problem, although this is kind of wicked.


title: RegionPlot not working as expected

text: I was trying to evaluate the following expression:               RegionPlot[a > 0 && 2 a + b == 0, {a, -2, 2}, {b, -1.5, 1},         PlotLegends -> "Expressions"]      The output is: ![enter image description here](http://i.stack.imgur.com/2v6Ml.png) I think this is unexpected. Think about when $a = 0.5$. So, $b = -1$ which is within the range $[-1.5, 1]$. So, this values and other such values should be in a gray region in the plot. But they are not there. Any help?


title: Creating sums of elements from a list

text: I have a list $(d_1, d_2, .. d_k)$ and I want to create all sums that I get for adding only two elements for my list $(d_1+d_2, d_1+d_3,...d_{k-1}+d_k)$. The `RotateLeft` function gives me only some of my sums and I need all of them.


title: Embedded CDF Not Working

text: I happened to be looking at an old CDF (19 months old). It previously worked and does not now. It works if downloaded (opening or at URL). It requires dynamic functionality to be enabled but no longer prompts. I am uncertain how to resolve this. I apologise in advance if this is a duplicate and await redirection.


title: Computing a mean of median list of points

text: Given a array of lists with the same number of here N = 10 elements:               SuperList = {{5., 4.99667, 4.99335, 4.99002, 4.98669, 4.98337, 4.98004, 4.97671, 4.97338, 4.97006}, {5., 4.99667, 4.99335, 4.99002, 4.98669, 4.98337, 4.98004, 4.97671, 4.97338, 4.97006}, {5., 4.99667, 4.99335, 4.99002, 4.98669, 4.98337, 4.98004, 4.97671, 4.97338, 4.97006}, {5.,4.99667, 4.99335, 4.99002, 4.98669, 4.98337, 4.98004, 4.97671, 4.97338, 4.97006}, {5.1, 5.09667, 5.09335, 5.09002, 5.08669, 5.08337, 5.08004, 5.07671, 5.07338, 5.07006}, {5., 5., 5., 5., 5., 5., 5., 5., 5., 5.}, {5., 5., 5., 5., 5., 5., 5., 5., 5., 5.}, {5., 5., 5., 5., 5., 5., 5., 5., 5., 5.}, {5., 5., 5., 5., 5., 5., 5., 5., 5., 5.}, {5., 4.99667, 4.99335, 4.99002, 4.98669, 4.98337, 4.98004, 4.97671, 4.97338, 4.97006}};      How do I efficiently compute an array, which we'll call "MedianList" of length N where each element in the array is the median or mean of the sublist entries at the same index in the "SuperList"? For example, the first element would be:               MedianList[[1]] = Median[{5., 5., 5., 5., 5.1, 5., 5., 5., 5., 5.}];      The second element would be:               MedianList[[2]] = Median[{4.99667, 4.99667, 4.99667, 4.99667, 5.09667, 5., 5., 5., 5., 4.99667}];      And so forth.


title: What does "levelspec" mean in the documentation?

text: The following code returns the first three integer elements of `Sqrt[Range[100]]`:               Cases[Sqrt[Range[100]], _Integer, 2, 3]     {1, 2, 3}      The following code looks like the preceding code but returns a different result:               Cases[Sqrt[Range[100]], _Integer, {2}, 3]     {2, 3, 5}      As we can see in the following picture, the argument `{2}` is not documented (it has no braces in the documentation): ![enter image description here](http://i.stack.imgur.com/r0OZG.png) What does the second code with `{2}` instead of `2` mean?


title: How to solve for exponents in an infinite product?

text: Say I have a power series, $f(x,y) \in 1 + x\mathbb{Z}[[x,y]]$ Then it admits a unique expansion $$f(x,y) = \prod_{i=1}^\infty \prod_{j=0}^\infty (1 - x^i y^j)^{n_{i,j}}$$ for some integers, $i, j$. More to the point, the $n_{i,j}$ for $i \le N$ and $j \le M$ are determined uniquely by $$f(x,y) = 1 + \sum_{i=1}^N \sum_{j=0}^M f_{i,j} x^i y^j = \prod_{i=1}^N \prod_{j=0}^M (1 - x^i y^j)^{n_{i,j}} + O(x^{N+1}, y^{M+1})$$ > How do I solve for the $n_{i,j}$ given the $f_{i,j}$? In principle there is some matrix with integer coefficients that needs to be inverted, but do I have to first generate that matrix (how?) and invert it, or can I just write something like the above in Mathematica and say ``solve'' ?


title: Finding positions of multiple elements in lists

text: I realise that               Position[{2, 4, 8, 16, 32, 64}, 4]      will return               {{2}}      I would like to do something like this:               Position[{2, 4, 8, 16, 32, 64}, {4, 32, 64}]      and get               {{2}, {5}, {6}}      I have searched, but can't ind anything - I am clearly missing something obvious :/


title: How to export data from For loop in text file?

text: I'm new in Mathematica and I am trying to write numbers from 1 to 10 in txt file. But "Null" is everything that is written in my file. The code is:               Export["C:\\Users\\Sealy\\Desktop\\list.txt",            For[k = 1, k <= 10, k++, Print[List[k]]]]


title: Heavy duty operations, RAM, and Readyboost

text: I occasionally work with large 3D arrays and found that with calculations that take a long time, Mathematica completely fills my available RAM (6056 MB minus other active operations [mostly svchost]), and so completely bogs down my pc that it takes minutes to even [alt][dot] abort evaluation, or do anything at all in a different program. At one point I was working with an active 4 GB 2.0 USB plugged in with readyboost, and it prevented my computer from freezing. So my question, can I prevent Mathematica from freezing without the readyboost, and might upgrading to 8 GB RAM also solve the issue? To be clear, it doesn't run out of memory, it just takes up all working memory for the duration of the computations. I'm not sure if readyboost also increases performance, I know people usually disregard it for any but the lowest performing computers, but it's a lifesaver here.


title: How to generate random points in a region?

text: The Mathematica 10 documentation was updated for FindInstance adding support for regions. In my use case I'm trying to sample points in a set of disks:               region = DiscretizeRegion@RegionUnion@Table[Disk[RandomReal[4, {2}], RandomReal[1]], {10}]     FindInstance[{x, y} \[Element] region, {x, y}, Reals, 2] // N      However the above code fails and generates the following error:               FindInstance::elemc: "Unable to resolve the domain or region membership condition {x,y}\[Element]"      What's going wrong here?


title: Generating a (random) 2-dimensional cellular network

text: I want to generate a network of random cells like the following picture: ![enter image description here](http://i.stack.imgur.com/xYo3t.jpg) The general idea is to generate some random points (x,y) as coordinate of a vertex and then randomly choose some of these points to connect them to achieve (almost) a random cellular network since there are two constraints:   1. The length of edges is constant.   2. Degree of each vertex is 3. Thanks, _Update_ I have been thinking about this problem for a while. Here's the conclusion: By starting from a perfect honeycomb, we perform a series of random "neighbor switching" process: ![enter image description here](http://i.stack.imgur.com/6kOLg.png) By performing successive neighbor switching, we are able to build cells with different size.


title: How can I use BarChart to add label of the range of each set of data on the x axis?

text: ( _My code:_ )               DataFirst = {0, -1, 0.5, 1, -4.5, 4.5, -0.5, 6, -4.5, 0, -1.5,                   1.5, -0.5, 2.5, 0, 2, -1, 2, -1, 2, -6.5, -3, 2.5, -3, -0.5, 2.5,                   5, 2.5, -3, -2.5, 1.5, -2, 2, -0.5, 3.5, -2.5, 2.5, -1,                   1.5, -1, -3.5, 1.5, -1, -1, -2, 5.5, 4, 1.5, -6, -1.5, 0, -1, 2, 4,                  3, -2, -0.5, 0.5, -0.5, 0, -0.5, -1, 2, -5, 2.5, 2.5,                   7, -2, -2.5, -2.5, 2, -2.5, 4, 2, 4, -5, 1.5, -1.5, 2, -2.5, -3,                   2, -1, -2.5, 1, 5, 3, -0.5, -2.5, 0.5, -0.5, 1, 0.5, 4, -0.5,                   1, -1, 1.5, 0.5, 2.5};     max = Max[DataFirst];     min = Min[DataFirst];     dx = (max - min)/10;     fi = BinCounts[DataFirst, {min, max, dx}]     BarChart[fi]      I want to show the range of each set of data on the x axis. ![enter image description here](http://i.stack.imgur.com/zt7X1.jpg) for example，`min` to `min+dx`, `min+dx` to `min+2*dx` and so on until `min+9 *dx` to `max` *)


title: How to dequantify units in mathematica?

text: Is there a function which applied to a quantity returns its numerical value so I for instance can fill it into my `Predictorfunction`?


title: Is there an equivalent of Sum for And?

text: Is there an equivalent to `Sum` for `And`? That is, just like instead of `Plus@@Table[f[i], {i,3,6}]` (or `Total@Table[f[i], {i,3,6}]`) you can write `Sum[f[i], {i,3,6}]`, is there a single pre-defined function that can replace `And@@Table[f[i], {i,3,6}]`? If not, is there a better alternative for `And@@Table[...]`? Note that, at least in Mathematica 8, `Conjunction` is not the right tool (despite the claim in the documentation that "`Conjunction` is to `And` what `Product` is to `Times`") because it only substitutes logical values, that is, it can only replace the special case `And@@Table[f[var], {var, {False, True}}]` (and of course multi-variable versions of the same structure).


title: Exception/Error handling using returns codes

text: There is good explanation available for error handling on this and similar links. Here there is information on handling inappropriate input arguments and handling unprocessed functions using `$Failed`. But it is much of incomplete because I want to catch error message and according to that display some specific message. For example if I get               Integrate::idiv: Integral of E^n does not converge on {1,\[Infinity]}. >>      Than I want to display some specific message in words which is possible if I can capture this message and extract from it or if Mathematica returns some error code associated. Is there some better technique available than just using `$Failed` everywhere ?


title: ListPlot doesn't shows all points

text: I have a table: `p1 = Table[(Binomial[2000, k]*StirlingS2[1386, k]*k!)/(2000^1386), {k, 1, 1386, 1}];` I used `ListPlot[p1]` to draw a plot of this values. This is the plot, where on `Y` I have values of `p1` and on `X` I have values of `k`. But when I draw my plot, I see only points which are starting from $k \approx 560$. Why I can't see points for all values of `k`? Is this because of that values for small `k` are too small? How can I fix that?


title: Color inversion using ArrayPlot

text: I have a 3D data that I want to visualise its each slice with ArrayPlot. However, there is a problem the way it represents the data. As, > ArrayPlot by default generates grayscale output, in which zero values are > shown white, and the maximum positive or negative value is shown black. It conflicts with the general idea, cause it should represent 0 values as black, max value(if it is scaled, equals to 1) as white and the rest of the values as gray levels. I am playing with it and I wrote a code sample:               ArrayPlot[data, ColorFunctionScaling -> True, ColorRules -> {1 -> White, 0 -> Black}]      I am not sure whether it is correct. Actually, I am not satisfied with the result. Any help is appreciated.Thanks.


title: Computing the Hurst exponent or fractal dimension of fractional Brownian motion

text: The Hurst exponent is related to the fractal dimension by noticing that the fractal dimension $D$ is equal to $2-H$, where $d$ is the intrinsic dimension and $H$ is the Hurst exponent, for 1-D fractional Brownian motion. I can generate an fBm series in _Mathematica_ as follows:               tlow = 1;     thigh = 1000;     tinc = 1;     hurst = 0.4;         dataz=RandomFunction[FractionalBrownianMotionProcess[hurst], {tlow, thigh, tinc}, 1];      However, using the method described here to compute the fractal dimension, I am unable to get close to recovering the Hurst exponent used to generate the fBm. For example:               stdev[{x__}] := StandardDeviation[{x}]     stdev[{x_}] := 1     dataf = RotateRight[Mean[R /@ #/stdev /@ #] & /@ (Partition[dataz, 2^#] & /@ Range[10])]     Fit[Log[dataf], {1, x}, x]      Is this a numerical error or are there better ways to compute Hurst exponents and fractal dimension in _Mathematica_?


title: How to make a conditioning plot?

text: I'd like to make a conditioning plot just like coplot in R. Is there a pre- made solution or do I have to make a bunch of plots individually? Edit: This is an example from r screenshots. It is a way of looking at multivariate data. Each individual graph represents the respective bar in the conditioning variable or factor. In this case you see ozone vs solar for different levels of wind and temp. ![Image](http://i.stack.imgur.com/QeehJ.png) Edit2: The R-integration looks interesting. I just found a StackExchange question about returning the plot to an output cell in Mathematica, so that works. I just thought there would be a built in function as these plots seem pretty popular in statistics. In r-code I would just type coplot(a~b|c) to see a vs b for levels of c.


title: Plotting piecewise function with distinct colors in each section

text: I have a piecewise function that I would like to plot but I was wondering if it is possible that each part of the function that is plotted when its corresponding condition is true be plotted with a different color from the other parts. That is, if I have a Piecewise function `Piecewise[{{val1, cond1},{val2,cond2},{val3,cond3}}]` then I want `val1`, `val2`, and `val3` to be plotted with different colors so that I can differentiate each case in the plot.


title: Is Wolfram Language suitable for building web applications?

text: My goal is to find a technology which will afford me to build web applications (e.g. simple social networking site) as quickly as possible (with as little code as possible). I was impressed by Stephen Wolfram's video presentation: it looks like that the Wolfram Language is the tool which I sought: such that any task that I can formulate in a few words can also be implemented in the language with a line or two of code. But I've seen no explicit discussion about using Wolfram Language for building websites and web applications. Update. Let me clarity what I mean. Consider the following example. * * * Suppose I’m going to organize an event (a seminar) so I decided to make a website to communicate with participants conveniently: every potential participant will sign up and fill in a registration form; then he will be able to post questions and subscribe to other’s questions he is interested in so that he will be notified by email when such question is answered. And when I want to get some additional info from participants (e.g. an exact time of participant’s arrival to the airport), I add this additional field to the registration form and set up a procedure that will every day send an email “Please answer this additional question” to every user that has not answered it yet. So I write something like this:               mysite = CreateWebsite(     Title: "The seminar"     Authorization: {"Facebook","Twitter","Google"}     )          mysite.AddQuestionnaire(     "Name": text     "Surname": text     "Date of arrival": date     )          mysite.AddQuestionsAndAnswers(SubscribeButton = True, NotificationType = "Email")          mysite.Deploy("http://theseminar.com")      And then I get a standard-looking website with all mentioned functionality. Everything has a default, and if I want to change some details, I just specify the corresponding options explicitly. * * * It seems that this should be the right way to create websites. Such that the website creator can concentrate all his mental efforts on the conceptual design of his application without need to waste it on the low-level stuff like html and css. This looks like fitting well with the ideology of Wolfram Language. This would democratize web development, i.e. a lot of internet users who are not professional web-developers would be able to quickly create web applications tailored for their needs. There are important benefits when the user of a piece of software is himself the creator of this software — the feedback-based iteration becomes extremely fast and effective: when you-as-a- user see some possibility to improve the software, you immediately and accurately convey this vision to you-as-a-programmer who will change the software; then you-as-a-user immediately see the result and assess it; then continue such iterations until the result is perfect.


title: Multiple level lists

text: Let there be a list,               Sample={{{1, 2, 3}, {a, b, c}}, {{2, 3, 4}, {d, f, g}}}      I want to go to individual sublists and do some operation on it.I tried a few things like rule and replace.               sam /. {x_, y_} -> {x -> {a_, b_} -> {a + b}, y /. {w_, e_} -> w^e}      but I get               {{{1, 2, 3}, {a, b, c}} -> {a_, b_} -> {a + b}, {{2, 3, 4}, {d, f, g}}}      But I am not getting to individual lists. I want to use only rule or replace. **Edit** : To make my question more clear I want to specify that I am not interested in one particular list operation. My idea is to be able to traverse sublists using `Rule` or `Replace` and then work on it. My expected result is like               {{{1 + a, 2 + b, 3 + c}}, {2^d, 3^f, 4^g}}


title: Efficient image Import

text: I have several sets of 20 images I need to import. ![enter image description here](http://i.stack.imgur.com/l0yz5.png) Each time they have different categories. "Name"<>"Cat"<>"No" Electric B 1 for example. I need to create lists that contain the images for those different categories. As of now this is what i am doing :               importOne[set_, cat_, num_] :=       ImageResize[       Import[FileNameJoin[{NotebookDirectory[], set,               set <> cat <> ToString[num] <> ".png"}]], 128]                    ElectricB = importOne["Electric", "B", #] & /@ Range[6];     ElectricC = importOne["Electric", "C", #] & /@ Range[5];     ElectricN = importOne["Electric", "N", #] & /@ Range[5];     ElectricE = importOne["Electric", "E", #] & /@ Range[4];      And then, thanks to previous question/answers : ![enter image description here](http://i.stack.imgur.com/VTO9P.jpg) **What would be a more efficient mean to import automatically for different sets ?** As of now I need to repeat this operation for each set.


title: Which Distributions can be Compiled using RandomVariate

text: Recently, Oleksandr kindly showed a list of Mathematica commands that can be compiled. RandomVariate was part of that list. However, whether this can be compiled depends upon the distribution that is being sampled.               Needs["CompiledFunctionTools`"]          cf1 = Compile[{{m, _Real}, {s, _Real}},       Module[{v1, v2, v3, v4, v5, v6},        v1 = RandomVariate[NormalDistribution[m, s]];        v2 = RandomVariate[UniformDistribution[{m, s}]];        v3 = RandomVariate[GammaDistribution[m, s]];        v4 = RandomVariate[PoissonDistribution[m]];        v5 = RandomVariate[ChiSquareDistribution[m]];        v6 = RandomVariate[ExponentialDistribution[m]];        {v1, v2, v3, v4, v5, v6}        ]       ]      Using CompilePrint shows that RandomVariate can be compiled for the Normal Distribution or the Uniform Distribution and not with some others.               CompilePrint[cf1]          2 arguments             4 Integer registers             8 Real registers             1 Tensor register             Underflow checking off             Overflow checking off             Integer overflow checking on             RuntimeAttributes -> {}                  R0 = A1             R1 = A2             Result = T(R1)0          1   R2 = RandomNormal[ R0, R1]]     2   R3 = RandomReal[ R0, R1]]     3   I0 = MainEvaluate[ Function[{m, s},                   RandomVariate[GammaDistribution[m, s]]][ R0, R1]]     4   I1 = MainEvaluate[ Function[{m, s},                   RandomVariate[PoissonDistribution[m]]][ R0, R1]]     5   I2 = MainEvaluate[ Function[{m, s},                   RandomVariate[ChiSquareDistribution[m]]][ R0, R1]]     6   I3 = MainEvaluate[ Function[{m, s},                   RandomVariate[ExponentialDistribution[m]]][ R0, R1]]     7   R4 = I0     8   R5 = I1     9   R6 = I2     10  R7 = I3     11  T(R1)0 ={ R2, R3, R4, R5, R6, R7 }     12  Return      Does anyone have a list of all the distributions that can be compiled (including, PDF, CDF and RandomVariate functionality)?


title: Searching for phrases in a block of text

text: One could call this a pattern finding question with dictionary (or WolframAlpha) lookup, but let me give you some background first. I have a couple of friends who are trying to improve their English listening skills by watching TV shows in English, with English subtitles. I have access to the subtitles in text format which I can import and process as I like. Now it is easy to pick out common words from a list of words using something like `Tally`, but what I would like to do is more complicated. I want to pick out phrases (and perhaps some longer or slang-like words) that a non-native speaker may not recognize. I understand I need some sort of a lookup for this, and I thought of using WolframAlpha's `Phrase:WordData` pod, but it doesn't show up for every word, and didn't exactly do what I really wanted. I'll provide an example block of text below if anybody would like to go ahead and try it using whatever method they would like.               myStr = "Wow that must have been an awful result. That was not even close! People didn't even find out until they reviewed the footage.";     myStrList = StringCases[myStr, WordCharacter ..]      And this gives > {"Wow", "that", "must", "have", "been", "an", "awful", "result", "That", > "was", "not", "even", "close", "People", "didn", "t", "even", "find", "out", > "until", "they", "reviewed", "the", "footage"} Now I'd like an output that might look like something like > {"awful", "not even close", "find out", "reviewed", "footage"} I know this is rather vague, but I think determining search patterns and how the search would be executed would be a good start.


title: Integrating Squared of Interpolating Function with respect to one variable

text: I am interested in evaluating a two dimensional interpolating function produced by solving the wave equation. Here is the code that includes the resulting interpolating function.               pde = D[y[x, t], t, t] == D[y[x, t], x, x]          solnDerivative = NDSolve[{pde, y[x, 0] == Exp[-(x)^2], Derivative[0, 1][y][x, 0] == 0,        Derivative[1, 0][y][-50, t] == Derivative[0, 1][y][-50, t],       Derivative[1, 0][y][50, t] == - Derivative[0, 1][y][50, t]},        Derivative[0, 1][y][x, t], {x, -50, 50}, {t, 0, 130}]          ifunDerivative  = First[Derivative[0, 1][y][x, t] /. solnDerivative]      Here, I wanted to first integrate squared of `ifunDerivative` with respect to t from `{0,130}` then get a new interpolating function as a function of `x` only. The first problem I ran into is that it won't evaluate this integral and spits back out the input.               integratedFunction = Integrate[(ifunDerivative[x, t])^2, {t, 0, 130}, x]      How can I go about numerically integrating interpolating function squared with respect to `t`? Then, obtain a solution that depends only on `x`? Please help me! Thank You!


title: Solving a time-dependent Schroedinger equation

text: I want to solve the time-dependent Schroedinger equation: $$ i\partial_t \psi(t) = H(t)\psi(t) $$ for matrix, time-dependent $H(t)$ and vector $\psi$. What is an efficient way of doing this so that it efficiently scales to high- dimensional spaces?


title: Defining a Gaussian Distribution Fit to data

text: I am given a set of data and told ahead of time that the data will need to be fitted to a _Gaussian Distribution_. I know that _Mathematica_ has preset functions for linear, quadratic, and cubic fits, but how do I define a new equation to fit the data to? From this, I will need the s.d., the `x_average`, and the `A` values. The _Gaussian Distribution_ is to be defined as so:               N(x) = A/(sqrt(2*3.1416)*w)*exp(-(x-x_average)**2/(2*(w**w**2))      * * * So far I have:               Needs["ErrorBarPlots`"];          SetDirectory[];     SetDirectory["/Users/stevendang/Downloads"];          dataContent = Import["data.dat"];          dataOrganized =       Table[{{dataContent[[i, 1]], dataContent[[i, 2]]},       ErrorBar[dataContent[[i, 3]]]}, {i, 2, Length[dataContent]}];      ErrorListPlot[dataOrganized,       FrameLabel -> {"Y, X", "Gaussian Distribution"},       PlotRange -> {{0, 30}, {0, 40}}]          dataFit =       Table[{dataContent[[i, 1]], dataContent[[i, 2]]}, {i, 2, Length[dataContent]}]          FindFit[dataFit, (A/((2*3.1416)^(1/2)*w))*e^(-(x - xave)^2/(2*w^2)), {A, w, xave}, x]      Also I've tried "FindDistributionParameters" instead of FindFit but Mathematica doesn't have a built in Gaussian Distribution to work with. Any thoughts? The following isn't giving me values for A, w, xave.


title: ParametricPlot - Problem with ColorFunction

text: I am unhappy with the following mapping:               ParametricPlot[{Re@Sin[u + I v], Im@Sin[u + I v]},      {u, -Pi/2, Pi/2}, {v, -Pi/2, Pi/2},      ColorFunction -> (ColorData["DarkRainbow"][#3] &),      ImagePadding -> 20,      ImageSize -> 400,      PlotPoints -> 30]      ![enter image description here](http://i.stack.imgur.com/VwoCa.jpg) because of the distinct coloring of its left and right part. I found a certain fix with this:               ParametricPlot[{Re@Sin[u + I v], Im@Sin[u + I v]},      {u, -Pi/2, Pi/2}, {v, -Pi/2, Pi/2},      ColorFunction -> (Blend[{Red, Green, Yellow, Blue, LightBlue, Blue,            Yellow, Green, Red}, #3] &),      ImagePadding -> 20,      ImageSize -> 400,      PlotPoints -> 30]      ![enter image description here](http://i.stack.imgur.com/iY1J8.jpg) But I really would prefer to use one of the inbuilt gradients to color my figure according to its polygon size or "mesh density". Thanks in advance for your suggestions.


title: Wrong values at the boundary of differential equation solution

text: I have a second order ordinary differential equation and want to solve it numerically. Although I have specified values at the boundary, Mathematica solution does not match with boundary conditions.               h = 10.6     F = 0.001     d = 1.0     L = 100*d     phi[x_] :=       Piecewise[{{0.5*(1 - Tanh[x]),          x < L*0.5/d}, {0.5*(1 + Tanh[x - L/d]), x > L*0.5/d}}]     s = NDSolve[{u''[x] == (h)*phi[x]*phi[x]*u[x] - F*d*d*(1 - phi[x]),         u[-2.5] == 0.0, u[L + 2.5] == 0.0}, u, {x, -2.5, L + 2.5}]     vL[x_] := u[x]/(1 - phi[x])          Plot[Evaluate[{vL[x]} /. s], {x, L/d + 1.5, L/d + 2.5},       PlotRange -> All]          {u[-2.5], u[L + 2.5]} /. s      ![Mathematica graphics](http://i.stack.imgur.com/sPymr.png) > >     {{9.02944, -1.11442*10^-25}} >   What is the correct way to set the boundary conditions?


title: How do you put conditions on indices in a sum?

text: I'm relatively inexperienced with mathematica, so I apologize if this is a trivial question. I want to take a double sum over a function $f(i,j)$ of two indices, of the form $$ \sum_{i = -\infty}^\infty \sum_{j = 0\atop j\not = i}^m f(i,j). $$ That is, in the inner sum I want to sum over only those indices $j$ in my range of summation that satisfy the assumption $j \not = i$. How can I input such a sum to Mathematica?


title: Speeding up numerical Fourier Transform

text: I wrote this function `NFourierTransform`, which takes a function $f(k)$ and numerically calculates the fourier transform integral for discrete values of $k \in [k_{\text{min}},k_{\text{max}}]$, finally returning an `InterpolatingFunction` object.               NFourierTransform[f_Function, {kmin_, kmax_}] :=       Interpolation@       Table[{k, Chop@NIntegrate[f@x E^(-I k x), {x, -Infinity, Infinity}]},        {k, kmin, kmax, (kmax - kmin)/100}]      In my application (calculating the time propagation of wave functions) I need to evaluate `NFourierTransform` for a function $\psi(k,t)$, where $t$ assumes discrete values in some interval $[t_{\text{min}},t_{\text{max}}]$. So effectively I create a table of `NFourierTransform`.               TimePropagate[f_Function, kl : {kmin_, kmax_}, {tl__}] :=      Quiet@Table[        NFourierTransform[f[#] Exp[-(#^2/2) t] &, kl], {t, tl}]      Calculating a very simple example with only 2 time values, e.g. `TimePropagate[Exp[-Abs@#] &, {-3, 3}, {0, 0.1, 0.1}]` takes about 20 seconds to evaluate. Is there any way to use `Compile` to speed up the calculations? As far as I know that's only possible for numeric function arguments. What are, in your experience, suitable setings for `NIntegrate` options such as `MaxRecursion` or `AccuracyGoal`, and how do they effect evaluation time?


title: LibraryLink path problem

text: I have a library function that need to load some external data files. But it looks that the path in the default path of library function is the path that Mathematica is currently in. Is there a way to make a dynamic library that use the current path as the default path? Here is an example: Consider a library function that reads a integer from the file example.txt, which is at the same directory as the dynamic library files. The example.txt contains only one integer number in it:               cat example.txt     20      And here is the source of the library function:               #include "WolframLibrary.h"     #include <iostream>     #include <sstream>     #include <fstream>     #include <string>          using namespace std;          DLLEXPORT mint WolframLibrary_getVersion(){       return WolframLibraryVersion;     }     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){       return 0;     }          EXTERN_C DLLEXPORT int readstring(WolframLibraryData libData, mint Argc, MArgument* Args, MArgument Res)     {       int a;       string line;            ifstream file("example.txt");            getline(file,line);       istringstream iss(line);       iss>>a;            MArgument_setInteger(Res, a);       return LIBRARY_NO_ERROR;     }      In the above code, the `ifstream file("example.txt")` tries to load a file that at the same directory as the library file, but since the current directory is the directory of Mathematic, it cannot find the file example.txt and will crash the kernel. There are two solutions that I know:   1. Use absolute path. For example change  `ifstream file("example.txt")` to something like `ifstream file("/Users/xslittlegrass/example.txt")`   2. Change the current directory of Mathematica by something like SetDirecotory["/Users/xslittlegrass/"] before calling the library function. Question: Is there other solutions, that can somehow tell the library function to search it's current directory? Because I will use the library function in parallel, and there may be many copies of library files in different locations, so I would prefer a more clean way to call the library function, instead of manually changing the path each time I call.


title: Positioning ChartLabels in a horizontal stacked BarChart

text: I can create a `BarChart` with horizontal bars (using `BarOrigin -> Left`) and _Mathematica_ will automatically position the `ChartLabels` on the left hand side:               data1D = RandomReal[{1, 10}, 10];     labels = DictionaryLookup["D*", 10];          BarChart[data1D, BarOrigin -> Left, ChartLabels -> labels,       BaseStyle -> {FontFamily -> "Calibri", 14}]      ![enter image description here](http://i.stack.imgur.com/pP9Go.png) However, if I want to plot a stacked chart in the same way, the `ChartLabels` appear below the bars:               data2D = RandomReal[{1, 10}, {10, 2}];          BarChart[data2D, BarOrigin -> Left, ChartLayout -> "Stacked",       ChartLabels -> {labels, None},       BaseStyle -> {FontFamily -> "Calibri", 14}]      ![enter image description here](http://i.stack.imgur.com/rM2LS.png) How can I get the labels for the stacked chart to appear as they do in the simple chart?


title: Using SimMetrics Java Function on Mathematica

text: I would like to know if it's possible to use/install this java library on Mathematica. This library, named SimMetrics, has a lot of string similarity functions that I would like to test. Here is the list of functions: > Levenstein, NeedlemanWunch, SmithWaterman, SmithWatermanGotoh, > SmithWatermanGotohWindowedAffine, Jaro, JaroWinkler, ChapmanLengthDeviation, > ChapmanMeanLength, QGramsDistance, BlockDistance, CosineSimilarity, > DiceSimilarity, EuclideanDistance, JaccardSimilarity, MatchingCoefficient, > MongeElkan, OverlapCoefficient. I have no knowledge on Java and use a MAC. A thought in Leonid Java Reloader, but it's a complete .jar file, not a small class. ## Update I download the simmetrics_jar_v1_6_2_d07_02_07.jar from the link above, saved it on notebook directory and tryed:               Needs["JLink`"]     ReinstallJava[ClassPath->"/System/Library/Java/JavaVirtualMachines/:"<>NotebookDirectory[]<>"simmetrics_jar_v1_6_2_d07_02_07.jar"]          Now I have to use LoadJavaClass? How can a list the available classes? If I unzip the .jar file, the classes are inside this folder: uk/ac/shef/wit/simmetrics/similaritymetrics/ for example: Levenshtein.class


title: Having Mathematica solve or help solve a set of 8 equations

text: There is a set of DDE's that arise in leukemia dynamics and I'd like to find the equilibrium points of the system by setting all of the derivatives equal to zero. The system can be described in _Mathematica_ code as follows:               Ctotal = y0 + y1 + y2 + y3 + z0 + z1 + z2 + z3;     p[C_, T_, cn_, p0_, k_] := p0*Exp[-cn*C]*k*T;     dy0dt[ry_, u_, d0_, qC_, cn_, p0_, k_] :=        (ry (1 - u) - d0)*y0 - qC*p[Ctotal, T, cn, p0, k]*y0;     dy1dt[ay_, d1_, qC_, cn_, p0_, k_] :=        ay*y0 - d1*y1 - qC*p[Ctotal, T, cn, p0, k]*y1;     dy2dt[by_, d2_, qC_, cn_, p0_, k_] :=        by*y1 - d2*y2 - qC*p[Ctotal, T, cn, p0, k]*y2;     dy3dt[cy_, d3_, qC_, cn_, p0_, k_] :=        cy*y2 - d3*y3 - qC*p[Ctotal, T, cn, p0, k]*y3;     dz0dt[rz_, d0_, ry_, u_, qC_, cn_, p0_, k_] :=        (rz - d0)*z0 + ry*u*y0 - qC*p[Ctotal,T,cn, p0, k]*z0;     dz1dt[az_, d1_, qC_, cn_, p0_, k_] :=        az*z0 - d1*z1 - qC*p[Ctotal, T, cn, p0, k]*z1;     dz2dt[bz_, d2_, qC_, cn_, p0_, k_] :=        bz*z1 - d2*z2 - qC*p[Ctotal, T, cn, p0, k]*z2;     dz3dt[cz_, d3_, qC_, cn_, p0_, k_] :=        cz*z2 - d3*z3 - qC*p[Ctotal, T, cn, p0, k]*z3;     dTdt[sT_, dT_, n_, qT_, cn_, p0_, k_] :=        sT - dT*T - p[Ctotal, T, cn, p0, k]*Ctotal + 2^(n)*p[Ctotal, T, cn, p0, k]*qT*Ctotal;      Now, setting them all equal to zero and using `Solve` did not get me very far. I have a feeling that because there are so many equations, `Solve` having trouble finding a solution. Maybe it will find one, but it might take a long time before something happens. I have had some mild success using `FindRoot[]`, however that only gives me an approximate solution to my problem, and it is very possible that there will be more than one equilibrium point as well. I'd like to also note that I want to be able to solve for y0, y1, y2, y3, z0, z1, z2, z3,and T. Does anyone have any ideas? I know it's kind of a complex system, but there's got to be a way to get some equilibrium points here, besides the obvious solution `(0, 0, 0, 0, 0, 0, 0, 0, sT/dT)` EDIT1: Here's what I used as a solve argument               Solve[ dy0dt[ry, u, d0, qC, cn, p0, k] == 0 &&      dy1dt[ay, d1, qC, cn, p0, k] == 0 &&      dy2dt[by, d2, qC, cn, p0, k] == 0 &&      dy3dt[cy, d3, qC, cn, p0, k] == 0 &&     dz0dt[rz, d0, ry, u, qC, cn, p0, k] == 0 &&     dz1dt[az, d1, qC, cn, p0, k] == 0 &&     dz2dt[bz, d2, qC, cn, p0, k] == 0 &&     dz3dt[cz, d3, qC, cn, p0, k] == 0 &&     dTdt[sT, dT, n, qT, cn, p0, k] == 0, {y0, y1, y2, y3, z0, z1, z2, z3, T}]      If possible, I want to do it analytically. There should be at least three. Even if it did find one of the non-trivial equilibrium points it would be helpful.


title: PrincipalValue option of Convolve not working in 9.0.1?

text: The `PrincipalValue` option of `Convolve` is used in this question to define the Hilbert transform. However, in _Mathematica_ 9.0.1, the convolution version gives a wrong answer, while the Fourier transform based version still works.               (* Fourier transform version *)     hilbertTransform = Function[{f,u,t},          Module[{fp = FourierParameters -> {1, -1}, x},             FullSimplify@InverseFourierTransform[-I (2 HeavisideTheta[x] - 1)                  FourierTransform[f, u, x, fp], x, t, fp]         ]     ];     hilbertTransform[#, v, w] & /@ {Sin[v], Cos[v], 1/(1 + v^2), Sinc[v], DiracDelta[v]}          (* {-Cos[w],Sin[w],w/(1+w^2),(1-Cos[w])/w,1/(π w)} *)          (* Convolve based version which failed for DiracDelta *)         hilbertTransform2[f_, u_, t_] :=          FullSimplify[Convolve[f, 1/u, u, t, PrincipalValue -> True]/π]     hilbertTransform2[#, v, w] & /@ {Sin[v], Cos[v], 1/(1 + v^2), Sinc[v], DiracDelta[v]}          (* {-Cos[w],Sin[w],Log[(-1)^(-(1/(1+w^2))) E^(π/(-I+w))]/π,(1-Cos[w])/w,0} *)      Is this a bug?


title: using deletecases for twittermessages using the timestamp

text: I have a Excelsheet with tweetsmessages. These tweets are all written in Dutch. I would like to analyse these tweets in relation to the timestamp.               tweets = Import["E:\\mathematica\\data\\tweets_gr2014_v5.xls", {"Data", 1}];          tweets[[2 ;;, {1, 2}]]      The result is : The result is: { {"19-3-2014 23:13", "##GR2014 - Een goeie in tv commentaar: #Wilders schreeuwt wel veel, maar hij wil helemaal niet in steden regeren. Hij doet bijna nergens mee"}, {"19-3-2014 21:49", "#020kiest eerste uitslag Amsterdam zo op AT5 #GR2014 #at5"}, {"19-3-2014 22:26", "#033kiest pvda verliest veel... was wel te verwachten nietwaar? #GR2014"}.......} Then I use StringCases to split the individual words in the tweet messages.               tweets1 = Transpose@{tweets[[2 ;;, 1]],  StringCases[ToLowerCase[tweets[[2 ;;,      2]]], RegularExpression["\\w(?<!\\d)[\\w'-]*"]]};      The next step is dat I would like tot delete all stop words. Therefor I have a listing with Dutch Stop words. stopwoordenNL = { "aan", "al", "alles", "als", "altijd", "andere", "ben", "bij", "daar", "dan", "dat", "de", "der", "deze", "die", "dit", "doch", "doen", "door", "dus", "een", "eens", "en", "er", "ge", "geen", "geweest", "haar", "had", "heb", "hebben", "heeft", "hem", "het", "hier", "hij", "hoe", "hun", "iemand", "iets", "ik", "in", "is", "ja", "je", "kan", "kon", "kunnen", "maar", "me", "meer", "men", "met", "mij", "mijn", "moet", "na", "naar", "niet", "niets", "nog", "nu", "of", "om", "omdat", "onder", "ons", "ook", "op", "over", "reeds", "te", "tegen", "toch", "toen", "tot", "u", "uit", "uw", "van", "veel", "voor", "want", "waren", "was", "wat", "werd", "wezen", "wie", "wil", "worden", "wordt", "zal", "ze", "zelf", "zich", "zij", "zijn", "zo", "zonder", "zou", "ten", "per", "lid", "pagina", "toe", "indien", "alle", "den", "bent", "hebt", "nee", "ja", "wel", "mee", "ter", "zie", "aldus", "alsmede", "alsnog", "betreffende", "danwel", "derhalve", "zoals", "zowel", "hierbij", "hierboven", "hiermee", "hierna", "hiertoe", "hiervan", "hiervoor", "tenzij", "and", "for"}; Without using the timestamp I used the script:               DeleteCases[tweets[[All, 2]], w_ /; MemberQ[stopwoordenNL], ToLowerCase[w]]];      But it doesn't work when I analyse two columns. How can I delete the stop words?


title: Why LibraryLink function crashes at a second time?

text: I'm trying link one of Lapack's function to Mathematica through LibraryLink, and the Library function works great at the first execution but crashes at the second time. Here is the code (modified from here)               MMASrc="     #include <WolframLibrary.h>     #include <WolframCompileLibrary.h>          DLLEXPORT mint WolframLibrary_getVersion(){       return WolframLibraryVersion;     }     DLLEXPORT int WolframLibrary_initialize(WolframLibraryData libData){       return 0;     }          EXTERN_C void zspsv_(char* UPLO, const mint* N, mint* NRHS, mcomplex* A, mint* IPIV, mcomplex* B, mint* LDB, mint* INFO);               EXTERN_C DLLEXPORT int lpkSolveAXBS(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){            MTensor ta=MArgument_getMTensor(Args[0]);       MTensor tb=MArgument_getMTensor(Args[1]);       mint N=*MTensor_getDimensionsMacro(tb);       mcomplex* A=MTensor_getComplexDataMacro(ta);       mcomplex* B=MTensor_getComplexDataMacro(tb);            char U='U';       mint IPIV[N];       mint NRHS=1;       mint LDA=N,LDB=N;       mint INFO;       mint i,j;            mcomplex AP[N*(N+1)/2];            for(j=0;j<N;j++)         for(i=0;i<=j;i++)           AP[i + (j+1)*j/2] = A[i*N+j];            zspsv_(&U,&N,&NRHS,AP,IPIV,B,&LDB,&INFO);            MArgument_setMTensor(Res,tb);       return LIBRARY_NO_ERROR;     }               ";     Needs["CCompilerDriver`"];          CreateLibrary[MMASrc,"lpk","Debug"->True,"TargetDirectory"->"/tmp",             "CompileOptions"->"-llapack"];          A={{1. +0. I,0. +0. I,0. -6.94908*^-13 I,0. -6.94908*^-13 I},                {0. +0. I,1. +0.0352595 I,0. -4.51893*^-11 I,0. -4.51893*^-11 I},                {0. -6.94908*^-13 I,0. -4.51893*^-11 I,1. +0.0376938 I,0. +0. I},                {0. -6.94908*^-13 I,0. -4.51893*^-11 I,0. +0. I,1. +0.0378932 I}};          B={1. +0. I,0. +0. I,0. +6.94908*^-13 I,0. +6.94908*^-13 I};          lpkSolve=LibraryFunctionLoad["/tmp/lpk.dylib","lpkSolveAXBS",             {{Complex,2},{Complex,1}},{Complex,1}]     (*LibraryFunction[<>,lpkSolveAXBS,{{Complex,2},{Complex,1}},{Complex,1}]*)          Abs[LinearSolve[A,B]-lpkSolve[A,B]]//Max     (*2.02047*10^-28*)          Table[LinearSolve[A,B],{40000}];//AbsoluteTiming     (*{0.470767,Null}*)          Table[lpkSolve[A,B],{40000}];//AbsoluteTiming     (*{0.086038,Null}*)          Table[lpkSolve[A,B],{40000}];//AbsoluteTiming      In executing `In[10]`, I hear a beep sound and then the kernel crashes and there is no output. Why the kernel crashes at the second time of invoking the LibraryLink function? How to fix that? **Update** As Todd Gayley commented under halirutan's answer, this is a bug. **Update** Still not fixed in version 10.0.


title: Plotting a function by converting it to a delayed differential equation

text: I am having a little trouble calculating the Dickman Function from scratch. I have downloaded the notebook from the above link and the have following code:               Off[      InterpolatingFunction::dmval, NDSolve::precw, Power::"infy", Less::"nord", NDSolve::"nlnum"      ];          Clear[F];     F[0][x_] = Which[x < 0, 0, 0 <= x <= 1, Exp[1 - 1/x], x > 1, 1];     With[{ε = 10^-5, n = 20},       Do[ndsol[k] =          NDSolve[{F[k]'[x] == F[k - 1][x/(1 - x)]/x, F[k][ε] == F[k - 1][ε]},            F[k], {x, ε, 1},           WorkingPrecision -> 35, MaxSteps -> 10^5, PrecisionGoal -> 18,            AccuracyGoal -> 18][[1, 1, 2]];         Print["Step ", k, "..."];         F[k][x_] =            Which[             x < 0, 0,              0 <= x <= 1, Evaluate[ndsol[k][x]/ndsol[k][2]],              x > 1, 1],         {k, n}]]     Plot[F[20][a], {a, 0, 1}, PlotRange -> All, PlotStyle -> Red]      It makes the following plot: ![enter image description here](http://i.stack.imgur.com/EXGip.gif) which is a plot of $$\rm {F}(\alpha)=\int_{0}^{\alpha}\rm {F} \bigg ( \frac{t}{1-t} \bigg)\frac{\,dt}{t}$$ I am having trouble modifying the above _Mathematica_ code so I can eventually plot $$\rm {G}(\beta)=\int_{0}^{\beta}\bigg [\rm {G} \bigg (\frac{t}{1-t} \bigg )-\rm {F} \bigg (\frac{t}{1-t} \bigg ) \bigg]\frac{\,dt}{t}$$ using the same method. Ultimately, I would like to go on to plot $$\rm {H}(\gamma)=\int_{0}^{\gamma}\bigg [\rm {H} \bigg (\frac{t}{1-t} \bigg )-\rm {G} \bigg (\frac{t}{1-t} \bigg )-\rm {F} \bigg (\frac{t}{1-t} \bigg ) \bigg]\frac{\,dt}{t}$$


title: SparseArray internal structure

text: According to the documentation: > `SparseArray` is treated as a raw object by functions like `AtomQ` and for > purposes of pattern matching. Furthermore, they have specific functions to access and format subparts (`Dimensions`, `ArrayRules`, `Normal`, etc. ), though they also have an intricate internal structure. There is however little information on what exactly certain elements mean. Some examples:               Normal@SparseArray[{2, 3, 4} -> {1, 1, 1}, {6}]     InputForm@SparseArray[{2, 3, 4} -> {1, 1, 1}, {6}]      > >      {0, 1, 1, 1, 0, 0} >      SparseArray[Automatic, {6}, 0, {1, {{0, 3}, {{2}, {3}, {4}}}, {1, 1, > 1}}] >                 x = SparseArray[{{i_, i_} -> 1, {3, 2} -> 2, {5, _} -> "x"}, {5, 4}, -1];     Normal@x           InputForm@x      > >        {{1, -1, -1, -1}, >         {-1, 1, -1, -1}, >         {-1, 2, 1, -1}, >         {-1, -1, -1, 1}, >         {"x", "x", "x", "x"}} >   >       SparseArray[Automatic, {5, 4}, -1, >            {1, {{0, 1, 2, 4, 5, 9}, {{1}, {2}, {3}, {2}, {4}, {4}, {3}, {2}, > {1}}}, >            {1, 1, 1, 2, 1, "x", "x", "x", "x"}}] >   For example, what is the purpose of the _Automatic_ at the first position and what other values can be used instead of it?


title: Plotting the frequency spectrum of a data series using Fourier

text: testData = Table[N@Sin[500 x], {x, 0, 100}];     ListLinePlot[Abs[Fourier[testData]], PlotRange -> Full]      Gives me ![enter image description here](http://i.stack.imgur.com/zM6mT.png) Which I do not expect because the Fourier Transform is `FourierTransform[Sin[500 x], x, f],` > >     I Sqrt[Pi/2] DiracDelta[-500+f]-I Sqrt[Pi/2] DiracDelta[500+f] >   I'm not saying that Mathematica's Fourier function is somehow faulty. But could someone please explain why there isn't a peak around 500? This is the frequency of the signal after all...


title: How can I solve this PDE with initial conditions?

text: I wish to solve the following second order partial differential equation $$u_{tt}=c^2 u_{xx}$$ with the initial conditions $$u(x,0)=e^x,\quad u_t(x,0)=\sin x$$ In _Mathematica_ , I evaluated the following code:               DSolve[{D[p[x, t], {t, 2}] == c^2 *(D[p[x, t], {x, 2}]),              p[x, 0] == Exp[x], D[p[x, t], t] == Sin[x]},           p[x, t], {x, t}]      _Mathematica_ responded with > DSolve::deqx: Supplied equations are not differential equations of the given > functions. I think the problem lies in the initial conditions. How can I fix this code?


title: How to find the distance of two lists?

text: I have two lists as the followings:               ab = {1, -1, -1, -1, 1, 1};     ac = {1, -1, -1,  1, 1, 1};      How I can find the difference (more precisely, the **edit distance** ) between them? In this case the result should be 1, since there is one item difference between `ab` and `ac`. Note: in my case, the list elements only take the values 1 and -1, and both lists are one dimensional of the same length, but it is always nice to see more general solutions (elements are of `Reals`, lists are matrices, etc.). Thank you.


title: Taking Log Transformation of unit circle using Presentations package

text: << Presentations`          circle = ComplexCircle[0.1, 1/2];     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      The above code works, creating the following image. ![Mathematica graphics](http://i.stack.imgur.com/6ozno.png) However, if I change the center to the origin:               circle = ComplexCircle[0, 1/2];     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      The code fails, giving the following error message: > Coordinate {DirectedInfinity[-1], 0} should be a pair of numbers, or a > Scaled or Offset form. But this works with center at the origin:               circle = {Red, Thickness[0.02],         ComplexCurve[Exp[I t], {t, 0, 2 Pi}]};     domain = Draw2D[{Opacity[0.6], circle},        Frame -> True,        Axes -> True,        PlotRange -> 2,        FrameLabel -> {Re, Im},        PlotLabel -> z, ImageSize -> 200];     image = Draw2D[{Opacity[0.6], circle // ComplexMap[Log]},        Frame -> True,        Axes -> True,        PlotRange -> 4,        FrameLabel -> {Re, Im},        PlotLabel -> w,        ImageSize -> 200];     Row[{domain, image}]      Producing this image: ![Mathematica graphics](http://i.stack.imgur.com/E5mf7.png) What's going on?


title: How to Compute Aggregate Best and Worst Cases for a Large Number of Estimates?

text: I need to aggregate multiple estimations, but I haven't been able to find a built-in function in _Mathematica_ that aggregates multiple probablity estimations (I am specially interested in estimations based on the `PERTDistribution`) I am being told that I need to:   1. Compute the standard deviation of each estimation   2. Compute the square of each task’s standard deviation, which is known as the variance.   3. Total the variances.   4. Take the square root of the total. First of all, is that correct? And if it is, is there a function in _Mathematica_ that can do all that for me? Something like a hypotetical `AggregateDistribution` that would work like:               AggregateDistribution[PERTDistribution[{min, max}, mode], numberOfEstimatesToAggregate]      Any guidance on a function that provides this or a way to do it would be welcome.


title: Is it necessary to have a prior computational background or is it possible to learn Mathematica as a first programming language?

text: I have a background in economics and I'm very interested in learning _Mathematica_ but I'm afraid of starting out because I have seen that most programmers already have a good background in some kind of procedural language, and I don't! My goal is to start learning _Mathematica_ , and take it as my Swiss army knife. I don't want to spend time to become good in another language first, and start to study to be a good software developer in _Mathematica_ only after that. So, my question is: Is it strictly necessary to have a prior knowledge in another kind of language, or one can master, from level zero, and be a great Mathematica programmer just starting programming through _Mathematica_? It seems to me that there aren't any efforts (books, tutorials, documentation) in this sense directed to the self learner. What do you think? Is there a way?


title: RevolutionPlot3D: axis of revolution that doesn't pass through the origin

text: This is a follow up question to RevolutionPlot3D: but NOT revolving about the z axis so please check that for the context. It seems that `RevolutionAxis` requires the axis of revolution to pass thru the origin. Suppose I want to use an axis of revolution that does not pass through the origin, e.g., the line $y=-1$ in the example above. What is a good way to accomplish this? I do realize that `RegionPlot3D` may be appropriate here, but even with seemingly simple examples such as the one above, it can struggle:               Show[       RegionPlot3D[1 <= Sqrt[(y + 1)^2 + z^2] <= 1 + x^2, {x, 0, 1},          {y, -3, 3}, {z, -3, 3}, PlotRange -> All, PerformanceGoal -> "Quality",          Mesh -> False, AxesLabel -> {x, y, z}, PlotPoints -> 100,          ViewPoint -> {0.87, 0.44, 1.76}, ViewVertical -> {0.32, 0.67, 0.67}],       Graphics3D[{Thickness[.01], Black, Line[{{0, -1, 0}, {1.15, -1, 0}}]}]     ]      ![enter image description here](http://i.stack.imgur.com/c5BNm.png) Bumping `PlotPoints` up to 200, 300, 400 doesn't alleviate the problem and gets really slow.