Circumnavigating a curve or going through it to show different behavior

I am not sure if what I want to do is possible in _Mathematica_. I've provided something simple below to convey what I want to do. Basically what I want to happen is that when the `Locator` crosses over the blue line, the `Disk[]` will turn red and stay red until the `Locator` crosses the blue line again (it should stay red regardless of where the `Locator` is).               Manipulate[      Plot[x^3, {x, 0, 1}, PlotRange -> {{0, 1.5}, {0, 1.5}}, Frame -> True,       Epilog ->         Inset[Graphics[{Blue, Disk[]}, ImageSize -> 30], {0.2, 1}]],      {{comp, {0.5, 0.7}}, Locator}]      ![enter image description here](http://i.stack.imgur.com/5QeWT.png) I am trying to make a Demonstration that shows the behavior of a single component (water in this case) on a pressure vs. temperature phase diagram. Water exists in 3 distinct phases and there is only a phase change from liquid to vapor (or supercritical) if a certain boundary is crossed (looks like the one I showed here) but you can go around that boundary and not change phase. So that's what I am trying to show here with the colored disk as the indicator of "phase change" EDIT:               Manipulate[      DynamicModule[{col = False, acc = 0, p = {420, Log[6]}},       EventHandler[Show[Quiet@LogPlot[Log[T], {T, 273.16, 647.096}, PlotStyle -> Thick] /.           l_Line :> EventHandler[l, {"MouseEntered" :> If[acc === 0,      (col = col /. {True -> False, False -> True})]}],         Frame -> True, PlotRange -> {{273.16, 700}, {Log[5.6], Log[7]}},          Epilog ->           Inset[Graphics[            Text[Style[Dynamic@If[col == True, "liquid", "vapor"], 18],              Scaled[{0.400, 0.1}]]]]],        {"MouseDown" :> (acc = 1; MousePosition[Dynamic@p]),          "MouseDragged" :> (MousePosition[Dynamic@p]),          "MouseUp" :> (acc = 0; MousePosition[Dynamic@p])},         PassEventsDown -> True]],      {{p, {420, Log[6]}}, Locator,        Appearance -> Graphics[{Disk[]}, ImageSize -> 12]}]      It will only work if the mouse is _not_ depressed.


How to determine the remaining sides given the three angles and one side of a triangle?

The measure of the interior angles of a triangle are $15^\circ$, $30^\circ$, $135^\circ$ and the length of one edge is 3. In order to determine the length of the remaining two edges, I've tried               a := 3;      eq1 := (a^2 + b^2 - c^2)/(2*a*b);      eq2 := (b^2 + c^2 - a^2)/(2*b*c);     eq3 := (c^2 + a^2 - b^2)/(2*a*c);      Solve[{eq1 == Cos[15 Degree], eq2 == Cos[30 Degree], eq3 == Cos[135 Degree]}, {b,c}]     (*     {{b -> 3 Sqrt[2], c -> (3 (3 Sqrt[2] - 2 Sqrt[6]))/(-3 + Sqrt[3])}}     *)      And               Solve[{x^2 + y^2        == (3 Sqrt[2])^2,             (x - 3)^2 +  y^2 == ((3 (3 Sqrt[2] - 2 Sqrt[6]))/(-3 + Sqrt[3]))^2}, {x, y}]     (*     {{x -> (3 (1 - Sqrt[3]))/(2 (-2 + Sqrt[3])),        y -> -3 Sqrt[(26 - 15 Sqrt[3])/(2 (7 - 4 Sqrt[3]))]},       {x -> (3 (1 - Sqrt[3]))/(2 (-2 + Sqrt[3])),        y -> 3 Sqrt[(26 - 15 Sqrt[3])/(2 (7 - 4 Sqrt[3]))]}}     *)      By putting `A := {0, 0, 0}`, `B := {3,0, 0}` and               C := {(3 (1 - Sqrt[3]))/(2 (-2 + Sqrt[3])), 3 Sqrt[(26 - 15 Sqrt[3])/(2 (7 - 4 Sqrt[3]))], 0}      Are the measure of the angles of the triangle $ABC$ $15^\circ$, $30^\circ$, $135^\circ$? How do I tell Mathematica to do that?


How to use an output of a Solve function in further calculations?

Following is the polynomial equation that gives me a single real root:               y[ts_, cp_, wg_, pa_, ps_, m_, dair_] :=        Solve[(.024*((9.81*ds[ts, cp, wg, pa, ps, m, dair])/               uj[ts, cp, wg, pa, ps]^2)^(1/3))*x^(5/3) + .2*x^(           2/3) - ((2.85/w[wg])^(2/3)) == 0, x];      I do get the result that I seek: > {x-> 303.6} I would like to use this result in my further calculations.   I have tried a couple of things which I have found here on the forum: Using the output of Solve   Extract numerical value using Solve   Assign the results from a Solve to a variable(s) But still can't get it to work. Ultimately I would like to have a variable that holds a value of this particular equation, so I can use it in my further calcs. **EDIT:** Here is what I have tried to do:               x /. y[288, 1520, 0.0186, 0.1, 10, 30, 1.21]      Result : > ReplaceAll::reps: "{y[288,1520,0.0186,0.1,10,30,1.21]} is neither a list of > replacement rules nor a valid dispatch table, and so cannot be used for > replacing." And               answ = x /. y[288, 1520, 0.0186, 0.1, 10, 30, 1.21]      Result: > z /. y[288, 1520, 0.0186, 0.1, 10, 30, 1.21] **EDIT 2** (Complete set of equations)               mj[cp_, wg_, pa_, ps_] :=        Sqrt[((γ[cp, wg] + 1)*(po[cp, wg, ps]/pa)^((γ[cp, wg] - 1)/γ[cp, wg]) - 2)/(γ[cp, wg] - 1)];     po[cp_, wg_, ps_] := ps*(2/(γ[cp, wg] + 1))^(γ[cp, wg]/(γ[cp, wg] - 1));     γ[cp_, wg_] := cp/(cp - (8.3141/wg));     tj[ts_, cp_, wg_, pa_, ps_] := ts*(pa/ps)^((γ[cp, wg] - 1)/γ[cp, wg]);     uj[ts_, cp_, wg_, pa_, ps_] := mj[cp, wg, pa, ps]*Sqrt[(γ[cp, wg]*8.3141*tj[ts, cp, wg, pa, ps])/ wg];     ds[ts_, cp_, wg_, pa_, ps_, m_, dair_] := Sqrt[(4*m)/(π*dair*uj[ts, cp, wg, pa, ps])];     y[ts_, cp_, wg_, pa_, ps_, m_, dair_] := Solve[(.024*((9.81*ds[ts, cp, wg, pa, ps, m, dair])/uj[ts, cp, wg, pa, ps]^2)^(1/3))*x^(5/3) + .2*x^(2/3) - ((2.85/w[wg])^(2/3)) == 0, x];     w[wg_] := wg/(15.816*wg + .0395);      Input used:               ts = 288  cp = 1520 wg = .0186 pa = .1 ps = 10 m = 30 dair = 1.21


Ηow to create an interpolated CDF from its samples?

I want to use a distribution I have only aggregate statistics on, namely its CDF sampled at certain points. I would like to keep it "nonparametric" (remain noncommittal on the parametric form), but I need some interpolation over these points. Also, I would like to use a PDF of the distribution. So I would need an interpolation that is monotone and differentiable over a list. What is there to do? (FWIW: With `Interpolation[]`, only a first-order interpolation is monotone, but then there are non-differentiable breakpoints in the piecewise linear function.) Here is a list I would interpolate over: **EDIT** : This is the US taxable income distribution for 2009 which I manually extended with two endpoints to help it look like a CDF. This latter point might be silly, let me know how you'd do better.               {{0,0},{5000.,0.00373625},{10000.,0.0269361},{15000.,0.0621601},{20000.,0.121612},      {25000.,0.178247},{30000.,0.234482},{40000.,0.3516},{50000.,0.453972},{75000.,0.654898},      {100000.,0.78906},{200000.,0.952381},{500000.,0.991166},{1.*10^6,0.997134},      {1.5*10^6,0.998442},{2.*10^6,0.998977},{5.*10^6,0.999727},{1.*10^7,0.9999},{10000000000,1}}


WhenEvent "StopIntegration" problem

The first example on the WhenEvent help page is               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,         WhenEvent[y[t] == 0, y'[t] -> -0.95 y'[t]]}, y, {t, 0, 10}];      Say I want to stop the integration at the first bounce, I would put               NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0,         WhenEvent[y[t] == 0,"StopIntegration"]}, y, {t, 0, 10}];      That, however, does not stop the integration (i.e. it goes on to t=10), neither does the condition y[t] < 0. What am I doing wrong?


How to expand a function into a power series with negative powers?

