If doesn't compile if its output is the output of Compile?

The smallest sample I can find to reproduce this problem is:               test = Compile[{}, If[True, 1]];     << CompiledFunctionTools`     CompilePrint@test      > >     ………… >      1    R0 = MainEvaluate[ Function[{}, If[True, 1]][ ]] >      2    Return >   The problem disappears when the `If[]` is followed by a semicolon:               test = Compile[{}, If[True, 1];];     CompilePrint@test      > >     ………… >     1     if[ !B0] goto 3 >     2     goto 3 >     3     Return >   or enclosed by a redundant `Do[]`:               test = Compile[{}, Do[If[True, 1], {1}]];     CompilePrint@test      > >     ………… >     1   I1 = I0 >     2   I3 = I2 >     3   goto 6 >     4   if[ !B0] goto 6 >     5   goto 6 >     6   if[ ++ I3 < I1] goto 4 >     7   Return >   while a redundant `Table[]` won't help:               test = Compile[{}, Table[If[True, 1], {1}]];     CompilePrint@test      > >     ………… >   >     1   I1 = I0 >     2   I4 = I3 >     3   T(R1)0 = Table[ I1] >     4   I2 = I3 >     5   goto 8 >     6   R1 = MainEvaluate[ Function[{}, If[True, 1]][ ]] >     7   Element[ T(R1)0, I4] = R1 >     8   if[ ++ I2 < I1] goto 6 >     9   Return >   This phenomenon may lead to a total failure of compilation when codes become more complicated:               ie = 200;     ez = ConstantArray[0., {ie + 1}];     hy = ConstantArray[0., {ie}];          f1 = Compile[{{steps}},         Module[{ie = ie, ez = ez, hy = hy},          Do[ez[[2 ;; ie]] = ez[[2 ;; ie]] + (hy[[2 ;; ie]] - hy[[1 ;; ie - 1]]);          ez[[1]] = Sin[n/10];          hy[[1 ;; ie]] = hy[[1 ;; ie]] + (ez[[2 ;; ie + 1]] - ez[[1 ;; ie]]), {n, steps}];         ez]];          f2 = Compile[{{steps, _Integer}, {test, True | False}},         Module[{ie = ie, ez = ez, hy = hy},          Do[ez[[2 ;; ie]] = ez[[2 ;; ie]] + (hy[[2 ;; ie]] - hy[[1 ;; ie - 1]]);          ez[[1]] = Sin[n/10];          hy[[1 ;; ie]] = hy[[1 ;; ie]] + (ez[[2 ;; ie + 1]] - ez[[1 ;; ie]]), {n, steps}];         If[test, ez]]];          f1[1500]; // AbsoluteTiming      > >     {0.0250000, Null} >                 f2[1500, True]; // AbsoluteTiming      > _Warnings……_ >   >   >     {0.5730000, Null} >   So, as the title said, `If` won't compile when its output is the output of `Compile`? Of course it can be easily circumvented, but I wonder if there's a universal rule behind this, or it's just another unreasonable behavior of `Compile`?


Manipulate (Linux version of Mathematica)

I'm runnning _Mathematica_ 9 on Ubuntu 11.10. After installing CDF player I still have problem (most of time) with `Manipulate`. Only way I'm able to change value of a parameter is by manually entering a value into into an edit field (dragging the slider or pushing buttons doesn't work). Can anyone suggest what I'm doing wrong? (Even simple `Manipulate[x, {x, 1, 5}]` doesn't work properly.)


Measuring curve length on a binarized image

With the help of almighty Mathematica 9, I got from this ![enter image description here](http://i.stack.imgur.com/79l19.jpg) To this: ![enter image description here](http://i.stack.imgur.com/rwDwl.png) with this code:               MorphologicalBinarize[       Import["http://i.stack.imgur.com/79l19.jpg"]~        ColorConvert~"Grayscale"];     Binarize[LaplacianGaussianFilter[%, 10]];     CommonestFilter[MaxFilter[DeleteSmallComponents[%], 2.3], 10];     SelectComponents[MorphologicalComponents[%], "Length", -1] // Image;     Pruning[Thinning[%, Padding -> 1], Padding -> 1]      I'm sure the code could be shorter and is perhaps in places redundant, but that's not why I'm posting here, as because now, I'm interested in measuring the length of the curve that I got. I wanted to create a tool to test this theory whenever would I want so. I couldn't find a way - I thought I was close when I transposed `ImageData` position on ListPlot, alas, I swiftly got lost there. I am very new to this wonderful tool and am learning it by trial and error. I'd appreciate any form of help.


StringReplace, ReplaceAll and Rule interact in a bizarre way

I have the following pair of things:               ClearAll[foo, labeledFoo];          labeledFoo = {"FooBarBazQuux", foo};      This works like you'd expect:               labeledFoo /. hdr_String :>        StringReplace[hdr, l_?LowerCaseQ ~~ U_?UpperCaseQ :> l <> " " <> U]          (* {"Foo Bar Baz Quux", foo} *)        So does this:               labeledFoo /. hdr_String :>        StringReplace[hdr, l_?LowerCaseQ ~~ U_?UpperCaseQ :> l <> " " <> U] /.         {hdr_String, x_} :> (hdr -> x)          (* "Foo Bar Baz Quux" -> foo *)      Heck, even this works:               labeledFoo /. {hdr_String, x_} :> (Rule @@ {StringReplace[hdr,        l_?LowerCaseQ ~~ U_?UpperCaseQ :> l <> " " <> U], x})          (* "Foo Bar Baz Quux" -> foo *)       This, though, doesn't work at all:               labeledFoo /. {hdr_String, x_} :> (StringReplace[hdr,       l_?LowerCaseQ ~~ U_?UpperCaseQ :> l <> " " <> U] -> x)          (* "Fo" ~~ l <> " " <> U ~~ "a" ~~ l <> " " <> U ~~ "a" ~~         l <> " " <> U ~~ "uux" -> foo *)      I really have no idea what's going on. This is so weird that I feel like I must be missing a simple syntax error, but all the other things that **do** work make me doubt that.


I want change gamma function form into beta function form

I want to integrate below form               x5^b*(1 - x5)^c*(e + d*x5^0.5 + f*x5)          1./Integrate[x5^b*(1 - x5)^c*(e + d*x5^0.5 + f*x5), {x5, 0, 1},        Assumptions -> {{b, c, e, d, f} \[Element] Reals, c > -1, b > -1}]      and the _Mathematica_ answer is               1./(Gamma[       1 + c] ((e Gamma[1 + b])/Gamma[2 + b + c] + (1. d Gamma[1.5 + b])/        Gamma[2.5 + b + c] + (f Gamma[2 + b])/Gamma[3 + b + c]))      but I want see this answer in form of Beta function what should I do?


Working with large data, pass-by-reference, compiled functions

I think I know the answer to this, but after two days of Googling, this is my last effort before going down an unwanted path... I have a function that takes lots of large data as arguments as well as assigns new values to one of the arguments in place. Here is what it looks like:                   LinearIsotropicElastic[youngMod_,poisson_,node_,dilitation_,devElongState_,families_,volumes_,refMagState_,volState_,internalForce_] :=     Module[{ti,td,forceState,bulkMod=youngMod/3.0/(1.0 - 2.0*poisson),shearMod=youngMod/2.0/(1.0 + poisson)},              ti = 3.0*bulkMod*dilitation[[node]]/volState[[node]]*refMagState[[node]];              td = 15.0*shearMod/volState[[node]]*devElongState[[node]];              forceState = ti + td;              internalForce[[node]] += Total[forceState*volumes[[families[[node]]]]];              internalForce[[families[[node]]]] -= forceState*volumes[[node]];     ]      In pure Mathematica, I used `SetAttributes[]=HoldAll` and everything works fine. The issue is I need to map this function over many thousand "node" and this takes forever, therefore I'd really like to compile this function. I have not been able to successfully get the tricks that have been offered to compile a function while changing one of its arguments. This is standard pass-by- reference stuff in C of course. Are there any suggestions before I resort to writing this function in C and LibraryLink'ing it in? I really don't want to go down this path, because I actually already have a working similar application in C++ and was building this in Mathematica to be a prototyping code and not deal with all the complexity of C/C++. Any help will be appreciated.


What are the differences between the “Home Edition” and the regular Mathematica?

The product page for _Mathematica Home Edition_ says: > Mathematica Home Edition is intended for hobbyists and enthusiasts alike, > for non-professional use. If you wish to integrate Mathematica in your work, > teaching, or research, other licensing options are available. but I cannot find there nor here any technical description of the differences. Are those two different products? Or is it the same software sold under two names corresponding to two different licensing restrictions?


How to solve the warning problem and obtain real roots without imaginary part?

I am trying to solve a equation with _Newton_ 's method via `FindRoot`, and the codes are: Define the functions:               τs[Ωs_,t_]:=2*Ωs*Coth[Ωs/(2*t)]     τb[Ωb_,t_]:=2*Ωb*Coth[Ωb/(2*t)]     Xs[Js_,Jb_,Ωs_,t_,δ_]:=(τs[Ωs,t]-4*Js-4*Js/(Sqrt[2])^δ)/(Jb+4*Js/(Sqrt[2])^δ+4*Js/(Sqrt[3])^δ)     Xb[Jb_,Ωb_,t_,δ_]:=(τb[Ωb,t]-4*Jb-4*Jb/(Sqrt[2])^δ)/(Jb+4*Jb/(Sqrt[2])^δ+4*Jb/(Sqrt[3])^δ)     ϕ[Jb_,Ωb_,t_,δ_]:=ArcCosh[Xb[Jb,Ωb,t,δ]/2]     BN[Jb_,Ωb_,t_,δ_,n_]:=Sinh[(n+1)*ϕ[Jb,Ωb,t,δ]]/Sinh[ϕ[Jb,Ωb,t,δ]]     fumfa[Js_,Jb_,Ωs_,Ωb_,t_,δ_,n_]:=(Xs[Js,Jb,Ωs,t,δ])^2*BN[Jb,Ωb,t,δ,n-2]-2*Xs[Js,Jb,Ωs,t,δ]*BN[Jb,Ωb,t,δ,n-3]+BN[Jb,Ωb,t,δ,n-4]      Solve a series of solutions:               Table[FindRoot[fumfa[2.0,1.0,Ωs,2.0,3.5,t,4]==0.0,{Ωs,4.0}],{t,0.1,4.0,0.2}]      However, I got the following warning message: > The line search decreased the step size to within tolerance specified by > `AccuracyGoal` and `PrecisionGoal` but was unable to find a sufficient > decrease in the merit function. You may need more than `MachinePrecision` > digits of working precision to meet these tolerances. And some of the solutions have imaginary parts though the coefficients are actually zeros:               {{Ωs->11.6453 +0. I},{Ωs->10.5823 +0. I},{Ωs->9.58167 +0. I},{Ωs->8.63181 +0. I},{Ωs->7.72096 +0. I},{Ωs->6.83656 +0. I},{Ωs->5.96386 +0. I},{Ωs->5.08324 +0. I},{Ωs->4.16381 +0. I},{Ωs->3.14345 +0. I},{Ωs->1.82232},{Ωs->5.70687*10^-6},{Ωs->4.74748},{Ωs->3.29661},{Ωs->1.28711},{Ωs->-1.26412*10^-6},{Ωs->-3.05724*10^-6},{Ωs->-0.0000392875},{Ωs->0.0000453593},{Ωs->0.0000543535}}      My questions are:   1. How to remove the warning message?   2. why there are imaginary parts in the solutions and how to assure `Reals` only computation?


How to smoothly change the radius of a circle by dragging its circumference?

I am attempting to set an `EventHandler` to change the radius of a circle by dragging on its circumference. But the response to the dragging is terribly slow. What is wrong with the code?               cnt[p_] := Return[Round /@ p];     grids[min_, max_] :=        Join[Range[Ceiling[min], Floor[max]],         Table[{j + 1, Lighter@Lighter@Lighter@Lighter@Blue}, {j,           Round[min], Round[max - 1], 1}]];          DynamicModule[{pnt = {1, 1}, VPOS = {1, 1}, rad = 1},       Dynamic@Graphics[        {Thick,         EventHandler[          Circle[ cnt[pnt] , rad],          {           "MouseDragged" :> (             VPOS = MousePosition["Graphics"];               rad = EuclideanDistance[pnt, VPOS];             )           },          PassEventsDown -> True          ],         Locator[Dynamic[pnt], None]          },        Axes -> True,        GridLines -> grids,        PlotRange -> {{-10, 10}, {-10, 10}}]       ]      ![enter image description here](http://i.stack.imgur.com/Xfrw4.gif)


How to color the surface of the Box of 3D graphics

Is there any possibility to color the surface of the Box of a `Graphic3D[]`?               Show[Graphics3D[Sphere[]], ViewPoint -> Above,      BoxStyle -> Directive[Large, Orange, Thick]]      I need to color the surface of the Box. (Like a wall).


How to find best MLE using `FindDistributionParameters`

This question is an extension of this question, if we change the initial values `FindDistributionParameters[data1, dist, {{a, 0.1}, {b, 0.1}, {c, 0.1}, {al, 0.1}, {be, 0.1}, {ph, 0.1}}] ` to `FindDistributionParameters[data1, dist, {{a, 0.2}, {b, 0.1}, {c, 0.1}, {al, 0.1}, {be, 0.1}, {ph, 0.1}}]` parameter estimates also change. So my question is if we have no idea about initial values then how we search best initial values or best MLE estimates which close to empirical distribution of `data1`. The empirical distribution with two parameters which are estimated with initial value's given above are plotted as ![enter image description here](http://i.stack.imgur.com/8be82.gif) Not a best fit. The code of above plot is: > data1 = {275, 13, 147, 23, 181, 30, 65, 10, 300, 173, 106, 300, 300, 212, > 300, 300, 300, 2, 261, 293, 88, 247, 28, 143, 300, 23, 300, 80, 245, 266}; > g1 = NIntegrate[(2.51339*2.51952*3.21532)/Beta[2.87484, 0.0825351]* > y^-(3.21532 + 1)*(1 + > 0.0609138*2.51952*y^-3.21532)^-((2.87484*2.51339)/0.0609138 + 1)*(1 - (1 + > 0.0609138*2.51952*y^-3.21532)^-(2.51339/ 0.0609138))^(0.0825351 - 1), {y, 0, > x}]; > > g2 = NIntegrate[(1.98156*1.98026*3.2635)/Beta[2.64639, 0.090212]* y^-(3.2635 > + 1)*(1 + 0.0328252*1.98026*y^-3.2635)^-((2.64639*1.98156)/0.0328252 + 1)*(1 > - (1 + 0.0328252*1.98026*y^-3.2635)^-(1.98026/ 0.0328252))^(0.090212 - 1), > {y, 0, x}]; > > Plot[{g1, g2, CDF[EmpiricalDistribution[data1], x]}, {x, 2, 400},   >  Exclusions -> None]


List of Parallelize[]-able functions

The question is clear and is inspired by this question and the first comment on this question. Although there are many tricks for parallelizing things that are not `Parallelize[]`-able it would be handy to know beforehand whether the function you need is boostable with `Parallelize`. From the official documentation we have the following list:   * All listable functions with one argument.   * Structure-preserving functions: `Map`, `MapThread`, `MapIndexed`, `Scan`, `Apply`.   * Reductions: `Count`, `MemberQ`, `FreeQ`.    * Products: `Inner`, `Outer`, `Dot`.   * Iterators: `Table`, `Array`, `Product`, `Sum`. Does the complete list exist?


Rectangle with rounded edges

Inspired from : Fit an image within a Rectangle [] in Graphics I would like now to fit an image within a Rectangle[] with **rounded edges** as shown in the example below : ![enter image description here](http://i.stack.imgur.com/tqIrf.png) Is it possible ?


Plot Matlab icon

I started to explore this on a whim and hasn't succeeded yet… Some introduction for the icon is found here but I can't understand it very well. (I admit that, though playing with `NDSolve` a lot, I suffered my unstable foundation of knowledge for PDE. ) A matlab code sample for the icon is found at the end of the document here and I have no doubt that it can be translated to _Mathematica_ code mechanically, but it'll be so boring! Can we plot it in a _Mathematica_ style? Has anyone tried it before?


Root finding in Mathematica

I am new to Mathematica. I have used the WolframAlpha online calculator to find roots of equations (listed under the heading `Root` in the output generated in response to a submission). When I try to find the roots of the same equation in Mathematica, I receive various errors. I have tried `FindRoot` and `Reduce`. Is there a function in Mathematica that corresponds to whatever is generating the `Root` output in the online WolframAlpha calculator? Thank you.


Export Animate command to MOV video

I'm trying to export a rather complex `Animate` command into a full-HD resolution video, but having no success so far. The animation has around 520 frames (the number of elements in the `trajectory` array). What I should be seeing is a tube object moving with a sphere object, and whilst I can see the animation is working with the `Animate` command, I cannot see the same results when I export the animation. I have tried different things but this just doesn't seem to work, I'm probably not using the export command in the right way. Instead of the 500~ frames trajectory of the tube and the sphere, I just see the animator moving from one side to other. I'm using the `Export` function, in the following way:               Export["my_output.mov",animationObject,"QuickTime",ImageSize->{1920,1080}]      My animation object follows this pattern:               (*theta and phi work as a function of s (the only animated variable) to change the view point*)     theta = N[Table[q, {q, 0.1, 2 \[Pi], (2 \[Pi] - 0.1)/Length[trajectory]}]];     phi = N[Table[q, {q, 0.5 \[Pi], 2.5 \[Pi], 2 \[Pi]/Length[trajectory]}]];          Animate[      Show[       (*data is a static array of around 5000 points*)       ListPointPlot3D[(*my list plot options and data*)],            (*A tube *)       Graphics3D[{White, Thickness [0.01], Opacity[0.4],Tube[trajectory[[1 ;; s]]]}],            (*A sphere*)       Graphics3D[{Yellow, Sphere[{trajectory[[s]]}, {0.02, 0.02}]}],            (*Just showing some grids with 10 grid lines*)       FaceGrids -> {(*Specific options for the face grids to show more lines, etc*)},            (*ViewPoint changed according to the corresponding value of s in the theta and phi arrays*)       ViewPoint -> Dynamic[{Sin[theta[[s]]] Cos[phi[[s]]],Sin[theta[[s]]] Sin[phi[[s]]], Cos[theta[[s]]]}],       ViewAngle -> 50 Degree],           (*Animate Parameters*)      {s, 1, Length[trajectory], 1}, DisplayAllSteps -> True,AnimationRepetitions -> 1, AnimationRunning -> False]      I'm using Mathematica 8 student version.


How to mix Unevaluated property of function arguments with expression assignments?

This is a follow-up to my (solved) question How to distribute a generic function of two arguments (without evaluating the arguments) Say, I have a binary function               f[x : a_List, y : b_List] := g[a, b]      Now if               u={u1,u2};     v={v1,v2};     w={w1,w2};      I want do distribute `f[u,v+w]` prior to evaluating `v+w` which works fine with the solution proposed by Mr. Wizard to my previous question               Distribute[Unevaluated@f[u,v+w]]     (** g({u1,u2},{v1,v2})+g({u1,u2},{w1,w2}) **)      But now what if I do               expr = v + w;      and try to distribute f[u,expr]? I would like to get the same result as before, however this yields               f[u,expr]        (** g({u1,u2},{v1+w1,v2+w2}) **       as of course `v+w` is evaluated when assigning to `expr`. Now a SetDelayed approach `expr := v+w` also doesn't help. I then thought of doing               expr = Hold[v+w];     Distribute[Unevaluated@ftest[u, ReleaseHold[expr]]]     (** g({u1,u2},{v1+w1,v2+w2}) **)      but this also gives the wrong (i.e. not the desired) result. So, how do I do this?


Cannot Plot Function

I cannot plot this function as I am getting errors. I am not sure what I am doing wrong. Seems to work when $$n \rightarrow 1,$$ but when $$n \rightarrow 2,$$ I get a whole bunch of errors and nothing is plotted. Here is the code: $$ \text{Plot}\left[\frac{n e^{-t (\lambda +\mu )} I_1\left(2 t \sqrt{\lambda \mu }\right) \left(\int_0^t \frac{e^{t (-\lambda -\mu )} I_1\left(2 t \sqrt{\lambda \mu }\right)}{\sqrt{\rho } t} \, dt\right){}^{n-1}}{\sqrt{\rho } t}\text{/.}\, \left\\{\lambda \to 0.99,\mu \to 1,\rho \to \frac{1}{2},n\to \\{2\\}\right\\},\\{t,0,10\\},\text{PlotRange}\to \text{All}\right]$$ Here is copyable code:               Plot[(n*BesselI[1, 2*t*Sqrt[λ*μ]]*                       Integrate[(E^(t*(-λ - μ))*                BesselI[1, 2*t*Sqrt[λ*μ]])/(t*Sqrt[ρ]),                      {t, 0, t}]^(-1 + n))/         E^(t*(λ + μ))/(t*Sqrt[ρ]) /.           {λ -> 0.99, μ -> 1, ρ -> 1/2, n -> {2}}, {t, 0., 10}, PlotRange -> All]


Interpolation steeply drops to 0 beyond data

I use Interpolation on unstructured 3-D-Data to visualize different regions via RegionPlot. A problem I run into is that the interpolating function steeply drops to zero beyond my set of data. This is unfortunate, as I with to show the region up to their theoretical boundary (which lies only a little bit beyond the data region). Is there a way to get Interpolation to perform a proper extrapolation for just a little margin beyond my data? This image shows the problem pretty well I think. ![Example for the problem](http://i.stack.imgur.com/bfzTz.png) The data that produced the image can be found here


Numbers in alternate bases transcend the evaluator?

It looks to me like a number in a base other than base 10 gets evaluated before the evaluator ever gets a chance to be tweaked. For example, `FullForm[16^^abcdef]` or even `FullForm[HoldAll[16^^abcdef]]` both produce `11259375`. Am I missing a trick that would get me some sort of less evaluated form? I guess I can use `BaseForm[]` when I need to record what base the number originally was in.


Safely generating multiple controls from a list of variables

Suppose I need to create sliders associated with variables from a given list:               ClearAll[a, b, c, d];     vars = {a, b, c, d};     Slider[Dynamic@#, {0, 1}] & /@ vars     Dynamic@vars      Unfortunately it works only for variables which don't have values:               ClearAll[a, b, c, d];     vars = {a, b, c, d};     a = 1;     Slider[Dynamic@#, {0, 1}] & /@ vars     Dynamic@vars      As you can see now the first slider is not working because Mma attempts to assign values to raw object `1` instead of `a`. Nevertheless simple               Slider[Dynamic@a, {0, 1}]     Dynamic@a      produces the desired result. So, what is the right way to do such things?


Given a Boolean representation of a system, how can the Reliability Function be displayed as symbolic algebra?

Can Mathematica 9 convert a Boolean representation of an RBD to its symbolic algebraic form? If I have a simple series Reliability Block Diagram made up of 2 components, c1 and c2 bexpr1=And[c1,c2] and the corresponding symbolic representation for the system would be RS1 = R1*R2 The system I am interested in is more complex and contains 7 components in a 4 path architecture: path1=And[c1,c2,c5,c7] path2=And[c1,c3,c5,c7] path3=And[c1,c3,c6,c7] path4=And[c1,c4,c6,c7] bexpr2=Or[path1,path2,path3,path4] How can the algebraic form of the reliability function be obtained for bexpr2 using Mathematica? The solution can be seen on page 5 of the PDF file at the following link http://www.reliasoft.com/newsletter/2Q2000/index.htm Thank you. Daniel, Thank you for your reply but I think it too is not correct and I' m not sure why. See below for a comparision of the two solution methods. Am I mis- interpreting something here ? Also, I agree that Eq.(3) is undersimplified. Perhaps the author intentionally left it in that form to help show how this problem can be solved manually (pencil & paper).               equation3 = (r1*r4*r6*r7) + (r1*r3*r6*r7) - (r1*r3*r4*r6*r7) + (r1*r2*r3*r4*     r5*r6*r7) + (r1*r3*r4*r5*r6*r7) - (r1*r2*r3*r4*r5*r6*r7) - (r1*r2*r3*r5*     r6*r7) - (r1*r3*r5*r6*r7) + (r1*r2*r3*r5*r6*r7) - (r1*r2*r4*r5*r6*     r7) - (r1*r3*r4*r5*r6*r7) + (r1*r2*r3*r4*r5*r6*r7) + (r1*r2*r5*r7) + (r1*     r3*r5*r7) - (r1*r2*r3*r5*r7) (* Eq.(3) ReliabilityEdge volume 1, Issue 1 *)      r1 r2 r5 r7 + r1 r3 r5 r7 - r1 r2 r3 r5 r7 + r1 r3 r6 r7 + r1 r4 r6 r7 - r1 r3 r4 r6 r7 - r1 r3 r5 r6 r7 - r1 r2 r4 r5 r6 r7 + r1 r2 r3 r4 r5 r6 r7 Original Problem               path1 = And[c1, c2, c5, c7];     path2 = And[c1, c3, c5, c7];     path3 = And[c1, c3, c6, c7];     path4 = And[c1, c4, c6, c7];     bexpr = Or[path1, path2, path3, path4]      (c1 && c2 && c5 && c7) || (c1 && c3 && c5 && c7) || (c1 && c3 && c6 && c7) || (c1 && c4 && c6 && c7) Ilian' s Solution (1)               dists = Table[{ToExpression["c" ~~ ToString[i]],         BernoulliDistribution[ToExpression["r" ~~ ToString[i]]]}, {i, 7}]       {{c1, BernoulliDistribution[r1]}, {c2, BernoulliDistribution[r2]}, {c3, BernoulliDistribution[r3]}, {c4, BernoulliDistribution[r4]}, {c5, BernoulliDistribution[r5]}, {c6, BernoulliDistribution[r6]}, {c7, BernoulliDistribution[r7]}}               survivalfunction1 = Expand[PDF[ReliabilityDistribution[bexpr, dists], 1]]      r1 r2 r5 r7 + r1 r3 r5 r7 - r1 r2 r3 r5 r7 + r1 r3 r6 r7 + r1 r4 r6 r7 - r1 r3 r4 r6 r7 - r1 r3 r5 r6 r7 - r1 r2 r4 r5 r6 r7 + r1 r2 r3 r4 r5 r6 r7               Simplify[survivalfunction1/       equation3] (* This show that the results are equivalent *)      1 Daniel' s Solution (2)               bexpr2 = BooleanConvert[bexpr, "ANF"]      (c1 && c2 && c5 && c7) [Xor] (c1 && c3 && c5 && c7) [Xor] (c1 && c3 && c6 && c7) [Xor] (c1 && c4 && c6 && c7) [Xor] (c1 && c2 && c3 && c5 && c7) [Xor] (c1 && c3 && c4 && c6 && c7) [Xor] (c1 && c3 && c5 && c6 && c7) [Xor] (c1 && c2 && c4 && c5 && c6 && c7) [Xor] (c1 && c2 && c3 && c4 && c5 && c6 && c7)               survivalfunction2temp = bexpr2 /. {And -> Times, Xor -> Plus}      c1 c2 c5 c7 + c1 c3 c5 c7 + c1 c2 c3 c5 c7 + c1 c3 c6 c7 + c1 c4 c6 c7 + c1 c3 c4 c6 c7 + c1 c3 c5 c6 c7 + c1 c2 c4 c5 c6 c7 + c1 c2 c3 c4 c5 c6 c7               survivalfunction2stringtemp = ToString[survivalfunction2temp]      "c1 c2 c5 c7 + c1 c3 c5 c7 + c1 c2 c3 c5 c7 + c1 c3 c6 c7 + c1 c4 c6 c7 + c1 \ c3 c4 c6 c7 + c1 c3 c5 c6 c7 + c1 c2 c4 c5 c6 c7 + c1 c2 c3 c4 c5 c6 c7"               survivalfunction2string =       StringReplace[survivalfunction2stringtemp, "c" -> "r"]      "r1 r2 r5 r7 + r1 r3 r5 r7 + r1 r2 r3 r5 r7 + r1 r3 r6 r7 + r1 r4 r6 r7 + r1 \ r3 r4 r6 r7 + r1 r3 r5 r6 r7 + r1 r2 r4 r5 r6 r7 + r1 r2 r3 r4 r5 r6 r7" survivalfunction2 = ToExpression[survivalfunction2string] r1 r2 r5 r7 + r1 r3 r5 r7 + r1 r2 r3 r5 r7 + r1 r3 r6 r7 + r1 r4 r6 r7 + r1 r3 r4 r6 r7 + r1 r3 r5 r6 r7 + r1 r2 r4 r5 r6 r7 + r1 r2 r3 r4 r5 r6 r7               Simplify[survivalfunction2/       equation3](* This show that the results are not equivalent *)      (r4 r6 + r2 (1 + r3) r5 (1 + r4 r6) + r3 (r5 + r6 + r4 r6 + r5 r6))/( r4 r6 + r2 (-1 + r3) r5 (-1 + r4 r6) + r3 (r5 + r6 - r4 r6 - r5 r6)) Let' s do a quick numerical sanity check.               r1 = r2 = r3 = r4 = r5 = r6 = r7 = 1;          survivalfunction1  (* This is the correct numerical value *)      1               survivalfunction2  (* This is numerically not possible, must be less than or      equal to one *)      9 Upon examination of survivalfunction2 I notice there are no negative signs in the algebra . . . not sure why. Also, I apologize here if everything is not formatted with all proper formatting, I'm still unfamiliar with much at StackExchange. * * * Clay, Thank you for the reply. I believe there may be a problem with your code as it produces a result that differs from Eq.(3) in the referenced PDF file. I tested the following code on the system architecture that I posted (associated with Eq.(3) ) and other simpler systems and it appears to accurately produce the algebra for the reliability function. dists = Table[{ToExpression["c" ~~ ToString[i]], BernoulliDistribution[ToExpression["r" ~~ ToString[i]]]}, {i, 7}]; Expand[PDF[ReliabilityDistribution[bexpr2, dists], 1]] The above code was produced by Ilian Gachevski in his posting at Wolfram Community. Thanks again for your inputs.


Mathematica as a report generator

I would like to use Mathematica as a kind of report generator. I'm working in a Mathematica notebook and I want to handle Mathematica like this: 1) I want to define one cell as a text cell. In this cell I want to integrate an expression (maybe as an inline cell) lets say a*b (a and b have been defined in an input cell before). 2) After evaluating this cell a*b should be replaced by (assume a=10 and b=5) 50, so that the resulting cell would look like this. > some text ....... 50.. some other text...... More general: I want to have the possibility to call a function or an expression (which has been defined before) in a text cell. The displayed result of the call should be updated, whenever I change the input values.


New list generated from the sum of elements taken from two lists

I have been using mathematica for a while, but I have problem wrapping my head around list manipulation functions. I would appreciate any suggestions. Here is what I want to do. ListV is a list of vectors:               ListV= {{x1,y1,z1},{x2,y2,z2},...}= {V1,V2,...}      ListU is also a list of vectors :               ListU={{a1,b1,c1},{a2,b2,c2},...}= {U1,U2,...}      ListU and ListV may have unequal lengths. I want to make a new list (ListUV) which would contain all the new positions generated by the sum of all vectors in ListU and ListV. Mathematically, that would be > ListUV= {V1+U1, V2+U1, ..., V2+U1, V2+U2, ... }. Thanks for any suggestions.


Asymptotic Rate of Growth

How can I calculate the Asymptotic Rate of growth of a function, for instance like: $X^3 - X^2 - X -1$ EDIT: For instance, as you can see in this graph, after the 1200 the function approximates to the limit. I want to if there is a easy way to calculate the rate of grow, after 1200 for instance. ![enter image description here](http://i.stack.imgur.com/FejWE.png) **Edit** I'm trying to find a generalized way in order to graphically find it for Fibonacci, Tribonacci, Tetranacci sequences


How to define logical expressions for platonic solids?

A more general question would be: How to find logical expressions for 3D-objects described by closed polygon sets? Finally a simple question is more prolific, therefore: ## How to define logical expressions for platonic solids ? I study this question for two days now, and I thought, I found an answer already:               PolyhedronData["Tetrahedron", "RegionFunction"]          (* out *)      Sqrt[2] + 4 Sqrt[3] #3 >= 0 &&        4 Sqrt[3] #3 <= 3 Sqrt[2] + 8 Sqrt[6] #1 &&        4 Sqrt[3] (Sqrt[2] #1 + #3) <= 3 Sqrt[2] (1 + 4 #2) &&        4 (Sqrt[6] #1 + 3 Sqrt[2] #2 + Sqrt[3] #3) <= 3 Sqrt[2] &      So far, so good. But then I discovered ...               PolyhedronData["Octahedron", "RegionFunction"]          Missing["NotAvailable"]      ok, this is not dramatic, I can define this myself. But doing so, I found out, it is better to give up those incomplete and specific `RegionFunction` definitions of Mathematica. This led me back to my question: How to define region functions for the 5 platonic solids in a better way? What are your ideas, your suggestions? At the moment I just want to concentrate on the platonics.               c = constant = Abs@1; (* -1 <= c <=  +1 *)      plotPoints = 100/2; (* half value while testing *)          RegionPlot3D[      And[x + y + z <= c, -x - y + z <= c,        x - y - z <= c, -x + y - z <= c, -x - y - z <= c, x + y - z <= c,        x - y + z <= c, -x + y + z <= c], {x, -c, c}, {y, -c, c}, {z, -c,        c}, PlotPoints -> plotPoints]      ![octahedronRegionFunction](http://i.stack.imgur.com/4MvgF.gif) The octahedron region function could be simplified to: (not sure, if it's really a good idea )               RegionPlot3D[      Abs@x + Abs@y + Abs@z <= c, {x, -c, +c}, {y, -c, +c}, {z, -c, +c},       PlotPoints -> plotPoints]      two region functions for tetrahedrons of interest               RegionPlot3D[      And[x + y - z <= c, +x - y + z <= c, -x + y + z <= c, -x - y - z <=         c], {x, -c, +c}, {y, -c, +c}, {z, -c, +c}, PlotPoints -> plotPoints]          RegionPlot3D[      And[x - y - z <= c, -x - y + z <= c, -x + y - z <= c, +x + y + z <=         c], {x, -c, +c}, {y, -c, +c}, {z, -c, +c}, PlotPoints -> plotPoints]      # What would be `nice` regionFunctions for `Dodecahedron` or `Icosahedron`, to complete the 5 platonics ? You may checkout yourself the definitions for `RegionFunction` done by Mathematica. Especially non-convex polyhedrons have no region functions defined. (code from Mathematica, modfied):               Manipulate[      Column[{PolyhedronData[g], PolyhedronData[g, p]}], {{g, "Octahedron",         "polyhedron" // Style[#, GrayLevel@.4, "Menu"] &},        PolyhedronData[All]}, {{p, "RegionFunction" (* init *),         "property" // Style[#, GrayLevel@.4, "Menu"] &},        Complement @@ PolyhedronData /@ {"Properties", "Classes"}}]


Why is AstronomicalData so slow?

I'm having trouble getting some pretty simple functions using `AstronomicalData` to perform at anywhere near the speed I need them to. For example, I have many places where I need to compute something like               ParametricPlot[      {AstronomicalData[        "Mercury", {"RightAscension",          DatePlus[Date[], d], {$GeoLocation[[1]] , $GeoLocation[[2]]}}], d},      {d, 0, 365}, AspectRatio -> 1/1.6]      but find that it takes far to long for even this simple fragment to run. I want to put several such fragments (e.g. one for each of several astronomical objects) into a single figure, and even to dynamically change the parameters for the figure (such as location and date) inside a `Manipulate`, which would be prohibitively slow given the times I'm seeing with even the simple fragment above. Why is `AstronomicalData` so slow? Is there something I can do to speed it up so I can use it as I hope to?


How do I get rid of a "jump" in my plot?

How can I prevent plotting functions from "connecting" _inside_ a plot points that should "wrap around" _outside_ the plot? For example, how do I eliminate the horizontal lines running across the following `ParametricPlot`? ![enter image description here](http://i.stack.imgur.com/Wn2tr.png) In this figure, the paths that reach the right hand end of the graph at 24 should continue at 0 (these are hours, so 24=0) without passing backwards across the figure. * * *               Show[      ParametricPlot[       {AstronomicalData[         "Mars", {"RightAscension",           DatePlus[Date[], d], {$GeoLocation[[1]] , $GeoLocation[[2]]}}], d},       {d, 0, 365}, AspectRatio -> 1/1.6, PlotStyle -> Blue],      ParametricPlot[       {AstronomicalData[         "Mercury", {"RightAscension",           DatePlus[Date[], d], {$GeoLocation[[1]] , $GeoLocation[[2]]}}], d},       {d, 0, 365}, AspectRatio -> 1/1.6, PlotStyle -> Red],      ParametricPlot[       {AstronomicalData[         "Jupiter", {"RightAscension",           DatePlus[Date[], d], {$GeoLocation[[1]] , $GeoLocation[[2]]}}], d},       {d, 0, 365}, AspectRatio -> 1/1.6, PlotStyle -> Green]      ]      * * * FWIW, the (almost) final result, with help from SE: ![enter image description here](http://i.stack.imgur.com/5jAcd.png)


Nested Derivative

These two expressions are mathematically the same, but when substituting with the same rule, yield different results. What is happening?               Derivative[1][Derivative[1][x][t]][t] == 5 t + 3 x[t] /.        {x -> Function[{t}, 1/3 (-5 t + Derivative[1][Derivative[1][x][t]][t])]}          D[x[t], t, t] == 5 t + 3 x[t] /.        {x -> Function[{t}, 1/3 (-5 t + Derivative[1][Derivative[1][x][t]][t])]}


How can I get Mathematica to recognize equality of symbolic matrix expressions?

I have two matrix expressions:               X.Transpose[T].Transpose[X]       and               X.T.Transpose[X]       I want _Mathematica_ to recognize that these expressions are equal. Is it possible to do that?


Importing Text file and removing columns

I have a file that has 7 column but i only want to import two column from it, that is 1st and 3rd column from the file. How can i do that and this is the list for example:               {1.1033,6.1371,46471,0,1,,0}     {1.1064,6.2101,46504,0,1,,0}     {1.1371,0,46537,0,1,Z,0}     {1.1598,0.0731,46571,0,1,,0}     {1.1946,0.1461,46604,0,1,,0}     {1.1871,0.2192,46638,0,1,,0}     {1.217,0.2922,46671,0,1,,0}     {1.234,0.3653,46704,0,1,,0}     {1.2541,0.4384,46738,0,1,,0}     {1.2509,0.5114,46771,0,1,,0}     {1.2244,0.5845,46805,0,1,,0}     {1.2009,0.6575,46838,0,1,,0}     {1.1916,0.7306,46871,0,1,,0}     {1.2287,0.8037,46905,0,1,,0}     {1.2406,0.8767,46938,0,1,,0}     {1.2517,0.9498,46971,0,1,,0}     {1.2385,1.0228,47005,0,1,,0}     {1.2545,1.0959,47038,0,1,,0}


Savitzky-golay filter

How to use Savitzky-golay filter on csv file? I have file.csv in this format:               0.1,1.6,2.8,0     0.2,1.2,2.3,1     0.7,1.5,2.4,2     0.6,1.2,2.7,3     0.4,1.4,2.9,4     0.3,1.3,2.5,5      description               number1,number2,number3,id      I need to load CSV, use savitzky-golay filter on numbers1, numbers2 and numbers3 seperatly. And then save it into csv again. Can you help? EDIT: I've already tried to parse csv, try filter from example and plot it:               table = Take[Import["file.csv"]];     first = table[[All,1]];     c = SavitzkyGolayCoefficients[20, 20, 4];     c = N[c];     filterOutput = SavitzkyGolayFilter[test, c];     ListLinePlot[{filterOutput, first}]      How to save it to CSV again in same format. What does `SavitzkyGolayCoefficient` menas?


Searching for roots of complex function

I'm searching for roots of complex function $$ 2\imath q \ln(-2\imath k)+\imath\pi-2\imath \Im(\ln(\Gamma(1+2\imath q)))+\ln(\frac{\Gamma(1+\imath q-\imath q x/k)}{\Gamma(1-\imath q-\imath q x/k)})+\ln(\frac{\sqrt{-x+1}-\sqrt{-x-1}}{\sqrt{-x+1}+\sqrt{-x-1}}) $$ where $k=\sqrt{(-x+1)(-x-1)}$; $x$ is complex number with $\Re(x)<-1$ and $\Im(x)>0$ and $q$ is real and positive parameter. If a change a little bit starting values of $x$ in `FindRoot` function, result changes extremely. Please, can you tell me how to fix the result and what is the better way to find complex roots of such equations. Code:               2 I*q*Log[-2*I*Sqrt[(-x + 1) (-x - 1)]] + I*\[Pi] -  2*I*Arg[     Gamma[1 + 2*I*q]] + Log[Gamma[1 + I*q - I*q*x/Sqrt[(-x + 1) (-x - 1)]]] -      Log[Gamma[1 - I*q - I*q*x/Sqrt[(-x + 1) (-x - 1)]]] + Log[Sqrt[-x + 1] -      Sqrt[-x - 1]] - Log[Sqrt[-x + 1] + Sqrt[-x - 1]]


Getting long complex-valued integrals when simpler real-valued expressions exist

I have a long list of real-valued functions I'd like to integrate symbolically. For many of them, Mathematica gives me results with long complex-valued expressions involving weird functions such as `EllipticF`, even though I know that if I first manually apply a simple substitution such as $u=\sin\theta$ or $u=\cos\theta$, I will get a simple elementary real-valued expression. As an example, I want to integrate $\arcsin(a/\sin\theta)\cdot\cos\theta$ for some constant $a$ which satisfies $0<a<\sin\theta$ throughout the integration domain. Now, `Integrate[ArcSin[a/ Sin[theta]] Cos[theta], theta, Assumptions -> 0<a<Sin[theta]]` gives the result $$\sin (\theta ) \sin ^{-1}(a \csc (\theta ))+\frac{i a \cot \left(\frac{\theta }{2}\right) \sqrt{1-\frac{a^2 \tan ^2\left(\frac{\theta }{2}\right)}{-a^2+2 \sqrt{1-a^2}+2}} \sqrt{\frac{a^2 \tan ^2\left(\frac{\theta }{2}\right)}{a^2+2 \sqrt{1-a^2}-2}+1} \left(F\left(i \sinh ^{-1}\left(\sqrt{\frac{a^2}{a^2+2 \sqrt{1-a^2}-2}} \tan \left(\frac{\theta }{2}\right)\right)|-\frac{a^2+2 \sqrt{1-a^2}-2}{-a^2+2 \sqrt{1-a^2}+2}\right)-2 \Pi \left(\frac{a^2+2 \sqrt{1-a^2}-2}{a^2};i \sinh ^{-1}\left(\sqrt{\frac{a^2}{a^2+2 \sqrt{1-a^2}-2}} \tan \left(\frac{\theta }{2}\right)\right)|-\frac{a^2+2 \sqrt{1-a^2}-2}{-a^2+2 \sqrt{1-a^2}+2}\right)\right)}{\sqrt{\frac{a^2}{a^2+2 \sqrt{1-a^2}-2}} \sqrt{\frac{2 a^2+\cos (2 \theta )-1}{\cos (2 \theta )-1}}},$$ where $F=$ `EllipticF` and $\Pi=$ `EllipticPi`, but if I first perform the subsitution $u=\sin\theta$ and then evalute `Integrate[ArcSin[a/u] , u] /. u -> Sin[theta]`, I get the much simpler $$\frac{a \csc (\theta ) \sqrt{\sin ^2(\theta )-a^2} \log \left(\sqrt{\sin ^2(\theta )-a^2}+\sin (\theta )\right)}{\sqrt{1-a^2 \csc ^2(\theta )}}+\sin (\theta ) \sin ^{-1}(a \csc (\theta )).$$ How do I make Mathematica give me the second result without explicitly performing the variable substitution? In my case, all my functions are of the form $\cos\theta\cdot f(\sin\theta)$ or of the form $\sin\theta \cdot f(\sin^2(\theta))$ or of a form which does not need any special substitution (but my list of functions is too long for me to group them according to this). Can I encourage Mathematica to try the substitutions $u=\cos\theta$ and $u=\sin\theta$ first, or can I convince Mathematica that everything is real- valued and not to worry about subtleties concerning complex-valued functions?


How to code a simple audio equalizer?

I would like to code a simple Manipulate-based equalizer to make bass and treble adjustments in wav-file, but I haven't found any clues in documentation. Wiki says that I have to deal with linear filters, but I have no idea what is it. Is it a very advanced stuff?


Finding the position of a specific value in a list

Is it possible to easily find the position of a specific value in a list? For example, if the list is `{{x1,y1},{x2,y2},...,{xn,yn}}` I would like to know the position of `y = 123456.78`. I would prefer to not use `If`.


Creating a graph with variable size of vertices and variable thickness of edges

I'm trying to create a graph to represent transitions between different states of a system. I would like to represent the time the systems spent in a state with the size of the vertex and the frequency of transition between two states with the thickness of the edge connecting the two vertices. In short I need to control the size of vertices and the thickness of edges. Now that I grasp the difference between Graph and GraphPlot a bit better, I wanted to implement this using the newer `Graph` functunality, specifically `VertexSize` and `EdgeStyle`. Here is my clumsy attempt:               trans = Uncompress@        "1:eJyVV01vwjAMRfu47U/sv3RKKc2KGsahxw2YOE0aXPff17RJSZD8/HIBga3Efn5+\     dl4/f/rT32q1ujyNH+35cj09+F8v40d1/j1+XY+\     Ht8P30T2Pf9ihbyvn7Y0T3GbjzZtyM5LbYmcP9Els++FdTWJy7EwrOEYzTjbeRkHyODnvB\     adgnb7d8KHi4e3OgBudmb5sB3xsV1CBOTLpymCdv1sp/\     mBlzhq9tJrfqolRC9aSDNSzGPwxFv5f05GAldDVoJKbrgBWJsnCIuFMB/\     28JVXNMR7IQsfVvZSTCD07V79Z78Clo1VLIS+YVn5/2H67Q3h4M83wZr2B4W/\     oCmhaFDXSWysUWcVpH4sElyUTFYsEGxnPRl7nlRgTFoFBu0xGjuDToRLAs5GeeDWqes22H\     ORPLDl/FENXLXCmuVWQanrkBwmT88uGjhh8JgIyYRI91EW4aBoqtOIbg60RxD+IAGjuZC+\     QRSeXfC2qkhGor6gqD60WfdoZTOy8SGu9iONKFEJeVO7eELQGMvOD0UDYaXHN5a6DT5Zlv\     GuYlu2TmhIyD726bP5gSnswmEttWR9puG1wH6WE1VuSBI2sVNA6cfxlK6JIx7utFDE7vI5\     lyAL+Kv09FopgpA9t+\     cIcCcjZMXgYV4YWrHd86DFyR2xpTh012aCEY8sSoy3sX3A0OHUHTjWYWgR8fv/wd/kB";     l = VertexList[Graph[trans]];     (*Weigths for vertices*)     r = RandomReal[{0.5, 1}, Length[l]];     vs = Transpose@{l, r} /. List[a_, b_] -> Rule[a, b];     (*Adjust font size*)     vls = Transpose@{l, r} /.         List[a_, b_] -> Rule[a, Directive[Black, Bold, 20*b]];     (*Weigths for line thicknes*)     rr = RandomReal[{0.1, 1}, Length[DeleteDuplicates@trans]]/100;     es = (First@# -> Directive[Thickness[Last@#], Opacity[.5]]) & /@         Transpose@{DeleteDuplicates@trans, rr};     g = Graph[DeleteDuplicates@trans,        VertexLabels -> Placed["Name", Center],        VertexShapeFunction -> "Capsule", VertexSize -> vs,        VertexLabelStyle -> vls, EdgeStyle -> es,        EdgeShapeFunction ->         GraphElementData["ShortUnfilledArrow", "ArrowSize" -> 0.03]]      But the result is useless (the text is not readable and it's not clear from where to where the arrows are going): ![Resulting graph](http://i.stack.imgur.com/TdN55.png) **How can I either fix this graph so that it's readable or implement variable vertex sizes and variable edge thickens using`GraphLayout`?** **EDIT** @kguler's comment helps. so using:               esf = Function[         a, (First@            a -> ({Arrowheads[{{.03, 1}}],               Arrow[#1, {.10 + 6 Last@a, .15}]} &))] /@         Transpose@{DeleteDuplicates@trans, rr};     g = Graph[DeleteDuplicates@trans,        VertexLabels -> Placed["Name", Center], VertexSize -> vs,        VertexLabelStyle -> vls, EdgeStyle -> es, EdgeShapeFunction -> esf(*,       EdgeShapeFunction->GraphElementData["ShortUnfilledArrow",       "ArrowSize"->0.03]*)]      I get ![Mathematica graphics](http://i.stack.imgur.com/HQyLd.png), which is almost usable. Is there perhaps a way to draw vertices on top of the edges?


How can parts of a list of lists be printed to the nb, at regular interval positions?

I have a large list of lists with the dimensions {441,21,21,3} of which I need to print the x,y,z data from every 21st part up to 441. How can I print the 21x21x3 piece of every 21st part of this list? Here's what I've tried below that did not do the job. Also is there an more memory efficient way to perform this task?:               Table[Print["mylist parts", mylist[[i++21]]], {i, 1, 441}];


Why do I get the error: "The specified setting for the option FEFloatIterator cannot be used."?

"The specified setting for the option FEFloatIterator cannot be used." This an error I am getting in a sizeable interface, containing 138 declarations in an outer `DynamicModule` with one inner `Manipulate`. * * * This undocumented error appeared as a pop-up on a red-boxed control (in this case, an iterator [but not a float iterator!]) where the setting for the control depended on an initialization section which timed out because of a non-terminating computation.


Compute integral symbolically

I want to compute the following integral:                   Ro = 8         bo = -2.68*Pi/180         lo = 1.50*Pi/180         r = Sqrt[Ro^2 + (Dl*Cos[bo])^2 - 2 Ro*Dl^Cos[bo]*Cos[lo]]         z = Dl*Sin[bo]         sa = Sqrt[(0.6^2*r^2 + z^2)/0.4^2]         sb = ((r/0.9)^4 + (z/0.4^2)^4)^(1/4)         rhoBulge = rhoBB*(sa^(-1.85)*Exp[-sa] + Exp[-sb^2/2])         Integrate[rhoBulge*Dl*(1 - Dl/Ds), {Dl, 0, Ds}]      But I just obtain the integral rewritten and no solution. I'm new in mathematica, so any tip or help would be awesome. Thanks!


How can I overload autocompletion to work with full contexts?

I would like for the autocomplete feature to search through contexts, for example if I have a symbol named A`B`C`MyFunction, when I type A` and press "cmd + shift + k" it will complete it. _Edit_ To be clear, I don't want to have to type the path because it's usually very long, and I don't want to have to type the function name again, even if the path itself gets auto completed. I want the following: If I have these functions:               Very`Long`Context`For`My`Function1     Very`Long`Context`For`My`Function2     ...      I want to be able to type Very` and then press CMD+Shift+k, to get a dropdown menu saying exactly               Very`Long`Context`For`My`Function1     Very`Long`Context`For`My`Function2     ...


