How do I put an image on the complex plane?

I watched this video and became interested in transforming an image. But I have no good idea on how to embed an image in the complex plane using _Mathematica_. I have a method that seems to work, but there has to be a better way to do this. Can somebody point me in the right direction?               a = Reverse[ImageData[ImageApplay[Mean,img]]]          f[c_] := Module[{re, im, d1, d2},        {d1, d2} = Dimensions[a];        re = Round[Re[d2 c]];        im = Round[Im[d1 c]];        If[1 <= re <= d2 && 1 <= im <= d1, a[[im, re]], 1]     ];          ListDensityPlot@Table[f[(y + x I)], {x, -1, 1.5, 0.02}, {y, -1, 1.5, 0.02}]


Mean Squared Deviation for Population Data

I've been using the Lotka-Volterra equation to estimate population sizes and need to find the MAD (mean absolute deviation), MSD (mean squared deviation) and mape (mean absolute percentage error) for my estimated population data vs the actual population data. I have 14 years of data. Important part of code I've been working on is below. However when I run this I get wrong/strange output. Any ideas? The sum code I'm using for MSD is likely the one that needs to be fixed and is at the very end. Thanks.               MyLVPredatorError[myPreyPopList_, myPredatorPopList_, myalpha_, myc_, myd_, myh_] :=          Module [{n, myPredatorPopValueList, myPredatorPopErrorList,          myLastN, myLastP, CurrentP, MSD, MSDError, MSDSqr,          numberOfValues, DebugFlag = False},              (* Step #3: Calculate the Predator Population Values  *)                                          If[DebugFlag, Print["Entering While loop"]];                    (*************)                                             myPredatorPopValueList = myPreyPopList;         myLastN = myPreyPopList[[1]];         myLastP = myPredatorPopList[[1]];         n = 1;              (* Calculate the prey population for varying number of predators *)          While[n <= numberOfValues,                 CurrentP = myLastP + (((-myd*myLastP) + (myc*myalpha*myLastN*myLastP))*myh);               myPredatorPopValueList[[n]] = CurrentP;               myLastN = myPreyPopList[[n + 1]];               myLastP = myPredatorPopList[[n + 1]];                                                         myPredatorPopValueList[[n]] = CurrentP;               MSDError = myLastP - CurrentP;               MSDSqr = MSDError*MSDError;                       If[DebugFlag, Print["n = ", n]];                                                         If[DebugFlag, Print["numberOfValues =", numberOfValues]];                                                          If[DebugFlag, Print["myPredatorPopErrorList =", myPredatorPopErrorList]];                    n = n + 1             (* end of While loop *)          ];                                         If[DebugFlag, Print["leaving While loop"]];                                                      MSD = Sum[MSDSqr, {n, numberOfValues}]/14;              Return[MSD];           (* end of the MyLVPredatorSoln module *)                                   ];


While loop not breaking when condition is met

I am having trouble with the while loop not breaking,               While[Abs[f[a, b] - f[aold, bold]] > 10^-5,      aold = a; bold = b;      α = dfx[a, b];      β = dfy[a, b];      l[t_] = {a, b} + t*{α, β};      h[t_] = f[l[t][[1]], l[t][[2]]];      dh[t_] = D[h[t], t];      tnew = t /. Solve[dh[t] == 0, t];      a = a + tnew*α;      b = b + tnew*β;      count++;      If[count == 10, Break[]];      ]      When I print the output, `Abs[f[a, b] - f[aold, bold]]` is way smaller than `10^-5`, the condition should be met around `5` loops.   Can you see what is wrong with the code?


For loop with steps other than 1

I would like to do a For loop with a jump 2*Pi instead of 1.               For[j = 0, j <= nmax, (incr = 2 Pi), ...]      Actually what I want to do is `j = n 2 Pi`, where `n` takes values from 0 to `n-1`, so the iteration stops at `nmax = (n - 1) 2 Pi`. I know this is a pretty trivial question, but I have not found anything equivalent in the "Documentation center".


Sampling a musical instrument (or re-tuning MIDI)

I'd like to try to convert a piece of MIDI music made with SoundNote to another tuning (not microtonal or even split-black-keys, just a slightly different tuning for each note). I searched for pitch parameters and it seems it only accepts "C" or "Db", not frequencies, and plays the piece in 12-tone equal temperament. (Am I right? Or could I somehow make a MIDI note sounding at a different frequency than those pre-defined notes?) So I'm trying to recreate piano sound with Play function. I add some harmonics to a sine wave but the more I add, the worse it sounds. Adding attack and decay shouldn't be very hard but for adding the harmonics in right amounts, I'd need to sample. I could have access to a piano and get some sound samples. In what file format should I record them so that Mathematica could run a Fourier transform on it? What functions should I use? How do I give a sound file as an input? Or, is there any way to re-tune a MIDI file with some other program after I compose it with Mathematica and export?


Lyapunov Exponent