Is there any way to expand this expression               a+b(1-Exp[-T/(b c)]/(z-Exp[-T/ (b c)])      (where `a`, `b`, `c`, and `T` are constants) as a series in _negative_ powers of $z$? The result should be in the form               a0 + a1 z^(-1) + a2 z^(-2) + a3 z^(-3) + ... + an z^(-n)      I tried solutions like `Series[a + b (1 - k/(z - k)), {z, 0, -5}]` but this did not work. Thank you.


Problem with transparency when I export an eps file

I have the following simple Mathematica code:               Clear["Global`*"];     x = Cos[t];     y = Sin[t];     L1 = ParametricPlot3D[{x, y, t}, {t, 0, 50},         PlotStyle -> {Blue, Thickness[0.003]}, Axes -> True,         AxesLabel -> {"x", "y", "t"}, BoxRatios -> {1, 1, 1},         AxesStyle -> Directive[Black, FontSize -> 17, FontFamily -> "Helvetica"],         PlotPoints -> 500, PlotRange -> All, ImageSize -> 500];     L2 = Graphics3D[{EdgeForm[None], Opacity[0.2], GrayLevel[0.1],      Specularity[White, 20], Mesh -> None, Lighting -> None,      Cuboid[{-1, -1, 38}, {1, 1, 50}]}];     P1 = Show[{L1, L2}, ViewPoint -> {1.3, -2.4, 1.5}]       However, when I try to export this three-dimensional plot in eps format, all the part of function which is inside the cuboid, that is when z>38 does not appear. It seems that somehow during the export the options `Opacity` is overruled. Is there a way to export this plot correctly?


Row inside FrameLabel doesn't work in Mathematica 9

So as to automate/customize plot titles I use `Row` inside e.g. FrameLabel:   `FrameLabel -> {"x", "y", Row[...]}` Now with Mathematica 9, the plot doesn't show the bit referring to Row. Does someone know how to fix this?


defining recursively a function with multiple if conditions

I am trying to recursively define a function which satisfies the following system of equations and which depends on two parameters $n$ and $l$, $$ \begin{align} A(x, n, l) &= F[ A(x,n-1,l) ]\\ A(x, n, l) &= x^l \mbox{ if } l = n \\ A(x, n, l) &= 0 \mbox{ if } l < n \\ \end{align} $$ In order to do this I used the following code (here I make the expression for $F$ explicit):               A[x_, n_, l_]:=       Boole[n > l]((1 - x)/(1 + x^l) * (Sum[A[x, n-1-i, l] * x^i, {i,0,l-1}])       + x^l/(1 + x^l)) + Boole[n == l] * x ^ l      The function defined in this way, $A(x, n, l)\;$, gives the probability that tossing a coin $n$ times gives exactly one run of $l$ consecutive $1$s, where $x$ is the probability getting $1$ on single toss and $(1-x)$ is the probability getting $0$ on single toss. When I try to plot one of these functions, for instance,               Plot[A[x, 7, 7], {x, 0, 1}]      I encounter the following error: > RecursionLimit::reclim: Recursion depth of 256 exceeded. Is my code wrong? Is there an other way to recursively define a function, taking into account the fact that the third condition must be satisfied for _all_ the values $l<n$, where $l$ and $n$ are not specified at the moment of the definition.


Add keyboard shortcut to the DisplayFormula style

Is there a way to set up key bindings for the `DisplayFormula` and `DisplayFormulaNumbered`styles? I am using _Mathematica_ 9 on mac OS X 10.7.5. This would be very useful as it is time consuming having to click through with the mouse each time.


Look up info associated with a given CAS chemical identifier from the NIST webbook & NCI CADD Chemical Identifier Resolver

I would like to retrieve information associated with a given CAS registry number (Chemical Abstracts Service nr) from the NIST webbook web site in Mathematica, using the provided API (e.g. for geraniol, http://webbook.nist.gov/cgi/cbook.cgi?ID=106-24-1&Units=SI&Mask=2000#Gas- Chrom) (note I use the NCI CADD cactus server to convert InChiKeys to molecular structures if NIST doesn't list the molecular structure). E.g. for a few example CAS chemical identifiers                   casnrs = {"106-24-1", "28115-92-6", "281-17-4", "28122-24-9", "28122-25-0", \     "28122-28-3", "281-23-2", "28123-26-4", "28123-68-4", "28123-70-8"};      I would like to download all associated information listed at the NIST webbook site. What is the best method to go about doing this in Mathematica? Edit: with the help of some of the posts below I came to the following solution: (below is also an alternative method based on importing the website as XML) ## Import molecular structures               getmolstrcactus[casnr_, threed_] :=        Module[{str, notes, inchikey},         If[threed == True, str = "?get3d=true"; notes = "Cactus/Corina MM",          str = ""; notes = "Cactus"];        Quiet[Check[{Import[            "http://cactus.nci.nih.gov/chemical/structure/" <> casnr <>              "/sdf" <> str, "MOL"], "Cactus/Corina MM"}          , inchikey =            StringReplace[            ImportString[              URLFetch["http://webbook.nist.gov/cgi/cbook.cgi",                "Parameters" -> {"ID" -> casnr, "UNITS" -> "SI",                  "MASK" -> "2000"}], {"HTML", "Data"}][[2, 4]],             "IUPAC Standard InChIKey: " -> ""];          Check[{Import[             "http://cactus.nci.nih.gov/chemical/structure/" <> inchikey <>               "/sdf" <> str, "MOL"], "Cactus/Corina MM"},           {"NA", "NA"}]]]];     import2Dmolstr[casnr_] :=        Module[{},         raw = Import[          "http://webbook.nist.gov/cgi/cbook.cgi?Str2File=C" <> casnr,           "String"];        If[StringLength[raw] != 183,         {Quiet[ImportString[raw, "MOL"]], "NIST"},          getmolstrcactus[casnr, False]]];     AbsoluteTiming[import2Dmolstr /@ casnrs // TableForm]      ![2D molecular structure](http://i.stack.imgur.com/ljhwP.png)               import3Dmolstr[casnr_] := Module[{},        Quiet[Check[{Import[            "http://webbook.nist.gov/cgi/cbook.cgi?Str3File=C" <> casnr,             "MOL"], "NIST/MOPAC6/GAUSSIAN94 PM3"},           getmolstrcactus[casnr, True]]]];     AbsoluteTiming[import3Dmolstr /@ casnrs // TableForm]      ![3D molecular structure](http://i.stack.imgur.com/aXrCJ.png) ## Import infrared and/or electron ionization mass spectra               importspectrum[casnr_, type_] := Quiet[Module[{}, If[type == "Mass",          Check[           ImportString[             StringReplace[              Import["http://webbook.nist.gov/cgi/cbook.cgi?JCAMP=C" <>                 StringReplace[casnr, "-" -> ""] <> "&Index=0&Type=" <>                 type, "String"], {x : NumberString ~~ " " ~~                  y : NumberString :> x <> "\n" <> y}], "JCAMPDX"][[1]],            "NA"], Check[           Import["http://webbook.nist.gov/cgi/cbook.cgi?JCAMP=C" <>               StringReplace[casnr, "-" -> ""] <> "&Index=0&Type=" <> "IR",              "JCAMPDX"][[1]], "NA"]]]];      importmassspectrum[casnr_] := importspectrum[casnr, "Mass"];     importIRspectrum[casnr_] := importspectrum[casnr, "IR"];          plotIRspec[casnr_] := Module[{}, spec = importIRspectrum[casnr];        Quiet[Check[          ListPlot[spec, Joined -> True, PlotRange -> All,            PlotStyle -> PointSize[0]], "NA"]]];     plotmassspec[casnr_] := Module[{}, spec = importmassspectrum[casnr];        Quiet[Check[          ListPlot[spec, Filling -> Axis, FillingStyle -> Blue,            PlotRange -> All, PlotStyle -> PointSize[0]], "NA"]]];          plotIRspec["7647-01-0"]      ![IR spectrum](http://i.stack.imgur.com/BpLAJ.png)               AbsoluteTiming[plotmassspec /@ casnrs // TableForm]      ![spectra](http://i.stack.imgur.com/NKXPi.png) ## Import other info               removeHTML[str_] :=        StringSplit[StringReplace[str, "<" ~~ Except[">"] .. ~~ ">" -> ""],         "\n"];     stringclean[str_] :=        StringReplace[        str, {"»" -> "", "«" -> "", ";" -> "",          "alpha" -> "\[Alpha]", "beta" -> "\[Beta]", "gamma" -> "\[Gamma]",          "delta" -> "\[Delta]", "epsilon" -> "\[Epsilon]"}];     stringcheck[str_, part_] :=        Quiet[Check[         If[StringTake[str, StringLength[part]] == part,           StringReplace[str, part -> ""], "NA"], "NA"]];     CAScactusinfo[casnr_] :=        Quiet[Module[{formula, mw, inchi, inchikey, name, synonyms, source},         formula =           Check[Import[            "http://cactus.nci.nih.gov/chemical/structure/" <> casnr <>              "/formula", "String"], "NA"];         If[formula != "NA",          mw =            Import["http://cactus.nci.nih.gov/chemical/structure/" <>              casnr <> "/mw", "String"];          inchi =            StringSplit[             Import["http://cactus.nci.nih.gov/chemical/structure/" <>                casnr <> "/stdinchi", "String"], "InChI="][[1]];          inchikey =            StringSplit[             Import["http://cactus.nci.nih.gov/chemical/structure/" <>                casnr <> "/stdinchikey", "String"], "InChIKey="][[1]];          name =            Import["http://cactus.nci.nih.gov/chemical/structure/" <>              casnr <> "/iupac_name", "String"];          synonyms =            StringJoin[            Riffle[Import[              "http://cactus.nci.nih.gov/chemical/structure/" <> casnr <>                "/names", "List"], "|"]];          source = "NCI/CADD Cactus Chemical Identifier Resolver";,          {formula, mw, inchi, inchikey, name, synonyms, source} = {"NA",              "NA", "NA", "NA", "NA", "NA", "NA"};];         {formula, mw, inchi, inchikey, name, synonyms, source}]];     CASnistinfo[casnr_] :=        Module[{raw, data, parts, formula, mw, inchi, inchikey, cas, name,          synonyms, stereoisomers, source, cactusinfo},        raw = Check[          ImportString[           URLFetch["http://webbook.nist.gov/cgi/cbook.cgi",             "Parameters" -> {"ID" -> casnr, "UNITS" -> "SI",               "MASK" -> "2000"}], {"String"}], ""];        data = ImportString[raw, {"HTML", "Data"}];        If[And[data != {},           data != {" Standard Reference Data Program", " Data Gateway",             "Chemistry WebBook"}],         parts = {"Formula : ", "Molecular weight : ", "InChI=",            "IUPAC Standard InChIKey: ", "CAS Registry Number: ",            "Other names:", "Stereoisomers:"};         formula =           StringReplace[stringcheck[data[[2, 1]], parts[[1]]], " " -> ""];         mw = stringcheck[data[[2, 2]], parts[[2]]];         cas = casnr;(* stringcheck[data[[2,5]],parts[[5]]]; *)          name =           stringclean[           StringSplit[StringSplit[raw, "<title>"][[2]], "</title>"][[1]]];         synonyms =           Quiet[           Check[If[Length[StringPosition[raw, parts[[6]]]] != 0,              Quiet[stringclean[               StringJoin[                Riffle[removeHTML[                  StringSplit[                    StringSplit[raw, "strong>Other names:"][[2]],                     ""][[1]]], "|"]]]], "NA"], "NA"]];         stereoisomers =           Quiet[Check[            If[Length[StringPosition[raw, parts[[7]]]] != 0,              Quiet[stringclean[               StringJoin[                Riffle[removeHTML[                  StringSplit[                    StringSplit[raw, "strong>Stereoisomers:"][[                     2]], ""][[1]]], "|"]]]], "NA"], "NA"]];         inchi = Quiet[stringcheck[data[[2, 3, 1, 1]], parts[[3]]]];         inchikey = stringcheck[data[[2, 4]], parts[[4]]];         If[inchi == "NA", cactusinfo = CAScactusinfo[casnr];          inchi = cactusinfo[[3]];          inchikey = cactusinfo[[4]];          source =            "NIST Webbook and NCI/CADD Cactus Chemical Identifier \     Resolver";, source = "NIST Webbook";];         {casnr, formula, mw, inchi, inchikey, cas, name, synonyms,           stereoisomers, source},         {formula, mw, inchi, inchikey, name, synonyms, source} =           CAScactusinfo[casnr];         {casnr, formula, mw, inchi, inchikey, casnr, name, synonyms, "NA",           source}]];     AbsoluteTiming[CASnistinfo /@ casnrs // TableForm]      ![chemical info](http://i.stack.imgur.com/K2Ubj.png) ## Import gas chromatography retention indices (Note: here I partly parse the raw HTML, in the post below there is also a nice solution based on importing as XML)               CASnistRIs[casnr_] :=        Quiet[Module[{raw, raw2, fun, RItypes, nRItypes, data, dat, pos,           RItypecol, RIdata, inchikey},         Check[          raw = URLFetch[            "http://webbook.nist.gov/cgi/cbook.cgi?ID=" <> casnr <>              "&Units=SI&Mask=2000#Gas-Chrom"];          raw2 =            Drop[StringSplit[             StringSplit[               StringSplit[raw,                  "
Gas \     Chromatography
"][[2]],                "
References"][[1]],              "
"], 1];          fun[s_] := StringSplit[StringSplit[s, "Type="][[2]], "#"][[1]];          RItypes = Map[fun, raw2];          nRItypes = Length[RItypes];          data = ImportString[raw, {"HTML", "Data"}];          pos = Position[data, "Column type"][[1, 1]];          RItypecol = {};          RIdata = ArrayFlatten[Table[dat = Drop[data[[pos + i - 1]], 1];             If[Dimensions[dat][[2]] == 5,               dat = Transpose[                 Insert[Transpose[dat],                   Table["NA", {Dimensions[dat][[1]]}], 3]];];             RItypecol =               Append[RItypecol,                Table[RItypes[[i]], {Dimensions[dat][[1]]}]];             dat, {i, 1, nRItypes}], 1];          RItypecol = Flatten[RItypecol];          RIdata = Transpose[Insert[Transpose[RIdata], RItypecol, 1]];          RIdata =            Transpose[            Insert[Transpose[RIdata],              Table[casnr, {Dimensions[RIdata][[1]]}], 1]];          data = ImportString[raw, {"HTML", "Data"}];          inchikey = stringcheck[data[[2, 4]], "IUPAC Standard InChIKey: "];          If[inchikey == "NA",            inchikey =              Quiet[Check[               StringSplit[                 Import["http://cactus.nci.nih.gov/chemical/structure/" <>                    casnr <> "/stdinchikey", "String"], "InChIKey="][[1]],                "NA"]];];          RIdata =            Transpose[            Insert[Transpose[RIdata],              Table[inchikey, {Dimensions[RIdata][[1]]}], 2]];          RIdata =            Insert[RIdata, {"CAS nr", "InChiKey", "RI type", "Column",              "Active phase", "Temperature (\[Degree]C)", "RI", "Reference",              "Temperature program"}, 1], "NA"]         ]];     AbsoluteTiming[CASnistRIs["106-24-1"]  // TableForm ]      ![RI info](http://i.stack.imgur.com/QKhLz.jpg)


symbolic integration error

I'm running Mathematica 10.0.0 and encountered a disturbing error in the symbolic integration of a rather simple function               Integrate[(1 - x)*(1 + 2*x)^6/Sqrt[1 - x^2], {x, -1, 1}]/Pi      The correct value for this integral is 15 (and NIntegrate gives that correctly) but Mathematica evaluates it symbolically as 1/π+29/2. I tried Wolfram Alpha, and it also gives the wrong answer. Any idea what is going on? ![incorrect Wolfram Alpha symbolic evaluation of this integral](http://i.stack.imgur.com/ALWWd.png) the correct answer is 15π=47.1239 * * * splitting the integrand into two parts does give the correct answer 15,               Integrate[(1 + 2*x)^6/Sqrt[1 - x^2], {x, -1, 1}]/Pi -       Integrate[x*(1 + 2*x)^6/Sqrt[1 - x^2], {x, -1, 1}]/Pi      somehow Mathematica has difficulty with square root singularities in the integrand?


Simplify results further

I have an extremely long result in polynomial form following some matrix operations. However, given the symmetry of the problem, I can safely say that the solution will reduce much further than is being displayed here, especially if it can be expressed in summation notation. When I look at simple cases I can see many obvious simplifications that are not being done, primarily with z variables being left in denominators instead of being divided out. Is there any way I can have mathematica simplify all the way? Can it perform the summation contraction?               a = {{a1}, {a2}, {a3}}/za;     b = {{b1}, {b2}, {b3}}/zb;     c = {{c1}, {c2}, {c3}}/zc;     d = {{d1}, {d2}, {d3}}/zd;     k = {{k1}, {k2}, {k3}};     s = {{s11, s12, s13}, {s21, s22, s23}, {s31, s32, s33}};     G =        a.Transpose[a] + b.Transpose[b] + c.Transpose[c] + d.Transpose[d];     MatrixForm[      Simplify[Transpose[k].s.Inverse[G].Transpose[s].k]] (*Answer is not a matrix but calling like this gives a simpler looking output.*)


Reproducing nested loops using Map?

I keep producing bits of code like the following:               stuff = Module[         {curTarget = #},         getRowsForUserAndTarget[u, #, curTarget] & /@ validUsers     ] & /@ allTargets;      Basically, I'm iterating through all the targets and all the users. Using a For loop it would look something like this (in python):               res = []     for user in validUsers:         for curTarget in allTargets:             res.append(getRowsForUserAndTarget[u, user, curTarget])      It seems like I should be able to do this succinctly in map notation using something like:               getRowsForUserAndTarget[#userthing, #targetthing]& /@ validUsers /@ validTargets      but I don't know how to keep the mapped arguments from interfering with each other, or how to reference which one I mean; and I'm a little hazy about the order of iteration (validUsers would go first, then validTargets?) Can someone set me straight? This would seem like a common pattern that I am abusing with my Module[] solution...


Coloring edges in GraphPlot

I'm a little stuck with graph drawing part of my research — I can't use the `Graph` function for plotting my graphs, because my graph is a multi-graph. `Graph` is convenient because it colors edges quite easily. Since I have a 3-regular (or even 4-regular) graph, where there are 3 (or 4) perfect matching, I want each of the matching to be colored differently. What's the best way to color a group of edges (each perfect matching with it's own color) in the given adjacency list in `GraphPlot`? To simplify it, we can assume, that groups goes one by one (e.g. we have 6 edges: 3 groups of two edges, following each other               {1<->2, 3<->4, 1<->3, 2<->4, 1<->2, 3<->4}      In `Graph`, I've constructed a nice lambda function, that wraps all elements of a list in a `Style` function, that colors the edge. But in a `GraphPlot` I can't wrap edges in a `Style` function. There's an `EdgeRenderingFunction`, wich draws all the edges. How do I put three different `EdgeRenderingFunctions` for the one edge-set? Or is that the wrong way to go? Any ideas, how to do that? **Answer:** The labeled answer is absolutely correct. Little generalization of what I needed and how to implement it:                 GraphPlot[{{1 -> 2, 1}, {3 -> 4, 1}, {1 -> 3, 2}, {2 -> 4, 2}, {1 -> 2, 3},                                {3 -> 4, 3}}, MultiedgeStyle -> .2,                   ImagePadding -> 10,                   EdgeRenderingFunction -> (Switch[#3, 1, {Red, Line[#1]},                   2, {Blue, Line[#1]}, 3, {Green, Line[#1]},                   4, {Dashed, Line[#1]}] &), VertexLabeling -> True,                   Method -> "CircularEmbedding"]      ![enter image description here](http://i.stack.imgur.com/UnWnU.png)


What do AstronomicalData's "SetTime" and "RiseTime" values refer to?

What astronomical event do `AstronomicalData`'s `"NextRiseTime"`, `"NextSetTime"`, `"LastSetTime"`, and `"LastRiseTime"` values refer to? Are these times that the geometric centers of the objects in question cross the horizon, or their outer limbs; do they take into account refraction, or do they refer to the crossing of the geometric horizon?


Localizing Pattern Names

When I want to define a function that uses a pattern, how should I localize the pattern name (i.e., `x_` localizing the symbol `x`)? I have traditionally used `Module` but Workbench seems to freak out at times that I have unused symbols. Is this just a bug in Workbench, or is there a proper way of doing this? **Edit** So I have been a bit vague in exactly what I mean. To clarify, suppose I make a function in Workbench as:               test[g_, f_] :=         Module[{x},             g /. f[x_] :> x         ]     ]      I will have an error on the `Module` line stating "the local variable 'x', is not used". Please note this example is just to give the bare minimum so that I get the Workbench error, and to illustrate what kind of localization I mean. That is I want to use a symbol for use in a pattern label, not as a variable.


Export to PDF on OS X, font missing on Windows

Here is another problem with Mathematica plots and PDF. I have Mathematica 9.0.1 on Mac OS X. I want to export my plots to PDF to include them in a LaTeX document. If I export the plot with the command `Export["test.pdf",plot]` I get inconsistent results. The PDF exported from OSX looks good in Preview, but the font is missing if I open it on Adobe Acrobat on Windows, and it is replaced by Adobe Serif MM. Here is `pdffonts` output:               name                                 type              emb sub uni object ID     ------------------------------------ ----------------- --- --- --- ---------     Mathematica1                         Type 1            yes no  no       8  0     Times                                TrueType          no  no  no      11  0      Finally, if I open the file exported in OSX with Preview and save it again, it looks good on both platforms. Here is the `pdffonts` output of the new file:               name                                 type              emb sub uni object ID     ------------------------------------ ----------------- --- --- --- ---------     AQZZRA+Mathematica1                  Type 1            yes yes yes     10  0     HPLGMT+Times-Roman                   TrueType          yes yes no       8  0      Is there a way I can get Mathematica to produce the same output as Preview? If not, is there a command line tool that can re-save the PDF file so that the fonts are embedded correctly?


Changing package content in batch

I would like to know if it's safe to do batch operations in a list of package files, applying a function like this:               SetAttributes[packStringReplace,HoldRest]     packStringReplace[packPath_String,{replaceRule__}]:=Module[{pack},         pack=Import[packPath,"Text"];         pack=StringReplace[pack,{replaceRule}];         Export[packPath,pack,"Text"]     ]          packs=FileNames["*.m","/packageDirectory",∞];     packStringReplace[#,{"text1"->"text2","text3"->"text4"}]&/@packs      Can `Import` and `Export` change something inside pack in some unexpected way? It's safe? Or should I use `ImportString` or another `Import` equivalent? If yes, why? ## Update As pointed by @AlbertRetey in the comments, it's safer do use: `Export[packname,pack,"Text",CharacterEncoding->"ASCII"]` instead of `Export[packPath,pack,"Text"]`


Import[ ] drops leading zeros from data when importing a CSV file

I need to load data from the CSV file shown below. ![Mathematica graphics](http://i.stack.imgur.com/DYaJt.png) Import[ ] drops the leading zeros in column 3 when it imports the CSV file, but they are security identifiers, and I need them. ReadList[ ] keeps the leading zeros, but I can't get it to break the columns into separate elements. Each record ends up as long string. The options: Word, WordSeparators, ect. don't do what they are supposed to do. I could probably save the file as a TSV, or go into the CSV file and prepend a "'" and the appropriate number of zeros, or use a function to count the number of characters in column three and prepend the missing zeros, but that's just klugy(sp). What is the right way to ReadList[ ] the file? Here are the first few records in the file (copied by hand). The leading zeros in column three don't appear when the CSV file is loaded in Excel, but they do show up when the file is loaded in Notes++. > date,secid,cus_sed,tick,repno,dis_to_df,impl_rate,prob_df   >  01/31/2004,753,01381710,AA,0323N,3.20387,BBB,0.00068   >  01/31/2004,756,00431F10,AABC,34341,2.88794,BB,0.00194   >  01/31/2004,757,03237110,ANCPA,0591N,3.18587,BBB,0.00072   >  01/31/2004,759,00440310,AACE,A02B8,3.23057,BBB,0.00062 > 01/31/2004,767,45814710,FILM,A06F0,2.04099,B-,0.02063


Joining only particular dates with DateListPlot

I have the following datasets:               dataset1={{{1997}, 98/79}, {{1998}, 26/61}, {{1999}, 22/15}, {{2000}, 100/       63}, {{2007}, 284/57}, {{2008}, 226/31}, {{2009}, 15/4}, {{2010},        221/63}};          dataset2={{{1997}, 25/79}, {{1998}, 17/61}, {{1999}, 28/25}, {{2000}, 20/       21}, {{2007}, 106/57}, {{2008}, 128/31}, {{2009}, 59/16}, {{2010},        32/9}};      I want to plot them using `DateListPlot[{dataset1,dataset2}]` (plus appropriate additions, such as `Joined`, etc.). Note, however, that there is a missing gap here: the years 2001 through 2006. I have multiple datasets (over five of them) so the dots can be hard to understand. If I use the `Filling->Bottom` addition, it cleans it up a bit, but still a bit hard. If I use `Joined->true`, it just connects 2000 and 2007 (as it should) but this implies data that I don't have. Is there a way, using _Mathematica_ , to connect the points for the years 1997 through 2000 and the years 2007 through 2010 - but not to draw a line in the middle between 2000 and 2007, as that skews the data?


SQLDateTime from a time column is missing the milliseconds component

Can anyone confirm this? I am using M9.0.1 on win7 64bit connecting to a SQL Server db. When I fetch a datetime column the SQLDateTime objects contain 6 entries, 5 integers and a fractional second component. When I fetch a date the SQLDateTime objects contain 3 integers. When I fetch a time column there are 3 integer entries even though that column contains times with millisecond components that are not zero.


How to collect/reduce with respect to multiple variables?

I have this code:               a == b + c + d - e      Is it possible to collect or reduce this expression into this:               c + d == a + e - b      where I focus on the left side of the equation. I am only aware of ways to reduce an expression with respect to one single variable, but here I would like to reduce it with respect to `(c + d)`. Is this possible somehow?


Simple problem with Manipulate and Plot

Would anyone have an idea why the following doesn't work:               rule = {z -> x^2 + 2 x + y};     Manipulate[      Plot[z /. rule, {x, 0, 10}],      {{y, 2, "y"}, 1, 5}      ]      But the following do:               rule = {z -> x^2 + 2 x + y};     z /. rule;     Manipulate[      Plot[%, {x, 0, 10}],      {{y, 2, "y"}, 1, 5}      ]      and:               Manipulate[      Plot[z /. z -> x^2 + 2 x + y, {x, 0, 10}],      {{y, 2, "y"}, 1, 5}      ]      I was looking to `Plot` and `Manipulate` the results from a `Solve` of multiple equations, but it seems like I haven't understood the substitution rules correctly. Thanks, Jaleno


How can I get the list of dates in the next $n$ years

How can I get the list of all dates from today 21.02.2012 (which is a palindrome) up to say next $n$ years? Then finding the other palindromes are not difficult. I could not find an easy way to generate the list using `DateList`.


How to exclude some points to make them more evenly distributed in a figure

If there are some points in a figure, how can I exclude some points to make them more evenly in the figure? 'Evenly' here can be defined as the number of points in each $0.01*0.01$ box is at most one. Without loss of generality, we can produce some random data to copy with (we can also give data directly, which is too long and tedious to present them here. So, we do not talk about how to produce the data but how to copy with the given data)               ListPlot[RandomReal[{-1, 1}, {10000, 2}]]      ![enter image description here](http://i.stack.imgur.com/7CuuS.jpg) Any help or suggestion will be appreciated!


deleteduplicates Delete elements of a list

I have a math problem about Mathematica, I am looking help from you. I hope that you could help me. The Math Problem:               list= { {0,0,1},{1,0,0},{0,1,0} ,{1,2,3}};      as you know that list is a List, and the first three elements of the list is list[[1]]、list[[2]]、list[[3]]. but the three elements of list[[1]]、list[[2]]、list[[3]] are all the same, that is 1,0,0. the only difference is their order. So I need a function to deal with the List: The Results must been `p={{0,0,1} ,{1,2,3}}` (also can been p={{1,0,0} ,{1,2,3}},etc). I know two functions can do that: (1)               p = DeleteDuplicates [ list, Sort[#1] == Sort[#2] & ];      (2)               p = Union[list,  SameTest -> (SameQ[Sort[#1], Sort[#2]] &) ]      when List has 100,000 elements (Length[list]=100,000) , the speeds of these two functions are too slow(It takes me a day, but has no results). eg               list={};     For[i=1,i<=100000,i++,     list=Append[list,{0,0,Random[Integer,{1,5}]}]     ];     p = DeleteDuplicates [ list, Sort[#1] == Sort[#2] & ];      Could you help me or give some suggestions ?


Don't simplify an expression

I have an expression that I want Mathematica to fully expand without any simplification afterwards. I want the output to look like the following example. > >     (x+y)^2 ⇒ x^2+xy+yx+y^2 >   Could you help me to solve this problem?


Factorisation diagrams

Here is a way to visualize the factorisation of natural numbers. How do we get this or a similar kind of output using _Mathematica_? See the list of images generated for number from 1 to 36: ![factorisation diagrams for 1 to 36](http://i.stack.imgur.com/eX9BX.png)


Get x and z coordinate from an image and make a parametric surface

In this blog entry, this step is mentioned: > I grabbed an image of a Peugeot wine glass from the web and used the Get > Coordinates function to digitize its outline, which I fed to Interpolation > to get the x and z parametric functions of the curve. _While I understand that I can get the coordinates of x and y, how can I get the z coordinates, and convert that to a Parametric Curve?_


Modules that initialize themselves on first call

I use a lot of functions that extract a specific data item from a file with many data items. I want these functions to load data (slow) and return the item (fast) on first call, but just return the item on subsequent calls. If I were using VB, I would declare static variables init along with other variables to hold the data, load the data and set init True on first call, and bypass the data load with an If init <> true then xxxx endif portion of the function on subsequent calls. But variables listed within the {} of a Module don't persist from call to call. My workaround is to give the data an absurdly long variable name and exclude it from the the Module[{var1,var2,...} list, and use ValueQ to check if longvariablename has been evaluated. For example:               getPce[date_,column_] := Module[{dates, value, b, e},        If[! ValueQ[longvariablename], longvariablename = Import["path\\file];         value = SomeFunction[date_,column_]; (* get item(s) from longvariablename *)      ]      This is a clumsy. I'm sure there is a nice Mathematica way to do this, but I've never been able to figure it out.


How to figure out how to make WolframAlpha work predictably

I'd like to get football data out of Wolfram|Alpha and into Mathematica 9, but I'm having some minor difficulty. Naturally, I'd like to know how to accomplish this task (details below), but I'm more interested in learning how I should have figured it out on my own.               TeamNames = {"Giants", "Redskins", "Cowboys", "Eagles", "Packers",         "Bears", "Vikings", "Lions", "Falcons", "Saints", "Panthers",         "Buccaneers", "49ers", "Seahawks", "Rams", "Cardinals", "Patriots",        "Dolphins", "Bills", "Jets", "Ravens", "Bengals", "Steelers",         "Browns", "Texans", "Colts", "Titans", "Jaguars", "Broncos",         "Chargers", "Raiders", "Chiefs"};     Table[WolframAlpha[ TeamNames[[i]] <> " in 2010",         {{"Schedule:NFLTeamData", 1}, "ComputableData"}],         {i, 1, 32}]      This code gets the schedules for all but three teams (Cardinals, Bills, Texans). I'm unable to get schedules for those teams through the "WolframAlpha" command, although they are available through the web interface. So here's the (big) question in a nutshell: how do I figure out how to phrase a WolframAlpha query so that it gets exactly what I want? Of course that question is too broad, but I mean that a best answer will not be a simple command that gets the data I want, but a route by which I could have figured it out myself.


Problem with NIntegrate in NonlinearModelFit

We are receiving many error messages when using NIntegrate with NonlinearModelFit. Here is a much-simplified version of the code. It arrives at the correct answer after several messages saying that it is stopping the integration. In the real version, which is fitting Beta distributions, the situation is similar but more complicated, and it is not clearly getting the best fit.               data = {{0, 0}, {1, 1}, {2, 4}}          cnet[x_, b_, c_] := NIntegrate[b + 2 c u, {u, 0, x}]          Print[cnet[0, 0, 1]]     Print[cnet[1, 0, 1]]     Print[cnet[2, 0, 1]]     Print[cnet[3, 0, 1]]          Chop[NonlinearModelFit[data, cnet[x, b, c], {b, c}, x]]


Multiple templates for a single user-defined function

How do I use the `::usage` tag to allow the Mathematica v9 front end to know that there are multiple ways to call an overloaded function (a function that can have different number of arguments? For example, if I sequentially run the two commands               myfunc::usage = "foo[x,y,z] will combine x, y and z for you.";     myfunc::usage = "foo[x,y,z,w] will be even better.";      The second line has overwritten the first and the front end doesn't know about both cases. A built-in example of what I'm talking about is `Table` which the front-end recognizes as having many different templates.


ConditionalEntropy and Statistics`Library`NConditionalEntropy

There is a function available from the Statistics`Library context called NConditionalEntropy that appears to compute ConditionalEntropy. Thus ...               Statistics`Library`NConditionalEntropy[{1, 1, 1, 0, 1, 1, 0, 0}, {1,      0, 0, 1, 0, 1, 0, 0}]      outputs 0.954434 When I look at the definition of Conditional Entropy in Wikipedia (http://en.wikipedia.org/wiki/Conditional_entropy), it suggests that it is the expectation of the base 2 log of the PDF of a marginal distribution of p[x,y] that it calls p[x] divided by the PDF of the distribution p[x,y], where the results are weighted according to this same distribution p[x,y]. So, this gave me hope that I could recreate ConditionalEntropy as an expectation and see if I really understood what was going on. Thus, I write the following code:               xv = {1, 0, 0, 1, 0, 1, 0, 0, 1};(* just some test data*)     yv = {1, 1, 1, 0, 1, 1, 0, 0, 1};(* just some test data*)     ed = EmpiricalDistribution[     Flatten[Outer[     List, xv,yv], 1];     Expectation[     Log[2, PDF[MarginalDistribution[ed, 1], x]/     PDF[ed, {x, y}]], {x, y} \[Distributed] ed]//N      And I get 0.918296 But when I write ...               Statistics`Library`NConditionalEntropy[xv, yv]      I get 0.899985 In case I've got the order of arguments wrong, I've also tried               Statistics`Library`NConditionalEntropy[yv, xv]      But this yields 0.972765, which still does not match up. Several theories for the discrepancy: 1) I do not understand the concept of Conditional Entropy well enough 2) My code for implementing conditional entropy is missing something 3) Other Help appreciated.


Partitioning an integer into $k$ equal parts

Say I have an integer $M$. Is there a one-line command to create a partition of $M$ into $k$ integers s.t. the difference between any two integers is as small as possible? For example, with $M = 100$ and $k = 10$, we would create the partition: {10,10,10,10,10,10,10,10,10,10}. However, for $k = 7$, we might have the partition: {14,14,14,14,14,14,16}, or better {14,14,14,14,14,15,15}. For a partial solution, you can of course write:               M = 100;     k = 7;     BalancedPartition = Array[Floor[M/k] &, k];     BalancedPartition[[k]] += M - k*Floor[M/k];     BalancedPartition      > {14, 14, 14, 14, 14, 14, 16}


Long text inside a grid does not word wrap

If I create a simple grid with `Ctrl`+`,` and paste a long piece of text outside the boxes (I'm sure you can find some yourself), then that text does not break at the width of the window in _Mathematica_. Instead, you have to scroll through it with a newly appeared scroll bar at the bottom. How can this be fixed? As an example, you can see bellow here how the word 'also' is getting cut off. I am typing this in, it is not the output of a cell: ![try1](http://i.stack.imgur.com/5IiPO.png) Really, my goal is to put text besides a picture. So thanks to Kuba, here is an attempt to first create a Row which should WordWrap, and then turn that output cell into a text and TraditionalForm cell, and fill it in with my content: ![try2](http://i.stack.imgur.com/i21rw.png) However, you can see that this breaks the text indeed, but on a new line bellow the picture, I would like to get it alongside the picture.


How to color a BSplineSurface

I am trying to color a `BSplineSurface` in a complex way but not having any luck using `ColorFunction`. I can use `ColorFunction` if I using `BSplineFunction` and `ParametricPlot3D` but would prefer not to go that route. Here is an example of the surface I would like to color:               Graphics3D[{EdgeForm[], SeedRandom[4];       BSplineSurface[Table[{x, y, 0.25 + UnitStep[30 - Abs[x] - 0.001] UnitStep[50 -Abs[y] - 0.001] (0.25/RandomReal[{0.1, 2}]^2)},        {x, -30, 30, 5.}, {y, -50, 50, 5.}]]}, Boxed -> False]      I would like to be able to color the peaks with one color (red) and have that color fade away to gray in the flat parts.![enter image description here](http://i.stack.imgur.com/UYVUq.png)


Solving an Integral Numerically

I have been trying to solve the integral equation below, but cant seem to find a way out of this. Can someone please help me out with suggestion? $f(t)=\int_0^{\infty}\frac{K_1a(t)}{a(t)+K_2}\,dt$ where $K_1$ and $K_2$ are some constants and $a(t) = \frac{Q}{(4\pi Nt)^{3/2}}*\exp(-x^2/(4Nt))$. Thank you so much


Memory issue when using LinearSolve

When I use `LinearSolve` to solve a large system of linear equations where the left hand side is a matrix and the right hand side is a vector, the process takes a very long time and eventually a message appears telling me that there is not enough memory. Could anybody please help me to override this problem?               coords = Flatten[Table[{j, i} , {i, {0, 2, 4, 6}}, {j, {0, 2, 4, 6}}], 1];          ElementNodes = {{1, 2}, {2, 3}, {3, 4}, {1, 5}, {1, 6}, {2, 5}, {2,         6}, {2, 7}, {3, 6}, {3, 7}, {3, 8}, {4, 7}, {4, 8}, {5, 6}, {6,         7}, {7, 8}, {5, 9}, {5, 10}, {6, 9}, {6, 10}, {6, 11}, {7, 10}, {7,         11}, {7, 12}, {8, 11}, {8, 12}, {9, 10}, {10, 11}, {11, 12}, {9,         13}, {9, 14}, {10, 13}, {10, 14}, {10, 15}, {11, 14}, {11,         15}, {11, 16}, {12, 15}, {12, 16}, {13, 14}, {14, 15}, {15, 16}};          NumOfElements = 42 ; NumOfNodes = 16 ; Eevalue = 69; Ee =       Table[10^4, {NumOfElements}]; P = 100 ; dof =       2 * NumOfNodes; ebcDof = {1, 2, 25, 26} ; ebcDofValues = {0, 0, 0,        0} ;      nbcDof = {8}  ; nbcDofValues = {-P} ;            ElemetsArea = {1, 1, 1, 1, 1, 1, 1, 1, 1,           1, 1, 1, 1, 1, 1, 1, 1, 1,           1, 1, 1, 1, 1, 1, 1, 1, 1,           1, 1, 1, 1, 1, 1, 1, 1, 1,           1, 1, 1, 1, 1, 1};     ElementsModulusE = {69, 69, 69, 69, 69, 69, 69,          69, 69, 69, 69, 69, 69, 69,          69, 69, 69, 69, 69, 69, 69,          69, 69, 69, 69, 69, 69, 69,          69, 69, 69, 69, 69, 69, 69,          69, 69, 69, 69, 69, 69, 69};          KPlaneTruss[coords_ , ElementNodes_, NumOfNodes_, NumOfElements_ ,        ElemetsArea_ , ElementsModulusE_ , ebcDof_, ebcDofValues_ , nbcDof_,        nbcDofValues_ ] :=      Module [ {dof , K, R, d, k, lm , x1 , y1 , x2 , y2 , L , ls, ms,         Llist , lslist , mslist, Kf, Rf , Freedof , FreeValues, T, ds1,         ds2, , detKf},        dof = 2*NumOfNodes ; K = Table [ 0 , {dof} , {dof}] ;        R = Table [ 0 , {dof}] ; d = Table [ 0 , {dof}] ;        R[[nbcDof]] += nbcDofValues;        Llist = lslist = mslist = Table[ 0 , {NumOfElements}];       Do [ lm = {(2*ElementNodes [[i, 1]] ) - 1 ,           2 ElementNodes [[i, 1]] , ( 2 ElementNodes [[i, 2]] ) - 1 ,           2 ElementNodes [[i, 2]]}  ;         {{x1 , y1} , { x2 , y2}} =  coords[[ElementNodes [[i]]]];          L = Sqrt[(x2 - x1)^2 + (y2 - y1)^2]; ls = (x2 - x1)/L ;         ms = (y2 - y1)/L ;        k = ElemetsArea[[i]]* ElementsModulusE[[i]]/          L*{{ls^2 , ls ms , -ls^2 , -ls ms} , {ls ms ,             ms^2 , -ls ms , -ms^2}, {-ls^2 , -ls ms , ls^2  ,             ls ms}, {-ls ms , -ms^2 , ls ms , ms^2}}  ;        K[[lm, lm]] += k ; Llist[[i]] += L ; lslist[[i]] += ls ;          mslist[[i]] += ms  , {i, 1, NumOfElements}];       Freedof =  Complement [ Range[dof] , ebcDof] ;        Rf = R[[Freedof]] - K[[Freedof , ebcDof]].ebcDofValues  ;       Kf = K[[Freedof , Freedof ]] ;        detKf = Det[Kf];       If[detKf == 0 , d = Table["Ind", { dof}] ,         (*FreeValues = LinearSolve [ Kf,Rf] ;*)         d[[Freedof]] += FreeValues ; d[[ebcDof]] += ebcDofValues ;        ]; {Kf, Rf}]      Here I am implementing the function I have created to get the L.H.S matrix and the R.H.S vector               {matrix, R} =       KPlaneTruss[coords, ElementNodes, NumOfNodes, NumOfElements,        ElemetsArea , ElementsModulusE, ebcDof, ebcDofValues , nbcDof,        nbcDofValues ]


Recover data points from RGBColor of known ColorScheme

In general I want to recover the z-values from an image of a DensityPlot. A simple example might just be               Flatten[Table[{x, y, x Sin[x y]}, {x, 0, 2 \[Pi], \[Pi]/50},         {y, 0, 2 \[Pi], \[Pi]/50}], 1]     ListDensityPlot[%, PlotRange -> All, ColorFunction ->"RedBlueTones",         Frame -> False,ImageSize -> 800, PlotRangePadding -> None]     Export["img.jpg", %]      I can get all the color data just by               pixelData = ImageData[Import["img.jpg"], "Real32"]      but when I want to get a z-value according to the RGBColor of any individual pixel within "pixelData" I'm lost. I guess it's rather straight forward using something like the inverse of               ColorData["RedBlueTones",z]      I also don't care about any range specifications since I can rescale to the desired range provided with the bar legend of the image of interest. Any ideas? Thanks in advance.


$Failed below input area of new cell in notebook

The _Mathematica_ 9 installation on my laptop has developed an odd feature. Just underneath the grey line indicating the input area for a new cell, the expression `$Failed` appears in small type at the left hand end. This occurs even before I type anything in a fresh notebook created at start- up. I tried deleting both the `Kernel`'s and `FrontEnd`'s init.m files but that did not help. As soon as I start to type an input, it disappears. It doesn't seem to interfere with kernel evaluations but is just annoying. ![This is how it looks in a new notebook created at start- up.](http://i.stack.imgur.com/TlvDv.png)


Inhomogeneous phase-portrait with StreamPlot

I have a problem with a must-be simple streamplot. The potential function governing the motion is U, and I have the following code in Mathematica:               U = -((1000.` x (1.25` - 1.` Sqrt[1 + 625.` x^2]))/Sqrt[1 + 625.` x^2])     StreamPlot[{Φ, -U}, {x, -0.05, 0.05}, {Φ, -1.5, 1.5}, StreamPoints -> Fine]      The problem is that I get the following plot: ![Wanna-be beautiful streamplot](http://i.stack.imgur.com/pOxIy.png) What did I do wrong, or how should I overcome this horror? EDIT The result should look like the following phase plane plot created by MatLab: ![MatLab version](http://i.stack.imgur.com/nvpE8.png) The MatLab code snippet:               f=@(Y) [Y(2); -1/2*Y(1)*(1000-1250/sqrt(1+625*Y(1)^2))];     y1=linspace(-0.06,0.06,20);     y2=linspace(-0.5,0.5,20);     [x,y]=meshgrid(y1,y2);          u=zeros(size(x));     v=zeros(size(y));          for i=1:numel(x)         Yprime=f([x(i); y(i)]);         u(i)=Yprime(1);         v(i)=Yprime(2);     end          quiver(x,y,u,v,'r');     figure(gcf)     xlabel('x')     ylabel('xdot')     axis([-0.08 0.08 -0.6 0.6])      I used the same equation here, unfortunately due to the aspect ratio the arrows are a bit distorted. I would like the Mathematica plot to have arrows 'all over the place' as in MatLab, so somehow the seeding should be altered. I would prefer the streamplot of mathematica rather than the MatLab version, as the StreamPlot shows the arrows along trajectories, whereas MatLab generates only a vectorfield.


MapIndexed and Compile

I am having trouble compiling a function that uses the `MapIndexed` function on the second level. The compilation runs fine, but at evaluation time I get an error that I cannot explain right now. The following scenario shows the problem: First I define a compiled version and a noncompiled version of a simple funciton using `MapIndexed`:               MapIndexedCompileTest = Compile[{{list1, _Real, 2}, {list2, _Real, 2}},                                MapIndexed[list1[[#2[[1]], #2[[2]]]] + #1 &, list2, {2}]]          MapIndexedTest[list1_, list2_] := MapIndexed[list1[[#2[[1]], #2[[2]]]] + #1 &, list2, {2}]      `MapIndexedTest` shows that the function works just fine:               MapIndexedTest[{{1, 2}, {1, 2}}, {{1, 2}, {1, 2}}]      But `MapIndexedCompiledTest` yields the error: > >     "CompiledFunction::cflist: Nontensor object generated; proceeding with >      uncompiled evaluation" >   when evaluated the same way:               MapIndexedCompileTest[{{1, 2}, {1, 2}}, {{1, 2}, {1, 2}}]      Does anybody know what goes wrong? **New intel I just got when reading answers:** The problem seems to be that the index represented by the second argument is not correct when using compiled. To see that I defined the following functions, which should just return the current index inside the Mapping function:               MapIndexedGiveIndexCompiled = Compile[{{p, _Real, 2}}, MapIndexed[#2 & , p, {2}]];     MapIndexedGiveIndex[p_] := MapIndexed[#2 & , p, {2}];      The above functions should obviously return the same results when used on a 2 rank tensor, but they do not, `MapIndexedGiveIndexCompiled` delivers the wrong result:               MapIndexedGiveIndexCompiled[{{1, 2}, {3, 4}}]      delivers: > {{{1}, {2}}, {{1}, {2}}} while `MapIndexedGiveIndex` returns the expected result: > {{{1, 1}, {1, 2}}, {{2, 1}, {2, 2}}} This should explain why `[[2]]` is not working, but overall it looks like a bug to me.


Histogram plot with descriptive statistics on the plot

I am wondering in Mathematica Can we generate histogram plot with descriptive statistics, such as mean, median, and skewness, attached to the plot ? For example, we may place all the statistics to the right of the plot Here is what I have done. First I created the function:               descriptivestatistics[       data_] := {{"Mean", "Median", "Stdv.", "Skewness",          "Kurtosis"}, {Mean[data], Median[data], StandardDeviation[data],          Skewness[data], Kurtosis[data]}} // TableForm      Then, I placed them on the same list as follows: `{Histogram[data,"PDF",Automatic],descriptivestatistics[data]}`, but I think there is better way to do it. Also, I want to export to be a report e.g., .doc or .pdf Can any one give me suggestions ? Thank you


Union of plotted regions as sum of colors

I wish to plot 2 functions $f$ and $g$ so that the region bounded by $f$ has color $c_f$, the region bounded by $g$ has color $c_g$, and the region bounded by both has color $c_f+c_g$. E.g. $c_f$ is red, $c_g$ is blue, $c_f+c_g$ is magenta. I tried this:               Plot[{Sin[x], Cos[x]}, {x, -π, +π}, Filling -> {1 -> {Axis, Blue}, 2 -> {Axis, Red}}]      ![bad](http://i.stack.imgur.com/N52i4.png) I found no documentation on how to do additive mixture of colors in a plot. How can I do so?


How can I make Plot axis thicker?

When I insert a figure created using GraphicsGrid into my (LaTeX) document, the axis are hardly visible. How can I increase thicknes of the axis in plot produced by Plot and LogLogPlot?


RSolve works slow and does not give an analytical solution for solving high order linear difference equations

RSolve@@{{a[n]-a[n-10]==101}~Join~Table[a[i+1]==101+10i,{i,0,9}],a[n],n}      I want to get the exact form of general formulas, but `RSolve` only gives a `DifferenceRoot` object. I tried `FunctionExpand` but it does not work.


Remove borders in a series of images

I have a series of mouse MRI images, here are two ![enter image description here](http://i.stack.imgur.com/xni6T.jpg) ![enter image description here](http://i.stack.imgur.com/01a5d.jpg) How can I automatically remove the metal cage around the mouse to make it look like this: ![enter image description here](http://i.stack.imgur.com/ImP6U.jpg) The position of the cage is not always in exactly the same position. Making the image more horizontal would also be nice. Also each image should have the same dimensions.               image1 = Import["http://i.imgur.com/iGia7W6.jpg"]


Exporting a .xlsx file with about 500 columns

When I want to `Export["text.xlsx", data]` where `data` is a matrix with 500 columns and 10000 rows, I get the error message: > Export::toomany3: "Cannot export to !(\"XLSX\"). The number of columns > exceeds the limit of this format." However, if I write the data as csv and load it into excel, everything works. Is there a way to write the data of this size to xlsx directly? Test sample:               data = RandomReal[{-1, 1}, {10000, 500}];     Export["test.xlsx", data]      This happens with Mathematica 8 and 9.


vector/list containing matrices as elements dot product

`mA = {{a11, a12}, {a21, a22}}; mB = {{b11, b12}, {b21, b22}}; mC = {{c11, c12}, {c21, c22}}; mD = {{d11, d12}, {d21, d22}}; v={{mA},{mB}}; w={{mC},{mD}};` What I want is a dot product between w and v: `v.w=v1*w1+v2*w2=mA.mC+mB.mD`


Bresenham's line algorithm

Bresenham's line algorithm is producing discretized line for given two points for purpose of plotting for example. Like that: ![enter image description here](http://i.stack.imgur.com/s4Ewt.png) I have to stress that I'm interested in positions, not a plot. Wikipedia link I've provided includes an algorithm of course. I've just rewritten it thoughtlessly, I don't have time now or special need to work on neat implementation. But if someone want to improve it (compile e.g.), got it already or know something more, I think this thread may be usefull for future visitors. Very nice implementation can be found on rossetacode :P, according to that this algorithm should be built in so maybe someone knows how to get it. Anyway, here's that code:               bresenham[{x1_, y1_}, {x2_, y2_}] :=       Module[{dx, xi, dy, yi, ai, bi, x, y, d},          If[x1 < x2, {xi, dx} = {1, x2 - x1};, {xi, dx} = {-1, x1 - x2};];          If[y1 < y2, {yi, dy} = {1, y2 - y1};, {yi, dy} = {-1, y1 - y2};];          x = x1; y = y1;          Sow[{x, y}];          If[dx > dy,           (ai = 2 (dy - dx); bi = 2 dy; d = bi - dx;            While[             If[d >= 0,              {x, y, d} += {xi, yi, ai},              {x, d} += {xi, bi}];             Sow[{x, y}];             x != x2])           ,           (ai = 2 (dx - dy); bi = 2 dx; d = bi - dy;            While[             If[d >= 0,              {x, y, d} += {xi, yi, ai},              {y, d} += {yi, bi}];             Sow[{x, y}];             y != y2])           ]] // Reap // Last // First


How can I analyse Mathematica data using Wolfram|Alpha?

How can I analyse data stored in _Mathematica_ using Wolfram | Alpha? Here is an example: I have a list: `a = {1, 2, 3, 4, 5}` I can plot it in _Mathematica_ , like this: ![enter image description here](http://i.stack.imgur.com/46dCx.jpg) But once I try to use Wolfram | Alpha, an error message appears: ![enter image description here](http://i.stack.imgur.com/FhU2K.jpg) How can I perform different types of analyses on _Mathematica_ data using Wolfram | Alpha?


How to get special solutions of this system of equations?

I only want to get all the solutions of this system of the solutions with a value of $k$, we have the same values of $m$               A = {1, 2, 3};     B = {2, 1, 0};     M = {a, b, c};     Solve[{a - b + c + m == 0,        SquaredEuclideanDistance[B, M] == k, (A - M). (B - M) == 0,        k > 0}, {a, b, c, m, k}, Integers]      In this ystem of the solutions, for example, $k = 6$, $m=1$ and $m = 3$.               A = {1, 2, 3};     B = {2, 1, 0};     M = {a, b, c};     Solve[{a - b + c + m == 0,        SquaredEuclideanDistance[B, M] == 6, (A - M). (B - M) == 0}, {a, b,        c, m}, Integers]      I do not how to start. How do I tell _Mathematica_ to do that?


Load a Mathematica Notebook using .Net code

I have gotten a tremendous amount of information from the question posted at (Load a Mathematica Package via .Net code), which my application is very similar to. Specifically in that thread, the author uses:               MathKernel k = new MathKernel();  //Establishes a Mathematica kernel       k.Compute("<< XYZ`XYZGraphs`");   //Runs an entire package file        string res = k.Result.ToString(); //Collects the result of the file      I was wondering if there was a similar process for a Notebook file? When I tried referencing a Notebook file in the same manner, the math kernel returns `$Failed` as the result. Other solutions I thought might work but have not had any success with have been using `IKernelLink` and `IMathLink`, or converting the Notebook file to a Package file. I also saw a thread about running from the command line but I am not sure how I would get the results of the Notebook back into .Net using that method. I would greatly appreciated any advice, thanks!


How can PixelConstrained be emulated with DensityHistogram?

This `DensityHistogram` doesn't display very well. Some bins are shown much larger than others and, oddly, empty bins appear to be drawn smaller than occupied bins.               DensityHistogram[RandomVariate[BinormalDistribution[.5], 50000], {100, 100}]      ![enter image description here](http://i.stack.imgur.com/jx6pn.png) In `ArrayPlot`, similar problems are solved with `PixelConstrained`. How can `PixelConstrained` be emulated with `DensityHistogram`?


Creating a custom context with a Hold construct

I'm trying to create a function "InContext" to execute a piece of code inside a certain context (and to return the result of evaluating that piece of code). One approach is to place the code inside a given string.               InContext[context_String]:=Module[{action},     Begin[context];     action = ToExpression[#];     End[];     action]&;      This can be checked by giving the code string "a=1":               InContext["customcontext`"]["a=1"]     (*1*)     a     (*a*)     customcontext`a     (*1*)      However I would like to use a full Mathematica Expression as code (i.e. not inside a string), ideally something like Hold[code]. I've tried, for example:               InContext2[context_String]:=Module[{action},     Begin[context];     action = ReleaseHold[#];     End[];     action]&;      But the result is not the intended, as the code gets evaluated in the Global context:               InContext2["customcontext`"][Hold[b=2]];     (*2*)     b     (*2                      should be b*)     customcontext`b     (*customcontext`b        should be 2 *)      Why is the context changing differently this time, and how can it be made to change "correctly" so that the code is evaluated in the custom context?


Using mathematica to discover algorithms?

In Steven Wolfram's blog entries, he discusses using mathematica to discover algorithms. I have tried several different google searches for papers on such topics, and have found none. I suspect this is a case where I'm not using the proper search terms. I could imagine some sort of genetic algorithm based approach that takes a genome and turns that into an algorithm, but I would be curious what specifically he is discussing.


Plot3D unable to understand input function

I'm attempting to plot the Wigner Function of the Morse Oscillator defined as               f[λ_, m_, n_, y_, k_] =          (2/Pi)N1[λ, n] N1[λ, m]ξ^(2λ - m - n - 1)*          Sum[Sum[b[λ, m, r]b[λ, n, s]ξ^(r + s)*                  BesselK[m - n - r + s + 2*I*k, ξ], {s, 0, n}], {r, 0, m}]       where               N1[λ_, n_] =  Sqrt[(2*λ - 2 n - 1)*Gamma[n + 1]/Gamma[2*λ - n]]          b[λ_, n_, j_] = (-1)^j*(1/j!)*Gamma[2*λ - n]/(Gamma[2*λ -                               2 n + j]*Gamma[n - j + 1])          ξ = 2*λ*Exp[-y]      I found that if I use the function `f` in Mathematica's `Plot3D`, I get an error: ![enter image description here](http://i.stack.imgur.com/FPn1k.png) However, if I first evaluate `f[1,0,0,y,k]`, and then plug the result into `Plot3D`, I get: ![enter image description here](http://i.stack.imgur.com/CdSvJ.png) ![enter image description here](http://i.stack.imgur.com/Uk514.png) Why does Mathematica have trouble plotting `f[1,0,0,y,k]` if I plug it directly into `Plot3D`, but has no trouble if I first evaluate `f[1,0,0,y,k]`? Is there a way for Mathematica to understand `Plot3D[f[1,0,0,y,k],{y,-3,3},{k,-3,3}]`? I want Mathematica to plot the function automatically without me having to first evaluate the function and then copy and paste the output into `Plot3D`. For example, one thing I'd like to do is `Manipulate[Plot3D[f[5,n,n,y,k],{y,-3,3},{k,-3,3}],{n,0,4,1}]`. Thanks. $\bf{\large{Edit}}$ Interestingly, for               f[1, 0, 0, 1., 1.]      I get:               0.468399 DifferenceRoot[   Function[{\[FormalY]$, \[FormalN]$}, {4 (-1 - \[FormalN]$ +                0) (-\[FormalN]$ + 0) 1^2 \[FormalY]$[\[FormalN]$] -         2 (-1 - \[FormalN]$ + 0) (\[FormalN]$ E^(2 1.) +            2 \[FormalN]$^2 E^(2 1.) + \[FormalN]$^3 E^(2 1.) +            2 I \[FormalN]$ E^(2 1.) 1. +                2 I \[FormalN]$^2 E^(2 1.) 1. + \[FormalN]$ E^(2 1.)                 0 + \[FormalN]$^2 E^(2 1.) 0 - 2 E^(2 1.) 0 -            5 \[FormalN]$ E^(2 1.) 0 - 3 \[FormalN]$^2 E^(2 1.) 0 -            4 I E^(2 1.) 1. 0 - 4 I \[FormalN]$ E^(2 1.) 1. 0 -                2 E^(2 1.) 0 0 - 2 \[FormalN]$ E^(2 1.) 0 0 +            2 E^(2 1.) 0^2 +            2 \[FormalN]$ E^(2 1.) 0^2 - \[FormalN]$ E^(2 1.)             r - \[FormalN]$^2 E^(2 1.) r + 2 E^(2 1.) 0 r +                2 \[FormalN]$ E^(2 1.) 0 r + 2 E^(2 1.) +            4 \[FormalN]$ E^(2 1.) + 2 \[FormalN]$^2 E^(2 1.) +            4 I E^(2 1.) 1. + 4 I \[FormalN]$ E^(2 1.) 1. +                2 E^(2 1.) 0 + 2 \[FormalN]$ E^(2 1.) 0 - 2 E^(2 1.) 0 -            2 \[FormalN]$ E^(2 1.) 0 - 2 E^(2 1.) r -                2 \[FormalN]$ E^(2 1.) r - 2 \[FormalN]$ 1^2 +                2 0 1^2) \[FormalY]$[          1 + \[FormalN]$] + (1 + \[FormalN]$) E^(         2 1.) (-\[FormalN]$ + 2 0 - 2 1) (4 + 7 \[FormalN]$ +            3 \[FormalN]$^2 + 4 I 1. + 4 I \[FormalN]$ 1. + 2 0 +            2 \[FormalN]$ 0 - 8 0 - 6 \[FormalN]$ 0 - 4 I 1. 0 -            2 0 0 + 2 0^2 - 2 r - 2 \[FormalN]$ r + 2 0 r + 4 1 +                2 \[FormalN]$) \[FormalY]$[              2 + \[FormalN]$] + (1 + \[FormalN]$) (2 + \[FormalN]$) E^(         2 1.) (-1 - \[FormalN]$ + 2 0 - 2 1) (-\[FormalN]$ + 2 0 -            2 1) \[FormalY]$[3 + \[FormalN]$] == 0, \[FormalY]$[0] ==            0, \[FormalY]$[1] == BesselK[2 I 1. + 0 - 0 - r, 2 E^-1.]/(       Gamma[1 + 0] Gamma[-2 0 + 2 1]), \[FormalY]$[2] ==        BesselK[2 I 1. + 0 - 0 - r, 2 E^-1.]/(        Gamma[1 + 0] Gamma[-2 0 + 2 1]) + (        2 E^-1. 0 BesselK[1 + 2 I 1. + 0 - 0 - r,           2 E^-1.])/((2 0 - 2 1) Gamma[1 + 0] Gamma[-2 0 + 2 1])}]][1]      However, for               f[1, 0, 0, 1, 1]      I get:               (4*BesselK[2*I, 2/E])/(E*Pi)


Incompatible InterpolatingFunction between V9 (and earlier) and V10

I am encountering compatibility issues when loading `DumpSave`(d) definitions in V10 that have been created with earlier versions. V10 appears to be unable to digest `InterpolatingFunction from earlier version. When looking at an example functions in both versions I get the following: Definition from the Documentation               points = {{0, 0}, {1, 1}, {2, 3}, {3, 4}, {4, 3}, {5, 0}};     ifun = Interpolation[points]      In V9.0.1 this is digested as:               ??ifun     Global`ifun     ifun=InterpolatingFunction[{{0,5}},{4,3,0,{6},{4},0,0,0,0,Automatic},{{0,1,2,3,4,5}},{{0},{1},{3},{4},{3},{0}},{Automatic}]      In V10:               ??ifun     Global`ifun     ifun=InterpolatingFunction[{{0,5}},{4,3,0,{6},{4},0,0,0,0,Automatic,{},{},False},{{0,1,2,3,4,5}},{{0},{1},{3},{4},{3},{0}},{Automatic}]      Particularly the second part is not identical: V9.0.1:               ifun[[2]]     {4,3,0,{6},{4},0,0,0,0,Automatic}      V10:               ifun[[2]]     {4,3,0,{6},{4},0,0,0,0,Automatic,{},{},False}      Can somebody explain the differences to me? Is there a way to still be able to use the old definitions (which were time consuming to create) in V10?


Print notebook with all cells opened

I have a long _Mathematica_ notebook where some cells on multiple levels are closed for clarity. When I export the notebook as a _PDF_ via `Print` or `Save as`, the print only contains the opened cells. I want to be able to print all cells - even the closed ones - into the _PDF_.   When I open them via `Cell -> Grouping -> Open all Subgroups` my actual notebook is changed destructively, and I have to re-close certain groups by hand because there's no proper undo. Did I miss any option?


Plot has red 'film', no error message

I am encountering really strange behavior: I wrote a function that plots values some data. After executing the code the resulting plot has the red 'error' colour, but only momentarily (maybe 0.1 sec). There is no error message, so the plot seems fine. However, when I export the graphic, the red colour is exported too. There seems no way to get the graphic without the red. I am (in this case) not interested in what caused the error message but want to export the graphic without te red colour. Does anyone know how to do this? I tried using Quiet[] but that did not help. * * * My code:                PlotBetaCI[whole_,everyminute_]:=             Module[             {len,linearmodels,betas,lows,highs},                  len=Length[everyminute];                  linearmodels=Quiet@LinearModelFit[Transpose[{#,whole}],x,x]&/@everyminute;                  betas=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,1]]&/@linearmodels}];                  lows=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,3,1]]&/@linearmodels}];                  highs=Transpose[{Range[len],#["ParameterConfidenceIntervalTableEntries"][[2,3,2]]&/@linearmodels}];                  ListPlot[{betas,Sequence@@Transpose[{lows,highs}]},Joined->{False,Sequence@@ConstantArray[True,len]},PlotStyle->Black,PlotMarkers->{Graphics[{Line[{{-1,-1},{1,1}}],Line[{{-1,1},{1,-1}}]},ImageSize->10],Sequence@@ConstantArray[Graphics[{Line[{{0,0},{0.04,0}}]},ImageSize->10],len]},ImageSize->Large,PlotRange->{Automatic,{Automatic,1.5}}]         ]      The command to actually plot is (this produces the plot I am talking about)               PlotBetaCI[rmssd, everyminutermssd]      _rmssd_ is a list of values. _everyminutermssd_ has the same length, but depth 10.


Slow image processing using ReplaceAll

Can anyone explain me, why this line of simple code is so slow? And can it be improved somehow?               p = Import["http://www.ultimatte-software.com/images/2FSN-TLW-wide03-ultimatte-software-blue.jpg"];          Timing[Image[(ImageData[p] /. {r_, g_, b_} -> {b} 2 - {g} - {r})]]


FrameTicks and Ticks on Axes in Same Plot

I have a plot where I would like ticks shown on both the axes and the frame, with them labeled separately. I have custom labels for the frame and want the horizontal axis labeled with ticks automatically. Despite setting both the `Ticks` and the `Frame` properties, I cannot get the ticks to show up on the axes. Is there a way to do this without drawing the ticks manually or something like that? My example is shown below, I am able to get automatic ticks on the top of the frame, but these are not labeled either.               Plot[xt[t], {t, 0, .5*10^-3},        Ticks -> Automatic,        FrameLabel -> {{"x [m]", None}, {"t", None}},       Frame -> True,       FrameTicks -> {{Automatic, None}, {{{0, "t'"}, {.0005, "t'+5 ms"}}, Automatic}}]      ![Plot with no axes ticks](http://i.stack.imgur.com/NXyHc.png)


Solving mixed integer programming using Mathematica

Let $x_{ij}$ be an $n\times k$ matrix defined as follows: $ x_{ij}=\begin{cases} 1, & \text{if }s_i\text{ is assigned to }S_j \\ 0, & \text{otherwise } \end{cases} $ and $S$ is a set of $k$ clusters and $s_i$ is a set of points to be assigned to these clusters. The following integer programming defition gives the exact solution to k-means clustering: $ \min_{x_{ij}} \sum_{j=1}^k\sum_{i=1}^n x_{ij} \lVert s_i - \frac{\sum_{l=1}^n x_{lj}s_l}{\sum_{l=1}^n x_{lj}} \rVert^2 $ such that the following cnstraints hold: $ \sum_{j=1}^k s_{ij} = 1,\ i=1,\ldots,n $ $ \sum_{i=1}^n s_{ij} \geq 1,\ j=1,\ldots,k $ $ x_{ij}\in\{0,1\},\ i=1,\ldots,n\ \textrm{and}\ j=1,\ldots,k $ How can this be programmed in Mathematica? Mathematica has a Linear Programming package but the domain specification cannot be set to mixed integers (reals and integers)? Does the following function specification do mixed integer programming:               LinearProgramming[c,m,b,lu,{dom1,dom2,…}]      The problem is NP-hard so I am not expecting fast solutions...


How to calculate the mode of a probability distribution

I was wondering if there is any command to get the mode of the probability distributions. Calculating manually, the mode is (alpha-1)/(alpha+beta-2) While the mean, median or variance of the beta dist can be found. For example, the mean can be found using this following command:               Mean[BetaDistribution[α, β]]      As suggested by @kguler , this command `ArgMax[PDF[BetaDistribution[2, 3], x], x]` works perfectly fine. However, when I changed the value of the parameters to something like thousands, the running process took a very long time. Is there any other command that will produce the results much faster? Cheers.


Inverting matrix of unknown size

I have a matrix that has a variable number of columns and rows (but it is always square). The matrix is: $$ \Gamma = \begin{bmatrix} \Theta & 0 & 0 & 0 & T & 0 & R_j \\ u \Theta & \rho & 0 & 0 & u T & 0 & R_j \\ v \Theta & 0 & \rho & 0 & v T & 0 & R_j \\ w \Theta & 0 & 0 & \rho & w T & 0 & R_j \\ H \Theta -1 & u \rho & v \rho & w \rho & \Omega \rho +H T & \frac{5 \rho }{3} & R_j \\ k \Theta & 0 & 0 & 0 & k T & \rho & k R_j \\ Y_i \Theta & 0 & 0 & 0 & Y_i T & 0 & Y_i R_j+\rho \delta_{ij} \\ \end{bmatrix} $$ where the indices $i,j$ are the row and column indices respectively. For example, if $i,j={1,2}$ the matrix would look like: $$ \Gamma = \begin{bmatrix} \Theta & 0 & 0 & 0 & T & 0 & R_1 & R_2 \\ u \Theta & \rho & 0 & 0 & u T & 0 & R_1 & R_2 \\ v \Theta & 0 & \rho & 0 & v T & 0 & R_1 & R_2 \\ w \Theta & 0 & 0 & \rho & w T & 0 & R_1 & R_2 \\ H \Theta -1 & u \rho & v \rho & w \rho & \Omega \rho +H T & \frac{5 \rho }{3} & R_1 & R_2 \\ k \Theta & 0 & 0 & 0 & k T & \rho & k R_1 & k R_2 \\ Y_1 \Theta & 0 & 0 & 0 & Y_1 T & 0 & Y_1 R_1+\rho & Y_1 R_2 \\ Y_2 \Theta & 0 & 0 & 0 & Y_2 T & 0 & Y_2 R_1 & Y_2 R_2 + \rho \\ \end{bmatrix} $$ The values for $i$ and $j$ can be arbitrary. When I put this in as is (just treating the subscripts as notation), I get terms divided by the Kronecker delta only which is impossible. Is there a way to invert this and keep it general in terms of $i,j$? The code to enter the matrix is:               G =        {         {Θ, 0, 0, 0, T, 0, Rj},         {Θ*u, ρ, 0, 0, T*u, 0, Rj},         {Θ*v, 0, ρ, 0, T*v, 0, Rj},         {Θ*w, 0, 0, ρ, T*w, 0, Rj},         {Θ*H - 1, ρ*u, ρ*v, ρ*w, T*H + ρ*Ω, 5/3*ρ, Rj},         {Θ*k, 0, 0, 0, T*k, ρ, Rj*k},         {Θ*Yi, 0, 0, 0, T*Yi, 0, Rj*Yi + ρ*δ}       };     Ginv = FullSimplify[Inverse[G]];


Find all permutations with reversals / cyclic permutations removed

I have a list of all non-cyclic permutations of n labels. How can I get rid of all elements which are redundant in the sense that they are the inverse of another one. For instance if n=4, the elements {1,2,3,4} and {1,4,3,2} are related by reversal and right rotation by one element. So I want to discard the latter. Cheers!


PlotLegend disappears if Plot is used with ColorFunction

Working some charts on V10, I discovered that `PlotLegends` disappears if used together with `ColorFunction` inside `ListPlot` or `Plot`. Here is one example for `Plot`:               Plot[Sinc[x],{x,0,10},PlotLegends->{"Teste"},PlotStyle->Thick]      ![enter image description here](http://i.stack.imgur.com/PVv1U.png)               Plot[Sinc[x],{x,0,10}, PlotLegends->{"Teste"}, PlotStyle->Thick          ,ColorFunction->(ColorData["AvocadoColors"][#2]&)     ]      ![enter image description here](http://i.stack.imgur.com/pPxzt.png) The same problem to ListPlot. I'm on Mac using V10. Anyone else confirm this?


Why are fonts in my notebooks grainy after transferring to a new machine?

After transferring _Mathematica_ (and successfully transferring my license) to a new machine (a Retina MacBook Pro) all the fonts in my documents look jagged: ![enter image description here](http://i.stack.imgur.com/UXQKE.png) How do I get _Mathematica_ to show smooth fonts that take advantage of the Retina display? * * * For comparison, this is how sharp fonts are in a well-behaved application: ![enter image description here](http://i.stack.imgur.com/mrDSj.png)


Timing: how make a program to work faster using built in functions and tables

I want to improve my code to make it working faster even for very large numbers.               fun[n_, a_, b_] := (       low = n^a;       low2 = n^b;       p = Table[Binomial[n, x]*StirlingS2[a, x]*x!/low, {x, 1, a}];       pp = Table[Binomial[n, x]*StirlingS2[b, x]*x!/low2, {x, 1, b}];       ListPlot[{p // N, pp // N}, some options]     )      I know that I should use as many built-in functions as I can, so I made it. And also I should not repeat the same thing many times. I want to run this function for values like for example $n = 1000000, a = 800000, b = 800000$. Is it possible to improve the speed of the program? And is it possible to evaluate the function for such huge numbers in a reasonable time (for example less than 2 hours)? Maybe is any way to make working on tables faster?


Calculus 1 Related Rates -Total Derivative issues

I'm trying to do part a) of this calculus 1 problem in _Mathematica_ V9: http://tutorial.math.lamar.edu/Classes/CalcI/RelatedRates.aspx#Deriv_Rates_Ex4 Warning noob code below!               st = 5/14 == r/h; (* 1. Similiar triangles to relate radius and height *)     radius = Solve[st, r][[1]]; (* 2. Get radius in terms of height *)     dr = Dt[radius]; (* 3. Get dr in terms of dh *)     dv = Dt[v == (1/3) r^2 h]; (* 4. Implicitly diff the volume of our leaky cone *)     dv /. { Dt[v] -> -2, dr[[1]], radius[[1]], h -> 6 } (* replace unknowns with knowns *)      My problem is in the last line above. There's still an `h` remaining. Why didn't it get replaced? If I could properly replace it, I can then take one more step and solve this related rates problem by solving for `Dt[h]`.


Change associativity of the @ operator

The @ operator in Mathematica is right-associative by default, i.e.               f@g@h      evaluates as               f@(g@h)      Is it possible to make the @ operator evaluate the involved functions in a left-associative order `(f@g)@h` instead?


Generating a variable size table one element at a time

I can produce a variable size list of strings like `AACBBAABC` with this code:               test[n_] :=        Flatten[ Table[ StringJoin @@ Table[ Subscript[\[Zeta], i], {i, 1, n}], ##] & @@        Table[{ Subscript[\[Zeta], i], {"A", "B", "C"}}, {i, 1, n}], n - 1]      My problem is that ultimately `n` will be such that the table has $10^{17}$ elements.   What I want to do is generating the elements one at a time so that I can run a test on the string to validate it. The number of good strings will be $<<10^{17}$. In essence I need a code that will have a variable number of loops depending on `n`. My $70$ year old brain is having a problem coming up with an answer!


How to export a header before the data in the result file?

I would like to export a phrase to my result data as a heading. I'm exporting the data correctly with                Export["file.dat", table].       But I'm doing several simulations with different parameters and I would like to write down this parameters in the file. I'm trying with                Write["file.dat", {"Resonance simulation Data =", DateString[], "Parametros: Nz = ", Nz, " CP = ", CP, " K1 = ", K1}];       but this erases the precedent data if it's put after the `Export` or it is erased if it came before. How could I do this?


NDSolve not returning the expected solution

I'm trying to simulate a simple circuit with Mathematica. The equation of the circuit is $R \dfrac{dQ}{dt} + \dfrac{Q(t)}{C} = f_{sig}(t)$. This is the definition of $f_{sign}$, and the function seems to work, since the plot is good.               newfSign[t_] :=        If[OddQ[Floor[t/τ]], 1/2*Subscript[V, max] (Cos[2*π *β*t/τ] + 1), Subscript[V, max]]      ![Plot of $f_{sign}](http://i.stack.imgur.com/8PyFM.png) This is the definition of the solution:               s = NDSolve[{R*Q'[t] + Q[t]/C2 == newfSign[t], Q[0] == 0}, Q, {t, 0, 4 τ}]      And I try to plot it with this command:               Plot[Q[t]/C2 /. s, {t, 0, 4 τ}, PlotRange -> All]      Getting this result, which is not what would be expected, given the forcing function $f_{sign}$. ![Plot of NDSolve](http://i.stack.imgur.com/khzgo.png) Those are the values I'm using:               Subscript[V, max] = 5     β = 10     τ = 500*10^-6     R = 2000     C2 = 0.22*10^-6      Am I missing something?


Upvalues, TagSet and UpSet, what's the difference, when should a use each?

Some of the big mysteries of ~~Universe~~ Mathematica for me is the application of UpValues. I know about this question and know the very poor Mathematica documentation on that. I'm very curious to know if someone that not Leonid uses this too. Just to get some clue on how it works, I would like to know what's the difference between `TagSet` and `UpSet`. Can I say that `UpSet` is subset of `TagSet`? For instance, I can say these examples are equivalent.               name[alien]^= "Alf"         alien /: name[alien] = "Alf"      In what situations should I apply each case?


Importing a Base64 encoded string

everyone, I'm handling some paragraphs enconded with Base64 from CSV file format. The problem is that Mathematica can't decode it. It seems Mathematica Encode/Decode their own Base64. I'm thinking write my decode method by my own, but I ask it first. By example: I used `base64.b64encode` on python with the string:               s = '"Hola los felicito por su equipo de comunicadores. Me encanta verlos pues ustedes se salen de las   simplezas y superficialidades de los noticieros tradicionales.Un saludo desde Montreal- Canada.          Adelante! así como van en poco tiempo tendrán muchos mas seguidores que  la ""Gran prensa Colombiana"" la cual ha venido mintiendo por décadas.          "'      And outcome:                b = 'IkhvbGEgbG9zIGZlbGljaXRvIHBvciBzdSBlcXVpcG8gZGUgY29tdW5pY2Fkb3Jlcy4gT\     WUgZW5jYW50YSB2ZXJsb3MgcHVlcyB1c3RlZGVzIHNlIHNhbGVuIGRlIGxhcyAgIHNpbXB\     sZXphcyB5IHN1cGVyZmljaWFsaWRhZGVzIGRlIGxvcyBub3RpY2llcm9zIHRyYWRpY2lvb\     mFsZXMuVW4gc2FsdWRvIGRlc2RlIE1vbnRyZWFsLSBDYW5hZGEuCgpBZGVsYW50ZSEgYXP\     DrSBjb21vIHZhbiBlbiBwb2NvIHRpZW1wbyB0ZW5kcsOhbiBtdWNob3MgbWFzIHNlZ3VpZ\     G9yZXMgcXVlICBsYSAiIkdyYW4gcHJlbnNhIENvbG9tYmlhbmEiIiBsYSBjdWFsIGhhIHZ\     lbmlkbyBtaW50aWVuZG8gcG9yIGTDqWNhZGFzLgoKIg=='      On Mathematica: ![enter image description here](http://i.stack.imgur.com/NJ5ug.png) ![enter image description here](http://i.stack.imgur.com/ITVv2.png) But if you use another base64 decoder like decoderb64, it can do the job. Thanks in advance,


Eliminate z from two equations in x, y, z and plot y as a function of x

I have this equation to begin with: $$1 - 3 x y = 5 z - 2 x $$ I want to solve this equation for $z(x,y)$, then plug $z(x,y)$ I plug $z$ inside a second equation: $$ y = 7 x z - \frac{z}{x} $$ Finally, I want to plot $y(x)$ for $-5 < x < 5$ and $-5 < y < 5$. I tried numerically, but the following doesn't work:               eqn1 =  1 - 3 x y  ==  5 z - 2 x       eqn2 = y == 7 x  z - z/x          Table1 = Table[z /. Solve[eqn1], {x, -5, 5, 1}, {y, -5, 5, 1}] // MatrixForm          Table[y /. Solve[eqn2 /. Table1, y], {x, -5, 5}]      I think the problem is feeding the values from `Table1` into the second table. How do I feed the data from `Table1` as the domain for solving `eqn2`?


Normal // Association // Dataset workaround for some user query operators

Given example tabular data (ie, with rows and columns, or "data frames")               data = Table[<| "key1" -> i, "key2" -> i + 10 ,         "key3" -> i + 20|>, {i, 4}] //Dataset      ![enter image description here](http://i.stack.imgur.com/wIYwO.png) The following query operator almost works to associate (the values of) a selected "primary" key at first level:               primaryKey[key_] := Sequence[All, Slot[key] -> KeyDrop[#, key] &]       This allows the lookup syntax:               data[primaryKey["key1"]][3]          (* 3 -> <|"key2" -> 13, "key3" -> 23|> *)      How to modify this query to handle:   1. Return only the value `<|"key2" -> 13, "key3" -> 23|>`, similar to how `data[All, #key1 &] // Normal` returns only the values `{1, 2, 3, 4}`.   2. Dataset doesn't recognize the implicit global association structure, flattening the data by 1 level: data[primaryKey["key1"]] ![enter image description here](http://i.stack.imgur.com/fvSyd.png) The following workaround works but how to incorporate in the operator?               data[primaryKey["key1"]] // Normal // Association // Dataset      ![enter image description here](http://i.stack.imgur.com/RXhc1.png) The same issue arises from other restructuring operators, like generating an association from (the values of) two specified keys eg               data[All, #key1 -> #key3 &][2]          (* 2 -> 22 *)      Whereas               data[All, #key1 -> #key3 &] // Normal // Association //        Dataset // #[2] &          (* 22 *)


Converting fortan into Mathematica: a correct form for an iterator

I have to convert a fortran program into Mathematica's one. The fortran program defines some integer indicators, then, with a Do loop, it initializes their values, and then, with other Do loops, it gives the correct value for each (i,j) :                 INTEGER iswnod (IMAX+1,JMAX+1) ! vertex indicator of a grid       INTEGER iswlx  (IMAX,JMAX+1)   ! x-link indicator of a grid       INTEGER iswly  (IMAX+1,JMAX)   ! y-link indicator of a grid            DO i=1,Nx+1       DO j=1,Ny+1           iswnod(i,j)=0             END DO       END DO            DO i=1,Nx       DO j=1,Ny+1           iswlx(i,j)=0             END DO       END DO            DO i=1,Nx+1       DO j=1,Ny           iswly(i,j)=0             END DO       END DO                 DO i=1,Nx       DO j=1,Ny          iswnod(i,j)=iswnod(i,j)+1                iswnod(i+1,j)=iswnod(i+1,j)+1                iswnod(i,j+1)=iswnod(i,j+1)+1                iswnod(i+1,j+1)=iswnod(i+1,j+1)+1           iswlx(i,j)=iswlx(i,j)+1          iswlx(i,j+1)=iswlx(i,j+1)+1          iswly(i,j)=iswly(i,j)+1          iswly(i+1,j)=iswly(i+1,j)+1          end if            END DO       END DO      So, I tried to convert it into Mathematica, but I don't know how to considerer all these conditions. Infact, normally a Do loop has the form: > Do[expr,{ind1, 1, n1},{ind2,1,n2},...] How to write the 8 expressions of the last loop? And first, how to initialize the values? I tried in this way: > nx = 100; > > ny = 100; > > iswnod[x_, y_] := 0; > > iswlx[x_, y_] := 0; > > iswly[x_, y_] := 0; > > Do[Sequence[iswnod[i, j] = iswnod[i, j] + 1, iswnod[i + 1, j] = iswnod[i + > 1, j] + 1, iswnod[i, j + 1] = iswnod[i, j + 1] + 1, iswnod[i + 1, j + 1] = > iswnod[i + 1, j + 1] + 1, iswlx[i, j] = iswlx[i, j] + 1, iswlx[i, j + 1] = > iswlx[i, j + 1] + 1, iswly[i, j] = iswly[i, j] + 1, iswly[i + 1, j] = > iswly[i + 1, j] + 1], {i, 1, nx}, {j, 1, ny}] ; But as result I have only: > Do::itform: Argument iswnod[i+1,j]=iswnod[i+1,j]+1 at position 2 does not > have the correct form for an iterator. >> I don't know how to do. Thank you for your attention


Does Mathematica support importing ISO 8601 date strings?

Does _Mathematica_ have a built-in function to convert ISO 8601 formatted date strings (e.g. `2012-01-04T00:00:00`) to a date list? ISO 8601 strings come in a variety of formats:               Date alone: 2012-12-03     Combined date and time: 2012-12-03T22:02     Combined date and time with time zone: 2012-12-03T22:02:47.23+01      On top of that individual components can be omitted (see the Wiki page). I am looking for a solution that covers the whole ISO 8601 standard.


LogPlot axes labels destroyed when working in high precision

(I'm using _Mathematica_ 8.) I have a Taylor series:               poly = Normal[Series[E^x, {x, 0, 10}]]      I want to produce a log-linear plot of the error. This is easy enough with the following code:               LogPlot[Abs[E^x - poly], {x, -1, 1}]      This produces ![a log-linear plot](http://i.stack.imgur.com/T4sqC.png) Now, I want to plot even smaller values of the error (in particular I want the plot to be sensible near zero), so I tell `LogPlot` to use high precision as follows:               LogPlot[Abs[E^x - poly], {x, -1, 1}, WorkingPrecision -> 30]      However this destroys the labeling on the y-axis: ![bad behavior of LogPlot\[\]](http://i.stack.imgur.com/THXrl.png) Does anyone know what has gone wrong here? How do I fix it?


Is learning to use Mathematica useful for pure theoretical research in Mathematics and Computer Science?

I am looking for opinions from _Mathematica_ users about _Mathematica_ itself. After reading the faq, I thought that in some sense I "wish to solve a problem using _Mathematica_ " ... although I understand that this question is probably too vague. I hope not to be distracting here. I see that some researchers (in math and computer science) at my university use _Mathematica_ to carry out intricate calculations. I wonder if mathematical software today is so good that it can do better than humans at symbolic manipulation. This would mean that it would be really worthwhile to acquire some background in using such software, especially in those fields of research where one often has to deal with huge formulas. Also, two subquestions:   1. How does one cite the use of _Mathematica_ in a research paper? One could in principle say "beginning from formula X, using _Mathematica_ we get Y". Would that be accepted professionally?   2. Are these systems foolproof (particularly _Mathematica_ )? I mean, is it known that there are no special instances of symbolic-manipulation problems for which the software could end up doing an error dealing with them? P.S. I didn't find a proper tag for my question.


Find solutions of equation involving Bessel functions

I'm new in Mathematica and I'm trying to find the solutions of this equation involving Bessel functions $$\eta \frac{ J_{n+1}(\eta a)}{J_n(\eta a)}+\chi \frac{ I_{n+1}(\chi a)}{I_n(\chi a)}=0$$ where, $$ \eta =\sqrt{\frac{\beta ^2 \left(\sqrt{\frac{4 \alpha ^2 \omega ^2}{\beta ^2}+1}-1\right)}{2 \alpha ^2}} \,\,\,,\,\,\,\,\,\chi =\sqrt{\frac{\beta ^2 \left(\sqrt{\frac{4 \alpha ^2 \omega ^2}{\beta ^2}+1}+1\right)}{2 \alpha ^2}}$$ and $$ \alpha =\sqrt{\frac{h^2 M}{12 \left(1-\nu ^2\right) \rho }} \,\,,\,\,\, \beta =\sqrt{\frac{M T}{\left(1-\nu ^2\right) \rho }}$$ So at the end, my equation is a function of n (which is an integer), $\omega$, h and T. I need to find the values of $\omega$ or eigenfrequencies for which the equation is satisfied. Based on this post Trying to solve a transcendental equation involving bessel functions, I tried the following:               f[n_, ω_, h_,T_] := η*BesselJ[n+1,η*a]/BesselJ[n,η*a]                                 + χ*BesselI[n+1, χ*a]/BesselI[n,χ*a]      and               Manipulate[Plot[f[n_, ω_, h_, T_], {ω, 0, 10}, PlotRange -> {-1000, 1000}],                                          {n, 0, 5, 1}, {h, 0.1, 1}, {T, -1, 1}]      but the plot does not show anything. (I set a=1) Thanks for your help!


How do I format an Exported plot to Excel?

I have the following piece of code:               Plot[StateResponse[        nss,        {0.01 UnitStep[t - tstep], 0, 0, 0, 0}, {t, 0, tstop}] // Evaluate,      {t, 0, tstop} ,      PlotLabel -> "State Variable Open loop response to 1% step in Dd"]      which gives me a five variable plot. I want to export this plot to excel to compare with some other data but can't get `Export` to format the exported _Mathematica_ data as I want, i.e. in six columns. Can anyone help on this?


Manipulate showing the trajectory of a particle along a parametric curve

I have a particle which follows a certain trajectory given by `rx` and `ry`               rx = E0*q*(-T*w*Cos[T* w] + Sin[T* w])/(2*m*w^2)     ry = E0*q*(-1 + Cos[T*w] + T*w]*Sin[T* w])/(2*m*w^2)      I am able to plot `rx` and `ry` but I need to have an animation of a particle (a point) which follows this path from `T = 0` to `T = 10` microsec. Here is the code.:               Manipulate[       ParametricPlot[{           (E0*q*1.6*10^-19*(-T*ω*Cos[T*ω] + Sin[T*ω]))/(2*m*1.6*10^-27*ω^2),            (E0*q*1.6*10^-19*(-1 + Cos[T*ω] + T*ω*Sin[T*ω]))/(2*m*1.6*10^-27*ω^2)         },         {T, 0, temp},          AxesLabel -> {Row[{Style["rx", Italic], " (cm)"}], Row[{Style["ry", Italic], " (cm)"}]},         PerformanceGoal -> "Quality",          Epilog -> {           PointSize[0.04],            Point[{             (E0*q*1.6*10^-19*(-temp*ω*Cos[temp*ω] + Sin[temp*ω]))/(2*m*1.6*10^-27*ω^2),              (E0*q*1.6*10^-19*(-1 + Cos[temp*ω] + temp*ω*Sin[temp*ω]))/(2*m*1.6*10^-27*ω^2)           }]       }],        Style["horizontal", Bold],        {{m, 1, "mass"}, 1, 4, 1, ImageSize -> Tiny, Appearance -> "Labeled"},        {{ω, 200*2*π*1000, "frequency"}, 200*2*π*1000, 400*2*π*1000, 1*2*π*1000,          ImageSize -> Tiny, Appearance -> "Labeled"},        {{E0, 40, "amplitude"}, 40, 80, 1, ImageSize -> Tiny, Appearance -> "Labeled"},        {{q, 1, "charge"}, 1, 7, 1, ImageSize -> Tiny, Appearance -> "Labeled"},       Delimiter,       {{temp, 1*10^-6, "pulselength"}, 10^10 - 6, 20*10^-6, 10*10^-6, ControlType -> Trigger},       ControlPlacement -> Left]      Any help will be appreciated.


Warning and Errors during Compile

I defined a compiled function               cf = Compile[{{x, _Integer}, {n, _Integer}},        z = (n^x);         Binomial[n, #]* StirlingS2[x, #] *(#!)/z & /@ Range[x]];      and I want to run this for               n = 300000.0;     x = 186200;     Timing[cf[x, n]]      But I have below warnings/errors:               Join::heads: Heads CurrentValue and List at positions 1 and 2 are expected to be the same.     Join::heads: Heads CurrentValue and List at positions 1 and 2 are expected to be the same.     Join::heads: Heads CurrentValue and List at positions 1 and 2 are expected to be the same.     general:stop : Futher output of Join::heads will be suppressed during this calculation.     CompileFunction::cfse : Compiled expression     949792642757151450284577945707701821742626866813<<1019743>>\     0000000000000000000000000000000000000000000000000 should be a \     machine-size integer.     CompiledFunction::cfex: Could not complete external evaluation at instruction 2; proceeding with uncompiled evaluation      Can you help me understand what I am doing wrong? Because for this values of `n` and `x` this compile function should be evaluated fast, but it is working very slow.


How to write values of function to file?

For example, say I wanted to plot Sin(x) like this:               Plot[Sin[x],{x,0,2 Pi}]      But instead of plotting to a graph, I want to now tabulate the values of Sin[x] to a data file. How do I achieve this? **EDIT:** Sorry I wasn't clear enough, I mean plot the x values in one column and the y values in the second column


Calling MATLAB from Mathematica

How can I call MATLAB functions directly from Mathematica and transfer data/variables between the two systems?


Could the PrecisionGoal for NDSolve be a negative number?

The help of Mathematica doesn't say so much about the `PrecisionGoal` for `NDSolve`, and I never considered much about it even after I met the warning message > NDSolve::eerr for several times when I was trying to solve a set of PDEs these days: every time I met it I would simply considered it as a proof for the defect of my assumption for the initial or boundary condition, and my resolution strategy for it is to modify the conditions or sometimes I will also lower the value of the `PrecisionGoal` as the help says. However, this time I can't ignore it anymore, for I accidentally found that for one of my assumptions, the suitable `PrecisionGoal` for it is a negative integer… The thing named "Precision" in my mind was always a positive integer, but this time it is negative! Why?…… What's the exact effect of "PrecisionGoal" option for `NDSolve`?


MapThread over sublists of different length

I have a list which looks like this: `l={{1,0,3,4},{0,2},{0,0,1,3},{1,2,0}}`. Now I would like to count how many 0s the sublists contain in the first, second,... slot. The result for this example should be: `{2,2,1,0}`. Since the sublists do not have the same length `MapThread` does not work. I would be grateful for a solution.