Moving two Spheres in the Opposite Direction

We know that we can achieve to a box contained two spheres by the code:               Graphics3D[Table[Sphere[{i, Mod[i^2, 10], Mod[i^3, 12]}], {i, 2}]]      ![enter image description here](http://i.stack.imgur.com/kVJzR.png) How can the left sphere move in a vector path to the right of the box and the right one move to the left of the box simultaneously?


Ndsolve, transmission line transients

I am trying to use `NDSolve` to analyze transients in transmission lines. I started with this simple one:               s = NDSolve[{∂_(t,t) u[t,x] == 2*∂_(x,x) u[t,x], u[0,x] == 1,                    u^((1,0))[0,x] == 0, u[t,0] == Sin[t]},                  u, { t, 0, 40}, { x, -10, 10}];      So: voltage is initially constant (at `t = 0`). One end of the line is shorted. But, this is not approved. _Mathematica_ says: > >     NDSolve::ndnco: The number of constraints (1) (initial conditions) is > not equal to >     the total differential order of the system plus the number of discrete > variables (2). >> >   How could `NDSolve` be used for transmission line transient analysis?


How can I export specific data into different pages in .PDF format?

I have made various `Grid`-s and arranged them column-wise in another `Grid`. All `Grids` are working fine and I exported that final `Grid` into PDF format. The entire `Grid` appeared in a single page after exporting, but I want to `Export` some `Grid`-s to one page and remaining ``Grid`-s to another page. I tried the following code but it doesn't work:               grid1 = Grid[{{Style["Life Alerts", Bold, 20], SpanFromLeft,       SpanFromLeft}, {Style["Alert", Bold, 15], Style["<>", Bold, 15],       Style["%Life", Bold, 15],       Style["OnDay", Bold, 15]}, {Style["L1", Bold, 15],       Style["<", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}, {Style["L2", Bold, 15],       Style[">", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}, {Style["L3", Bold, 15],       Style[">", Bold, 15], Style["90", Bold, 15],       Style["0.35", Bold, 15]}}, Alignment -> {{Left}, Center},        Background -> {None, {Yellow}}, Frame -> True,        FrameStyle -> Directive[Thickness[4], Black], Spacings -> {1, 1},          Dividers -> {{}, {True, True, True}}];      ![Mathematica graphics](http://i.stack.imgur.com/co1BZ.png)                 (*Exporting code*)       Export[SystemDialogInput["FileSave",".Pdf"], (Grid[{{grid1}, {grid1}}])]      Can anybody help me?


Change syntax from other programs to mathematica syntax

Is there a good way to transform syntax from other computer algebra systems or from latex to mathematica syntax?


which is better, using Assert[] or manual checks on arguments and other computations?

I never used Asserts in Mathematica, but trying to see what advantage they have over just argument check and additional definitions of the function to capture unwanted input. For example, which one of these 2 would you think is better?               ClearAll[f]     f[x_] := (Assert[x > 0]; Sqrt[x])     On[Assert];     f[2.]     f[-2.]      The last call above generated in the console a beep and a message:               Assert::asrtf: Assertion -2.>0 failed. >>      But I could also just write               ClearAll[f];     f[x_] := Sqrt[x] /; x > 0          f[2.]     f[-2.]      and the second call will return unevaluated               f[-2.]      and If I want a beep, I could always do something like               ClearAll[f];     f[x_] := Sqrt[x] /; x > 0     f[x_] := Throw["f[x] not supported for negative values"]      or something along these lines. Since asserts seem to be used to assert that input to a function is within the ranges supported by the function, what benefit they have over the other method shown above? Or should one look into using Asserts inside the function itself, i.e. in the middle of a computation, to check that intermediate results are within expected ranges? But also then, I would use a simple `If` check instead, and return an error code to the caller (which I prefer) or use Throw. An example from help shows this:               myFun[x_] :=      Block[{y},       y = x^2;       Assert[y > 5];       Sin[y]       ]      So that the call `On[Assert]; myFun[1.0]` generated `Assert::asrtf: Assertion y>5 failed`. But I can write instead               myFun[x_] :=      Block[{y},       y = x^2;       If[y <= 5, Throw["y<=5"]];       Sin[y]       ]      and now the call `myFun[1.0]` will also generate a message and a beep as well from the same place. I guess I am looking for when in Mathematica the use of Assert would be better and recommended over these other ways of checking. My only guess now is that Assertion code can be disabled and enabled more easily, and this can have an effect on run time. i.e. after testing the code, I can disable Asserts from the final version, and it should run faster, since all these checks are not being done at run time any more. But with the manual checking as above, that code remains there all the time. thanks


Finding a best fit curve and plotting it

I have a list as shown below:               m01 = {{250, 0.083121}, {200, 0.0888446}, {150, 0.0992422}, {100, 0.121567}, {50, 0.186825}}      I'm new to Mathematica, and would like to know how can I do these jobs: 1- How can I can plot it with `ListPlot` and make minimal formations on it? 2- How do I fit a curve on it? Witch command I use? How to put the curve plot together with the points?


Exporting a Large Multidimensional Sparse Array

I'm trying to export a sparse array from Mathematica to share with collaborators who primarily use Matlab. The sparse array in question is 4 dimensional, (72 x 93 x 94 x 172) with ~4M non-zero elements. I've tried a number of possibilites but haven't found a working format. Is there a cross-program compatible format for large multidimensional (sparse)matrices? The data is easily exported in the native Mathematica `WDX` and `MX` formats, except, as far as I can tell these can't be read by any other programs. Based on this question/answer (support-for-compressed-sparse-column-sparse- matrix-representation), I've tried the `HarwellBoeing` `RSA` format.               test = SparseArray[RandomInteger[{1, 100}, {10^6, 4}] -> RandomInteger[10, 10^6]]     Export["text.rsa", test]      This returns: `Export::rank:` The sparse array `SparseArray[<<1>>]` to be exported in `HarwellBoeing` format is not a matrix of rank 2. I've also tried the `MatrixMarket` `MTX` format:               Export["text.mtx", test]      This gives a different error: `Export::type:` `SparseArray[<<1>>]` cannot be exported to the `MatrixMarket` format. The matlab format, the most obvious choice, also doesn't work:               Export["text.mat", test]      Another new error this time: `Export::type:` `{<<1>>}` cannot be exported to the `MAT` format. However, the Matlab `MAT` format appears to support 3 dimensional sparse arrays, in this case we can export each 3D array making up the 4D array and it works, although when imported into matlab each file is actually 100 2D arrays, so the 3D actually support isn't implemented correctly and does not give a matlab 3D matrix.               MapThread[Export, {# <> ".mat" & /@ ToString /@ Range[100], test}]


How to change alignment of Grid/Matrix created using menu (Insert->Matrix/Table->New)

When I create a `Grid` using the menu, as follows: ![Mathematica graphics](http://i.stack.imgur.com/q9XiX.png) and then start to add data, I'd like to make the alignment to be left and not center which is the default ![Mathematica graphics](http://i.stack.imgur.com/E4U0F.png) There is no option to change this when creating new Grid as one can see: ![Mathematica graphics](http://i.stack.imgur.com/1s20B.png) If I try to change the alignment in code by making new variable like this                  data2 = Grid[data, Frame -> All, Alignment -> Left]      and then use `data2` from now on, I find it is no longer possible to add rows/columns to data2. Question: How to control alignment of Grid/Matrix when it is created using the menu? Is there a way to do that afterwords while keeping the functionality of adding rows/column? I am using V9 on windows 7. **update** adding a row, after making new copy with correct alignment, does actually work. The cursor has to be on the row itself, and not outside, and not by selecting the whole grid. This screen shot shows the correct way. Again, make sure the cursor is inside the grid, at the row where the new row needs to be inserted. ![Mathematica graphics](http://i.stack.imgur.com/AKWWK.png) **Update 12/27/12** Just wanted to point out the difference between making a Grid using the menu, vs. the command Grid. When using the menu to create a Grid, the data added to the Grid can be access as a matrix, directly. But when creating the Grid in code using the command itself, the data is wrapped by the Grid, and one needs an extra dimension to access the data. This picture explains: ![Mathematica graphics](http://i.stack.imgur.com/k6aKm.png) So, this shows that it would have been better to be able to make the Grid using the menu. But becuase it is missing the alignment option, one has to use the command itself, but then one must remember to add the extra dimension now each time.


Computing 10-dimensional volume of a 9-sphere

I'm trying to compute 10-dimensional volume of a 9-sphere with radius r using Monte Carlo.               r = 1000     F = Piecewise[{{1, Sum[x[i]^2, {i, 10}] <= r}}, 0]     NIntegrate[F, {x[1], -1000, 1000}, {x[2], -1000, 1000}, {x[3], -1000, 1000}, {x[4], -1000, 1000}, {x[5], -1000, 1000}, {x[6], -1000, 1000}, {x[7], -1000, 1000}, {x[8], -1000, 1000}, {x[9], -1000, 1000}, {x[10], -1000, 1000}, Method -> {"MonteCarloRule", "Points" -> 1000000}]      But the results always off by the factor of 1e(P/2), where 1eP = The correct factoring. I'm wondering where did I do wrong? ![enter image description here](http://i.stack.imgur.com/Ijr0V.png) Also I want to clean up the code               NIntegrate[F, {x[1], -1000, 1000}, {x[2], -1000, 1000}, {x[3], -1000, 1000}, {x[4], -1000, 1000}, {x[5], -1000, 1000}, {x[6], -1000, 1000}, {x[7], -1000, 1000}, {x[8], -1000, 1000}, {x[9], -1000, 1000}, {x[10], -1000, 1000}, Method -> {"MonteCarloRule", "Points" -> 1000000}]      I try to do this               NIntegrate[F, Table[{x[i], -r, r}, {i, 10}], Method -> {"MonteCarloRule", "Points" -> 1000000}]      But it doesn't work as Table[] gives list. I need to make it into sequence somehow. But trying to apply Sequence[] to Table[] still give me a list. Is there anyway to get around this?


How to create an executable notebook in Mac OS X

All, I am looking for help to create a notebook to be executed via terminal in MAC OSX. The notebook uses the front end. This is what I have so far               #!/Applications/Mathematica.app/Contents/MacOS/Mathematica -script          UsingFrontEnd[NotebookEvaluate["/Users/MyFolder/MyFile.nb"]]      When I run the script in snow leopard Mathematica opens a new notebook containing the above code displayed in quotes, when run in lion I get a window saying the notebook cannot be opened. I will be very grateful to anyone who can point me in the right direction as to how to proceed. Many thanks


How to plot stability region of Fourier analysis

Stability limits for Runge–Kutta methods in the complex ΩΔt-plane are needed to be plotted like this: ![enter image description here](http://i.stack.imgur.com/EQ5hC.png) For example, let `P=1+z` where `z` is complex. Under the stability condition `|P|<=1`, the plot line should be that of RK-1 in the given plot. Similarly, if `P=1+z+1/2*z^2`, then when `|P|<=1` the plotting line is the corresponding of RK-2. I am trying to code `P=1+z` like this:               Clear[yRe, yIm, w, NP, k, ϕ]     a = 1;     zexp = a*(Cos[ϕ] + I*Sin[ϕ]) + 1     xp[ϕ_Real, a_Real] = Abs@zexp*Cos[ϕ];     yp[ϕ_Real, a_Real] = Abs@zexp*Sin[ϕ]     NP = 30;     For[k = 1, k <= NP, k++,      w = 2.*Pi*(k - 1)/NP;      yRe[k] = xp[ϕ, a] /. {ϕ -> w};      yIm[k] = yp[ϕ, a] /. {ϕ -> w};      ]     yRe = Table[yRe[k], {k, 1, NP}];     yIm = Table[yIm[k], {k, 1, NP}];     pointsz = Transpose[{yRe, yIm }];          pic1 = ListPlot[pointsz, AxesOrigin -> {0, 0},        PlotStyle -> Directive[Thick, Black, PointSize[Large]],        AxesStyle -> Directive[Black, 15],        AxesLabel -> {"Re(ωΔt)",          "Im(ωΔt)"}, AspectRatio -> Automatic]      The resulted plot as following is not correct. The truth is like RK-1 in the above figure. ![enter image description here](http://i.stack.imgur.com/Qyrfs.png) How can i get the correct plot lines of RK-1 and RK-2 using Mathematica? Thanks.


Degree Symbol missing in PolarPlot when exported to PDF

I am trying to produce a polar plot. The axis should be in degrees. While no error occurs, the `pdf` export isn't working properly. Instead of the degree symbol I get a square (while using `acrobat`) and a 'D' when I use `nitro`. The code I am using is               r = 2.81794*10^(-15);     m = 511;     a1 = 1/m;     a2 = 5.9/m;     ds1[theta_] :=       10*r^2*(1/(1 + a1*(1 - Cos[theta])))*((1 + Cos[theta]*Cos[theta])/       2)*(1 + (a1^2*(1 - Cos[theta])^2)/((1 +           Cos[theta]*Cos[theta])*(1 + a1*(1 - Cos[theta]))))     ds2[theta_] :=       10*r^2*(1/(1 + a2*(1 - Cos[theta])))*((1 + Cos[theta]*Cos[theta])/     2)*(1 + (a2^2*(1 - Cos[theta])^2)/((1 +           Cos[theta]*Cos[theta])*(1 + a2*(1 - Cos[theta]))))          Needs["PlotLegends`"]     PolarPlot[{ds1[theta], ds2[theta]}, {theta, -π, π}, PolarAxes -> True,        PolarGridLines -> True, PolarTicks -> {"Degrees", Automatic},        PlotRange -> Automatic,        PlotLabel ->        Style[Framed["Klein-Nishina Compton Cross Section"], 20, Red,         Background -> Lighter[Yellow]],         PlotLegend -> {"1keV", "5.9keV"}, LegendShadow -> {.01, -.01}, LegendTextSpace -> 5,        LegendBackground -> LightPurple, LegendSize -> {0.5, 0.5},         Background -> LightYellow]            Export["Klein.pdf", %]      ![Mathematica graphics](http://i.imgur.com/7K2I9.png) I also tried to export it in other formats, which is working fine, however I need `.pdf` format...


How to calculate the unknown quantity in an infinite series?

![enter image description here](http://i.stack.imgur.com/Jhx7L.jpg) ![enter image description here](http://i.stack.imgur.com/KnCsn.jpg) I'd like to calculate x value in this equation. Basically, I tried to 2 types of method which are FindRoot and NSolve. But, I have failed the calculation caused by these errors up to now. If there is anyone who knows this problems, plz let me know what I should do first! Thank you for your cooperation.


Quickly display a color graphically

When manipulating colors, the output is shown as a textual expression like `Hue[1/5]`, `RGBColor[2/3, 1, 1/3]`, `GrayLevel[3/5]`. It can be hard to visualize what color these represent. How can you quickly display the color itself on screen?


How can I use nested conditionals inside my functions?

I'm a big fan of using conditionals inside my functions to deal with cases, that is, to pattern match in stages and possibly leave a function unevaluated.               In[1]:= f[x_] :=      (        (          (            True            ) /; EvenQ[x]          ) /; x > 2        ) /; x < 10          In[2]:= f[4]     Out[2]= True      However I don't fully understand the extent to which I can do this. For example, mixing If statements in doesn't work:               In[3]:=          h[x_] :=          (            If[x > 2,             (               True               ) /; EvenQ[x]             ,             False             ]            ) /; x < 10              In[4]:= h[4]         Out[4]= True /; EvenQ[4]      A clarification on both the limitation and merits of this style of coding would be helpful. I find this style of programming to be handy for a number of reasons, but a primary reason is the ease of defining a blanket default case and letting the pattern matching do its work, e.g. `f[_] := $Failed`.


Implicit Equality and RegionPlot

I have the following problem: I would like to do a RegionPlot like               RegionPlot[F[x,z,y]<1,{x,0,1},{y,0,1}]      The problem is that the variable z is an implicit (and not reducable via e.g. Solve, meaning too non-linear) but continuous function of x and y, for example               G[x,y,z]==0.      The functions F and G are well-defined. Would anyone know how to solve this issue in a general way?


How to compile the code for generate Pythagorean_triple?

I am finding Pythagorean_triple, it worked slowly. I tried to compile, but it gives some warnings. I also use "Case" or "Do" ,both of them failed.I'm sure my CCompiler has been set correctly. How can I compile the following code?               With[{m = 200},      Select[Flatten[Table[{x, y, z}, {x, m}, {y, x, m}, {z, y, m}],         2], (#1^2 + #2^2 == #3^2 &) @@ # &]      ]


One-column table not properly displayed by TableForm

I want a table with a single column of data, and with headings along both the rows and the column. One might expect it to work like this:               TableForm[{"one", "two", "three"},       TableHeadings -> {{"$10MM", "$20MM", "$30MM"}, {"col"}}]      But this does not work; it displays the data and the row labels correctly, but it does not label the column. What am I missing?


Is it possible to produce "tilt-shift" effect in Mathematica?

I attempted to produce a kind of miniature faking look from a street scene photo. I tried to shift the perspective lines close to parallel to each other to obtain such effect. However, the result looks ugly. Is there a better way to do it? This is the original photo. ![This is the original photo.](http://i.stack.imgur.com/AkqJW.jpg) This is the result from the code below. ![enter image description here](http://i.stack.imgur.com/R8ObL.jpg)               im = Import["http://i.stack.imgur.com/AkqJW.jpg"]          pts = {{0, 0}, {0, 1}, {0.25, 0},  {0.25, 1}, {0.5, 0}, {0.5,1}, {1, 0}, {1, 1} };     imgcol = BSplineFunction[ImageData[im ], SplineDegree -> 1];     Manipulate[       Module[{f},        f = BSplineFunction[Partition[pts, 2], SplineDegree -> 1,          Method -> {"Extrapolation" -> "Clamp"}];             ParametricPlot[        f[u, v], {u, 0, 1}, {v, 0, 1},        ColorFunction -> (imgcol[1 - #4, #3] &),        MaxRecursion -> 0,        PlotPoints -> ControlActive[20, 100],        Mesh -> None,         Epilog -> { Gray, Opacity[.7], Line[Partition[pts, 2]]},         ImageSize -> {300, 300},        PlotRange -> {{0, 1}, {0, 1}},        PlotRangePadding -> Scaled[0.01],        FrameTicks -> None        ]        ],      {{pts, {{0, 0}, {0, 1}, {0.25, 0},  {0.25, 1}, {0.5, 0},  {0.5, 1},         {1, 0}, {1, 1} }}, {0, 0}, {1, 1}, Locator },      TrackedSymbols :> {pts}      ]


How to simplify the integration result of the following program?

In the following program, the `fec[x]` is a function depending on $x$ while `q3[t]` and `q5[t]` are functions depending on $t$. Now, I want to use `Integrate` for the polynomial which is composed by `fec[x]`, `q3[t]`, `q5[t]`, et al. for the independent variable $x$. I believe the result `c` is zero, but I don' t know why the software could not convert it to zero automatically. Could you help me?               inta = Cos[q3[t]] fec[x] q5[t]^2 D[q3[t], t]^2;     a = Integrate[inta, {x, 0, L1}];          b1 = Cos[q3[t]] q5[t]^2 D[q3[t], t]^2;     b = Integrate[fec[x], {x, 0, L1}] b1;          c = a - b;


Rendering of a HighlightGraph in a Manipulate content pane distorted by changing the highlighted edge

A `HighlightGraph` inside a `Manipulate` initially displays correct however after approximately 2 seconds, the layout changes and the text, links and nodes get displaced. It appears to be caused by the Manipulate cell, after the initially correct display - is again being evaluated after two seconds (judging by the appearance of the darkening of the evaluation indicator right side of the cell). Please find a simplified example and see how components "jump" away from the initial, correct placement. The real problem I experience is on a larger graph and the effect is substantially more dramatic, as nodes are displaced in a manner that the graph becomes illegible. Despite the simplicity of this mock-up, It does show the reevaluation (if that is what it is) after two seconds and the displacement of nodes and text. What is causing this and how can I avoid it, preferable without changing what I am trying to display? To my knowledge, it is only happening when I combine a graph with self-loops and Vertex labelling inside a `Manipulate` wrapped around `HighlightGraph`.               f = {1 <-> 5, 5 <-> 6, 5 <-> 5, 6 <-> 4, 4 <-> 5, 5 <-> 3, 3 <-> 6,           6 <-> 2, 2 <-> 4, 4 <-> 1, 1 <-> 3, 3 <-> 2, 2 <-> 1};     h = Graph[f, VertexLabels -> description, ImagePadding -> 10];     Manipulate[HighlightGraph[h, f[[i]]], {i, 1, 12, 1}]       ![Mathematica graphics](http://i.stack.imgur.com/1XVV8.png)


Singularity / stiffness / precision errors with NDSolve

I have a relatively simple 2nd Order ODE problem I'm trying to solve numerically $p'' + \frac{1}{r}p' = A(\frac{p(r)}{p(r) + k_{m}})$ where $A = 7.5795*10^9$ and $k_{m} = 1$. So trying to get numerical solution in Mathematica between the boundaries $r_{o} = 5 \times 10^{-6}$ and $r_{c}$ ($r_{c}$ is at LEAST 0.000102329 and likely 10-30 microns bigger, but I'll use small estimate for this example . We also know $p(r_{o}) = p_{o} = 100$, and $p'(r_{c}) = p(r_{c}) = 0$; but this is seriously upsetting Mathematica; I'm getting the following warnings depending on what versions I run;               s = NDSolve[{D[r*O2'[r], r] - con*r*((O2[r])/(O2[r] + km)) == 0,  O2[rc] == 0, O2[ro] == po}, O2, {r, ro, rc},Method -> {"StiffnessSwitching"}, MaxSteps -> 100000]      Produces a host of errors of the form; > NDSolve::ndsz: At r == 0.00009971646984096604`, step size is effectively > zero; >singularity or stiff system suspected Trying the other condition               s = NDSolve[{D[r*O2'[r], r] - con*r*((O2[r])/(O2[r] + km)) == 0,  O2'[rc] == 0, O2[ro] == po}, O2, {r, ro, rc},Method -> {"StiffnessSwitching"}, MaxSteps -> 100000]      produces the errors > FindRoot::cvmit: Failed to converge to the requested accuracy or precision > within 100 >iterations. NDSolve::berr: "There are significant errors > {-0.125305,-99.99} in the boundary value >residuals. Returning the best > solution found." The attempted solutions look frankly obscenely wrong, so Im guessing there's a stiffness or singularity probem. I've tried a few tricks to try and circumvent this and I'm getting no joy; is there something I'm missing? So far I've tried increasing the value for rc, and re-writing the equation differently but I'm still having problems. Anyone any idea of why I'm getting these errors and how to resolve them?


Operator syntax for Merge-like Query

Is it possible to take advantage of Dataset's Query operator syntax to Merge parallel queries thereby avoiding Function's that are otherwise required? Using the planets data:                planets = ExampleData[{"Dataset", "Planets"}];          {moonMasses, nMoons } = {planets[All, "Moons", Median, "Mass"],        planets[All, "Moons", Length, "Mass"]}      ![enter image description here](http://i.stack.imgur.com/v1syL.jpg) These queries are nearly equivalent merges: (1) `Merge[{moonMasses // Normal, nMoons // Normal}, List]` ![enter image description here](http://i.stack.imgur.com/TWkoa.jpg) (2) `planets[All, "Moons", {Median[#], Length[#]} &, "Mass"] // Normal` ![enter image description here](http://i.stack.imgur.com/PKpcr.jpg) The values in (1) are unfortunately wrapped in an extra nested list (and further requres normalizing the data as Merge doesn't take `Dataset` arguments). (2) is preferred (normalizing here only because 10.0.0 `Dataset Format` is not usable). How to avoid using `Function` in (2), eg, to shorten the query to a syntax similar to:               planets[All, "Moons", {Median, Length}, "Mass"]


Finding the first five eigenvectors and values for a 500×500 matrix

I'm trying to find the first five eigenvalues and vectors of a matrix that has the following proporties:               L = 10;     NN = 500;     ℏ = 1;     a = 1;     V0 = 5;     dx = L/NN;     Clear[x]     x[n_] := -L/2 + (n - 1/2) dx     Vsw = -V0* i Piecewise[{{1, -1/2 < x < 1/2}, {0, x > 1/2}, {0, x < -1/2}}];     i = SparseArray[{{i_, i_} -> 1, {i_, j_} /; Abs[i - j] == 1 -> 0}, {500, 500}];     s = SparseArray[{{i_, i_} -> -2, {i_, j_} /; Abs[i - j] == 1 -> 1}, {500, 500}];     Hkin = 1/(dx)^2 s;     Hsw = Hkin + Vsw;      In simple English this means I have two matrices:   * one that is allmost diagonal with constant values   * another that is diagonal with a constant value, but only for a some region of definition of `x[n]` I think using piecewise is not good here, but I can't seem to find anything else that works. Also, I'm not sure if my use of `n` is OK here.


Usage of Block in Compile

When is there an advantage to using `Block` in `Compile`? For instance, if I have a multiple-step code, how do I decide which variable assignments I should put into the first argument of `Block[]`? Is it unwise to have functions being evaluated in there?


Permutation of arguments of product of functions

Given a function, g, which is symmetric in its argument, g(a,b)=g(b,a), consider the product g(a,b)*g(c,d)*g(e,f). I would like to get all the permutations of this product with respect to the arguments, that is, terms such as g(a,c)*g(b,d)*g(e,f), which respect the symmetry so that g(c,a)*g(b,d)*g(e,f) would not be among the generated terms. Is there a way to get Mathematica to do this? Many thanks for any help.


Discrete peaks to curve via Voigt summation

I have two data sets. One is an experimental recording of an absorption spectrum, composed of regularly spaced (wavenumber, intensity) coordinates with a fine wavenumber resolution, thus making superposed Voigt peaks. The second one is computation that gives coordinates (wavenumber, intensity) for the maximum of each peak. I want to obtain a function that would   * Take X,Y coordinates of my simulated dataset   * Generate a Voigt profile (mean X from dataset, integration Y from dataset, fixed Sigma, fixed Gamma)   * Repeat for the whole experimental dataset (~150 points displayed as green bars)   * Plot the sum of all these Voigt functions The Voigt profile is not a requirement, I can work with a Gaussian to begin with. So there would only be 3 parameters, 2 from the dataset and Sigma. ![enter image description here](http://i.stack.imgur.com/X1pBE.png) This graph was made in Origin, but I'm using _Mathematica_ 9.


Isolating characters in a string

I'm struggling to find the right function in mathematica to isolate specific characters in a string. I have got a formula as string (I imported it from an excelfile) like this: **y = 0.97*x1 + 0.521*x2 - 30.21 - 0.07431*x3 - 0.126*x4 - 0.1939*x5 - 0.361*x6** Now I want to isolate the coefficients, e.g. 0.97,0.521 from the x's and maybe store it seperately, so that I know which coefficients were for which x. I thought this would be easily done and I browsed through the help of mathematica, but I couln't find any example which helps me so far. Maybe some of you can help me out which functions is best for this task?


Reading between blank lines in external data files

I have an external data file with several columns and thousands lines of data. For the sake of this question, let's assume that we use               I1 = Import["data.out","Table"];      to import a sample data file which is the following               data = {{2,-1,0},{-4,0,2},{7,5,-1},{},{8,1,-3},{-5,2,-3},{},{-4,-1,3},{3,7,2},{0,0,2},{}}      We see, that there are empty sub-lists {} corresponding to blank lines to the external data file. Also, at the end there is always a blank line. Each blank line acts as a separator distinguishing between different piles in the data file. So, my question is the following: how can plot using `ListPlot` like               S1 = ListPlot[Flatten[List /@ data[[All, {2, 3}]], 1], Joined -> True,                   Frame -> True, Axes -> False, AspectRatio -> 1,                    PlotStyle -> {Black, PointSize[0.001]}]      all the different sets of data? In other words, how can I plot only the first sequence until the first blank line (`{2,-1,0},{-4,0,2},{7,5,-1}` according to the sample), or the data between let's say, 4rd and 5th blank lines, the last set, etc?


How to draw the image of a circle under the action of a transformation of the phase flow?

How to draw the image of a circle $x^2+(y-1)^2<1/4$ under the action of a transformation of the phase flow for the equation $\dot{x}=y,\ \dot{y}=-\sin x$? Here $\dot{x}$ means $dx/dt$. Any help or suggestions will be appreciated! The following code shows how to plot the trace of a point under that action which may be helpful.               splot =        StreamPlot[{y, -Sin[x]}, {x, -4, 4}, {y, -3, 3}, StreamColorFunction -> "Rainbow"];     Manipulate[       Show[splot,          ParametricPlot[           Evaluate[First[{x[t], y[t]} /.              NDSolve[{x'[t] == y[t], y'[t] == -Sin[x[t]], Thread[{x[0], y[0]} == point]},                {x, y}, {t, 0, T}]]],            {t, 0, T},            PlotStyle -> Red]],        {{T, 2}, 1, 20},        {{point, {3, 0}}, Locator},        SaveDefinitions -> True]


BarChart3D does not print zeros and odd tick positions

**Note: This is a version 9.0.0 problem that is fixed in 9.0.1.** * * * I want to generate a simple 3D view of some frequencies for two variables. I have the counts in a 4x3 matrix, say. This is my bar chart code:               BarChart3D[      Map[Labeled[#, Text[Style[#, Black, Opacity[1.], Bold, 20]],          Above] &, {{1, 0, 2}, {0, 0, 2}, {2, 1, 0}, {0, 2, 1}}, {2}],      ChartLayout -> "Grid",      BarSpacing -> Large,      ChartElements -> Graphics3D[Cylinder[]],      ChartStyle -> Directive[Opacity[0.3]],      AxesLabel -> {None, None, None},      Ticks -> {{{1/2, "Del"}, {2, "Nor"}, {2 + 3/2, "Amp"}},        {{1/2, "Osteo"}, {1.75, "Ewing"}, {3, "Rhabdo"}, {4.25,           "Neuro"}}, {0, 1, 2}},      ViewPoint -> {1.3`, -2.4`, 2.`}      ]      And this is what I got with _Mathematica_ 9.0 (more precisely, 9.0.0.0 Mac OS X.) ![Mathematica graphics](http://i.stack.imgur.com/JfX39.png)   * First, for readability, I want to place a label in each column. But as you can see, zeroes are not displayed. How can I get BarChart3D to plot my zeros? Or probably better, to draw a flat disk in corresponding place.   * (Not as important) Notice how I placed the ticks for the _x_ and _y_ axes. The matrix is 4x3, so I don't understand where those positions come from (the ones I had to use to put the labels - see `Ticks` above). My guess is that my positions are probably wrong, although visually seem ok for now. Help would be much appreciated. **Update** As workaround for zeros, I put a `If[#==0,0.01,Labeled[...]]` in `Map` and displays ok. Still, I am intrigued on how to position tick labels correctly, with `Ticks` or some other option.


How do I change the way Mathematica pronounces English words (e.g. "futile" is not pronounced correctly)?

I am absolutely desperate. I cannot get my Borg to pronounce "futile" correctly.               Speak["Resistance is futile."]      Leo pronounces "futile" as expected and there is no indication that this word is pronounced differently in the US and the UK. I have also tried various incorrect spellings but with no real success. Is it actually possible to install and use other speakers? Are there means to adapt the pronounciation of specific words or phrases? **EDIT:** Question 1: "few-tile" and "hoss-tile" as suggested below sound very good on my computer. Fact is, "futile" and "hostile" are not pronounced incorrectly but do follow the American pronounciation. We are probably spoiled by British actors (Patrick Steward) mingling in American series. Believe it or not, I watched the "Scorpion" episode (species 8472 appears for first time) of ST-TNG and yes, Data and Geordie use American pronounciation. **EDIT:** Question 2: Mathematica resorts to the default "voice" installed in the (in my case) Windows 7 set-up. Adaptions such as speaker's speed are also inherited by Mathematica.


How to prevent output truncation when importing large Graphics?

The `Evaluation` Preferences in _Mathematica_ specify a maximum output size of `1048576` Bytes before truncation occurs. That makes a lot of sense when thinking about large lists of data, but is causes trouble when displaying large `Graphics`. Here is an example. It is produced using version 9.0.1.0 on a MacBook Pro with Retina display running OS X 10.7.5. I'm importing a `PDF` file with a large polygon count.               Export["t1.pdf", Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}]];     First@Import["t1.pdf"]      ![large output](http://i.stack.imgur.com/ml6nU.png) This truncation warning does nothing to save space in the notebook, and the full output is in fact generated. So it would be nice if one could automatically suppress the truncation warning which serves no purpose here. I don't think it's a valid solution to just increase the truncation Byte limit above its default value, because that would affect regular data output as well, and I don't want to increase the limit for that case. Normally I would of course avoid exporting and importing `PDF` from 3D graphics, but it can't always be avoided if you have an external `PDF` file you'd like to display in the notebook.


Interpolation impossible for ListPlot with Missing?

I have a list of data to plot. I would like to plot them with lines but delete some data before plotting and leave the lines disconnected where data is deleted. For example,               ListPlot[Sin[0.5 Range@100] /. {a_?Negative -> Missing[]}, Joined -> True]      This works well. However, the data is not dense enough to make smooth plots. Thus I want to turn on interpolation:               ListPlot[Sin[0.5 Range@100] /. {a_?Negative -> Missing[]},       Joined -> True, InterpolationOrder -> 2]      However, This ends up with en error message and the same figure without interpolation. > ListPlot::ioproc: > "{{1.,0.479426},{2.,0.841471},{3.,0.997495},{4.,0.909297},{5.,0.598472},{6.,0.14112},<<39>>,{46.,Missing[]},{47.,Missing[]},{48.,Missing[]},{49.,Missing[]},{50.,Missing[]},<<50>>} > may contain non-machine-precision numbers, complex numbers, or invalid > entries." I think to set the data points to `Missing[]` should be the right way to remove data. Thus is it a bug that the data fail to interpolate? I would have first interpolated data by hand using               Interpolation[data] /@       Range[Min[data[[All, 1]]], Max[data[[All, 1]]],        (Max[data[[All, 1]]] - Min[data[[All, 1]]] + 1)/(10.*Length[data])]      and send the result to ListPlot. But let me still ask this question because I thought `InterpolationOrder -> 2` should work but it didn't.


Name scope confusion

Sorry for the too ambiguous title. First consider a following code snippet.               x = "x"; y = "y";          kk[] := Module[ {q, w, m},         q[a_] := a + 1;         w[a_] := a^2;         m[Global`x] = q;         m[Global`y] = w;         m     ]      With this function `kk` I can write code like this,               kk[][x][1]    (* output -> 2 *)     kk[][y][2]    (* output -> 4 *)      as expected. However, I want to change the name of the global variables `x` and `y` to those of the local variables `q` and `w`. Thus, consider a below snippet. q = "x"; w = "y";               kk2[] := Module[ {q, w, m},         q[a_] := a + 1;         w[a_] := a^2;         m[Global`q] = q;         m[Global`w] = w;         m     ]      Note that the only change to the above code is the global variable names `x` and `y`. However, this function `kk2` does not work as expected anymore. Can you explain? The output I got was,               kk2[][q][1] (* unevaluated *)     kk2[][w][2]      Thanks in advance. EDIT: add `[]` to each `kk2` calls as pointed by m_goldberg


Area enclosed by two functions

i want to calculate the area percentage of a function in a certain regime above a constant threshold. For example:               f[x] = sin[x] x²       from 0 to 2 with a threshold `g(x) = k` If I would do it by hand, I would identify the intersections points between the two functions and than calculate the integrals of the right ones and substract the value of G(x) from F(x) to just get the volume above the threshold. Depending on the number of intersections there quite a number of integrals to consider. So I thought, let _Mathematica_ do the the leg work! Well, but I am quite a novice in _Mathematica_ , and soon realised that I have only a vague idea how to do it in _Mathematica_. Probably there is even a better way to do it than described in the middle paragraph, because at the end it could also just approximate the enclosed areas numerically. Can anyone show me how to do it? Edit: Thank your very much for your answers/solutions. With a small correction (probably I explained poorly what I wanted) the solution from rasher worked just fine (and I understood the code used). In will also try to learn from Chenminqi solution which looks defintely more sophisticated and exceeds my current mathematica knowledge. So again, thanks to everyone!


Automatically add appropriate prefix to Quantity

Is there a function that automatically adds the appropriate prefix to a `Quantity` object? For example, I would like a function               quantityWithAppropriatePrefix[Quantity[0.000001,"Meter"]]      that would yield > >     Quantity[1,"Micrometers"] >   For some units this hack works:               UnitConvert[UnitConvert[0.00001,"Meter"],"Imperial"],"SI"]      > >     Quantity[10., "Micrometers"] >


Write memory usage to file in script

Is there a way to write the MemoryInUse into a file once a minute? In this Debugging memory leaks question there is a neat dynamic diagram showing the MemoryInUse over time. My problem is that I run my mathematica script without the front-end (math -script mystuff.m) and it seems that Dynamic does not work.


Graph adjacency matrix with unconnected nodes

I am trying to display a series of 9x9 adjacency matrices which represent directed graphs on a 3x3 grid. The issue I am running up against is this (compounded by that fact that I don't really know how to do anything in Mathematica): only the connected nodes appear, and they do so with a Mathematica-decided geometry. I'd like every point in the adjacency matrix to refer to the same fixed coordinate on the 3x3 grid every time. It seemed that `VertexCoordinates` might work, but it only refers to the vertices that have degree > 0, right? Insight on how to accomplish this? Any help would be much appreciated.


Table with dependent iterator

I'm trying to build a table where the iterator is based off of the ith-1 entry in the table. In other words, the value at _i_ is based on a function with _i-1_ as its input. EXAMPLE: Let's assume we're trying to get a pressure profile for a static column of gas. Since a gas's density changes greatly with pressure changes, we would want to break the static column into, say, 50 sections. So, we set the pressure at the bottom of the column and calculate the pressure at the top of the section ( _i+1_ ) using the formula $\ P_h = \rho g h/g_c$ (hydrostatic equation). The next section's known pressure is at _i+1_ and we'd solve for _i+2._ I've tried For and Table and can't get it to work. Thanks in advance. Update: I've figured out how to do it with the For[] construct, but not without the loop.               pc = List[4100];     For[i = 1, i < 50, i++,     pc = Append[pc, pc[[i]] - \[Rho]gh/gc]]


Output of the comand Put

I have a do loop in which I "Put" a ListPlot of a list in every iteration by doing               Put[ListPlot[list],"file"]      While the process is running and is still not finished, I get the desired plots in "file", but once the process is finished, I do not get the plot but the numerical values of the list with something like               {"      0.0134559544171447}", " {298.", " 0.013484438740159787}",        " {299.", " "}, {"      0.013512496857553435}", " {300.",      " 0.013540123145712023}}]}", " {}}}",      " "}, {"  {AspectRatio -> GoldenRatio^(-1)", " Axes -> True",      " AxesOrigin -> {0", " 0.0098}", " "}, {"   PlotRange -> {{0.",      " 300.}", " {0.00977737893161915", " 0.016994445972500355}}",      " "}, {"   PlotRangeClipping -> True",      " PlotRangePadding -> "}, {"    {Scaled[0.02]",      " Scaled[0.02]}}]}"}}      this is just a small piece of the output. I am working in the background by using "nohup" and running an .m file (in case it might have something to do with my issue). What do I have to do so that I always get the ListPlots as output? Thanks


Should I use \\\" or \" to match " in regex?

Both of the following return `True`:               StringMatchQ["foo\"bar", RegularExpression[".*\".*"]]               StringMatchQ["foo\"bar", RegularExpression[".*\\\".*"]]      Which is more correct? Also what about               StringMatchQ["foo\\bar", RegularExpression[".*\\\\.*"]]     StringMatchQ["foo\\bar", RegularExpression[".*\\.*"]]


Optimizing functions taking matrix arguments

I'm looking for general information on how to optimize matrix valued functions, I have the following function I'm looking to maximize (or figure out if this is possible at all).               MaximizeFunction[W_, DataCoupled_] :=        Module[{newDataCouple},         (* Elementwise Multiplication on a list of 2 element vectors *)         newDataCouple = Flatten[List[Dot[W, #] & /@ DataCoupled], 1];         (* Take the first and second elements of each of the vectors in the previous list and            perform an independence test on them to obtain the p-value *)         Return[           IndependenceTest[Extract[#, 1] & /@ newDataCouple,Extract[#, 2] & /@ newDataCouple]]];      Input values are of the type:               DataCouple = {{.5, .8}, {.7, .9}, {.6, .9}, ... }      W = {{1, 0}, {0, 1}}      Could I then use `NMaximize` or `Maximize` to optimize this function?


Solutions of cubic equation D>0 or D<0

I have problem to obtain three roots of cubic equation                N[Solve[a x^3 + b*x^2 + c*x + d == 0, x], 15]      using analytical procedure http://en.wikipedia.org/wiki/Casus_irreducibilis Discriminant of the system is positive and solutions which I obtained with the formula x1, x2 and x3 and Mathematica Solve are not the same?                a = 1;      b = 0.00100025;      c = 0.100000250125;      d = 0.0000500125;                p = (3 a c - b^2)/(3 a^2);      q = (2 b^3 - 9 a b c + 27 a^2 d)/(27 a^3);           N[q^2/4 + p^3/27]           t1 = \[Psi]1 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]1^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];     t2 = \[Psi]2 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]2^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];     t3 = \[Psi]3 Power[-(q/2) + Sqrt[q^2/4 + p^3/27], (     3)^-1] + \[Psi]3^2 Power[-(q/2) - Sqrt[q^2/4 + p^3/27], (3)^-1];          \[Psi]1 = 1;     \[Psi]2 = -(1/2) + Sqrt[3]/2 I;     \[Psi]3 = -(1/2) - Sqrt[3]/2 I;           x1 = t1 - b/(3 a);      x2 = t2 - b/(3 a);      x3 = t3 - b/(3 a);           N[x1]      N[x2]      N[x3]      N[Solve[a x^3 + b*x^2 + c*x + d == 0, x], 15]      And which formula to use in the case if the discriminant is negative? For example if the equations is in the following form                NSolve[0.5 + 25.1 x + 10. x^2 + x^3==0,x]


How to print coordinates above certain points

How do I place the x and y values of the points I have found (maxandmindistance) above the point in a plot? Here is my code so far:               Distance[t_] := t*(t - 1)*(t - 1.5)^2*(t - 3)     Velocity[t_] := Simplify[Distance'[t]]     maxandmindistance = Solve[Velocity[t] == 0, t]     Show[Plot[Distance[t], {t, 0, 3}],       Graphics[{Red, PointSize[Large],         Point[{t, Distance[t]} /. maxandmindistance]}]]      This results in a function with dots along it. They are the maximum and minimum values for the function. The problem is that the coordinates (x,y values) are not shown.


Get Coordinates 4 significant digits limitation

The tool "get coordinates" (clicking on a plot), seems to work with a fixed number of significant digits (4), in a way that we can quickly lose sensibility (the tool really becomes useless). The following example shows the problem:               Plot[a, {a, 1950, 1950.2}]      ![enter image description here](http://i.stack.imgur.com/BPI1k.png) I imagine that this is a feature tending to the bug classification. Is there a way of correcting this behavior? (on 9.0.1)


Expectation of a composite Markov-Gamma distribution

In a model I have a discrete two-state first order Markov process, defined by a (2x2) transition matrix with two free parameters. If the first state occurs then the process outputs zero for that period. If the second state occurs then the process outputs a Gamma-distributed random variable characterised by another two parameters. I can work out the theoretical mean and variance of the overall stationary process using pen and paper, but I am unsure how to check my results (and also I want to practice my Mathematica) using symbolic calculations. Put another way, I would like to know how to calculate the mean and variance to which the composite Markov-Gamma process will converge. My code is below - all I have currently is a way to calculate the mean of the Markov process, P, and its stationary mean (Mean[S]). However, I would like to be able to derive the mean and variance of R inserted into P for times when the process is in state 2, and zeros for when P is in state 1. Many thanks! Ben               M = {{1 - pdw, pdw}, {pwd, 1 - pwd}}     P  = DiscreteMarkovProcess[{1, 0}, M]     S = StationaryDistribution[P]     R = GammaDistribution[a,b]


Launching Remote Kernels takes a lot of time

I recently played around with establishing a remote kernel setup without using mathematica grid. To do this I use the `LaunchKernels[]` command and `ssh` to establish the connection. A call to my remote desktop (RemoteDesktop) then looks like:               Needs["SubKernels`LocalKernels`"]     LaunchKernels[RemoteMachine["RemoteDesktop",        "ssh -x -f -l username `1` math -mathlink -linkmode Connect `4` -linkname `2` -subkernel -noinit >& /dev/null &", 8]]      Which returns the following error: > SubKernels`Protected`kernelFlush::time: Operation LinkWrite timed out after > 15.` seconds It actually took me some time to figure out, that launching a kernel on RemoteDesktop actually takes longer than the predefined limit of 15 seconds. If I increase the limit to some way higher timespan like this:               Parallel`Settings`$MathLinkTimeout = 100.      `LaunchKernels[]` sure takes its time, but all the kernels are launched eventually. **So I cannot help but wonder: Is this an ordinary behavior or do you think something is going wrong regarding my setup, which results in launching kernels taking more time? If so, what could be the reason?** Further information: I am working on a MacBook Pro with OS X 10.9 and Mathematica 9.0.1. I testet remote connections to another Mac with OS X 10.8 and Mathematica 9.0.1 and a 64 Bit Linux Machine. Launching kernels took way longer than 15 seconds in each of these two scenarios.


Memory problem with producing complex graphics of general type

The problem I am about to ask has appeared once here: Memory Leak in Frontend - anyone know a workaround?. However, in this question I would like to put it in a bit different context. **Problem recipe:**   * Set $HistoryLength to 0 (this forces mathematica not to keep any history of evaluations)   * Create a graphic object, which contains many colors/opacities/primitives/pointsizes/...   * Open system monitor in your operational system   * Rasterize the object in mathematica   * Export it (optional), clear all the variables   * Check your system monitor: memory used by mathematica frontend has grown larger **Example of the problem:** This example is not minimal, but is aesthetically appealing. Following the recipe, first set the history length:               $HistoryLength = 0;       Then create a graphic object. In this case, it is a set of approx 0.5 10^4 points, having random positions inside a 0.5 radius sphere, random sizes and random colors, following some colorscheme. A cylinder is added afterwards to make the object look like a tree.               PointNumber = 10^4;     BushSize = 0.5;     PointLocations =        Select[(2 BushSize {Random[], Random[], Random[]} - {0.5, 0.5,              0.5}) & /@ Range[PointNumber], Norm[#] < BushSize &];     PointNumber2 = Length[PointLocations];     PointSizes = 0.01 Random[] & /@ Range[PointNumber2];     PointColors =        ColorData["PlumColors"][Random[]] & /@ Range[PointNumber2];     GraphicObject =        MapThread[{#1, PointSize[#2], Point[#3]} &, {PointColors,          PointSizes, PointLocations}];      Now, open the system monitor and rasterize everything:               TreeStuff =       Rasterize[       Graphics3D[{Opacity[0.8], Brown, EdgeForm[],          Cylinder[{{0, 0, -1}, {0, 0, 0.1}}, 0.01], GraphicObject},         PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, ImageSize -> 600,         Boxed -> False]]      As you can see, mathematica front-end has expanded in size by some 50 Mb! It is not all, at all. If you reevaluate the notebook, mathematica will pick another set of random points and will expand in the memory again. However, if you re-rasterize an object which has been rasterized before, memory will not be leaked. **Discussion:** The described behavior is clearly a bug. Say, one is producing an animation. If a given frame has been rasterized and saved, no information needs to be stored about it in the memory. Nevertheless, it gets stored incrementally. It seems hard to imagine, that nobody has ever created complex graphics with mathematica before. In particular, in processing datasets or in creating animations, one has to rasterize such graphics many times. In this case, if the parameters of graphics change, mathematica takes all the system memory. Therefore, at least somebody, making complex graphics with mathematica, must have faced a similar problem before. What do people commonly do to treat this issue? How can one clear the frontend memory, which expands so obviously in system monitor after each new evaluation of the above presented code? **P.S.** The code outputs this pretty tree: ![enter image description here](http://i.stack.imgur.com/EAoPy.jpg)


Specify the color of a horizontal grid line in a plot

I wish to plot a function and add a red, horizontal grid line at the height of the Euler-Masheroni constant. I am successful in ploting the line at Exp[EulerGamma], but I am having difficulties with getting it red Code:               ListLinePlot[robinplot, PlotRange -> All, GridLines -> {{}, {Exp[EulerGamma]}}]      I have used this code but it only makes my robinplot red:                ListLinePlot[robinplot, PlotRange -> All, GridLines -> {{}, {Exp[EulerGamma]}}, PlotStyle->{Red}].      How can I get a red line at height Exp[EulerGamma]?