Does anyone know a (simple) Mathematica code for computing the Lyuponov Exponent for the Rossler System? Thank you Rossler System:               rossler = {           x'[t] == -(y[t] + z[t]),           y'[t] == x[t] + 0.1 y[t],           z'[t] == 0.2 + x[t] z[t] - 5.7 z[t],           x[0] == 1, y[0] == 1, z[0] == 1          }


Assign keyboard shortcut unique to notebook

What is the most portable way to assign keyboard shortcuts unique to each notebook? To clarify I would like to have the keyboard shortcut change when simply changing the current `InputNotebook`. Currently I'm have the following code which allows for me to essentially have the defined function be defined in a notebook and execute in the Global` context.               FrontEndExecute@      FrontEnd`AddMenuCommands[       "DuplicatePreviousOutput", {MenuItem["Ctrl &q",          FrontEnd`KernelExecute@ToExpression@MakeBoxes[            F2[]            ], MenuKey["q", Modifiers -> {"Control"}],          System`MenuEvaluator -> Automatic]}]      I would like to somehow attach functions to notebooks without changing the context(most ideal). Alternatively I might be able to use something like a custom `FrontEnd'NotebookExecute` instead of `FrontEnd'KernelExecute`.


How to write a robust memberQ that test membership in set theory sense?

Select[{{"foo", "bar"} -> "a", {"foo", "baz"} ->         "a", {"foo", _} -> "a"}, MemberQ[{{"foo", "bar"}}, #[[1]]] &]          (* {{"foo", "bar"} -> "a", {"foo", _} -> "a"} *)      I'd like the answer to be `{{"foo", "bar"} -> "a"}`. The built-in `MemberQ` seems to use `MatchQ` for testing equality. I'd like a `memberQ` that uses `SameQ` or `TrueQ[Equal[#1, #2]]&`, and works for possibly funky arguments such as patterns.


Replacing a sum of expressions

I have an equation which Mathematica solves but gives a huge output. However I notice in this output that the same expression occurs many times. Namely: $E=864 a^6 - 432 a^4 b^2 + 54 a^2 b^4 - b^6 + 54 b^4 x^2$ where $a,b,c$ are constants. However this expression can appear in the form $-E$, $E^2$, $\sqrt{E}$, $4E$, ... I'm struggling to tell Mathematica to make the replacement $(864 a^6 - 432 a^4 b^2 + 54 a^2 b^4 - b^6 + 54 b^4 x^2) \space \to \space E$ wherever it appears. All the ways I've tried (I'm not that handy with Mathematica I note) don't change output. Any ideas?


How can I align the labels of the buttons on a setter bar to the button centers?

I tried to align the labels on the buttons of a `SetterBar`to the button centers. This is my code:               lis = {"1", "2", "3", "dsf"};     SetterBar[Dynamic[buttonValue],        Table[lis[[iteration]], {iteration, 1, 4}],        BaseStyle -> {Red, Alignment -> {Center, Center}}, {ImageSize -> {100, 50}}]      How do I get the labels of the buttons aligned to their centers? Can any one show me how?


Unexpected dots from Line

I have noticed cases where `Line` produces dots in a graphics object when I think it shouldn't. The first of these is:               Line[{{0., 0.}}]      The second is:               Line[{{0., 0.}, {0., 0.}}]      Longer lists of same point do not produce dots. To see this evaluate               repeatPts [pt_, n_] := Line[ConstantArray[pt, n]]     Graphics[{Thickness[.125], repeatPts[{0., 0.}, #], repeatPts[{1., 1.}, #]},       ImageSize -> 50, Frame -> True, FrameTicks -> None, PlotRangePadding -> .3] & /@ Range[5]      ![Dots.png](http://i.stack.imgur.com/Y6IKI.png) Is this version or platform depended? I got the results shown above on with V9.0.1 running on OS X. Should it be considered a bug or a weird feature?


Reading Eigenvalue / Eigenfunction result from Reduce

I am trying to find the eigenvalue/eigenfunction solution to: $$\tag 1 y''+3y + \lambda y=0 ; y'(0)=0, y'(\pi)=0$$ I used DSolve and Reduce and they seem to converge, however (embarrassingly) I am having a difficult time understanding the Reduce output (which seems to have an issue with a particular branch point). Ignoring that warning, how do you read the output below?                sol = DSolve[y''[x] + 3 y[x] + a y[x] == 0, y, x]           {{y -> Function[{x}, E^(Sqrt[-3 - a] x) C[1] + E^(-Sqrt[-3 - a] x) C[2]]}}            Reduce[        y'[0] == 0 && y'[Pi] == 0 && a != 0 && (C[1] != 0 || C[2] != 0) /.         sol, a] // FullSimplify      During evaluation of In[29]:= Reduce::useq: The answer found by Reduce contains unsolved equation(s) {0==(2 I [Pi] C[3]-2 [Pi] Sqrt[-Power[<<2>>]])/(2 [Pi])}. A likely reason for this is that the solution set depends on branch cuts of Mathematica functions. >>                 (C[1] !=          0 && ((C[3] \[Element] Integers && Abs[C[3]] == C[3] &&          3 + a == C[3]^2 && C[1] == C[2] && a != 0) ||          a == -3)) || (a == -3 && C[2] != 0)


Google Map in Notebooks?

Using Mark McClure's GPXToGoogleMap results in a HTML and Javascript code which can be viewed by any browser. Is it possible to load this map into the notebook, which obviously means for example that               <script src="http://maps.google.com/maps?file=api&v=2.s&key="         type="text/javascript">     </script>     <script src="/Users/meinmacbookpro/Desktop/Messprojekte/gps.js"          type="text/javascript">     </script>      should be implemented somehow into the Mathematica code?


Bags and non-standard evaluation

What can internally be happening here? Is the evaluator just messing with us and going non-standard because it's a `Bag`? Or am I just not seeing how something like this could be done in _Mathematica_?               AppendTo[$ContextPath, "Internal`"];          In[19]:= ClearAll[x, y];     {x, y} = {Bag[{1, 2, 3}], Bag[{4, 5}]};      Heads are               In[21]:= Head /@ {x, y}          Out[21]= {Bag, Bag}      But they are just a head, no depth. Depths               In[22]:= Depth /@ {x, y}          Out[22]= {1, 1}      However, they are different. I take their second elements, or I print them in `InputForm`               In[23]:= BagPart[#, 2] & /@ {x, y}     InputForm /@ {x, y}          Out[23]= {2, 5}          Out[24]= {InputForm[Internal`Bag[{1, 2, 3}]], InputForm[Internal`Bag[{4, 5}]]}


Formatting legend text font

I am using this code to plot a graph, and I am trying to make the font of the legend bigger.               <<PlotLegends`     ListLogLogPlot[{Sort[moby]}, PlotRange -> Full, Joined -> True,          PlotLegend -> {"Moby Dick"}, LegendPosition -> {0.30, -0.20}, LegendShadow -> None,          LegendBorder -> None, PlotStyle -> {Dashed}, BaseStyle -> {FontSize -> 14}]      This only seems to change the font size of the labels on my axis. But I also want the legend to be size 14.


Extracting information from list

I have a huge list that looks like this:               list = {8, 12, 201, 0.001, 3, 7, 100        (InterpolatingFunction[{{0., 0.0018}},"<>"][2916/35] +         InterpolatingFunction[{{0., 0.0018}}, "<>"][2916/35]),        23, 44, 11, -0.002}      I want to extract only the numbers, specifically the numbers around 10. I tried using this `Select[list, _?(7 <= # <= 13 &)]` but it returns an empty list. I think this happens because the list has both numbers and the `100 (InterpolatingFunction...` that I want to ignore. I would also be happy just to extract ALL numbers hence ignoring the `100(InterpolatingFunction...` elements. Could you give me some tip please?


Number format of axes in a plot

How can I have a conditional format of the values appearing in the axis of a plot ? I have in mind the number format options available in Excel for plots as described here http://peltiertech.com/Excel/NumberFormats.html. I'm mostly interested in how to format numbers as shown in the paragraph "Thousands, Millions, etc." in order to display 100 000 as 100k and 100 000 000 as 100M for example. Also is it possible to set this format by default in plots ?


Different results with DateRange and LeapYearsQ in Mathematica 9 and 10

With Mathematica 9.0 for Mac OS X x86 (64-bit) (January 24, 2013) one could use               DateRange[{2000}, {2010}, "Year"]      to achive               {{2000}, {2001}, {2002}, {2003}, {2004}, {2005}, {2006}, {2007}, {2008}, {2009}, {2010}}      or               leapyears = Select[DateRange[{2000}, {2020}, "Year"], LeapYearQ[#] &]      with the result               {{2000}, {2004}, {2008}, {2012}, {2016}, {2020}}      With Mathematica 10.0 for Mac OS X x86 (64-bit) (June 29, 2014)               DateRange[{2000}, {2010}, "Year"]      one will get               {{2000, 1, 1}, {2001, 1, 1}, {2002, 1, 1}, {2003, 1, 1}, {2004, 1,        1}, {2005, 1, 1}, {2006, 1, 1}, {2007, 1, 1}, {2008, 1, 1}, {2009,        1, 1}, {2010, 1, 1}}      `leapyears = Select[DateRange[{2000}, {2020}, "Year"], LeapYearQ[#] &]`               {{2000, 1, 1}, {2004, 1, 1}, {2008, 1, 1}, {2012, 1, 1}, {2016, 1,        1}, {2020, 1, 1}}      The Function `DateObject` does not clear a bean to me               DateRange[DateObject[{2000}], DateObject[{2012}], "Year"]      ![enter image description here](http://i.stack.imgur.com/Tcqmd.png) So, how can i get rid of the additional `month, day` information on V10, i.e. using `leapyears` and `DateObject` returning `Year` only?


Show[] combines my Graphics3D objects in an undesirable way

Thanks to those (Heike, Jens, MrWizard, and R.M.) who helped me yesterday with figuring out how to plot an EM wave. Now I am running into trouble with the `Show` command. I am trying to combine three Graphics3D objects:   * a slab   * a grating, and   * a wave. The wave is supposed to be comparable in size with the grating and it should fall on it from the top (like light would fall on a grating). `Show` puts these together as a GIANT giant slab with grating and a puny EM wave. The problem is that Mathematica puts all objects' coordinate axes origin to the same point. How can I control the relative placement and sizes of these objects in `Show`? My code follows:               (*     sw = slab width, sh = slab height, gw = grid width, gh =       grid height, cw = channel width, sl = slab length, EM1s =       strentgth of EM wave 1, EM1f = frequency of EM wave 1     *)          sw = 38; sh = 4; gw = 3; gh = 4; cw = 6; sl = 7 gw + 6 cw;     grating = Graphics3D[{RGBColor[0.917, 0.082, 0.478],         Cuboid[{{0, 0, sh}, {sw, gw, sh + gh}}],         Cuboid[{{0, gw + cw, sh}, {sw, 2 gw + cw, sh + gh}}],         Cuboid[{{0, 2 (gw + cw), sh}, {sw, 3 gw + 2 cw, sh + gh}}],         Cuboid[{{0, 3 (gw + cw), sh}, {sw, 4 gw + 3 cw, sh + gh}}],         Cuboid[{{0, 4 (gw + cw), sh}, {sw, 5 gw + 4 cw, sh + gh}}],         Cuboid[{{0, 5 (gw + cw), sh}, {sw, 6 gw + 5 cw, sh + gh}}],         Cuboid[{{0, 6 (gw + cw), sh}, {sw, 7 gw + 6 cw, sh + gh}}]},         Boxed -> False];     slab = Graphics3D[{RGBColor[0.101, 0.701, 0.623],         Cuboid[{0, 0, 0}, {sw, sl, sh}]}, Boxed -> False        ];     EM1s = 1; EM1f = 3; x1 = 2 Pi;     pts1 = Table[{t (x1/(2 Pi)), -EM1s Sin[EM1f t (x1/(2 Pi))], 0}, {t, 0,          2 Pi, 0.03}];     pts2 = {#, 0, -#2} & @@@ pts1;     EMw1 = Graphics3D[{Thickness[0.007],         {RGBColor[0.439, 0.188, 0.627], Line[pts1]},         {RGBColor[1, 0.721, 0.039], Line[pts2]}, Thickness[0.002],          Line[{#, # {1, 0, 1}}] & /@ pts1[[;; ;; 3]],          RGBColor[1, 0.721, 0.039],          Line[{#, # {1, 1, 0}}] & /@ pts2[[;; ;; 3]]},         AxesOrigin -> {0, 0, 0}, Axes -> {True, False, False},         Ticks -> None,         AxesStyle ->          Directive[Thickness[0.0075], RGBColor[0.439, 0.188, 0.627]],         Boxed -> False];     Show[slab, grating, EMw1, Axes -> False, Boxed -> False,       ImageSize -> {400, 520}, PlotRange -> All]      ![enter image description here](http://i.stack.imgur.com/K7K8R.jpg)


Why does Mathematica give the wrong answer when integrating?

I integrate               Integrate[Exp[I Cos[b - c]] Cos[b], {b, 0, 2 Pi}]      Mathematica gives:               2 I Pi BesselJ[1, 1]      Which is indepedent on $c$. However, the result is NOT independent on $c$. The numerical value of what Mathematica gives is `0. + 2.76492 I` while               NIntegrate[Exp[I Cos[b - 0.5]] Cos[b], {b, 0, 2 Pi}]      Gives               1.16655*10^-10 + 2.42645 I      Certainly not the same. If we multiply the value Mathematica gives with $\cos(0.5)$ the result is the same. What is wrong?


Are there advantages to using additional arguments of common functions rather than alternative ways of calculating with lists?

(Apologies for the long question title.) One of the interesting, if sometimes confusing, things about Mathematica is that there is always more than one way to do things. Even intermediate users can be confronted with the sudden realisation that there was an alternative syntax to do the same thing. There seem to be a number of less-well-known parts of the language hiding in plain sight as additional arguments to some very well known functions. Consider the following examples:   1. **Total** : `Total[somematrix, {2}]` is equivalent to   `Total /@ somematrix`   2. **Partition** : `Divide @@@ Partition[somevector, 2, 1]` is equivalent to   `Most[somevector]/Rest[somevector]`   3. **Join** : `Join[somematrixwith10rows, Array[f, {10, 1}], 2]` is equivalent to some complicated thing involving `Append` or `Transpose` to add a column at the end. I am sure there are others. The common thread between all three of the first example in each pair above is an additional argument that is often not well known, at least by me. Are there reasons for preferring one style over the other? It has been suggested to me that at least in the first example, the additional-argument version doesn't unpack and therefore saves memory over the case using `Map`. But are there other reasons, for example the ability to `Compile`, or other efficiency improvements? If it all down to personal taste and knowledge, I worry that it makes it hard to understand and learn from other people's code. And if there are best practices to follow, it would be good to make them more widely known.


A combination of Set::setraw and Set::shape errors

Please consider the following toy code:               In[1]:= toylist = {hyb["chip1"], hyb["chip2"], hyb["chip3"]};          toyindices = {{{3, 1}, {3, 2}}, {{2, 3}, {2, 3}}, {{1, 3}, {1, 2}}};          toydata = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{10, 11, 12}, {13, 14,           15}, {16, 17, 18}}, {{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}};          Table[Evaluate[toylist[[i]]] =        Extract[toydata[[i]], toyindices[[j]]], {i, 1, Length[toylist]}, {j,        1, Length[toyindices]}] (* Version B *)          During evaluation of In[1]:= Set::setraw: Cannot assign to raw object 7. >>          During evaluation of In[1]:= Set::setraw: Cannot assign to raw object 8. >>          During evaluation of In[1]:= Set::setraw: Cannot assign to raw object 7. >>          During evaluation of In[1]:= General::stop: Further output of Set::setraw will be suppressed during this calculation. >>          Out[4]= {{{7, 8}, {6, 6}, {3, 2}}, {{16, 17}, {15, 15}, {12,         11}}, {{25, 26}, {24, 24}, {21, 20}}}          In[5]:= hyb["chip2"]          Out[5]= {16, 17}      * * * Even though the toy code above is producing the results I want, Mathematica throws the `Set::setraw` error. Question1: Is the error happening because I am using strings as indexes? Question2: Would it be safe to ignore or even turn this error off? The toy code above was designed to help troubleshoot a real-world problem I have. In the real-world case, I get two errors `Set::setraw` and `Set::shape`, from the following statement:               Table[Evaluate[mmsignalnames[[i]]] =         Extract[celvarnames[[i]], mmammindices[[j]]], {i, 1,         Length[celvarnames]}, {j, 1, Length[mmammindices]}];      Would you have any advice about the `Set::shape` error? I can't tell if it is related to the `Set::setraw` error. * * * More detail about the real-world problem....   1. I have 24 different biology datasets that have unique names. I have created a list called mmsignalnames which is composed of indexed symbols such as mmsignal["GSM356796"], mmsignal["GSM356797"] .... up to all 24 datasets. This is what I was trying to replicate in the toycode variable above.   2. My desire is to programmatically load each of these mmsignal["GSM356796"] etc symbols with specific data from each experiment. Each of the mmsignal[ .... ] symbols needs to receive a subset of data from a master list containing all 24 experiments worth of data, where each experiment is a sublist within the master list. This is what I was trying to replicate in the toydata variable above, where in the toydata varaiable I have 3 experiments worth of data entered as sublists.   3. The coordinates used to extract information from the masterlist (or toydata above) are contained within a list of indices that will be the same for each experiment. In other words, the same indices are used to extract data from the same position in 24 different experiments. So, in my toy code above, the output provided by my toy code, is actually what I want, and perhaps sloppily, does programmatically load specific information into the hyp["chip"] symbols.   4. Unfortunately, my real-world problem also has the Set::shape error which I can't seem to replicate in my toycode.


Effects of single-point and multi-point calls of Point on plot range

Several Graphics primitives are listable. For instance, `Point` accepts lists of coordinates so that multiple calls to `Point` are often unnecessary. The results are the same, except for one thing I noticed while working on the eye fixation question, yesterday.               pts = RandomReal[10, {30, 2}];       pl1 = Graphics[Point@pts];    (* single Point function call    *)     pl2 = Graphics[Point /@ pts]; (* multiple Point function calls *)          GraphicsRow[{pl1, pl2}, Frame -> All]      ![Mathematica graphics](http://i.stack.imgur.com/wl3At.png) The difference lies in the effect on `PlotRange`. Whereas a list of `Point`s yields a `PlotRange` of:               AbsoluteOptions[pl2, PlotRange]          (*     ==> {PlotRange -> {{0.493385472, 9.588596333}, {0.2849334536, 9.012342799}}}     *)      using the multi-`Point` syntax gives:               AbsoluteOptions[pl1, PlotRange]          (*     ==> {PlotRange -> {{0., 1.}, {0., 1.}}}     *)      The Get Coordinates tool gets the same coordinates in both figures. The question is: is there any good reason for the `PlotRange` reported in `pl1` or is this a bug?


Open Excel file with Mathematica

I would like to open an Excel file and manipulate it as a COM object. While I'm able to open an instance of excel with               Needs["NETLink`"]     InstallNET[]     excel = CreateCOMObject["Excel.Application"]      This doesn't work for me:                wb = excel@Workbooks@Open["D:\\prices.csv"]      Producing these errors:               NET::netexcptn: A .NET exception occurred: System.Runtime.InteropServices.COMException (0x80028018): Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))        at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad). Is this a known problem? I would very much appreciate any ideas on how to open an excel file with Mathematica as a COM object.


Find the parameter values satisfying conditions for all roots of an equation

Hi I'm very new at Mathematica. My real problems concerns a much more difficult equation with many parameters, but I want to check that the method is good, so I made up a test equation. My test equation and roots:               equ = (5 x^3 + z + x z + x^2 (1 + z) == 0)       sol = x /. Solve[equ, x]      Here is problem. I'm looking to the parameter `z` such that all the roots of the equation are less than zero (edit: real parts less than 0, where, `z` is a real number and the roots can be complex:               Reduce[Re[sol[[1]]] < 0 && Re[sol[[2]]] < 0 && Re[sol[[3]]] < 0 && Im[z] == 0, z]      The answer is (I think) `z > 4`, but the function `Reduce` doesn't calculate this in a reasonable time. How do I proceed? * * * EDIT after few days: In equation with more parameters:               equ=-11.8193 + 12.0482 b - 59.0964 x + 12.0482 a x - 11.8193 d x + 12.0482 b d x + 0.320482 x^2 + 12.0482 c x^2 - 59.0964 d x^2 + 12.0482 a d x^2 + 1. x^3 + 0.320482 d x^3 + 1. d x^4      Reduce[ForAll[x, equ == 0 \[And] Element[{a, b, c, d}, Reals], Re[x] < 0], {a, b, c, d}]      It is good code? I waiting and waiting for a response from the Mathematica. Maybe it would be faster if the program could write only one/few numerical answer?


How to REALLY Hold arguments and capture FullForm?

I'm trying to write an expression deconstructor or `FullForm`-capturer; might even call it a parser, maybe, but that might be too glorious a word. I got some great ideas from "Head and everything but...", but have plunged headlong back into the fog of my own limited understanding again, which got even foggier when I tried to understand "...function arguments on a stack...". I'd be most grateful for ideas, advice, and more clarity. Consider this example: `a + b + c`. We know its `FullForm` is `Plus[a, b, c]`, and I can "capture" that `FullForm` in a `List` with something like               Cases[{a + b + c}, head_[args___] -> {head, args}]      which produces               {{Plus, a, b, c}}      Now I go get myself all drunk on recursion and think I can write               SetAttributes[capture, HoldAllComplete];     capture[expr_?AtomQ] := {Head@expr, expr};     capture[head_[args___]] := {head, capture /@ {args}};      so that something like `capture[a + b + c]` gives me fantastic detail               {Plus, {{Symbol, a}, {Symbol, b}, {Symbol, c}}}      or, in stunningly beautiful `TraditionalForm` $\left\\{\text{Plus},\left( \begin{array}{cc} \text{Symbol} & a \\\ \text{Symbol} & b \\\ \text{Symbol} & c \\\ \end{array} \right)\right\\}$ All is well till I try               capture[1 + 2 + 3] ~~> {Integer, 6}      OH NO, it's not Holding inside! What I want, of course, is $\left\\{\text{Plus},\left( \begin{array}{cc} \text{Integer} & 1 \\\ \text{Integer} & 2 \\\ \text{Integer} & 3 \\\ \end{array} \right)\right\\}$ My problem is revealed by `traceView2`, which I got from "... clearest way to represent ..." ![Trace of offending call](http://i.stack.imgur.com/bGgQv.png) We see that `1 + 2 + 3` arrives held to `AtomQ`, as expected, but greedy old evaluator grabs it right there and smooshes it into 6. Everywhere else in the trace, the same thing happens. I don't know an easy way to stop the evaluator inside my `capture` faction. It has occurred to me to copy and adapt the code of `traceView2` to my application, since it exploits `Trace` to get ahead of the evaluator, and I will proceed that way unless I receive a cool answer here. In my dreams I imagine something like               SetAttributes[capture, DudeReallyHoldAllCompleteEverywhere];      or               SetAttributes[capture, HoldAllComplete, Levels -> Infinity];


Creating ghost trail effects

Does anyone know how to create a ghost trail effect? For a simple example look at this screenshot: ![Ghosting Effect](http://i.stack.imgur.com/6QriY.png) You can find the actual animation here. What I would ultimately like to see it happen is to make the object move based on whatever equations you specify it. For instance, to make it move around a circle the object should have the position `(cos[t], sin[t])`. Or, lets say you have a list of specified coordinates `{(x1,y1), (x2,y2), ..., (xn,yn)}`, All I want to be able to see is the trace as an object takes in the coordinates I specify. Here is a simple ball moving without the ghosting effect.               Animate[      Graphics[       Disk[{Cos[u], Sin[u]}, .25],       PlotRange -> {{-2, 2}, {-2, 2}},       ImageSize -> 400,        Axes -> True      ],      {u, 0, 6}     ]      ![enter image description here](http://i.stack.imgur.com/qp8ew.gif)


Plotting spherical surfaces

I am trying to make surface plots of squashed spheres. The spheres are defined by a list of points. For simplicity, consider the round sphere:               pts = Flatten[        Table[{Sin[θ] Cos[ϕ], Sin[θ] Sin[ϕ],           Cos[θ]}, {θ, 0, π, π/14}, {ϕ, 0,           2 π, 2 π/14}], 1];      One way to plot this is               ListPlot3D[pts,-pts,BoundaryStyle -> None,ColorFunction -> "Rainbow",InterpolationOrder      -> 2]      `ListPlot3D` has the nice feature that it interpolates the data to make a smooth surface. However, the northern and southern hemispheres are shaded differently, so there is a clear break at the equator: ![enter image description here](http://i.stack.imgur.com/A7jdx.png) An alternative is to do               ListSurfacePlot3D[pts]      Now the shading is uniform (there is no break at the equator). However, the data is no longer interpolated (and interpolation is not an option for `ListSurfacePlot3D`), so the surface looks rough and lumpy: ![enter image description here](http://i.stack.imgur.com/xkfXr.png) I am trying to find a solution that combines the best of both world: the smooth surface of `ListPlot3D` with the uniform shading of `ListSurfacePlot3D`.   Any suggestions? Thanks!


How to find all vertices reachable from a start vertex following directed edges?

How to find all vertices reachable from a given start vertex following directed edges, in a cyclic directed graph given as               Graph[{v1, v2, ...},            {v1 -> v11, v1 -> v12, ..., v2 -> v21, v2 -> v21, ..., vn -> vn1, vn -> vn2, ...}]      where all the ending vertices of edges `vij` are in the list of vertices `{v1, v2, ...}`. ?


How do I produce iterative equations and bifurcation diagrams?

I need to produce orbit diagrams for different values of x for the following equation:               f[r_][x_]:= r*x - x^3      I'm fairly new to _Mathematica_ , so I haven't had a lot of practice using it. Basically I need to produce bifurcation diagrams for different values of `x`; then, using these plots, identify `r` values at which bifurcation occurs and determine the convergence ratio. Any help would be much appreciated.


Compose one image over another

I'm a newbie in image processing using Mathematica. I'd like to compose an image $A$ over an image $B$ into an image _C_ such that $\quad C[i,j] = B[i,j]$, if $A[i,j]$ is white $\quad C[i,j] = A[i,j]$, otherwise It would work if I could do `Min` on each pixel: $\quad C[i,j] = \min(A[i,j],B[i,j])$ but `Min` does not seem to work component-wise. Perhaps I could turn white in $A$ into transparency and then compose over $B$. How can I do this?


Mean path length of randomly generated graphs

I am looking to find the the average path length of 1000 random graphs with the following degree distribution, a few of the vertex degrees are included below               {2, 12, 5, 1, 12, 3, 6, 4, 2, 6, 3, 4, 4, 1, 2, 4, 4, 1, 4, 4, 7, 9}      Now, I have done this with finding the mean global clustering coefficient in a very straightforward way:               Mean[GlobalClusteringCoefficient /@         RandomGraph[         DegreeGraphDistribution[           {2, 12, 5, 1, 12, 3, 6, 4, 2, 6, 3, 4, 4, 1, 2, 4, 4, 1, 4, 4, 7, 9}],          10000]]      This did the job quite well for `GlobalClusteringCoefficient`, but is there a way to do this to get the average path length of all 10000 random graphs? My intuition was using `GraphDistance`, but it only works as a per vertex basis -- for it to work, it needs a complete graph or else it calculates the distance as infinity.


Problem with numerical integration

I am not very used to do numerical simulations on Mathematica. I have a problem with numerical integration of this function. Is there any way for this calculation? Input:               α := 0.07          A := Sin[θ]*Sin[θ2]*Cos[φ - φ2] + Cos[θ]*Cos[θ2]     B := Sin[θ]*Sin[θ3]*Cos[φ - φ3] + Cos[θ]*Cos[θ3]     V := Sin[θ2]*Sin[θ3]*Cos[φ2 - φ3] + Cos[θ2]*Cos[θ3]          c2 := (B*c*c3 - c3*c3)/(A*c - c3*V)          integrand :=       1/2 1/((-1 + E^(c^2 - α)) (-1 + E^(c2^2 - α)) Abs[A c - c3 V])       c^4 c2^2 c3^2 (1 + 1/(-1 + E^(c^2 - α))) (1 + 1/(-1 + E^(c3^2 - α)))      (1 + 1/(-1 + E^(c^2 + 2 A c c2 + c2^2 - B c c3 + c3^2 - 2 c2 c3 V - α)))       (1 + 3 Cos[2 θ]) (c Cos[θ] - c3 Cos[θ3])      (c2 Cos[θ2] - c3 Cos[θ3]) Sin[θ] Sin[θ2] Sin[θ3]          NIntegrate[integrand,          {c3, 0, ∞}, {θ3, 0, π}, {θ2, 0, π},          {φ3, 0, 2 π}, {φ2, 0, 2 π}, {c, 0, ∞}, {θ, 0, π}, {φ, 0, 2 π},          Method -> "MultiDimensional"]      Output:                   NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the      following: singularity, value of the integration is 0, highly oscillatory integrand, or      WorkingPrecision too small. >>              NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more      than 2000 times. The global error is expected to decrease monotonically after a number of      integrand evaluations. Suspect one of the following: the working precision is insufficient      for the specified precision goal; the integrand is highly oscillatory or it is not a      (piecewise) smooth function; or the true value of the integral is 0. Increasing the value of      the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical      integration. NIntegrate obtained -27257.8 and 652260.228217954` for the integral and error      estimates. >>      I am using Mathematica 8.0


Is it possible to suppress 'Out[xxx]=' without suppressing 'In[xxx]:='?

While I have not exhaustively searched `Help/Documentation Center` for an answer to my question, I have put forth a yeoman's effort without any success. Does anyone know if it is possible to suppress `Out=` on an on-going basis within a notebook without also suppressing `In:=` and if it is, could you please tell me how? Thanks!


Add one to a major diagonal of a matrix given a coordinate point

n = 10;          board = ConstantArray[0, {n, n}];          diag1[x0_, y0_] :=      Module[{x = x0, y = y0},       While[{x != 1 || y != 1},        x--;        y--        ];       While[{x != n + 1 || y != n + 1},        board[[x, y]]++;        x++;        y++        ]       ]      I have an n by n matrix of all zeroes. On a given coordinate in the matrix, I need to increase everything in its major diagonal by one. A runchart of this works fine. All that this does, is increase the (x-1,y-1) by one. I believe that the while loops are only executing the statements once, but I can't be sure.


CDF file posted in WordPress won't run

I just installed Mathematica 8.0.4.0, which has a CDF Deployment Wizard. This is supposed to make it easy to post a CDF file on a WordPress blog. I tried it, and it indeed was easy; the problem is that when I Previewed the post, the CDF logo showed up and created a rectangle that quickly turned solid gray. This is the entire code I used in my blog:

The example

      The two scripts were created by the Wizard and pasted into the post. You can download the file Elaborate Riemann Example.cdf yourself from the URL above, and, if you have CDF Player on your computer, you can run it. It works fine on my computer. But it won't appear within the post. Any ideas why?


Rearranging a biclustered matrix

I currently have a $77\times 38$ matrix, and I have used a clustering algorithm to cluster the row data and column data. The rows and columns of my matrix correspond to a list of country codes (not in numerical order). That is, I have a list of numbers:               {10, 28, 34, 44, ...}      where country 10 corresponds to row 1, country 28 to row 2, etc. I have a corresponding list for the columns of my matrix. I have independently clustered the columns and rows into groups of 3. For example, the row clusters look like so:               {{10, 1, 4, 2, ...,37 }, {28, 34, 27, 21, ..., 18}, {38, 20, ..., 12}}      Again, I have another clustering for the columns. I want to rearrange the rows and columns of my matrix such that the clustered rows and columns are next to one another. Using my example row cluster list, I want to rearrange the matrix such that row 1 corresponds to country 10, row 2 to country 1, row 3 to country 4, etc. After this, I wish to do the same with the columns of my matrix. Any help is appreciated. Edit: Haha, I apologize. I have a bad habit of haphazardly posting questions before going to sleep, hoping that my problems will all be solved in the morning. I have class now, but I'll probably update this later (+ examine all of the information already posted).


Applying l'Hôpital's Rule to NDSolve with Piecewise Function

OK, so I've been working on this problem for over a week and it's driving me crazy. I'm trying to solve a system of two differential equations in $x(t)$ and $y(t)$ using a "time-elimination method," such that $\tfrac{d x}{d t}/\tfrac{d y}{d t}=\tfrac{dx}{dy}$ reduces the system to a single differential equation in $x(y)$. The tricky part is that the initial condition needs to be defined at the steady state of the system $\\{x_{ss},y_{ss}\\}$, where $x'(t)=y'(t)=0$. The slope at this point is undefined since $dx/dy=0/0$ as $y\to y_{ss}$ by construction. I've seen two common ways of dealing with this. The first involves finding a kind of approximation to the solution by slightly perturbing the correct initial condition so that $x'(y)$ is always well defined. For example, suppose the system is defined as:               y0 = 1; yss = 10;     xdot = 2*x[t]-y[t];     ydot = (.01 + .1*x[t])*(Log[yss/y[t]]);      We can find a solution using:               xdoty[y_] = (xdot/ydot) /. {x[t] -> x[y], y[t] -> y};     NDSolve[{x'[y] == xdoty[y], x[yss - .001] == xss}, x, {y, y0, yss - .001}];      which yields the following results for $x(t)$ (purple) and $y(t)$ (blue): ![diffeqns_example1.png](http://i.stack.imgur.com/Kmclb.png) Notice that the solution for $y(t)$ "blows up" as it comes within .001 of $y_{ss}$. The second, more accurate approach is to overcome the ill-defined slope at the steady state via an application of l'Hôpital's rule. In _Mathematica_ , I usually deal with this by passing a `Piecewise` function to `NDSolve`, e.g.:               NDSolve[{x'[y]==Piecewise[{{xdoty[y],y<yss},{xdotyss,y==yss}}],x[yss]==xss},x,{y,y0,yss}]      where `xdotyss` is $x'(y_{ss})$ (a single scalar value) calculated after the application of l'Hôpital's rule. This yields the following results for the system: ![diffeqns_example2](http://i.stack.imgur.com/MBSmj.png) where both $x(t)$ and $y(t)$ are well-behaved throughout. The problem I am having is that this approach does not always seem to work well. Particularly, for some differential systems I can get the first "perturbation" method to give me approximately correct looking results, but the second "l'Hôpital method" always gives me the following error: > NDSolve::ndsz: At y == yss, step size is effectively zero; singularity or > stiff system suspected. Given that the first approach causes no errors, and the second approach is using the same differential equations to derive the value of the slope at that single point, shouldn't this always be a viable approach? I can't think of what would be causing the system to suddenly become "stiff." Any ideas?


How do I get VertexList to work directly on older graphs defined using rules?

In MMA 8, it seems that sometimes `VertexList` will work with rule-based graphs without needing GraphUtilities and at other times it won't. Once it starts working, it keeps working until I restart MMA. In addition, while it is working, `VertexList` is not colored Red to indicate shadowing. I know that I can use `GraphUtilities`VertexList` as shown below, but that is a bit much to type and I really want to understand why it is sometimes unnecessary. I also have dozens of notebooks with VertexList and don't really want to need to change all of them. Here is what happens:               In[1]:= VertexList[{a -> b}]     During evaluation of In[1]:= VertexList::graph: A graph object is expected at position 1 in VertexList[{a->b}]. >>         Out[1]= VertexList[{a -> b}]              In[2]:= GraphUtilities`VertexList[{a -> b}]         Out[2]= GraphUtilities`VertexList[{a -> b}]              In[3]:= Needs["GraphUtilities`"]         In[4]:= VertexList[{a -> b}]         Out[4]= {a, b}              In[5]:= $ContextPath = Rest[$ContextPath]         Out[5]= {"PacletManager`", "WebServices`", "System`", "Global`"}              In[10]:= VertexList[{a -> b}]         During evaluation of In[10]:= VertexList::graph: A graph object is expected at position 1 in VertexList[{a->b}]. >>         Out[10]= VertexList[{a -> b}]              In[7]:= GraphUtilities`VertexList[{a -> b}]         Out[7]= {a, b}      Is there any consistent way to force MMA to get VertexList to work on older style graphs without needing to use the full name? One more detail. When this works, I get exactly this behavior:               ?VertexList          VertexList[g] gives the list of vertices for the graph g.     VertexList[g,patt] gives a list of vertices that match the pattern patt. >>      which makes it look like the symbol is coming from System`


Importing High Precision (22 digits) data from a file

I want to import list from a file and I am using `ReadList` but my data is in format like this 8.2457409790900004e+08 but it i being imported like $8.24574*10^8$. Is there a way to increase the precision of import? Or even better, is there a way to change the notebook's precision globally ?


Meshing the surface of a non-convex object

I would like to mesh the surface of a cloud of points that may not be completely convex, for example the points in this question. Mathematica does not provide triangulation of 3D points, but there is a link to TetGen                Needs["TetGenLink`"]           {mypts, mysurface} = TetGenConvexHull[dat];      Graphics3D[GraphicsComplex[mypts, Polygon[mysurface]], Boxed -> False]      which results in this ![enter image description here](http://i.stack.imgur.com/I5TH5.jpg) Notice it doesn't get the surface meshing associated with subtle twist in the curved shape, and meshes points further away in the goal of creating a convex object. I suppose one could try to mesh the surface piece by piece and slowly merge it as in this answer, but that sounds like a nightmare. Here is the cloud of points for reference: ![enter image description here](http://i.stack.imgur.com/O0nL3.jpg)


Importing FITS file from HEALPix

I am trying to read FITS file created by HEALPix software. The file contains a spherical map of a scalar field. There is the online support on how to use the file in IDL, but not for Mathematica. I understand FITS is partly binary format, but I expect it is still standardised and contains readable description on how the data is stored. I tried reading Elements from the file in this way               Import["test.fits", #] & /@        Import["test.fits", "Elements"]      but the output is quite short and mainly empty lists, especially for               Import["test.fits", "Data"]     Import["test.fits", "TableData"]      The size of my file is 12.6 MB. Here is a link to the file. Is there another way to read the content of FITS file, besides these general 'Elements'? Do I need to know something about the structure of my FITS file in order to be able to read it with Mathematica? Could it be the problem is that Mathematica does not read all types of FITS files?


Dynamically show a specific number of the fractional part's digits

What is the fastest way to cut off all `n z` digits of the fractional part of a real number? (For example 12390.20934230) I came up with this so far:               Round[l_List, z_] :=       IntegerPart[l] +         Module[{r = RealDigits[l]},          Fold[10 #1 + #2 &, 0, Take[r[[1]], {Max[r[[2]],0]+z, r[[2]]+z}]] 10^-z]      Best would be a fast pure function to run over an array, and optimal would be to just show the output rounded (aka ScientificForm), but let the actual numbers as they are.


How can I change the scoping of a pure function returned by a function in a package?

I have written a small Mathematica package that contains a module that solves some differential equation with initial conditions. Suppose that the solution to this differential equation defines some other functions _y(t)_ and _z(t)_. I want this function to return these functions _y_ and _z_ as rules, much as NDSolve returns a rule for evaluating a function. Here is my first naive attempt to do this:               SolveEquation[x_, xp0_, x0_] := Module[{y, z},       sol = Flatten[         NDSolve[{x''[t] + x'[t]^3 == x[t]^2, x'[0] == xp0,            x[0] == x0}, {x}, {t, 0, 100}]];       y[t_] := (x[t] /. sol)^1/2;       z[t_] := y'[t] /. y[t];       Return[Join[sol, {Symbol["y"] -> Function[t, y[t]],Symbol["z"] -> Function[t, z[t]]}]]]      ` I can then correctly access the values of these functions with               rules=SolveEquation[x,0,100];     y[3]/.rules     9.89546      ` However, a call to _rules_ itself gives me:               {x -> InterpolatingFunction[{{0.,100.}},<>],y -> Function[t$, y$5338[t$]],       z -> Function[t$, z$5338[t$]]}      ` This is okay but in terms of human readability (the code will be used by individuals besides myself), I would much prefer:               {x -> InterpolatingFunction[{{0.,100.}},<>],y -> Function[t, y[t]],       z -> Function[t,z[t]}      ` or even better:               {x -> InterpolatingFunction[{{0.,100.}},<>],y -> x[t]^1/2,       z -> y'[t]/y[t]}      ` or some other way in which the dependence of each function on the others is made explicit. Is it possible to achieve this result by somehow changing the scoping of these variables or do I need to just settle for my method that works but appears sloppy?


Send HTML tables with SendMail

I'm trying to send some HTML table using _Mathematica_ `SendMail` function. To do it I wrote this function:               createHTMLTable[list_List] /; Length[Dimensions@list] == 2 :=       Module[{r, head, data}, head = First@list;       data = Rest@list;       head = Map["   " <> ToString[#] <> "	\n" &, {head}, {2}];       data = Map["   " <> ToString[#] <> "	\n" &, data, {2}];       headData = Join[{head}, data];       r = "
\n" <> StringJoin[##] <> "
\n" & /@ headData // StringJoin;       r = "<!DOCTYPE html>
                         " <> r <> "
                                  "       ]      When I send the mail, as in this example:               list = RandomInteger[100000, {10, 3}]          SendMail["From" -> "test@test.com", "To" -> "test@test.com",       "Subject" -> "Sending Email from Mathematica", "Body" -> createHTMLTable[list],       "Server" -> "XXXXX"]      there is no table in the mail, but only the HTML text. Anyone knows how to correct this? Is there another way to do it?


How can I access a variable in one evaluator from another evaluator?

I have two notebooks, each with a different kernel. Is there a way to grab the value of a variable in KernelA from KernelB?


Building Reusable Custom Controls?

I would like to build an application using Mathematica 10. I would very much like to structure the application for maximum maintainability. To this end I would like to segregate controls and user interfaces to one set of source code files and calculations to another set of files. The basic idea being that the calculations are UI agnostic. They receive data and return the results of calculations and know nothing of UI code. The he same calculation .m files may be used from multiple user-interfaces (CDF, Web, Unit Test,.net, etc.). Scope is important. I would like to minimize the risk of changing a variable in a calculation that unintentionally sets a variable value in UI or if I call a function that wraps a custom control, I want to keep all Manipulate variables local to the Manipulate or function that wraps the Manipulate. I have tried using DynamicModule and LocalizeVariables->True but find that variables used by Manipulate are completely visible and settable in the notebook calling my DynamicModule where my control is defined. (I may be working with a set of assumptions and definitions of scope from application development languages that are not the same in Mathematica...) Ideally I would like the ability to decide which variables are global and which variables are local to the manipulate. I would like to build a set of re-usable custom controls in Mathematica 10 with the following criteria:   1. Would like to wrap my control(s) in a function or module in a .m or .wl file under specific contexts.   2. Variables are local to Manipulate and not visible or settable from the calling notebook.   3. Would like to package user settings and return them from the module that wraps Manipulate. Something along these lines: mySettings = MyControl[] Where MyControl[] encapsulates the manipulate and returns a dataset or array of settings selected by the user. I would also like the Manipulate variables to be local to MyControl[] and not visible or settable in the calling code or notebook. Again, I'm probably working under scope definitions of local and global used in application development languages. Below is an example:               EKSWaveFormControl[] :=          DynamicModule[                 {treatmentSpecRow},                 Manipulate[                     Plot[ ctrlVdc + ctrlVac  ctrlgFunc[ 2 \[Pi] ctrlf t + ctrlPhi],{t,0, 0.4}],                         {{ctrlgFunc,Sin,""},{Sin,Cos, Tan, Cot }},                         Delimiter,                         {{ctrlVac,1.5,Subscript["V","ac"]}, -10,10},                         {{ctrlVdc, 0.5, Subscript["V","dc"]}, -1,1},                         Delimiter,                         {{ctrlf, 10, "Frequency"}, 0.001,100},                         {{ctrlPhi, 0, "\[Phi]"}, 0, 2 \[Pi]},                         Delimiter,                         Button[                             "Update",                              treatmentSpecRow = Dataset[ Association @ { Func -> ctrlgFunc,                                                                        Vac -> ctrlVac,                                                                       Vdc -> ctrlVdc,                                                                       \[Phi] -> ctrlPhi,                                                                       \[Omega] -> 2 \[Pi] ctrlf }]],                         ControlPlacement->Left, Paneled->True, LocalizeVariables->True]             ]      When a user clicks the "Update" button, I would like to return a Dataset or array of the settings. But otherwise keep all variables used by Manipulate local to the Module.


Selecting morphological components, of a certain size, centered on points of interest in an image

I have a set of points in an image, for example:               POI = {{32.5, 257.5}, {73., 250.5}, {55.5, 248.5}, {209., 246.5}, {186.5, 245.5}, {154.5, 241.}, {213.5, 235.5}, {169.5, 233.5}, {212.5, 233.5}, {104., 231.5}, {18., 229.5}, {93., 228.5}, {203.5, 227.5}, {109.5, 224.5}, {138., 223.5}, {222., 222.}, {208.5, 218.5}, {0.5, 210.5}, {65.5, 209.5}, {98.5, 208.5}, {7.16667, 205.167}, {30.5, 205.5}, {257., 205.5}, {88., 203.}, {210., 202.5}, {246.5, 203.5}, {257.5, 199.}, {40.5, 198.5}, {217.5, 198.5}, {193.5, 197.5}, {0.5, 195.5}, {44.5, 192.5}, {159.5, 188.}, {120.75, 185.}, {39.8333, 183.833}, {207., 184.}, {239., 184.5}, {178.5, 183.5}, {52.5, 182.5}, {19.3, 178.9}, {155.5, 180.5}, {167.5, 179.5}, {19.5, 174.5}, {89.5, 174.}, {206.5, 173.5}, {44., 169.5}, {32.5, 169.}, {130.5, 168.5}, {106.833, 166.833}, {202.9, 165.7}, {215.167, 164.833}, {231.5, 165.5}, {46.5, 164.5}, {242.5, 164.5}, {200.5, 160.5}, {255., 155.5}, {108.5, 154.5}, {197.167, 154.167}, {192., 153.}, {10.5, 151.5}, {32.5, 149.5}, {111.3, 146.3}, {136.5, 147.5}, {187.5, 147.5}, {257.5, 146.5}, {63.1667, 146.167}, {122.5, 144.}, {135.5, 144.5}, {177., 144.}, {218.5, 144.5}, {26.1667, 143.167}, {211.5, 141.5}, {188.5, 140.5}, {106.833, 137.833}, {0.5, 136.5}, {29., 136.}, {98.5, 135.5}, {185.5, 134.5}, {145.5, 133.5}, {113.5, 131.5}, {219., 130.5}, {70., 129.5}, {11.1667, 128.167}, {183.5, 128.5}, {63.5, 125.5}, {60.5, 124.}, {85.5, 124.5}, {67.5, 122.5}, {43.5, 121.}, {182.5, 121.5}, {155.5, 119.5}, {252.5, 119.5}, {124., 118.5}, {97.5, 117.5}, {45., 115.5}, {104.167, 114.833}, {69.5, 112.}, {40.5, 111.5}, {117.5, 111.}, {1., 110.}, {34.5, 109.5}, {189.5, 109.5}, {32.1667, 107.833}, {100.5, 106.5}, {45.5, 105.5}, {106.5, 104.5}, {205.5, 104.}, {167.5, 103.}, {173.5, 103.5}, {185.5, 102.5}, {123.5, 95.5}, {181.5, 95.}, {45.5, 94.5}, {26.5, 87.5}, {74.5, 86.5}, {179., 86.5}, {93.5, 83.}, {188.5, 83.5}, {13.5, 80.5}, {75.5, 79.5}, {41.5, 78.5}, {162.5, 78.5}, {9.83333, 76.1667}, {179.5, 76.5}, {151.5, 74.5}, {182., 72.5}, {141.167, 67.1667}, {235.5, 66.5}, {156., 64.5}, {167.5, 64.5}, {212.5, 64.5}, {199.833, 60.8333}, {157.5, 60.}, {121.5, 54.}, {198.5, 54.5}, {83.5, 48.5}, {179.5, 46.5}, {228.5, 46.5}, {127., 44.5}, {204.5, 44.5}, {35.5, 42.5}, {79.5, 41.5}, {66.5, 40.5}, {80.8333, 38.8333}, {190.5, 38.5}, {51., 36.5}, {243.5, 31.5}, {93., 29.5}, {232.5, 29.5}, {232.5, 22.5}, {35.5, 20.5}, {121.5, 20.5}, {159., 17.5}, {219.5, 14.5}, {253.5, 13.}, {214.5, 11.5}, {77.5, 9.5}, {7.,8.5}, {168., 8.5}, {219.833, 6.83333}, {83.8333, 4.83333}, {22.5, 3.}, {140.5, 0.5}, {227.5, 0.5}, {253.5, 0.5}};      I would like to generate rectangular morphological components (compatible with ComponentMeasurements) of a certain size that are centered on each of these points. Specifically, I would like the components to have a side length of $l$ pixels, and where each point in the morphological component is at most a fixed Manhattan distance $d_{max}$ away from its centerpoint. How might I do this, perhaps using Dilate? And is it possible to have overlapping morphological components? Update : Answer to the last point on whether components can overlap: No (see comment by belisarius below). Update 2 : The command:               Dilation[Components, r]      Will take a single pixel, and blow it up it up into a square block with $r$ pixels on either side of the centerpoint. If there were some manner of generating a single-pixel component at each of my POI positions, I believe that would solve my problem. Is there an easy manner of doing this?


How can I remove orange-box around the Graphics3D?

I don't know whether this is a correct question or not, but I played from two days on this problem and still I didn't find a solution. ![Mathematica graphics](http://i.stack.imgur.com/zKNjo.png) The save button is enabled whenever we have to specify width,length,height and middleheight of a `Graphics3D`. `Graphics3D` appears whenever we have clicked on the save button depending upon width, length, height and middleHeight values. This is my application concept. For this purpose I wrote a huge amount of code, but I show here only a little bit of the code related to `Graphics3D` and also the sizes of the `Buttons`,`InputFields`and the application-window Size.               Dynamic[Pane[                  Manipulate[designSpace, Paneled -> False,AppearanceElements -> None                            ](*Manipulate is closed here*),              Scrollbars -> {Automatic, Automatic},AppearanceElements -> None, ImageSize -> {560, 310},Alignment -> {Center, Center}                 ](*Pane is closed here*)            ](*Dynamic is closed here*)      Note:In the code designSpace is `Graphics3D` related code. The application window size is {580,480}, `Buttons`,`InputFields` sizes {160,60}, pane size {560,310}. Concept-wise it is working fine but the problem is:   1. `InputFields` and `Buttons` are blinking at the `Graphics3D` rotation time.   2. Some orange box appears around the `InputFields`,`Buttons`and `Graphics3D` whenever we have to double click on the application.   3. If we have clicked on any wall of `Graphics3D`.`createDialog` will appear in that we have to specify the positions, some `Image` overlap on that wall depending upon that specification. The third point concept is not working. This overlaps with the concepts that I already asked about in my earlier posts, but I still don't get it.


Exclude Sections/Subsections/... from evaluation

I'm working on a large notebook and I want to exclude some sections and subsections from being evaluated when I evaluate the whole notebook. Is there a way to exclude specific sections or subsections from the notebook evaluation while maintaining their original format? Or even better, format them e.g. by adding a gray background?


"Unflattening" a list

Imagine we have a list with some hierarchical structure:               list = {{{2,3},{2,4}},{{{3,4}}},{{5,6},{7,8}}};      Which we then flatten to some level in order to process the data points:               Flatten[list,1]     >> {{2, 3}, {2, 4}, {3, 4}, {5, 6}, {7, 8}}      We then do "something" to change the value of the elements in the list, without increasing or decreasing the number of elements:               >> {{5*10^9, 3}, {2, 4}, {3, 4}, {191991, 6}, {7, 8}}      Can we reverse the flattening procedure to go back to a list of the form:               >> {{{5*10^9,3},{2,4}},{{{3,4}}},{{191991,6},{7,8}}};


Creating legends for plots with multiple lines?

So I have a graph with multiple lists, for e.g.               data = {{1,2}, {3,4}, {3,5}, {2,3} . . .}      If I then do `ListLinePlot[Table[{#1,Log[b,#2]}&@@@data, {b,1,10,2}]]` I have no way to generate a legend for it, that I see anyway. I cannot put anything inside the `Table` which contains the iterator. Would I do something alone the lines of `Legend-> Log[Range[1,10,2,x]]`?


Show Legend with 3D ListPlot

> **Possible Duplicate:**   >  Creating legends for plots with multiple lines? I am trying to plot the color bar that shows the data range for the data plotted by `ListPlot3D`. I want to ask if I can use the `ShowLegend` command with the `LisPlot3D`? My code is as the following :               Needs["PlotLegends`"];     s = Import["C10002.xls"]     Rotate[ListPlot3D[s, PlotRange -> {0.048, 0.22}, Mesh -> None,        AxesLabel ->        Style[StandardForm[\[Phi]], FontSize -> 20, FontWeight -> "Bold"]],       30 Degree, {0, 1, 0}]          ShowLegend[       ListPlot3D[s, PlotRange -> {0.048, 0.22}, Mesh -> None,        AxesLabel ->        Style[StandardForm[\[Phi]], FontSize -> 20, FontWeight -> "Bold"]],       LegendPosition -> {1.1, -.4}]      I will be very thankful for your help.


Make PlotMarker explanation

> **Possible Duplicate:**   >  Creating legends for plots with multiple lines? I have a ListPlot of data points. To distinguish between datapoints coming from different sources, I give them different PlotMarkers, say green triangles for one, and red circles for another. An example could be:               Jones2012 = {{3, 2.5}, {2, 4}};     Adams1999 = {{1, 2}, {4, 4}};     ListPlot[{Jones2012, Adams1999}, Frame -> True,       PlotMarkers -> {{\[FilledCircle], 20}, {\[FilledUpTriangle], 20}},       PlotStyle -> {Red, Darker[Green]},       PlotRange -> {{0, 5}, {0, 5}}]      Now I want to have a small box in the upper right corner explaining what data the different markers correspond to, e.g. Jones 2012 is marked with red circles. I am thinking that the best way to do it would be to make a box as an object first, then insert this object in the graphics afterwards. My best try at making the box so far is:               triangle =       Graphics[{Thick, Darker[Green], Polygon[{{0, 0}, {1, 0}, {0.5, 1}}]},        ImageSize -> 10]     circle = Graphics[{Thick, Red, Disk[{0, 0}]}, ImageSize -> 10];     box = Framed@       Text[Style[triangle "Jones 2012" circle "Adams 1999", 12]]      or               box = Framed@       Text[Style[triangle "Jones 2012 \nAdams 1999" circle, 12]]      But what I would like to do is to have the symbols first on the line, followed by what it represents, then a new line with the next data set. So something like: "green triangle" Adams 1999 "red circle" Jones 2012 Preferably the symbols would be aligned, as well as the left edge of the text. I feel like I should be close, but can't seem to figure out that last little thing to get it how I want it. Thanks so much!


Extra lines in the legend of a ParametricPlot

> **Possible Duplicate:**   >  Creating legends for plots with multiple lines? Why does the legend of this plot have 5 lines (in mathematica 8, at least) instead of 3?               Needs["PlotLegends`"]     ParametricPlot[      Evaluate[Table[{k Cos[x], k*Sin[x]}, {k, 1, 3}]], {x, 0, 2 \[Pi]},       PlotStyle -> {Directive[Purple, Thick],         Directive[Thick, Orange, Dashing[{.03}]]},       PlotLegend -> Range[1, 3], LegendPosition -> {.5, -.8}]      ![Mathematica graphics](http://i.stack.imgur.com/mpywH.png) How could I plot the legend correctly? --EDIT-- This is not an answer, but it may come handy to someone with the same problem: Creating legends for plots with multiple lines? replacement of `PlotLegend` works.


Solving a differential equation with mixed conditions using DSolve

I want to solve a differential equation $$ \frac{d}{dx}\left(k_0 \left(\frac{T(x)}{T_0}\right)^n \frac{dT(x)}{dx}\right)=0,$$ with boundary conditions: $T(l)=T_0$, $\;T'(0)=-\frac{q_0}{k_0 T(0)^n}\;$ using `DSolve`, but I cannot get a solution. Can anyone help me?


Connect each point in the plot with all adjacent points

I have the following simple code. I need to connect each point in the plot with all adjacent points in vertical or horizontal line.               n = 5;     nodes = Flatten[        Table[{i (16 2.54)/n, j (16 2.54)/n}, {i, 0, n}, {j, 0, n}], 1];     dataPlot = ListPlot[nodes, PlotStyle -> PointSize -> Large];     nodelabels =        Table[Text[         Style[i + (n + 1) j + 1, 14, Bold], {0.7 + i (16 2.54)/n,           0.7 + j (16 2.54)/n}], {i, 0, n}, {j, 0, n}];     elementlabels =        Table[Text[         Style[i + (n) j + 1, 14,           Bold], {(16 2.54)/(2 n) + i (16 2.54)/n, (16 2.54)/(2 n) +            j (16 2.54)/n}], {i, 0, n - 1}, {j, 0, n - 1}];     Show[Graphics[{{Red, nodelabels}, {elementlabels}}], dataPlot,       AspectRatio -> 1, Axes -> True, ImageSize -> 600]      I have manually added some lines to show what I am looking for. ![enter image description here](http://i.stack.imgur.com/hRzvG.jpg) **note:** there is a way to do that using ListLinePlot but this method requires to overlay so many ListLinePlot. I would prefer to get solution using Vertex functions.


Export results to excel

I have the following problem solved in Mathematica               m=Table[For[i = 0, i <= .7, i = i + 0.1,        Print[NMinimize[{i*Abs[(E^-k*(N*p)^k)/k! - k^-g] +            i/3*Abs[p - N^-r] + (1 - (2*i)/3)*            Abs[Log[N]/Log[N*p] - (A*Log[N - B] + CC)], A != 0, B != 0,           CC != 0, N > 0, k > 1, N <= 1000, k <= 100, N - k >= 0,           N - B > 0, BB, g > 2, g < 3, r > 0, r < 1, N^-r < 1, k/N < 1,           p <= 1}, {A, B, CC, N, k, g, r, p},          Method -> "SimulatedAnnealing"]]], {j, 1}]      I want to turn it into a form which can be exportable to excel. I tried:               m//TableForm      but doesn't work. Can you please help me? Thank you in advance


Sorting list with variable

I want to sort (or sortby) the list. List contains uninitialized variable m and I can assume that `m` is a Natural number that is much larger then any constant. Example input:               a = {-116*m, 0, 3 - 11*m, 1 - m, -20*m - 7, -m}      Example output:               {-116*m, -20*m - 7, 3 - 11*m, -m, 1 - m, 0}      My effort:               MAGICNUMBER = 1000000;     Sort[a, (#1 /. m -> MAGICNUMBER) < (#2 /. m -> MAGICNUMBER) &]


Using 'Reduce' to solve a set of inequalities, specified by a list

I have a two lists $LHS$ and $RHS$, both of size $n$. I want to solve a system of inequalities of the form: $$LHS[1] \leq RHS[1]$$ $$LHS[2] \leq RHS[2]$$ $$LHS[3] \leq RHS[3]$$ $$\vdots$$ $$LHS[n] \leq RHS[n]$$ We assume that: Each $LHS[i]$ is a linear equation in $m$ variables, say: $\alpha_{1}, \dots, \alpha_{m}$ and each $RHS[i]$ is a linear equation in $m$ variables, say: $\beta_{1}, \dots, \beta_{m}$. We need to solve for $\alpha_{1}, \dots, \alpha_{m}$, $\beta_{1}, \dots, \beta_{m}$, which are positive integers. Take m=2. To solve a single inequality (for some $i$ between $1$ and $n$) I know that I need to enter: > Reduce[LHS[[i]]<=RHS[[i]],{[\alpha]0,[\alpha]1,[\beta]0,[\beta]1}] (I haven't put the constrains to make the code simpler) But, if I need to solve all the inequalities, **how do I input a list in 'Reduce'** ? Thanks a lot in advance.


ListPlot filling not appearing when point is out of range

In a non-joined `ListPlot` one can specify that a filling line is shown for each point:               ListPlot[Table[{x, Exp[-x^2]}, {x, -2, 2, 0.1}], Filling -> Axis, FillingStyle -> Red]      ![1](http://i.stack.imgur.com/eAUuX.png) But if the points are out of the plot range, the filling line no longer appears:               ListPlot[Table[{x, Exp[-x^2]}, {x, -2, 2, 0.1}], Filling -> Axis, FillingStyle -> Red,        PlotRange -> {0, 0.5}]      ![2](http://i.stack.imgur.com/I9vYi.png) Is there any way to still show the line up the plot range, to show that there is a point there (but you just can't see it)? Or must I draw the lines myself with a `Prolog`?


Is there a way to run Python from within Mathematica?

I know there is some support for running _Mathematica_ from Python, but is there any way to do the reverse. For example, to import some Python classes and use them in _Mathematica_?


Check if a (possibly nested) list is real

I have a very large matrix of numbers. I want to check if all its entries are real. At the moment I am using               realQ = And @@ Thread[Flatten[Im @ #] == 0] &      Is there any faster/safer/better way to do it?


Calculate one-tailed critical point from a probability distribution

I would like to calculate the numerical value of $\xi\in\mathbb{R}_{\geq0}$$$P(|U|<\xi)=0.95$$ where $U$ is standard-normal distributed. How may I do that in Mathematica?


up arrow works in math version 9, fails in math version 8 ^[[A

I have strange up-arrow behavior on command line Mathematica 8 versus Mathematica 9. Version 9 gives me history, where version 8 fails with escape codes. Any way to make them both work on the same system?               ubuntu@ip-10-45-11-134:~$ math     Mathematica 9.0 for Linux x86 (64-bit)     Copyright 1988-2013 Wolfram Research, Inc.          In[1]:= $KernelCount                                                                                Out[1]= 0         In[2]:= $KernelCount                                                                                Out[2]= 0     In[3]:= ubuntu@ip-10-45-11-134:~$ math8                                                                                Mathematica 8.0 for Linux x86 (64-bit)     Copyright 1988-2011 Wolfram Research, Inc.     In[1]:= $KernelCount         Out[1]= 0         In[2]:= ^[[A         In[2]:=          ubuntu@ip-10-45-11-134:~$


How can I truncate only a single vertex of a polygon?

One can truncate all the vertices of a polygon at once with `Truncate`. I want to do exactly that -- but only on a single vertex. Is this possible with _Mathematica_ 9? How?


Problem with loading my custom package

I've been having quite a bit of trouble loading a package I wrote. I've followed the suggestions on related questions on this site, as well as on _Mathematica_ 's own pages, and still nothing has worked. This is my package code:               BeginPackage["errorpropagation`"]     (* General error propagation formula *)          fError::usage =        "Calculate the error in a function f[{x1,x2,...}] with uncertainties {dx1,dx2,...}."          Begin["`Private`"]          fError[f_, xi__, dx__] :=        Sum[(D[f[xi], xi[[i]]]*dx[[i]])^2, {i, 1, Length[xi]}]^(1/2);          fErrorTest[x_] := Module[{a = 3}, x^3 - a];          End[]          EndPackage[]      And then I try to load it as such:               << pathToFile/errorpropagation.m     g[{x_, y_}] := x^2 + x y;     fError[g, {x, y}, {dx, dy}]     fErrorTest[3]      I've tried different variants of whether the `<<` command takes a string or not, and relative and full path names, but had no success. The package has worked for me if I open it and evaluate the cells in the package, but the whole point of writing a package was to avoid manual evaluation every time.


Pattern constraint for two or more variables

Is it possible to have a pattern constraint for a function with two or more variables where the pattern is a relation between the vars being accepted e.g.               f[x_,y_]:=...      and I want say, x< 10y. I don't think something like               f[x_,y_/; x<10y]      will work, or other variants of this that I have tried.


Consistent Plot Styles across multiple MMA files and data sets

I am starting to write a thesis for which I want to use MMA for all my plotting needs, mostly because a lot of the basic analysis has been done there. To ensure that I am applying styles consistently (plot colors, image size, label size, etc.), I need a method which I can use across multiple files. There are several types of plots that I will need:   1. `ListPlot` / `Plot`   2. `ListDensityPlot` / `DensityPlot`   3. `ListContourPlot` / `ContourPlot` I can think of several way of doing this:   1. Define my own functions `thPlot`, `thListPlot`, etc which have my default styles applied   2. Define my own style options into a variable, and use some combination of `FilterRules` and `Options` to make sure that options from that variable are applied to the right type of plot   3. Set default options using `Default` for the different types of plots. I am assuming that each of my datasets (which may have one or more plots) will be self-contained mathematica files that I can re-run. So, if I decide to change the style in some central location (via one of the methods above) I can re-run the MMA files and get the plots in the new style. What have people done in the past?


How do I get Nsolve to work with hyperbolic functions?

This is a rather simple numerical solution, but it simply doesn't work. Does anybody have a solution?               NSolve[x - Sinh[x] - 1 == 0, x]      > NSolve::nsmet: This system cannot be solved with the methods available to > NSolve.


2X slower with ; -- LibraryLink performance problem

This is the continued problem of the LibraryLink memory usage question here and here. In the following code, there is a 2X performance difference with only the change of ";".               MMASrc = "       #include <WolframLibrary.h>       #include <WolframCompileLibrary.h>            DLLEXPORT mint WolframLibrary_getVersion(){         return WolframLibraryVersion;       }       DLLEXPORT int WolframLibrary_initialize(WolframLibraryData \     libData){         return 0;       }            EXTERN_C void zspsv_(char* UPLO, const mint* N, mint* NRHS, \     mcomplex* A, mint* IPIV, mcomplex* B, mint* LDB, mint* INFO);                 EXTERN_C DLLEXPORT int lpkSolveAXBS(WolframLibraryData libData, \     mint Argc, MArgument *Args, MArgument Res){              MTensor ta=MArgument_getMTensor(Args[0]);         MTensor tb=MArgument_getMTensor(Args[1]);         mint N=*MTensor_getDimensionsMacro(tb);         mcomplex* A=MTensor_getComplexDataMacro(ta);         mcomplex* B=MTensor_getComplexDataMacro(tb);              MTensor tclone=0;              char U='U';         mint IPIV[N];         mint NRHS=1;         mint LDA=N,LDB=N;         mint INFO;         mint i,j;              mcomplex AP[N*(N+1)/2];              for(j=0;j<N;j++)           for(i=0;i<=j;i++)             AP[i + (j+1)*j/2] = A[i*N+j];              zspsv_(&U,&N,&NRHS,AP,IPIV,B,&LDB,&INFO);              libData->MTensor_clone(tb,&tclone);              MArgument_setMTensor(Res,tclone);         return LIBRARY_NO_ERROR;       }       ";     Needs["CCompilerDriver`"];          CreateLibrary[MMASrc, "lpk", "Debug" -> True,        "TargetDirectory" -> "/tmp", "CompileOptions" -> "-llapack"];          A = {{1. + 0. I, 0. + 0. I, 0. - 6.94908*^-13 I,          0. - 6.94908*^-13 I}, {0. + 0. I, 1. + 0.0352595 I,          0. - 4.51893*^-11 I, 0. - 4.51893*^-11 I}, {0. - 6.94908*^-13 I,          0. - 4.51893*^-11 I, 1. + 0.0376938 I,          0. + 0. I}, {0. - 6.94908*^-13 I, 0. - 4.51893*^-11 I, 0. + 0. I,          1. + 0.0378932 I}};          B = {1. + 0. I, 0. + 0. I, 0. + 6.94908*^-13 I, 0. + 6.94908*^-13 I};           lpkSolve = LibraryFunctionLoad["/tmp/lpk.dylib", "lpkSolveAXBS", {{Complex, 2}, {Complex, 1}}, {Complex, 1}];      Now test the performance and the memory usage:               MemoryInUse[]/1024.^2     Table[LinearSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A, B], {40000}]; // AbsoluteTiming          MemoryInUse[]/1024.^2          (*     32.2057     {0.560369,Null}     32.2242     {0.115091,Null}     37.1101     {0.121534,Null}     41.995     *)      Note that there seems to be a memory leaking problem, and it is identified as a bug by ruebenko. The work around suggested also by ruebenko is to use ";" at the end of each call to the LibraryLink function. While this solves the memory leak, the performance seems decreaed:               MemoryInUse[]/1024.^2     Table[LinearSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Table[lpkSolve[A,B];,{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2          (*     42.0031     {0.675034,Null}     42.0002     {0.241069,Null}     42.0022     {0.232982,Null}     42.0026     *)      using `Do` instead of `Table` doesn't solve the problem:               MemoryInUse[]/1024.^2     Do[LinearSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Do[lpkSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2     Do[lpkSolve[A,B],{40000}];//AbsoluteTiming          MemoryInUse[]/1024.^2          (*     42.0102     {0.595506,Null}     42.012     {0.221176,Null}     42.0138     {0.213203,Null}     42.0154     *)      So why there is a 2X performance difference just by adding ";" at the end of function call, or replace `Do` with `Table`? And how to fix it?


Recursive formula involving a piecewise function

I am trying to construct a recursion, `g[t]`, where   * `g[t] = a[t]` if `g[t-1] = 1`   * `g[t] = b[t]` if `g[t-1] = 2`. Additionally `a` and `b` are defined as:               a[t_] := If[0 <= RandomReal[] <= 0.94, 1, 2]     b[t_] := If[0 <= RandomReal[] <= 0.9, 2, 1]      So then I want (I've also tried it where I replace `a` and `b` with their original defintions):               g[t_]:= Piecewise[{{a[t], g[t - 1] = 1}, {b[t], g[t - 1] = 2}}]     g[1] = 1      This, however, is not working.


Using functions to make loops

I'm trying to make a simulation of an electron that goes through a magnetic and electric field perpendicular to each other and to the velocity of the electron but I'm running in some troubles with the _Mathematica_ language. I'm a beginner at _Mathematica_ language and I ended up probably using too much procedural programming and I would like suggestions on how I can improve it using real _Mathematica_ language. For those who saw this question before I edited it, the second problem was fixed and it was a simple logic mistake, so I took it of the question.               vel = {0.05*300000000, 0, 0}; (* velocity *)     pos = {0, 0, 0}; (* position *)     acel = {0, 0, 0}; (* acceleration *)     ce = {0, -5000, 0}; (* electric field *)     cm = {0, 0, -0.0003}; (* magnetic field *)     dt = 0.000000000001;     l = 0.05; (* length of the region where there are magnetic and electric fields *)     me = 9.10938*10^-31; (* electrons mass *)     q = -1.60217657*10^-19; (* elementary charge *)     data = Table[0, {i, 1000000}, {j, 2}];     For[count = 1, pos[[1]] <= 1.5*l, count++,          If[Abs[pos[[1]]] <= l, acel = q/me*(ce + (vel\[Cross]cm)), acel = {0, 0, 0}];           pos = pos + vel*dt + (acel*dt^2)/2; vel = vel + acel*dt;          data[[count, 1]] = pos[[1]]; data[[count, 2]] = pos[[2]]        ];     For[r = 100000; s = 0.00001, r > 0.001, r = (r/10); s = (s/10),          While[Abs[vel[[2]]] > r, cm[[3]] = cm[[3]] - s;                   vel = {0.05*300000000, 0, 0};                   pos = {0, 0, 0};                   data = Table[0, {i, 1000000}, {j, 2}];                      For[count = 1, pos[[1]] <= 1.5*l, count++,                           If[Abs[pos[[1]]] <= l, acel = q/me*(ce + (vel\[Cross]cm)), acel = {0, 0, 0}];                            pos = pos + vel*dt + (acel*dt^2)/2; vel = vel + acel*dt;                           data[[count, 1]] = pos[[1]]; data[[count, 2]] = pos[[2]]                         ];               ];         ];      I know that there are duplicate variable declarations and redundant statements in the code, its because I pasted everything together to post here, but it was originally apart.


How to Solve/NSolve/Reduce this rationalized equation

In this problem I don't know why the system is not solvable. I have just one unknown K0.                  sol[K0_]:=SetPrecision[-(2397273135785684105116286138088240239609486751943174/        6428810371332877606946043738694402071216515377775) - (        7849 Sqrt[-41616 + (        149163411674835586124096205921334157174479655112799 Sqrt[K0])/        35362087636687395438079446898535340978108366770607])/1400 + (       7849 I Sqrt[        41616 + (149163411674835586124096205921334157174479655112799 Sqrt[       K0])/35362087636687395438079446898535340978108366770607])/1400 + (       1752165303140718220448962503 Sqrt[-41616 + (       149163411674835586124096205921334157174479655112799 Sqrt[K0])/       35362087636687395438079446898535340978108366770607])/(       1605413612500000000 K0) - (       1752165303140718220448962503 I Sqrt[       41616 + (149163411674835586124096205921334157174479655112799 Sqrt[       K0])/35362087636687395438079446898535340978108366770607])/(       1605413612500000000 K0) + (       15630469741744099872889401708736470294234641513962455 Sqrt[-41616 + (       149163411674835586124096205921334157174479655112799 Sqrt[K0])/       35362087636687395438079446898535340978108366770607])/(       282585461012870216280087249803974135070469452098 Sqrt[K0]) + (       15630469741744099872889401708736470294234641513962455 I Sqrt[       41616 + (149163411674835586124096205921334157174479655112799 Sqrt[      K0])/35362087636687395438079446898535340978108366770607])/(      282585461012870216280087249803974135070469452098 Sqrt[K0]) + (      5994979010910966184793439691673144599099894289304 Sqrt[      K0])/158612235779223913220534429863991677577574124084351,50];                 NSolve[sol[K0] == 0, K0, WorkingPrecision -> 50]


Why are the elements of plots separated in exported PDFs?

When I export a plot to a PDF with something like               Export["test.pdf", Plot[Sin[x], {x, 0, 2 Pi}], "PDF"]      I get a file in which the axes have been separated from the rest of the plot in some editors and viewers (e.g., OmniGraffle): ![enter image description here](http://i.stack.imgur.com/YmBWh.png) Why is this happening? Is there a way to prevent it?


Is there a way to make the "Details" section of the documentation expand by default?

By default, the _Mathematica_ documentation opens with the "Details" section collapsed. ![enter image description here](http://i.stack.imgur.com/E4KRI.png) This is _never_ what I'm looking for — in fact, I've lost count of the times I've sought help on a feature and not found it anywhere on the feature's documentation page (at least not until I remember this shortcoming). Is there a way to configure _Mathematica_ doe that the "Details" section of the documentation opens is expanded by default?


Why does Simplify ignore an assumption?

Here is the example:               Simplify[x + y, x + y == a]     Simplify[x + y, x + y == 5]      Mathematica 9 output:               x+y     5      I expect the complexity of `a` to be lower than complexity of `Plus[x,y]`, and the result of the first line should be `a`. Even if I specify `ComplexityFunction` explicitly:               Simplify[x + y, x + y == a, ComplexityFunction -> LeafCount]      I still get `x+y` as a result. It's however obvious that `LeafCount[x+y]` is greater than `LeafCount[a]`. Why does Simplify ignore `x+y==a` but uses `x+y==5`? How can I define the former assumption in a right way?


Assign one button to two variables

I am trying to use the one button to assign to two variables. Here is an example of how I want it to work. expression:               "Magnitude = ", mstar, ", Distance = ", dstar,      sliders:               "Magnitude:", {{mstar, mSun, "Magnitude"}, mSun, 30},     "Distance:", {{dstar, dSun, "Distance"}, dSun, 600},      buttons:               "or Select Star:",      {{mstar&&dstar, mAltair&&dAltair, "Star"},       {mAltair&&dAltair -> "Altair", mCanopus&&dCanopus -> "Canopus",       mEpisilonIndi&&dEpisilonIndi -> "Episilon Indi"},       ControlType -> Setter}      In this example, it would work fine if it was able to assign both variables when pressing the desired button, however `&&` doesn't work like this. My only solution is to have a button for each variable;               "or Select Star:",      {{mstar, mAltair, "Subscript[Star, m]"},       {mAltair -> "Altair", mCanopus -> "Canopus", mEpisilonIndi -> "Episilon Indi"},       ControlType -> Setter},          "or Select Star:",       {{dstar, mAltair, "Subscript[Star, d]"},        {dAltair -> "Altair", dCanopus -> "Canopus", dEpisilonIndi -> "Episilon Indi"},        ControlType -> Setter}      However, this requires me to press both buttons, where my desired effect is to only have to press one. Is there a way I can achieve this?, I am aware that I can assign a variable two values such as;               Sun = {mSun, dSun}      I don't know the correct expression or even if it's possible. Can I do this and have my expression able to choose which value to use? Like this?               "Magnitude = ", star{value1}, ", Distance = ", star{value2},          "Magnitude:", {{star{value1}, Sun{value1}, "Magnitude"}, Sun{value1}, 30},     "Distance:", {{star{value2}, Sun{Value2}, "Distance"}, Sun{value1}, 600},          "or Select Star:",      {{star, Sun, "Star"},       {Altair -> "Altair", Canopus -> "Canopus", EpisilonIndi -> "Episilon Indi"},       ControlType -> Setter}      ## Edit This is the current coding which displays the first image:               Manipulate[     Column[{Row[{"Apparent magnitude = ", mstar, ", distance = ", dstar, "pc"}], Style[Row[{"Star has Absolute Magnitude of ", mstar - 5 ((Log10[dstar]) - 1)}], Bold, 24]}, Spacings -> {0, 1.5}],     "Choose apparent magnitude:", {{mstar, mSun, "m"}, mSun, 30},     "choose distance:", {{dstar, dSun, "d"}, dSun, 600},     "or select desired star:",     {{mstar, mSun, "m"}, {mAltair -> "Altair", mCanopus -> "Canopus", mEpisilonIndi -> "Episilon Indi", mRigel -> "Rigel", mProximaCentauri -> "Proxima Centauri", mSun -> "Sun", mZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter},     {{dstar, dSun, "d"}, {dAltair -> "Altair", dCanopus -> "Canopus", dEpisilonIndi -> "Episilon Indi", dRigel -> "Rigel", dProximaCentauri -> "Proxima Centauri", dSun -> "Sun", dZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter}]      ![Image 1](http://i.stack.imgur.com/dMDKq.jpg) This is an example of how I want it to be displayed by being able to use a single button to assign both variables. The coding in this second image is a little different using Switch functions for the two variables, however a third variable is required for the actual Switch. I believe this would benefit from being able to assign two individual values to one variable, otherwise the sliders still require two individual variables. Here is the coding of the two variable switches:               Switch[star, Altair, mRigel, Canopus, mCanopus, EpisilonIndi, mEpisilonIndi, Rigel, mRigel, ProximaCentauri, mProximaCentauri, Sun, mSun, ZetaOphiuchi, mZetaOphiuchi]     Switch[star, Altair, dRigel, Canopus, dCanopus, EpisilonIndi, dEpisilonIndi, Rigel, dRigel, ProximaCentauri, dProximaCentauri, Sun, dSun, ZetaOphiuchi, dZetaOphiuchi]      Here is the coding of the buttons:               {{star, Altair, "s"}, {Altair -> "Altair", Canopus -> "Canopus", EpisilonIndi -> "Episilon Indi", Rigel -> "Rigel", ProximaCentauri -> "Proxima Centauri", Sun -> "Sun", ZetaOphiuchi -> "Zeta Ophiuchi"}, ControlType -> Setter}      As there is now a single variable, `star`, which assigns the other two, `mstar` and `dstar`, the sliders require use of the same variable. A `Switch` cannot be placed where the `star` variable is as it's an invalid parameter.               "Choose apparent magnitude:", {{star, mSun, "m"}, mSun, 30},     "Choose distance:", {{star, dSun, "d"}, dSun, 600},      ![Image 2](http://i.stack.imgur.com/Fh8np.jpg) Hopefully this makes a more sense, I am very new to Mathematica and have only been using it for about a week. ## Edit 2 I adjusted the project to substitute the previous buttons with actual `Button` functions, it works flawlessly. The following image is how the new output is displayed: ![Image 3](http://i.stack.imgur.com/AVEUf.jpg) The buttons are now using the following code:               Button["Altair", mstar = mAltair; dstar = dAltair]


Trouble picking up package definitions

I open a new notebook and type               ClearAll[test];     test[x_] := x + 42;      I save it as `Temp.nb` and _also_ as `Temp.m`, using the menu _Save As... > Wolfram Mathematica Package (*.m)_. I now open up another notebook and type               << "Temp.m"      which succeeds. But the symbol `test` is not defined.               ?? test      > >     Information::notfound: Symbol test not found. >> >                 test[3]      > >     test[3] >   I'm confused, because the documentation for `Get`, a.k.a., `<<`, says > << name reads in a file, evaluating each expression in it and returning the > last one. It should have evaluated the expressions in `Temp.m`, then, I should think, and returned the [value of] the last one, which would be `Null`. One of those expressions is a `SetDelayed` for the symbol `test` and should have installed `test` in the Global namespace, no? Fresh kernel session, fresh reboot of MMA, also fails if file is saved as _Wolfram Language Package (*.wl)_ , yada yada.


Images in package Not visible

I want to make a package where some variables are initialized to images. but when i save the package, all images are in the form of `ImageData` that are very long. how do i fix it ?


Eigenvalues and Determinant of a large matrix

Can anybody kindly explain to me what is going wrong regarding a simple problem I have? I can find the eigenvalues of a large matrix using `Eigenvalues[]`, but when I try to find the determinant of the matrix minus eigenvalue times identity matrix, the result is not equal to zero. To make it clear please take a look at the following example:               n = 150;     m = RandomReal[{-5, 5}, {n, n}];     EIG = Eigenvalues[m];     DET = Det[(m - (EIG[[n]])*IdentityMatrix[n])]      For small values of `n`, `DET` equals zero, but when `n` becomes larger `DET` is no longer zero, and for `n = 150` (as in the example) `DET` will be a huge number! Could you please tell me whether the problem is from `Eigenvalues[]` or `Det[]` in _Mathematica_ , and how I can sort it out?


For some reason when you run Math.exe form windows command line, Mathematica disables the AltGr key. This is _a bit_ annoying since my keyboard locale has the keys [, ], {, }, @, $, \, | located under this key. This makes Mathematica unusable for many novice users. Is there a way to workaround this problem other than switching the keyboard locale? I can switch to US keyboard but my students can not since they have hard enough time finding characters that are typed on the keyboard. Is it possible to get AltGr key to work in Math.exe?


Simplify $\cos(n \pi)$ and $\sin(n \pi)$ when n is an integer

I was trying to calculate this integral in _Mathematica 9_ :               2/π Integrate[ Cosh[a x] Cos[n x], {x, 0, π}, Assumptions -> n ∈ Integers]      I got as a result : $$\frac{2 (a \sinh (\pi a) \cos (\pi n)+n \cosh (\pi a) \sin (\pi n))}{\pi \left(a^2+n^2\right)}$$ That's the same result I obtained manually, but how can I force _Mathematica_ to change $\sin(n \pi)$ into $0$ and $\cos(n \pi)$ into $(-1)^n$ ?


Limit of integral gives incorrect output

I'm trying to evaluate $\lim_{e\to 0} \, \frac{i}{e}\int_{\pi }^0 \frac{1-\exp (i e \exp (i \theta ))}{\exp (i \theta )} \, d\theta$ with Mathematica 9.0.1.0 on OS X. However, I get "Undefined" for this input:               Limit[I/e Integrate[(1 - Exp[I e Exp[I \[Theta]]])/Exp[I \[Theta]], {\[Theta], \[Pi], 0}], e -> 0]      We can see numerically that the correct answer is $-\pi$ by using this code:               With[{e = 0.000001}, I/e NIntegrate[(1 - Exp[I e Exp[I \[Theta]]])/Exp[I \[Theta]], {\[Theta], \[Pi], 0}] ] // Chop      What goes wrong in this process? Is it possible to get the correct result?


How can I change the default output number form to accounting form?

By default, large numbers are displayed in scientific form in output like `1.2345 x 10^8` in _Mathematica_ 8.0.4, but I would prefer having numbers in accounting form like `123,450,000` in output. How can I change the default output number form from scientific form to accounting form?


I want to define a function that has integer power

I am defining this function: `f[x_] = kr*g[x] + (c^l*x^l)/(KIR + c^l*x^l)` But I want to make `l` bigger than 0, so if I evaluate `f[0]` I want to get `kr*g[0]`. However, I get the expression evaluated at `0`, for example `0^l` instead of `0`. Thanks for the help


How to maximize a function over a rotation matrix?

I have list of pairs of points: $\{(x_i,y_i)\}_{1\le i\le n}$, $x_i \in \mathbb{R}^3$, $y_i \in\mathbb{R}^2$ and would like to optimize over a rotation $R \in SO(3)$, a translation $t \in \mathbb{R}^3$ and scalars $a,b \in \mathbb{R}$ such that $\sum_{i=1}^n{\|f(x_i|R,t,a,b) - y_i\|^2}$ is minimal. The model function $f$ is non-linear and varies in my applications. How can I find optimal parameter values $R,t,a,b$ for a given dataset with Mathematica (v9)? **Edit:** An example for $f$ would be:               f[{x_, y_, z_}, R_, t_, a_, b_] := Module[{qx, qy, qz},       {qx, qy, qz} = R.(z/a {x, y, a}) + t;       b {qx/qz, qy/qz}     ]      Here $a,b>0$ would be an additional constraint. A few data points as an example. A longer list can be found here.               {      {21.389, -24.551, 2.226, -5.25873, 3.72399},      {32.204, -7.055, 0.727, -28.5502, 20.8323},      {11.524, -12.171, 2.116, -9.31497, 13.5392},      {251.154, -8.349, 2.333, 21.8644, -62.8753},      {-12.07, -10.771, 2.09, -1.56909, 11.4189},      {-95.896, 7.367, 1.974, -56.4495, -28.5834},      {87.725, -2.845, 1.108, 4.35673, -6.32492},      {188.811, 99.661, 2.052, -35.3311, -40.9137}     }


Attaching the same message to several symbols

It is common in many packages, as well as system symbols, that the same message can be issued by several functions. Here's an example: ![Mathematica graphics](http://i.stack.imgur.com/erqUC.png) One mechanism that can be used for this is to define the message only once, and attach it to the `General` symbol. This is how the `infy` messages works as well. `infy` can appear to come from any symbol: ![Mathematica graphics](http://i.stack.imgur.com/cFGlC.png) When writing a custom package, it might not be the best idea to do this though because of the risk of message conflicts. Two packages might attach the same message identifier to `General`, so the one that's loaded last will overwrite the previous one. In fact, looking at the some standard packages (e.g. CUDALink), they do not attach messages to `General` even when the same message can be issued by several functions. Looking at the source code of the package, CUDALink uses a helper function to attach the same message text to several symbols in one go. **The question:** What is the best way to proceed when several functions need to be able to issue the same message, and indicate that it is coming from them? What do you use in your own packages? What's important for me is minimizing the risk of conflict with other packages and the simplicity of implementation.


Saving table of plots into a single figure within a pdf file

I have following code:                 Table[LogLogPlot[         a + 0.017*k + (-0.014*k)*Tanh[(k - 0.25)*b], {k, 0.1, 10}],           {b, {0.1, 0.2, 0.3, 0.4}}, {a, {1.0, 1.1, 1.2, 1.3}}]      I get then a table of plots and I can click on each of them to save them. But how do I save them all at once into a single PDF? If I instead do:                  GraphicsGrid[          Table[LogLogPlot[            a + 0.017*k + (-0.014*k)*Tanh[(k - 0.25)*b], {k, 0.1, 10}],              {b, {0.1, 0.2, 0.3, 0.4}}, {a, {1.0, 1.1, 1.2, 1.3}}]]      I cannot right click on the figure to save as some image, but rather have to export it. And I am really not satisfied by the result.               Export["grid1", %, "PDF"]      All axes and fonts are completely squeezed, big and unreadable. ![plot](http://i.stack.imgur.com/aiH7P.png) How do I set borders and fonts and all that in an easy manner? The best way would be really being able to right click on the table of plots and save it as it looks like.


Summing Multinormal Distributions

So, I'll explain the problem first. I have two populations that have values for two different channels (c1,c2). I've modeled these using MultinormalDistribution[]. I would like to add some noise to these distributions, which also exists in channels (c1,c2). I've tried doing this using TransformedDistribution[]:               hiDist = MultinormalDistribution[\[Mu]HiErr, \[CapitalSigma]];     loDist = MultinormalDistribution[\[Mu]LoErr, \[CapitalSigma]];     noiseDist = MultinormalDistribution[\[Mu]Noise, \[CapitalSigma]];          hiNDist =        TransformedDistribution[        h + n, {h \[Distributed] hiDist, n \[Distributed] noiseDist}];     loNDist =        TransformedDistribution[        l + n, {l \[Distributed] loDist, n \[Distributed] noiseDist}];      This works with regular Normal distributions, but fails when I use it with the Multinormal primitives. Any elegant way to do this? **EDIT 1** Changed a typo. "Failure" results when I try to call the thing. In place, the TransformedDistribution[] call will just output something like:                   TransformedDistribution[\[FormalX]1 + \[FormalX]2, {\[FormalX]1 \     \[Distributed]         MultinormalDistribution[{5000,           20000}, {{1000000, 0}, {0,            1000000}}], \[FormalX]2 \[Distributed]         MultinormalDistribution[{2000,           2000}, {{1000000, 0}, {0, 1000000}}]}]      However, when I try to use the distribution, e.g.               RandomReal[hiNDist,100]      Mathematica will throw the error: > RandomReal::udist: "The specification TransformedDistribution[[FormalX]> > 1+[FormalX]2, > {[FormalX]1[Distributed]MultinormalDistribution[{5000,20000},{{1000000,0},{0,1000000}}],[FormalX]2[Distributed]MultinormalDistribution[{2000,2000},{{1000000,0},{0,1000000}}]}] > is not a random distribution recognized by the system" While the code               n1 = NormalDistribution[5000, \[Sigma]];     n2  = NormalDistribution[10000, \[Sigma]];     n3 = TransformedDistribution[       x + y, {x \[Distributed] n1, y \[Distributed] n2}]      Gives the expected               NormalDistribution[15000, 1000 Sqrt[2]]


Extend a function defined for integers to a differentiable function of a real variable

Here is a function that calculates the probability of randomly landing on a Fibonacci number not greater than $n$:               f[n_Integer] := (Floor[Log[GoldenRatio, Sqrt[5] (n + (1/2))]] - 1)/n        ![1-50](http://i.stack.imgur.com/zRjSe.png) How can I extend/complete it to some differentiable function that agrees with the original values when given an "integer" input?


Evaluate in Plot leads to function error

Please help - I'm really struggling to understand why this evaluates with errors.               data = RandomReal[10, {4, 1000}];     metric[data_, perc_] := (x = Quantile[#, perc] & /@ data; Accumulate[x]/Total[x]);     Plot[Evaluate@metric[data, p], {p, 0.01, 0.99}, AxesLabel -> {"Percentile", "Proportion"},  PlotLegends -> {"Series A", "Series A+B", "Series A+B+C", "Series A+B+C+D"}]      Basically I need to see the results from the function as 4 separate curves in 4 colours. Placing the "metric" function inside the Plot means that it plots everything as one function, which doesn't help (although it evaluates error free). In line with other answers on here (here and others) I recognise I have to either Evaluate it or Apply the metric to the Plot pure function, but then I get a Quantile error (and critical/"fall over" errors with some of the other more complex metrics I'm using). I've tried using default values, Holds, matching patterns on when perc doesn't exist etc etc but to no avail. I'm losing years off my life trying to get this to work so any help would be really appreciated...


Where Statement

Is there a "parallel" way to perform these operations?               Indices = {}     For[i = 1, i <= Length[w], i++,      If[w[[i]] < 0, AppendTo[Indices, i]]]      Which gives a list of the Indices where the list w is negative. This is a little slow. Is there a faster cleaner way to get the same answer? This is essentially the Fortran 90 where statement.