title: How to make a piece of a pie chart change color upon clicking it?

text: I am trying to use the `EventHandler` and have managed to make the text change color upon clicking it, but cannot seem to make each piece of the pie chart change color as I click it. For the text I used this:               f[text_] := DynamicModule[{col = Red},        EventHandler[Style[text, FontColor ->  Dynamic[col]],                     {"MouseClicked" :> (col = col /. {Red-> Green, Green-> Blue,                                         Blue-> Red})}]]      When I apply this function `f` in the pie chart as follows:               PieChart[{{        Labeled[.5, Style[f["A"], Bold]],        Labeled[.5, Style[f["B"], Bold]]        }, {        Labeled[Style[.5, White], Style[f["C"], Bold]]        }       }]      it works. How can I make the pieces of the pie change color upon clicking them?


title: Colors associated to parts of a 3D distribution of points

text: Suppose we have a long list of random points (cartesian coordinates) in 3D space.               coords := ...;      Until now, I was associating colors in a radial way, from the center to the edge of the distribution :               SpriteColor = Blend[{InternalColor, MiddleColor, MiddleColor2, ExternalColor},#]&;      I'm now wondering how could we associate the colors by random "small patches" over the distribution of points, with smooth blending between the patches. What I mean by "patches" is this : some red here, blending to blue there, red again in another random part, blending to green over there, etc. The random distribution of colors should need the number of "patches" as input, and a set of colors (as in my example above, for the radial distribution). Any suggestion about how to do this ? For a crude example, here's a version with the radial colors (easy to do with the above color directive) : ![enter image description here](http://i.stack.imgur.com/hy9gK.jpg) And here's a **very crude** sketch (hand made) of what I would like to do, instead of a radial coloring. The patches should be randomly placed : ![enter image description here](http://i.stack.imgur.com/1Ni4J.jpg) Notice that I'm working with **_Mathematica 7_**. **EDIT :** Here's a full working example for a radial color distribution on a cube of points. I would like to distribute the colors on, say, 7 spots randomly distributed on the whole distribution of points, instead of an unique radial blend.               InternalColor := RGBColor[0.95,0.0,0.0, 0.99]; (* color at the center of the distribution *)     MiddleColor := RGBColor[0.0,0.95,0.0, 0.9]; (* color of transition to the exterior part *)     ExternalColor := RGBColor[0.0,0.0,0.95, 0.9]; (* color of the exterior part *)          testCoords = RandomReal[{-1,1},{10000,3}];          radialColors = Blend[{InternalColor, MiddleColor, ExternalColor2},#]&;          Graphics3D[{AbsolutePointSize[4],Point[testCoords,VertexColors->(radialColors[Norm[#]]&/@testCoords)]},Boxed->False,BoxRatios->{1,1,1},ImageSize->800,SphericalRegion->True]      Output : ![enter image description here](http://i.stack.imgur.com/pS6xV.jpg)


title: How to use subscript in pattern names?

text: For example I want to define a function with parameters σx and σy, that is, the function will be declared as:               f[σx_,σy_] := . . . I tried `Symbolize` but it doesn't work. How can I use `Subscript` in pattern names?


title: Plot on command within DynamicModule?

text: Suppose I have a `DynamicModule` with all sorts of controls to set some parameters for a graphics object.               DynamicModule[{a = 0, b = 0},       Column[{         Slider[Dynamic[a]],         Slider[Dynamic[b]],         Dynamic[Plot[Sin[(a + 1) t + \[Pi] b], {t, 0, 2 \[Pi]}]]       }]     ]      This graph is updated every time one of the dynamic parameters change. Now pretend my graphics is a really slow 3D plot. How can I construct it so that it only renders the graphic when I tell it to? A button? A mouse event?


title: SQL Queries with the Table function

text: Given the following connection to an SQL query works but the data comes out wrong:               data = Table[SQLSelect[conn, "All", {"col1", "col2"},         SQLColumn["col1"] == n && SQLColumn["col2"] ==  o], {n, 1, 8}, {o, 21,         30}];      If I do not use the 'Table' function, I get the expected results by inserting the actual numbers after == when running the query. I need to create a 54 x 289 table from my data and obviously for this large data set this will be impractical to key in and export piece by piece. Any suggestions?


title: Height-dependent filling color in 3D Data Plots

text: I would like to have the filling of my ListPlot3D display the same color than the one applied to the data. This question makes sense only in the case of conditional coloring of data (according to their height for example). Moreover, I am using the option `InterpolationOrder -> 0` and I understand what I ask is kind of tricky in case of higher orders. Here is a minimal example               table = {{1, 2, 1, 2}, {3, 1, 3, 2}, {4, 3, 4, 2}, {1, 2, 3, 4}};     ListPlot3D[         table,          InterpolationOrder -> 0,         ColorFunction -> "DarkRainbow",          Filling -> Axis,         FillingStyle -> {Opacity[1]}, Mesh -> None         ]      which gives gray filling beneath the data. My question is the following : Is it possible to specify a dynamic color in the `FillingStyle` so that it will match the data ?


title: Exporting Animations under Duration constraints to view on an iPad

text: I would like to show some eye-movements datas as animation on an iPad. That is to see the gazes as they occured as a function of time. Ideally We would only see the Graphics objects, not the dynamic controls. I have about 50 trials with each 3000 gazes I would like to show. Preferably, all in one video with each trial looping 3 times. Now I have encountered mny problems : To illustrate, this is equivalent to my situation exept I`ll have about 50 different animations instead of 2.               pts = RandomReal[{-#, #}, {100, 2}] & /@ Range[2];     graphObj = {{Blue, Rectangle[{-1, -1}, {1, 1}]},                  {Red,Rectangle[{-.5, -.5}, {.5, .5}]}}                    Manipulate[      Animate[       Graphics[{        graphObj[[stimNo]],        White, Line@pts[[stimNo]][[;; gazeNo]]},        Background -> Black,         PlotRange -> {{-3, 3}, {-3, 3}}],      {gazeNo, Range[2, 100, 1]},       DefaultDuration -> 3,       AnimationRepetitions -> 1,       AnimationRunning -> False,       Paneled -> False],      {stimNo, Range[2]},      ControlType -> Setter,      Paneled -> False]      ![enter image description here](http://i.stack.imgur.com/uKlub.png) QUESTIONS / PROBLEMS : -I am not sure of the best format for the iPad and how I could play those animations. -I have not been able to export the correct duration (3 seconds to see my 3000gazes}. -I could only achieve the above exporting the Animate[] object itself, leaving me with the controls on the .mov. My attempts to use ListManipulate [] have yet all failed. I must say I have looked at very bits of the help menu relating to exporting animations without success.


title: different values of integral with/without bogus assumptions

text: I do not understand why I get different answers for the following two identical integrals.               Integrate[Cos[10*Pi (z - x)], {x, 1/10, 1}, Assumptions :> {}]     Integrate[Cos[10*Pi (z - x)], {x, 1/10, 1}, Assumptions :> {x > 0}]      Output (respectively):               -Sin[10Pi*z]/5Pi     Sin[10Pi*z]/5Pi      Running version 9. Any help would be very appreciated. Thanks!


title: How can I speed up image importing?

text: The following examples show how slow it is to load a simple GIF. Can anything be done to make it faster? **System #1** : _Mathematica_ 8.0.1.0, HP notebook, Win7 64Bit, 2 x 2.4Ghz Intel Core i5, 2GB RAM, w/ integrated Intel graphics chipset               AbsoluteTiming[Import["ExampleData/rose.gif"];]     (*        ==> {1.3650781, Null}     *)      **System #2** : _Mathematica_ 8.0.1.0, MacBook Pro, OSX 10.7.2, 2.4GHz Intel Core i5, 8GB 1333 MHz DDR3 w/ integrated Intel HD graphics 3000 512MB               AbsoluteTiming[Import["ExampleData/rose.gif"];]     (*        ==> {2.549696, Null}     *)      Both installations are on local drives.


title: Is there a syntax for single-line comments for notebooks?

text: I'm aware that I can use `(* ... *)` to comment out stuff in a notebook. Many languages have a syntax for single-line comments, such as   * `//` in C, C++, Java, C#, ...   * `#` in shell, Python, ... For example, in C++ you can write               int x = 5;     // std::cout << "debug: x = " << x << std::endl;     return x;      in which the second line is commented out. Is there a way to quickly comment out just one line in _Mathematica_ , without having to type paired comment characters?


title: Easy Way to Create Trellis Plots in Mathematica

text: I'm trying to do multivariate statistical analysis on a data set and I'd like to quickly visualize my information first using Trellis-like plots. For example, I'd like to create scatterplots for body mass and height separated by region. I'm currently creating all the graphs individually and then displaying them together with GraphicsGrid but I'm wondering if there's a better way of doing it.


title: Obtaining the square-root of a general positive definite matrix

text: I have a matrix which I know to be positive definite. The entries of the matrix might be complicated but they are all real. To find an expression for the square root of this matrix (i.e., `SS = A`) I'm trying :               Ftemp = {{F11, F12, F13, 0, 0},               {F12, F22, 0, 0, 0},               {F13, 0, F33, 0,F35},               {0, 0, 0, F44, F45},               {0, 0, F35, F45, F55}}      All the elements in the matrix real. We know there exists a positive square root for this matrix , however , it will be horrible analytically. What I would like to know however, is which entries in the resulting solution will be different from zero (and thus which entries will be zero).


title: Simplify equations using list of rules

text: I have a set of equations that I want to simplify using a list of rules:               eqns={     I (ρ12'[t]+ρ21'[t])==ω1 (ρ12[t]-ρ21[t])+ω2 (-ρ12[t]+ρ21[t])+Ω23 (-ρ13[t]+ρ31[t])+Ω13 (-ρ23[t]+ρ32[t])+Ω24 (-ρ14[t]+ρ41[t])+Ω14 (-ρ24[t]+ρ42[t]),     I (ρ13'[t]+ρ31'[t])==Ω23 (-ρ12[t]+ρ21[t])+ω1 (ρ13[t]-ρ31[t])+ω3 (-ρ13[t]+ρ31[t])+Ω14 (-ρ34[t]+ρ43[t]),     I (ρ14'[t]+ρ41'[t])==Ω24 (-ρ12[t]+ρ21[t])+ω1 (ρ14[t]-ρ41[t])+ω4 (-ρ14[t]+ρ41[t])+Ω13 (ρ34[t]-ρ43[t]),     I (ρ23'[t]+ρ32'[t])==Ω13 (ρ12[t]-ρ21[t])+ω2 (ρ23[t]-ρ32[t])+ω3 (-ρ23[t]+ρ32[t])+Ω24 (-ρ34[t]+ρ43[t]),     I (ρ24'[t]+ρ42'[t])==Ω14 (ρ12[t]-ρ21[t])+ω2 (ρ24[t]-ρ42[t])+ω4 (-ρ24[t]+ρ42[t])+Ω23 (ρ34[t]-ρ43[t]),     I (ρ34'[t]+ρ43'[t])==Ω14 (ρ13[t]-ρ31[t])+Ω24 (ρ23[t]-ρ32[t])+Ω13 (ρ14[t]-ρ41[t])+Ω23 (ρ24[t]-ρ42[t])+ω3 (ρ34[t]-ρ43[t])+ω4 (-ρ34[t]+ρ43[t]),     I ρ12'[t]-I ρ21'[t]==ω2 (-ρ12[t]-ρ21[t])+ω1 (ρ12[t]+ρ21[t])+Ω23 (-ρ13[t]-ρ31[t])+Ω13 (ρ23[t]+ρ32[t])+Ω24 (-ρ14[t]-ρ41[t])+Ω14 (ρ24[t]+ρ42[t]),     I ρ13'[t]-I ρ31'[t]==Ω23 (-ρ12[t]-ρ21[t])+ω3 (-ρ13[t]-ρ31[t])+ω1 (ρ13[t]+ρ31[t])+Ω13 (-2 ρ11[t]+2 ρ33[t])+Ω14 (ρ34[t]+ρ43[t]),     I ρ14'[t]-I ρ41'[t]==Ω24 (-ρ12[t]-ρ21[t])+ω4 (-ρ14[t]-ρ41[t])+ω1 (ρ14[t]+ρ41[t])+Ω13 (ρ34[t]+ρ43[t])+Ω14 (-2 ρ11[t]+2 ρ44[t]),     I ρ23'[t]-I ρ32'[t]==Ω13 (-ρ12[t]-ρ21[t])+ω3 (-ρ23[t]-ρ32[t])+ω2 (ρ23[t]+ρ32[t])+Ω23 (-2 ρ22[t]+2 ρ33[t])+Ω24 (ρ34[t]+ρ43[t]),     I ρ24'[t]-I ρ42'[t]==Ω14 (-ρ12[t]-ρ21[t])+ω4 (-ρ24[t]-ρ42[t])+ω2 (ρ24[t]+ρ42[t])+Ω23 (ρ34[t]+ρ43[t])+Ω24 (-2 ρ22[t]+2 ρ44[t]),     I ρ34'[t]-I ρ43'[t]==Ω14 (-ρ13[t]-ρ31[t])+Ω24 (-ρ23[t]-ρ32[t])+Ω13 (ρ14[t]+ρ41[t])+Ω23 (ρ24[t]+ρ42[t])+ω4 (-ρ34[t]-ρ43[t])+ω3 (ρ34[t]+ρ43[t]),     -I ρ11'[t]+I ρ22'[t]==Ω13 (ρ13[t]-ρ31[t])+Ω23 (-ρ23[t]+ρ32[t])+Ω14 (ρ14[t]-ρ41[t])+Ω24 (-ρ24[t]+ρ42[t]),     -I ρ22'[t]+I ρ33'[t]==Ω13 (ρ13[t]-ρ31[t])+Ω23 (2 ρ23[t]-2 ρ32[t])+Ω24 (ρ24[t]-ρ42[t]),     -I ρ22'[t]+I ρ44'[t]==Ω23 (ρ23[t]-ρ32[t])+Ω14 (ρ14[t]-ρ41[t])+Ω24 (2 ρ24[t]-2 ρ42[t])     }      and the transformation rules are               rules={ρ12[t]+ρ21[t]->k1[t],ρ13[t]+ρ31[t]->k2[t],ρ14[t]+ρ41[t]->k3[t],ρ23[t]+ρ32[t]->k4[t],ρ24[t]+ρ42[t]->k5[t],ρ34[t]+ρ43[t]->k6[t],ρ12[t]-ρ21[t]->k7[t],ρ13[t]-ρ31[t]->k8[t],ρ14[t]-ρ41[t]->k9[t],ρ23[t]-ρ32[t]->k10[t],ρ24[t]-ρ42[t]->k11[t],ρ34[t]-ρ43[t]->k12[t],-ρ11[t]+ρ22[t]->k13[t],-ρ22[t]+ρ33[t]->k14[t],-ρ22[t]+ρ44[t]->k15[t],ρ33[t]-ρ11[t]->k13[t]+k14[t],ρ44[t]-ρ11[t]->k13[t]+k15[t]}      and its derivative `D[rules,t]`. I want to simplify the `eqns` so that it is free of `ρ` variables. I tried something like this but not work               ρls =       Flatten@Table[        ToExpression["ρ" <> ToString[i] <> ToString[j] <> "[t]"], {i,          1, 4}, {j, 1, 4}];     trans[expr_] := expr /. rules /. D[rules, t]     Simplify[eqns,       TransformationFunctions -> {Automatic, trans},       ComplexityFunction -> (LeafCount[#1] +           If[And @@ Table[FreeQ[#, x], {x, ρls}], 0, 10^3] &)]


title: MapThread on a nested Map

text: A simple problem I am facing is here:               list1 = RandomReal[{1, 2}, {3, 4, 30}];     list2 = RandomReal[{10, 20}, {3, 4, 30}];     Map[Map[(# + 1+Min[#]) &, #] &, #] &/@list1;      works fine, but whenever such a nested `Map` appears, I think there might be a better solution than what I am doing here. Now my problem is if I want to use a `MapThread` over the above function like the following, I stumble upon errors               MapThread[Map[Map[(# + 1/Min[#2]) &, #] &, #1] &, {list1, list2}];      Including this example and for even more nested situations, is there any general coding practice that is elegant, efficient and native to MMA functional language paradigm. Hope some one can help me with this type list manipulation here.


title: Plot a one-dimensional list of numbers as a column/row of labeled colored squares

text: I have a list of numbers and a matching list of labels. I want to plot a column of colored squares, with the color of each square matching (in some color scale) the value of the corresponding number. Moreover, each square should have its corresponding label printed on the side (left or right). I also want to plot a row instead of a column. In this case, the labels should be printed above or below the row, and the text should be 90º degrees rotated. How can I do this?


title: BoxWhiskerChart - Displaying Frameticks Bottom and Top

text: Is there an easy way to display Automatically the Frameticks at the bottom and top in a BoxWhiskerChart? Currently it is only showing the numbers at the bottom.               data = Table[{i, RandomVariate[NormalDistribution[i, 2], 100]}, {i,      100, 125}];     BoxWhiskerChart[data[[All, 2]], BarOrigin -> Left,      ChartLabels -> data[[All, 1]], AspectRatio -> 1,      GridLines -> {Automatic, None},      FrameTicks -> {{None, None}, {Automatic, Automatic}}]      ![enter image description here](http://i.stack.imgur.com/6qmOF.png)


title: Possible bug with second argument of Dynamic

text: According to the documentation, Dynamic Details & Options section, especially: > For interactive mouse operations `Dynamic[expr,{f_start, f, f_end}]` > **typically** evaluates `f_start[val,expr]` once when the mouse is pressed, > then evaluates `f[val,expr]` whenever the mouse is moved, and then evaluates > `f_end[val,expr]` once when the mouse is released. I find the following behaviour a possible bug:               x = {.5, .5};     Graphics[{ Circle[],                Locator[Dynamic[x, {Print[#] &, Automatic, None}]]             }]      ![enter image description here](http://i.stack.imgur.com/RKkrn.png) As you see `f_start = Print[#]&` is evaluated twice each time. Is this a bug? I've marked **Bold** the word **typically** in the quotation from documentation. Is this reffering to this case? * * * Here's the link to the question where Anon and I have faced this issue for the first time: Moving a locator based on the movement of another


title: How to combine some elements of a list?

text: In order to simplify my expression, I face a list manipulation problem. For example, given the input list               list = {a[1] cof[1], a[2] cof[2], a[3] cof[3], a[4] cof[4], a[5] cof[5], a[6] cof[6]};      I can calculate the values of `f[a[i]]` and then combine the idential elements (`f[]` is just a function of the `a[]`). The condition of this transformation is               f[a[1]] == f[a[3]] == f[a[6]]; f[a[2]] == f[a[4]];      so that the output list becomes               newlist = {(cof[1] + cof[3] + cof[6]) a[1], (cof[2] + cof[4]) a[2], cof[5] a[5]};      How can I get this kind transformation to newlist for the general case?


title: Creating a Table of Items for GIF creation

text: I want to create a table as shown below so that the steps from the first item to the second item, and the second item to the third item, etc. can be animated. ![Example Output](http://i.stack.imgur.com/uIVdR.gif) I am not at liberty to post tested code right now, but I think this would work:               Table[Grid[Partition[Riffle @@ {Range[n],Range[n]^2},2]], {n,1,3}]      Does anyone have a cooler way of doing this? And by cooler, I mean a way that doesn't require the use of Riffle and Partition (by creating something that is properly formatted for Grid to begin with). Also, if the above code doesn't work, can someone please tell me why?


title: How to set a zero offset for the frame origin?

text: I want to set a zero offset for the frame origin. In other words, the horizontal axis should start at exactly the lower bound, instead of having a small offset. For example, in the figure below, even though I set the range of x to be [0, 6], the x axis starts at a small negative value. What do I need to do to make the x axis start at exactly 0?               Needs["PlotLegends`"]     Plot[Sin[x], {x, 0, 6}, Frame -> True, FrameLabel -> {x, y},       RotateLabel -> True, PlotLegend -> {"a=1"},       LegendPosition -> {0.3, 0.3}, LegendSize -> 0.5,       LegendShadow -> None, LegendBorder -> None]      ![enter image description here](http://i.stack.imgur.com/d430s.png)


title: How can I speed up this multi-equation Solve problem?

text: I'm trying to solve a set of equations (chemical kinetics for a complex system, but don't worry about that). I ran it for 24 hours and I got no output. Here is the relatively simple code (I want to eliminate everything except for `Itot` and `x` and solve for one of them):               eq1 = x == (Etot - M - MI)/(Etot - 1/4 (-Kd + Sqrt[Kd] Sqrt[8 Etot + Kd]))     eq2 = Etot == M + 2*Di + M*Inh     eq3 = Itot == Inh + MI      eq4 = Kd == M*M/Di     eq5 = Ki == M*Inh/MI     Solve[{eq1, eq2, eq3, eq4, eq5}, Itot, {Di, M, Inh, MI}]      I hoped to benefit from knowing a few things, like the fact that all quantities are nonnegative and real. So I tried this (not sure if I've done it correctly because the documentation on Solve is a little confusing):               Solve[{eq1, eq2, eq3, eq4, eq5, x >= 0, Itot >= 0, Di >= 0, M >= 0,            Inh >= 0, MI >= 0}, Itot, {Di, M, Inh, MI}, Reals]      But again nothing in 24 hours. Any suggestions? Would it be helpful if I tried to remove a variable or two myself?


title: Change CurrentValue of a key press

text: I was wondering if there is a way that I could change the value of a key press such as `Shift`, `Ctrl`, etc. Normally, when nothing is pressed, the `CurrentValue` will return `False`. My hope is that I might be able to change these values to `True` with some sort of controller. For example, it would be great if I could use a check box to tell _Mathematica_ that `Shift` was depressed when it was not, but I understand that this is unlikely as these values are protected and probably fairly low level to change. Intuitively, I would say it can't be done, but was just hoping that by some chance it would be possible.


title: How do I make function A create and return function B?

text: My basic need is I have to take lots of data and other information and assemble it into a function (static parameters). I then need to call the function many times for numerical results for many values of the dynamic parameters. I then need to repeat with a new set of static parameters. I have a workable solution that I'm using now but it does not feel like a slick solution. So I'm looking for some fresh ideas.               MakeRegion[id_, g_, geo_] := (       listend = #[[-1]] & /@ (Select[          FindShortestPath[g, id, #] & /@ (Pick[VertexList[g],              VertexOutDegree[g], 0]), Length[#] > 0 &]);       cond = Table[          {crf, rrf, typerf, ptsrf} = {ApCenter, ApR, Type, ApPoints} /. geo[[listend[[i]]]];          Which[             typerf == "Polygon", PointInPoly[ptsrf, {x, y}],             typerf == "Circle", (x - crf[[1]])^2 + (y - crf[[2]])^2 <= r           ],           {i, 1, Length[listend]}];       Clear[region];       region[x_, y_] := Evaluate[Or @@ cond];       );      I do not think I need to go into the details of the code for you to get the idea. `MakeRegion` takes in geometry information and creates the function `region[x,y]` which is a logical domain that I can use in `NIntegrate` and other functions. Here is a simple example:               Clear[example]     example[a_] := (        Clear[fun];        fun[x_, y_] :=            Evaluate[x Total[RandomVariate[NormalDistribution[], a]] + y ];        );      The function `example` has no return value, but it defines the function `fun`, which I can use until I need to get a new instance of the function `fun` which I do by running `example[a]`.


title: Changing all link destinations in a notebook

text: I have a bunch of cells containing text and hyperlinks. i.e. of the form:               Cell[TextData[{      "Text",      ButtonBox["Linktext",       BaseStyle->"Hyperlink",       ButtonData->"linktag"],      "more text"     }], "Text"]       Is there a automated way of changing all of the link destinations so that they link to the same tag as the original, but in a different file, like this:               Cell[TextData[{      "Text",      ButtonBox["Linktext",       BaseStyle->"Hyperlink",       ButtonData->{"filename", "linktag"}],      "more text"     }], "Text"]       Note that "linktag" is a different string for most of the cells.


title: Assigning Sequence to Part of a SparseArray (bug?)

text: `Part` > ▪ You can make an assignment like `t[[spec]]=value` to modify any part or > sequence of parts in an expression. > > ▪ If `expr` is a `SparseArray` object, `expr[[...]]` gives the parts in the > corresponding ordinary array. `SparseArray` > ▪ List and matrix operations are typically set up to work as they do on > `Normal[SparseArray[...]]`. > > ▪ `Part` extracts specified parts of the array represented by a > `SparseArray` object, rather than parts of the `SparseArray` expression > itself.               array = Range[10]     (* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} *)          array[[2]] = Sequence[0, 0, 0];          array     (* {1, 0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10} *)          sparse = SparseArray[Range[10]];          sparse[[2]] = Sequence[0, 0, 0];          sparse[[2]]     (* {10} *)          ArrayRules[sparse]     (* ArrayRules::rect: Nonrectangular array encountered. >> *)     (* ArrayRules[SparseArray[Automatic, {10}, 0,          {1, {{0, 10}, {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}}},           {1, 0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10}}]] *)      Is it a bug?


title: Hilbert-Huang transform package

text: I am trying to learn Hilbert-Huang transform (HHT) and its applications (especially in ECG signal processing). There are several HHT packages (scripts) HHT for R and Matlab. Is there any known solution for _Mathematica_ or I should write my own implementation of HHT?


title: Interactive plot with checklist

text: I'd need to write an interactive plot. I have some function I defined and some point lists I get from external data file. I'd need to see those data along with my functions, and I know how to do that. However I would also like to have a checklist, and by clicking over each button I should be able to show/hide a function or a data point set. I don't need the full code, just a hint about how to get a checklist, and how to make it dynamically affect the function I'm plotting would be great!


title: Evaluate a list of Expressions from file

text: I have a list of expressions in a text file. I would like mathematica to evaluate and export the results at the end of the same file or in a new file. The expressions are in seperate lines in the text file.


title: Using DeleteCases and Map together

text: Given:               list1 = {{"a",1},{"b",2},{"c",3}}       I would like to delete any pair in list1 that does not have a first element that belongs to list2. > Example 1: If list2 = {"b"}, Output = {{"b",2}}   >  Example 2: If list2 = {"A","b"}, Output = {{"a",1},{"b",2}} Here's what I have so far:               DeleteCases[list1,{#,_}/; !StringMatchQ[#,list2, IgnoreCase -> True]&].      I know this won't work (because StringMatchQ doesn't accept a list of values to compare to as a parameter, which leads me to thinking I need to Map the function above to list2.


title: Pattern match any member of a Context

text: Let's say I have four functions: `x`, `y`, `X`x`, and `X`y`. Writing a pattern that matches `x`, but not `X`x` is easy               f[_x] := True; f[_] := False     { f[x[]], f[X`x[]] }     (* {True, False} *)      and the reverse is also straightforward               g[_X`x] := True; g[_] := False     { g[x[]], g[X`x[]] }     (* {False, True} *)      But, how would I match all members of `X``? Obviously, this works               h[_?(MemberQ[Names["X`*"], ToString@Head@#] &)] := True     h[_] := False     { h[x[]], h[X`x[]], h[X`y[]] }     (* {False, True, True} *)      but it seems excessive, especially if the `Context` contains a large number of functions.


title: How can I connect Mathematica to Clojure?

text: I'm using Clojure and I'd really love to be able to use some of Mathematica's functions inside it. Can anyone help with mathlinking it?


title: Parallelize matrix operations

text: I'm trying to reduce to a minimum the time of some matrix operations. When I don't parallelize and write the code in the most compact form I get the operation done in around 1sec (is this good? the matrices are around 1000x1000 machine precision numbers):               In[494]:= newtotd = AbsoluteTiming[        fullmat[[nodenumb]]/tempmat        ][[1]]          Out[494]= 1.006177      But if I try to have mathematica parallelizing it (4 cores) the performance is much worse:               In[492]:= newtotd = AbsoluteTiming[        Parallelize[fullmat[[nodenumb]]/tempmat]        ][[1]]          Out[492]= 2.362393      I also tried to write the code in a more explicit form, with Table (this actually gives the transposed "newtotd" matrix as a result, which is even better for me):               In[497]:= newtotd =      AbsoluteTiming[Table[         fullmat[[nodenumb, k]]/tempmat[[j, k]],         {j, Length[tempmat]}, {k, Length[tempmat]}]][[1]]               Out[497]= 3.154871      and as expected it's even worse. But I was hoping that ParallelTable would do better. I was wrong, I aborted the evaluation after 1 minute:               In[498]:= newtotd =      AbsoluteTiming[ParallelTable[         fullmat[[nodenumb, k]]/tempmat[[j, k]],         {j, Length[products]}, {k, Length[products]}]][[1]]               Out[498]= $Aborted      What's happening? I guess it should be something related to passing the matrices back and forth between the kernels, but how do I avoid it? (of course tempmat has no 0. entries) ( ** _EDIT_** ) The operation described in the first piece of code takes so long because there are lots of Infinity entries in the tempmat matrix. If I replace them with 1. and keep track of their position, I can then change the corresponding entries in the resulting matrix to be 0., but still this operation takes much longer than I can accept:               In[154]:= (*Get the position of all Infinity entries in tempmat*)          infpos = Position[tempmat, Infinity];     (*Replace them with 1.*)          Table[tempmat[[infpos[[i, 1]], infpos[[i, 2]]]] = 1., {i,         Length[infpos]}];     AbsoluteTiming[       newtotd = fullmat[[nodenumb]]/tempmat       ][[1]]     (*Set the corresponding entries in the newtotd matrix to be 0. as \     they should if I the Infinties weren't removed*)     AbsoluteTiming[       Table[newtotd[[infpos[[i, 1]], infpos[[i, 2]]]] = 0., {i,           Length[infpos]}];       ][[1]]               Out[156]= 0.046682          Out[157]= 2.423674      Perhaps you can think of a faster way to set all the "infpos" entries to 0 at the end?


title: Saving a text file with an unknown extension

text: I need to export a file with the extension .mac (short for macro in an external program), though it is essentially a text file (saving .mac in Microsoft notepad works fine). However if I try something like:               Export["test.mac", "The brown fox."]      I recieve the error:               Export::infer: Cannot infer format of file test.mac. >>      Is there a workaround?


title: How can you profile compiled code?

text: Is it possible to profile compiled code? I am using Workbench 2.0 and the Profile[] command but I do not get a profile of my compiled function. I apologize if the answer is readily available but I could not find it Workbench documentation nor using Google.


title: Plot failing over set domain with any functions

text: I'm here with a rather interesting problem which I have no clue how to fix. I am trying to plot a function:               Plot[x && 0 <= x <= (1/8), {x,-9,9}]      However the graph does not seem to appear at all. The interesting thing though is if I change $\frac{1}{8}$ to $\frac{185}{1000}$ the plot works normally. Change it to $\frac{184}{1000}$ and it stops working again. So why does nothing plot where the second value is below $\frac{184}{1000}$? Regarding to why I don't use the {x,-9,9} to set the domain. I am plotting other functions on the same graph and omitted them for this post. The error is still present when it is on its own. Also if you were wondering. Here are some other things I did to troubleshoot the error to save some time. Firstly, changing the first value of 0 to $\frac{1}{100}$ retrieves the same problem and the second value can not go below $\frac{184}{1000}$ but can still go above $\frac{185}{1000}$ so it doesnt seem like the issues relates to the difference between the minimum and maximum. Changing the function to $2x$ doesnt change this either and has the same possible values. Same with $2x^2$ and $\sqrt{x}$. So from this I can see this problem occurs with every single type of function. There is one parameter which changes this however. If we change {x,-9,9} to {x,-8,8} then $\frac{184}{1000}$ becomes possible. As a result of changing this the new possible values for the domain are $\frac{164}{1000}$ and above (instead of $\frac{185}{1000}$ and above). Anything lower and it doesnt work although I haven't gone to any larger denominators I'm sure its evident to see there is some issue here. Also, if this is just purely a Mathematica error. Any alternatives to set a domain for an individual function without using Show[plot1,plot2 etc.] would be awesome. If it helps I am on Mathematica 9.0. Thanks EDIT: Just clarifying here after a response. I wish for the final plot to still show from -9 to 9 because there are other functions being plotted on this graph and this is the domain I wish for the entire graph to go over.


title: How to graph a sphere with cartesian equations?

text: I'm new to Mathematica and I need to ask how to graph a sphere, cylinder, etc.. using cartesian equations. For example in sphere's case $x^2+y^2+z^2=1$ I tried to use `Plot3D` but it doesn't work..


title: Find point at which equation stops having roots (if it exists)

text: I am interested in the roots of this function:               f[M_, b_] := 1 - (2 M Gamma[2, 0, (1/M + b M)/Sqrt[b]])/(1/M + b M)      for fixed values of b. In particular I want the value of b at which the function of M stops having roots. My code to do this is:               Do[s = FindRoot[f[m, b], {m, n}][[1, 2]]; Print[s]; n = s + .5;, {b, .005, 1000, 5}]      It seems to work but I'm not sure how to keep trying new values of b until there are no more solutions, instead of trying bigger and bigger b_max (in this case 1000). Also I get some error messages from FindRoot; is this something to worry about? How accurate is this code? Thanks!


title: Can Mathematica show me a fraction with a repeating decimal notation?

text: The value of `3/817` when expressed using the `N[3/817, 100]` shows me data without helping me see the repeating patterns: After I mess around with the results in Notepad, I can reformat it in notepad so I see the repeating decimals, but what I would really like to see is a line over the repeating group of digits, like this: ![enter image description here](http://i.stack.imgur.com/yHBBy.png)


title: The guidelines for options or multiple arguments?

text: Where can I find some references concerning when to use options and when to use multiple arguments in designing and writing functions? Seems most built-in functions have arguments less than 3 and with a large number of options. Are you confusing at the choice of using arguments or options? And sometimes too many arguments which are ordered, the bad thing is that we may forget how to pass parameters with the right order. This is saying that, when using options, we don't care the order of options, just pick the ones needed. Sometimes multiple arguments could be combined to one list argument. Sometimes multiple arguments are convenient to be implemented into the rough/original demo functions. Sometimes multiple arguments are more frequently used in some of my short-run functions. Sometimes options will be added to some of my old functions, and especially long-run functions. Sometimes options can be well inherited and translated from different functions.


title: How to convert an image to a graph and get the positions of the edges?

text: I am trying to convert an image to a graph. My image is already skeletonized and looks pretty much like this: ![enter image description here](http://i.stack.imgur.com/cET4A.png) What I need to do is identify all vertices and edges, and in particular get a list of pixel positions for each edge. I've seen that using `MorphologicalGraph` would get me the vertices, but is there any way to also extract information about the position of the edges? EDIT: First, thanks a lot for all your comments! Let me clarify. @acl: I would like the lists of pixel coordinates for each edge to be grouped together. @Yves Klett: I think that this solution would not work, it gives a morphological graph and I need the pixel coordinates from the original image. @Silvia, @Daniel Lichtblau: I could extract all pixel positions this way, but I need to know which pixel belongs to which branch... @Vitaliy Kaurov: I need to know which vertex is connected to which, and this can be done using `MorphologicalGraph`. But I also need to know the exact path between 2 vertices, so for each branch on the image, I need the list of pixel coordinates. As you show in your answer, edges found using `MorphologicalGraph` do not match single-pixel image branches (and I need the latter). I guess that Silvia's answer would be a solution. What's interesting though is that to get to the morphological graph, Mathematica has to process the information on the pixel coordinates of the branches! But probably doesn't store it anywhere???


title: Can one affect the appearance of components of a control?

text: I'd like to control the appearance of the components of a `TabView[]` control. Such a control appears constructed of `Button`s, `ButtonBar`, and `Panel`. Some examples follow to illustrate my problem.               appearances = {"DialogBox", "Palette", "FramedPalette", "Frameless"};     Button[1, Print[1], Appearance -> #] & /@ appearances     ButtonBar[{1 :> Print[1], 2 :> Print[2]}, Appearance -> #] & /@ appearances     TabView[{a, b}, Appearance -> #] & /@ appearances      ![enter image description here](http://i.stack.imgur.com/Plqbd.png) In the above code I can change the appearances of an individual `Button[]` but not buttons in a `ButtonBar[]` or a `TabView[]`.               Button[1, Print[1], Background -> Yellow]      ButtonBar[{1 :> Print[1], 2 :> Print[2]}, Background -> Yellow]      TabView[{a, b}, Background -> Yellow]       ![enter image description here](http://i.stack.imgur.com/R0knv.png) The above presents a similar problem. Note that in the `ButtonBar[]` you can see a yellow halo around the entire control. Finally:               Panel[a, ImageSize -> 100, Background -> Yellow]     TabView[{a, b}, ImageSize -> 100, Background -> Yellow]      ![enter image description here](http://i.stack.imgur.com/cZgjN.png) A similar problem, I can affect `Panel[]` but not the panel component of a `TabView[]`. So, does anyway exist to reach settings that affect the component levels of a complex control? Any workarounds appreciated. ... As this seems relevant, I run version 9 on OS X.


title: Make Mathematica show function template's arguments in different lines (i.e. in column) by default?

text: I feel a bit uncomfortable with Mathematica 10's layout. I mean, I'm impressed how powerful functional programming can be and so on, but it's me or those programs are often just a bunch of nested functions with no way to make out which is the argument to whom? So, is there a way to split every function prototype in a column - with correct indentation - by DEFAULT? So to get, for example: ![indented](http://imageshack.com/a/img539/5096/dc2bbe.gif) instead of this: ![not indented](http://imageshack.com/a/img742/6458/5cf4bf.gif) That'd make everything easier - for me, at least. You may think I'm another of those "traditional coders" who can't stand the change, and yes, a sort of... But who cares? Any help, guys?


title: Value for x such that |(x-y)| is minimum

text: I have a list               Y={y1,y2,y3,...,yn}      And I would need to find x such that > `Abs[x-Y[[i]]]` for all $y_i$ in $Y$ is minimum. I unfortunatly can't remember my highschool Statistics courses where this function was defined.


title: How to place a matrix under controls (sliders) in a Manipulate?

text: I want to know how I can place a matrix under my sliders. Here is my code:               Manipulate[       Column[{         Style[{{a, 0, 0}, {0, b, 0}, {0, 0, c}} // MatrixForm,            FontSize -> 18, FontColor -> Black, TextAlignment -> Left],         Graphics3D[{GraphicsComplex[streckung[a, b, c], Polygon[i]]},            Axes -> True, Boxed -> True,            PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}},            ImageSize -> {{400, 400}}]}, Dividers -> {False, 2 -> Gray}],       {{a, 1, "x-Richtung"}, -3, 3},       {{b, 1, "y-Richtung"}, -3, 3},       {{c, 1, "z-Richtung"}, -3, 3},       ControlPlacement -> Left,       Initialization :> (         k := PolyhedronData["Cube", "VertexCoordinates"];         Short[i = PolyhedronData["Cube", "FaceIndices"]];         streckung[a_, b_, c_] := k.{{a, 0, 0}, {0, b, 0}, {0, 0, c}};       ;)]      And here is a photo how it should look like: ![enter image description here](http://i.stack.imgur.com/JWGLH.png)


title: Is there any faster way than Eigensystem to diagonalize a Hermitian matrix?

text: Is there any faster way than using "Eigensystem" to diagonalize(get all the eigenvectors and eigenvalues) of a Hermitian(self-adjoint) matrix? That would be amazing :). Thanks.


title: Is it possible to import dates and times directly as AbsoluteTime and by pass DateLists?

text: Date and time calculations are quite slow so I am exploring ways to minimize the number of calculations performed. As an example:               msft = FinancialData["MSFT", "Jan 1, 2005"]     Timing[DateListPlot[msft]]     {0.253632, *picture*}      whereas               Timing[      msft1 = msft;      msft1[[All, 1]] = AbsoluteTime /@ msft[[All, 1]];      DateListPlot[msft1]      ]     {0.214658, *picture*}      So it is faster to convert to `AbsoluteTime` and make a plot than to stick with date lists (as a side issue this can actually be done even faster with `ListPlot` or `ListLinePlot` and a tick function). When wanting to work with date lists to select subsets of data you will typically choose a search criteria in which the absolute time of elements is tested against some condition. So this is another example where it is useful to already have the data in absolute time. So the question is whether it is possible to import dates directly into Mathematica and have them as absolute times rather than date lists. My two specific examples would be `FinancialData` as per the example above -- can this be made to output absolute times via some configuration rather than having to convert the data post import? Also for Excel spreadsheets containing columns with dates (i.e. date strings as per Excel formats) and data. Can these be imported and converted to absolute times during the import process instead of converted to, and output as, date lists? (If solutions to this problem means that `Import` and `FinancialData` internals take date lists and convert to absolute time then I don't really see that as a solution. I am seeking ways to go direct to absolute time.)


title: How can I complete a correlation matrix with missing values?

text: I would like to complete a correlation matrix with missing entries, such that the resulting matrix is positive semi-definite. Say I want to find some x and some y in the next matrix that satisfy positive semi-definiteness:               matrix = {{1, y, 0.8}, {y, 1, x}, {0.8, x, 1}};      I have tried `FindInstance`, `Maximize` and `FindMaximum`. They all give good results. First a define a function that is used to feed the optimisation functions:               testmatrix[input_, xtest_, ytest_] :=  input /. {x -> xtest, y -> ytest}      The solutions now are:               sol1 = Maximize[Min[Eigenvalues[testmatrix[matrix, x, y]]], {x, y}]          sol2 = FindInstance[Min[Eigenvalues[testmatrix[matrix, x, y]]] > 0 && 0 < x < 1 && 0 < y < 1, {x, y}, Reals, 1]          sol3 = FindMaximum[Min[Eigenvalues[testmatrix[matrix, x, y]]], {x, y}]      All results give a positive semi-definite correlation matrix:               PositiveDefiniteMatrixQ[testmatrix[matrix, x /. sol1[[2]], y /. sol1[[2]]]]     PositiveDefiniteMatrixQ[testmatrix[matrix, x /. sol2[[2]], y /. sol2[[2]]]]     PositiveDefiniteMatrixQ[testmatrix[matrix, x /. sol3[[1]], y /. sol3[[1]]]]      However, when the size of the matrix and the number of unknowns increase, the calculation time explodes using all methods. Note that I don't require anything else than positive semi-definiteness. I would assume that `FindInstance` would be the fastest candidate since it does not require an optimal value. Who knows a way to make the procedure more efficient? Your help is much appreciated.


title: Is it possible to use C# LINQ from Mathematica using .NET/Link?

text: Using _Mathematica_ 's .NET/Link (`NETLink``) package, is it possible to call out to .NET's LINQ facilities for list manipulation and other operations?


title: Eliminate variables by dividing two equations

text: how is it possible to divide two equations with Mathematica? I have the following code:               eqn416 = a == Kp h (1 - E^(-ta/tau))     eqn417 = a/2 == Kp h (1 - E^(-ta2/tau))      Obviously one will get               2 E^(-(ta2/tau)) - E^(-(ta/tau)) == 1      by dividing them, but with               Eliminate[{eqn416, eqn417}, {Kp, h, a}]      I only get 'True'. And if I try just to eliminate 2 of them and assuming afterwards 'a' is not zero               Eliminate[{eqn416, eqn417}, {Kp, h}];     %[[2]]     FullSimplify[%, a != 0]      I'm not getting rid of 'a'!               FullSimplify[a (1 + E^(-(ta/tau)) - 2 E^(-(ta2/tau))) == 0,       a != 0]     (* Out[434]= a (1 + E^(-(ta/tau)) - 2 E^(-(ta2/tau))) == 0 *)      Any suggestions?


title: What's a robust way to insert another extension into a filename?

text: I'd like to add an extension to a filename before the file extension, otherwise leaving the given filename the same. In particular, absolute filenames should stay absolute, and relative filenames should stay relative. Examples: suppose the piece I want to insert is `".123"`, then   * `/home/me/dir/foo.txt` becomes `/home/me/dir/foo.123.txt`.   * `xyz.csv` becomes `xyz.123.csv`   * `foobar` becomes `foobar.123` (just append in case of no extension) I don't expect to be dealing with filenames that already have multiple extensions, but just in case, the desired behavior is   * `nomnom.tar.gz` becomes `nomnom.123.tar.gz` I can ensure that the filename does not end with a slash. The obvious way to do this is by concatenating the directory name, the file base name, the new piece, and the extension:               insertPiece[fn_, piece_] := FileNameJoin[{           DirectoryName[fn],           StringJoin[{FileBaseName[fn], piece, ".", FileExtension[fn]}]     }]      but is there some corner case I missed in which this wouldn't work? Is there a more efficient or more elegant way to do it?


title: Is there something like MaxProcessorUsed?

text: For standard procedures it is easy to test if the implementation is better or worse than other by using `Timing` etc. It does not help us with creating `Dynamic` interfaces/visualisations. Sometimes it is obvious that one way is _more laggy_ , but not always and it is not so precise method too. **So my question is** : is there something like `MaxProcessorUsed` analogical to `MaxMemoryUsed`, so I could start it, play with the notebook, end it and get the result in terms of `%` for example. * * * I have not found anything so I'm looking forward seeing your ideas. :) This seems to be a useful tool for GUI creators. Moreover, I've failed looking for anything to get information about current processor/cores state via _Mathematica_ functions. * * * Also, I'm aware that the performance is not so easy to measure. We have to take under consideration GPU usage, existance of multi core vs. single vs. multi thread etc. But let's focus on basic case now.


title: Colorbar doesn't appear

text: I have a list of data with dimensions $(2000,4)$. I plotted it using `ListPointPlot3D`, setting the fourth dimension as the color. As follows:               ListPointPlot3D[List /@ data[[All, {1, 2, 3}]],        PlotStyle -> ({PointSize[Large],             Blend[{{0, Darker[Green]}, {5, Yellow}, {10, Red}}, #1]} & /@           Flatten[data[[All, {4}]]]), RotationAction -> "Clip"]      I want to show the colorbar, I tried the function `ShowLegend`, but it didn't work. Any ideas?


title: Complex differential equation

text: I want to solve $dx/dt=\sqrt{(1-x^2)}$, where $x$ is complex. When I solve it by hand and analytically for some initial value and draw the imaginary part versus the real part, I obtain an ellipse, as expected. I tried to solve it with _Mathematica_ , but I failed. Here is my code:               s = NDSolve[{x'[t] == (1 - x[t]^2)^0.5, x[0] == 1 + I}, x[t], {t, 0, 10},           Method -> "ExplicitMidpoint",   "StartingStepSize" -> 1/10];          ParametricPlot[Evaluate[{Re[x[t]], Im[x[t]]} /. s], {t, 0, 10}, PlotRange -> Full]      ![Mathematica graphics](http://i.stack.imgur.com/W4uG3.png) I would appreciate if someone could help me to fix the problem.


title: Selectively Mapping over elements in a List

text: I am using the following code to easily generate a row of images of all eight planets of our Solar System:               Labeled[# // Text, AstronomicalData[#, "Image"]] & /@        AstronomicalData["Planet"] // Row      I like the above code because it is concise and gives nice output. However, if I wanted to do something similar for the moons in our Solar System, I run into the problem that only some moons have images. If I run the following line of code, I get a somewhat sloppy output with `Missing Image` errors embedded.               Labeled[# // Text, AstronomicalData[#, "Image"]] & /@        AstronomicalData["PlanetaryMoon"] // Row      I was wondering if there is a simple way to `Map` over a list of data conditionally? That is, if an element in a list does not meet a specific condition then skip over it. Note that I'm looking to avoid an explicit loop with an `If` construct. I really don't mind using a loop with an `If` statement, but I was curious if there was a concise idiom that anyone could shed some light on.


title: Undocumented WolframLibraryData::evaluateExpression

text: It seem there's this promising function in the callback object provided to MathLink C functions:               struct st_WolframLibraryData     {         /* ... */         int (*evaluateExpression)(WolframLibraryData, char *, int, mint, void *);         /* ... */     };      If this does what it seems it does, it would save the boring and lengthy code that comes with managing a `MLINK` object for some purpose. But I'm lost at interpreting the arguments (and if the second one is supposedly the string to execute, why is it not `const`?).


title: How to print horizontal lists in TableForm?

text: How to print the table with the first column as $\{1,2,3\}$ instead of $\begin{array}{c} 1 \\ 2 \\ 3 \\\end{array}$?               a = {{1, 2, 3}, 1, 4, 9};     b = {{4, 6, 2}, 16, 36, 4};     TableForm[{a, b}]      > ![enter image description here](http://i.stack.imgur.com/XSXVz.png) The aim would be to handle the following example:               c = Table[{{i, i + 1, i + 3}, i + 4, i + 5, N[1/i]}, {i, 1, 34}];     TableForm[c]


title: Why does Mathematica find a form for this general sum, but not for some special cases?

text: Today I found a Sum which Mathematica will simplify for a general parameter value $\nu$, but which will not simplify fully for special cases $\nu = 1, 3, ...$ despite the fact that the general answer is correct for these special cases, as far as I can tell. I was investigating an explicit form for $$ \frac{d}{d \nu} I_\nu(z) $$ Wolfram gives a series representation. Plugging this into Mathematica I find:               In[23]:= FullSimplify[(Sum[(-((2^-\[Nu] z^\[Nu] Log[2])/       Gamma[1 + k + \[Nu]]) + (2^-\[Nu] z^\[Nu] Log[z])/       Gamma[1 + k + \[Nu]] - (       2^-\[Nu] z^\[Nu] PolyGamma[0, 1 + k + \[Nu]])/       Gamma[1 + k + \[Nu]]) (1/k! (z/2)^(2 k)), {k, 0, \[Infinity]}])]          Out[23]= BesselI[\[Nu],       z] (EulerGamma - HarmonicNumber[\[Nu]] + Log[z/2]) -       2^-\[Nu] z^\[Nu] Gamma[1 + \[Nu]]       \!\(\*SuperscriptBox[\(HypergeometricPFQRegularized\),       TagBox[      RowBox[{"(",       RowBox[{      RowBox[{"{", "1", "}"}], ",",       RowBox[{"{",       RowBox[{"0", ",", "0"}], "}"}], ",", "0"}], ")"}],      Derivative],      MultilineFunction->None]\)[{1 + \[Nu]}, {1 + \[Nu], 1 + \[Nu]}, z^2/4]      But if I try the same thing for the special case $\nu =1$               FullSimplify[     Sum[(-((z Log[2])/(2 Gamma[2 + k])) + (z Log[z])/(2 Gamma[2 + k]) - (z PolyGamma[0, 2 + k])/(2 Gamma[2 + k])) (1/k! (z/2)^(2 k)), {k, 0, \[Infinity]}]]      It just returns the original sum. I have compared the original derivative of a Bessel function to the general expression for $\nu =1$ numerically and they seem to match. Why is it that Mathematica will not simplify these special cases?


title: double arrow in GraphPlot

text: Is it possible to combine two edges into one with a double arrow? For example:               GraphPlot[{1 -> 2, 2 -> 1}, VertexLabeling -> True,       DirectedEdges -> True]      results something like ![enter image description here](http://i.stack.imgur.com/oxohj.jpg) Is it possible to change it to something like ![enter image description here](http://i.stack.imgur.com/24lvj.jpg) without using the drawing tool to edit the graphics directly?


title: 3D plot of two 2D functions

text: I would like to plot two 2d functions in a 3d coordinate system. Examples are `z = x^2` and `z = y^2`. Each function has one independent variable, (either `x` or `y`), and a global dependent variable (`z`).


title: Can't plot recursive function

text: I am new to _Mathematica_ and now I could use some help. Trying to plot any of these functions generates a `$RecursionLimit` exception and I am wondering why.               G[y_] := 0.7 G[y - 1]     G[0] = 100;          J[y_] := 0.1*G[y - 1] + 0.6 J[y - 1]          H[y_] := 0.2*J[y] + 0.8*H[y - 1]     H[0] = 0          Plot[ G[x], {x, 0, 10}]      > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> Evaluating any of `G[2]`, `H[4]`, `J[3]` works fine. Any ideas would be much appreciated :)


title: Is there a way to outline text?

text: If I have:               Graphics[       {Red, EdgeForm[Directive[White, Thick]],        Inset[Style[Text@"Hi!", 44], {0, 0}]}, Background -> Black     ]        I unfortunately get:   ![hi](http://s13.postimage.org/63ji6ifh3/temp.jpg)   Which as you can see does not have a thick white outline. Is there a way to get around this since `EdgeForm` clearly does not work? By the way, I would rather NOT delve into making a larger, white `"Hi"` and then putting the red one on top. That's just not elegant. MMA 8.0.1 for students   OS Windows 7 64-bit


title: SuperscriptBox question

text: I am trying to define an object type in Mathematica as follows               Operator /: MakeBoxes[Operator[pow_, sym_], fmt_] :=      With[{sbox = If[StringQ[sym], sym, ToBoxes[sym]]},With[{abox = SuperscriptBox[#, pow]     &@sbox},InterpretationBox[abox, Operator[pow, sym]]]]      This works fine when I use integer powers for example               X = Operator[2,x]      gives me $x^2$, however it doesn't work if I use a symbol for the power for example               Y = Operator[a+b,x]      should give $x^{a+b}$ but it does not. What needs to be changed?


title: How to manipulate nested expressions?

text: I have the following expression, only slightly complicated, and I'd like to do two things:   1. `Plot` the elements of the lists (though messy, all are in the same range) in terms of the range of the random variable in `Expectation`. (0.1 in the working example)   2. Let the `Plot` work with `Manipulate` so that the user can experiment with different underlying values. With all these `SetDelayed` used, I could not get `Manipulate` to work (`Plot` is simply slow). Basically, I am not sure if I can simply feed a new value for `underlying` into the last line (`Expectation`), or I need `Replace`, or some rule, a `Block`, or `With`?               underlying := {0.8,0.7,0.5,0.4,0.8,0.7}     answers := MapThread[(Min[1,Max[#1 + #2 ,0]])&,{underlying, {e1,e2,e3,e4,e5,e6}}]     disc :={answers[[5]],answers[[6]],answers[[3]]/answers[[1]],answers[[4]]/answers[[2]]}      DB :={disc[[2]]/disc[[1]],disc[[1]]^2/disc[[2]]}      db :={disc[[4]]/disc[[3]],disc[[3]]^2/disc[[4]]}      deltasbetas = Expectation[{disc,DB,db},{e1,e2,e3,e4,e5,e6}           \[Distributed]UniformDistribution[Table[{0,0.1},{6}]]]          (* {{0.85,0.75,0.647807,0.600891},{0.883373,0.965877},{0.931221,0.705072}} *)


title: Why doesn't FindRoot work correctly?

text: I'm trying to find the roots of the following equation: ![enter image description here](http://i.stack.imgur.com/nY3bK.png) I need to find `λ`s for different values of `ξ`. I know that for all values of `ξ`, I must have `n<λ<n+1/2`. I use `FindRoot` to do this. When I put `ξ^2=2`, I can find all the correct roots. For example, for the first 5 roots, I have               FindRoot[x - Pi*Cot[Pi*x] == 0, {x, 0.5}]     (* Out[173]= {x -> 0.454288} *)          FindRoot[x - Pi*Cot[Pi*x] == 0, {x, 1.5}]     (* Out[174]= {x -> 1.36917} *)          FindRoot[x - Pi*Cot[Pi*x] == 0, {x, 2.5}]     (* Out[175]= {x -> 2.29891} *)          FindRoot[x - Pi*Cot[Pi*x] == 0, {x, 3.5}]     (* Out[176]= {x -> 3.24485} *)          FindRoot[x - Pi*Cot[Pi*x] == 0, {x, 4.5}]     (* Out[177]= {x -> 4.20427} *)      Comparing with the following plot, these roots are correct (The roots are where the red line is coinciding with the green curve): ![enter image description here](http://i.stack.imgur.com/T0vlj.png) But when I put some different value for `ξ^2`, for example `ξ^2=0.5` (which is a value which I need to use in my calculations), `FindRoot` doesn't give me the correct roots anymore:               FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 0.5}]     (* Out[191]= {x -> 0.362393} *)          FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 1.5}]     (* Out[192]= {x -> 1.18617} *)          FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 2.5}]     (* Out[193]= {x -> 2.11326} *)          FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 3.5}]     (* Out[194]= {x -> 2.11326} *)          FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 4.5}]     (* Out[195]= {x -> 3.07949} *)          FindRoot[x - 0.25*Pi*Cot[Pi*x] == 0, {x, 5.5}]     (* Out[196]= {x -> 5.04912} *)      Which are not the correct roots (specially the 4th and 5th ones) compared to this plot: ![enter image description here](http://i.stack.imgur.com/Y35FS.png) Why doesn't `FindRoot` work correctly? What am I doing wrong?


title: Notebook output behaving erratically

text: Normally, when reevaluating a cell, the following output cell is overwritten with the new result. I have a lengthy notebook in which at some point for unknown reasons each reevaluation generates a new output cell. I have no clue how to stop this - I think it has to do with the option `OutputAutoOverwrite`, but setting this to True does not help. Any clue on how to reset the behaviour of the notebook to the default? After experimenting more the situation gets even worse: If I set both `CellAutoOverwrite` and `OutputAutoOverwrite` to `True`, reevaluating expressions overwrite now the following output cell. But if there is a text cell following the output cell, the text cell gets overwritten with the revised output cell! And if there is a subsection cell following the output cell, the output cell is deleted, but the new output cell is placed after the subsection cell... Found the reason now for this strange behaviour: All text cells and subtitle cells had received the option `CellAutoOverwrite->True`. By manually changing this to `False` (but leaving `OutputAutoOverwrite` to `True`), the notebook behaves now again normally.


title: Controlling the frequency of dotting in a plot

text: It is possible to make a dotted `ListPlot`. For example:               x = Range[0, 1, 0.0001];     y = Sin[x];     ListPlot[Transpose[{x, y}], PlotRange -> All, Joined -> True, PlotStyle -> Dotted]      ![Dotted](http://i.stack.imgur.com/1Rw6r.gif) Is it possible to modify the frequency (i.e., spacing) of dotting?


title: Constrain integration to be over real domain

text: I am trying to integrate the following:               Integrate[(2*Cos[Sqrt[F]*z - G])/E^(D*(p + z)^2),  {z, -(h/2), h/2}]      I am getting solution in complex domain: > >     (1/(2 Sqrt[D]))E^(-(F/(4 D)) - I (G + Sqrt[F] p)) Sqrt[π] (E^(2 I (G + > Sqrt[F] p)) >     (-Erf[(I Sqrt[F] - D h + 2 D p)/(2 Sqrt[D])] + >       Erf[(I Sqrt[F] + D (h + 2 p))/(2 Sqrt[D])]) + >       I (Erfi[(Sqrt[F] - I D (h - 2 p))/(2 Sqrt[D])] - >           Erfi[(Sqrt[F] + I D (h + 2 p))/(2 Sqrt[D])])) >   What do I do to force _Mathematica_ to report solution only in real domain?


title: How to force 2+2=5

text: I was looking at this question (writing a program such that 2 + 2 = 5) and tried to write something in Mathematica, but I couldn't get something to work without completely replacing `Plus`. Neither of these worked:               Unprotect[Plus]     Plus[2, 2] := 5     Unprotect[Integer]     2 + 2 ^= 5      This book suggests that `Plus` and `Times` have special rules. Is this really impossible to do?


title: setting a variable equal to the output of FindRoot

text: So I set a function f[x]               f[x_] := x*E^(-x) - 0.16064      Then I set a variable 'actualroot' to the function FindRoot, starting at 3               actualroot = FindRoot[ f[x], {x, 3} ]      and get the output               {x -> 2.88976}      Later I want to compare this output with a different estimate (-2.88673) of the root, and calculate error, so I have               Abs[ (actualroot - estimateroot)/actualroot ]      and i get this output:               Abs[ (-2.88673 + (x -> 2.88976))/(x -> 2.88976) ]      How do I get mathematica to evaluate this expression? I also tried using N[] to give me a decimal evaluation but it didn't work.


title: Convolving/integrating problems

text: Let's say I want to convolve two functions (f and g), a gaussian with a breit- wigner:               f[x_] := 1/(Sqrt[2 π] σ)Exp[-(1/2) ((x - μ)/σ)^2];     g[x_] := 1/π (γ/((x - μ)^2 + γ^2));      One way is to use Convolve like:               Convolve[f[x],g[x],x,y];      But that gives:               (γ Convolve[E^(-((x - μ)^2/(2 σ^2))),1/(γ^2 + (x - μ)^2), x, y])/(Sqrt[2] π^(3/2) σ)      ,which means it couldn't do the convolution. I then tried the integration (the definition of the convolution):               Integrate[f[x]*g[y - x], {x, 0, y}, Assumptions->{x > 0, y > 0}]      But again, it couldn't integrate. I know that there are functions that can't be integrated analytically, but it seems to me that whenever I go into convolution, I find another function that can't be integrated. Is the numerical integration the only way to do convolution in Mathematica (besides those simple functions in the examples), or am I doing something wrong? My target is to convolute a crystal-ball with a breit-weigner. The CB is something like:               Piecewise[{{norm*Exp[-(1/2) ((x - μ)/σ)^2], (     x - μ)/σ > -α},     {norm*(n/Abs[α])^n*      Exp[-(1/2) α^2]*((n/Abs[α] - Abs[α]) - (        x - μ)/σ)^-n, (x - μ)/σ <= -α}}]      I've done this in C++ but I thought I try it in Mathematica and use it to fit some data. So please tell me if I have to make a numerical integration routine in Mathematica or there's more to the analytic integration.


title: How can I view WebMathematica documentation in Mathematica documentation?

text: I want to view `WebMathematica` documentation in `Mathematica`documentation,for that I read the following link. I followed same things what they mention,still it's not working. enter link description here I have all permissions,but I tried the following two ways. case 1: I placed `WebMathematicaDocumentation` folder in `FileNameJoin[{$InstallationDirectory, "AddOns", "Applications"}]` directory case 2: I placed `WebMathematicaDocumentation` folder in `FileNameJoin[{$UserBaseDirectory, "Applications"}]` directory. How can I resolve this ? Thanks in advance


title: Notebook manipulation to "Save as (HTML)"

text: In a previous question, I said that I wanted to display code as text in "Save as (HTML)". I am closer, but would like to ask the community for a better approach by telling the whole picture. I did my poor's man mathematica blog (here), which is a Rails app that renders HTML. The HTML comes from _Mathematica_ 's "Save as HTML", and the Rails app does some HTML manipulation to get it into the blog, including the CDF bits. So, within _Mathematica_ , what I do is I generate the graphics cells using special code like                  CellPrint[           ExpressionCell[            Manipulate[             Plot[Piecewise[{{k, u >= k}, {u, u >= -k && u < k}, {-k,                  u < -k}}], {u, -2, 2}, AxesLabel -> {"x-t", "\[Psi]"}], {k, 0,               2}], "Output", CellTags -> "psi.cdf", CellMargins -> 0.]];      which, as you can see, makes sure that the generated Cell has the tag "psi.cdf". Then I hide all the code cells (otherwise they get generated as images by "Save as...".) Then I do "Save as..." (HTML) and the standard HTML generator puts an HTML markup with the "psi.cdf" in it around tagged cells; and later (see below) the Rails app picks it up and transform that HTML bit into the HTML that actually embeds the CDF. Also, manually, I go to each of such tagged Cells and do "Deploy standalone" to get the "psi.cdf" into the same folder. Then, I upload all files to the server and off you go, the Rails app picks up the HTML markup generated for the tagged cells and replaces that by CDF embedding code and it gets properly displayed inside the blog. I have some issues: 1) I would like to display the code, for the Manipulate and the other graphics, but -as you can see above- the code is really wrapped into a CellPrint. Ugly, I think. If I ever publish that code it won't make people happy. In an ideal world, I would prefer to use 'plain code' and let the 'publishing' take care of the rest. 2) I would like to get help from the community (get ideas) as to how to use the "Save as (html)" better or if a much controlled way via a 'Publishing Palette' is more appropriate for this. Ideally, I think, only the InputCells should be tagged (if they have Manipulate as output) and the corresponding output cell should be 'deployed' etc automatically. Is this possible? Any ideas/insights are welcome. By the way, the Rails code is open source (here), not the best code in the world, but... Thanks in advance for all comments :) **Updates** I started working on a palette for this and posting more specific questions. Help will be appreciated: (1) About grabbing CellTags (2) Iterates properly, I think, but need to export Output cell to CDF (3) Funny characters in exported code (This was an old question, which I updated based on latest developments)


title: How to set an absolute path name using SetDirectory?

text: I tried the following:               Directory[]      > >     /Users/John >                 SetDirectory["Library/Mathematica"]      > >     /Users/John/Library/Mathematica >   The documentation for `SetDirectory` says: > For a relative path name, `SetDirectory` sets the directory relative to the > current working directory. So it seems that `SetDirectory` interprets my argument as a relative path name. How can I get `SetDirectory` to interpret my argument as an absolute path name, so that the result is `/Library/Mathematica` instead of `/Users/John/Library/Mathematica`?


title: Fastest way to select the longest cell

text: I'm trying to learn low-level notebook programming and I have a question. Is there faster way to select the longest cell in a notebook than this:               NB = CreateDocument[           ExpressionCell[#, "Input"] & /@ {"cell 1", Column@{"cell", "2"}, "cell 3"}]     pos = Position[#, Max @@ #][[ 1, 1]] &@                   ReplaceAll[CellSize, (# // AbsoluteOptions) & /@ Cells[NB]][[ All, 2]]          SelectionMove[Cells[NB][[ pos]], All, Cell]


title: Construct an infix operation from a list

text: Inspired by this question, if I have a list               {a, p, b, q, c}      where `p` and `q` are binary operators, such as `Plus` and `Times`, how would I construct the expression               a ~ p ~ b ~ q ~ c      and execute it? Obviously, the solution proposed in the other question of constructing it via strings is the most straightforward approach, but I would like to know if the infix formulation, above, is doable without resorting to string manipulation.


title: Prevent front-end from reformatting long fractions while editing

text: I am editing an expression containing wide fractions (typeset with fraction boxes): ![Nicely typeset equation](http://i.stack.imgur.com/PXcKL.png) But if, while editing the equation, the fraction exceeds some threshold (seems to be approximately the window width), the front-end will helpfully replace my nicely-typeset fraction box $$\frac{\text{numerator numerator numerator}}{\text{denominator denominator denominator}}$$ with `(numerator numerator numerator)/(denominator denominator denominator)` (on one line, with parentheses added). This also happens if you write the equation correctly, and then resize the window to be narrower than the fraction (even if the cursor isn't in that cell!) ![RUINED](http://i.stack.imgur.com/Tu90s.png) The automatic reformatting persists after resizing the window back: ![RUINED FOREVER](http://i.stack.imgur.com/sKQkW.png) The result is an unreadable jumble. This is a serious problem for anyone using a tiling window manager. The same issue occurs with wide expressions inside of square-root signs. Is it possible to disable this behavior?


title: MathLink compile errors

text: Don't you just love it when your computer is working fine, you work with some good examples, everything is wonderful and your relationship with your computer is the best? I do. But what happens when your computer gets upgraded or maybe something changes along the way and then you come back to some old programs that you need? Two things can happen, either they work or they don't. It has happened again. I'm not sure what I did in my macbook to mess up some path or to delete something that Mathematica needs but now my MathLink program isn't working. Consider the solution I offered a while ago: http://mathematica.stackexchange.com/a/5730/877 In this answer I explained step by step how to get the MathLink program to work. I have the source code and I repeatedly compiled it and it was working fine. Today as I was writing a new MathLink program I started to get errors which I just couldn't figure out. So I went back to a program which I knew worked in the past and to my surprise, now that program doesn't work. I had made a MakeFile for my mathlink program, here is the trash I get now when I run it:               dhcp09:mma jmlopez$ make     /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions/mprep mlprog.tm -o mlprogtm.cpp     g++ -c -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions mlprogtm.cpp     g++ -c -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions mlprog.cpp     g++ -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions mlprogtm.o mlprog.o ../fortran/myprog.o ../fortran/libminuit.a -L/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/CompilerAdditions -lMLi3 -lstdc++ -lgfortran -framework Foundation -o mlprog     Undefined symbols for architecture x86_64:       "__Unwind_Resume", referenced from:           _mlipinterfacecontainer_new in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_interfaces_changed in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_get_decimal_names in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_get_domain_names in libMLi3.a(mlipinterface.c.o)           MLLists::MLList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~MLList()in libMLi3.a(mlipinterface.c.o)           MLLists::MLList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~MLList()in libMLi3.a(mlipinterface.c.o)           MLHashTables::MLHashTable<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, MLHashTables::MLGenericHashFunction<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::~MLHashTable()in libMLi3.a(mlipinterface.c.o)           ...     ld: symbol(s) not found for architecture x86_64     collect2: ld returned 1 exit status     make: *** [mlprog] Error 1      Oh, and this is not just for my programs, the example programs also don't work anymore. When I run make in               /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MathLinkExamples      I get the same errors:               /usr/bin/gcc -c  -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MathLinkExamples/../CompilerAdditions addtwotm.c     /usr/bin/gcc -c  -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MathLinkExamples/../CompilerAdditions addtwo.c     /usr/bin/c++  -I/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MathLinkExamples/../CompilerAdditions addtwotm.o addtwo.o -L/Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit/MathLinkExamples/../CompilerAdditions -lMLi3 -lstdc++ -framework Foundation -o addtwo     Undefined symbols for architecture x86_64:       "__Unwind_Resume", referenced from:           _mlipinterfacecontainer_new in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_interfaces_changed in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_get_decimal_names in libMLi3.a(mlipinterface.c.o)           _mlipinterfacecontainer_get_domain_names in libMLi3.a(mlipinterface.c.o)           MLLists::MLList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~MLList()in libMLi3.a(mlipinterface.c.o)           MLLists::MLList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~MLList()in libMLi3.a(mlipinterface.c.o)           MLHashTables::MLHashTable<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, MLHashTables::MLGenericHashFunction<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::~MLHashTable()in libMLi3.a(mlipinterface.c.o)           ...     ld: symbol(s) not found for architecture x86_64     collect2: ld returned 1 exit status     make: *** [addtwo] Error 1      Have you experienced this? Did I do something to my computer to mess it up? How do I fix it so that I can get back to my actual work? I know this must be because it can't find some libraries but I don't know which libraries it now decided that it wants. This problem is under Mac OS X.


title: Filling from Gridline to edge of plot

text: Hi I would simply like to fill in the region from a vertical gridline to the right boundry of the plot Here is an example               z0vals = {1.*^-8, 1.*^-7, 1.*^-6, 0.00001, 0.0001, 0.001};     evvals = {25, 26, 28, 30, 34, 44};     ptsS = MapThread[List, {z0vals, evvals}]     ListLogLinearPlot[ptsS,     PlotRange -> {{10^-8, 1}, {25, 50}},     Frame -> {True, True, False, False},     FrameLabel -> {Style["x", FontSize -> 16],      Style["y", FontSize -> 16]}, GridLines -> {{0.01}, None}]      that looks like this (i.e. shade the region from x = 0.01 to 1) many thanks. ![enter image description here](http://i.stack.imgur.com/kYOee.png)


title: Compile recursive function modifying global variables

text: How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive subroutine (there are more than one), as:   * that would require a lot of tensor copying which would cause a slowdown;   * even if passing globals would be possible, returning all affected globals from each subroutine would be tedious as each function must return a regular tensor of uniform data type. Consider the following toy problem to calculate the factorial:               fact[x_] := Module[{sub, global = 1},        sub[y_] := If[y > 0, global = global*y; sub[y - 1]];        sub@x;        global];      How to compile it without passing `global` to `sub`? While this code works nicely in the general _Mathematica_ interface, the following compiled version will call `MainEvaluate` as there is a `SetDelayed` expression which the compiler cannot handle:               factC = Compile[{{x, _Integer}}, Module[{global = 1, sub},         sub[y_] := If[y > 0, global = global*y; sub[y - 1]];         sub@x;         global]];      Is there any way to overcome this problem?


title: Unit ratio in plots?

text: I want to make a plot in which unit interval on both axes to have equal lengths visually. i.e. I want (1,1) and (0,0) to make a square rather than an elongated rectangle. ![enter image description here](http://i.stack.imgur.com/gj7EO.png)


title: Pattern Matching with Indexed Object

text: If I have a list of rules associated with indexed variables like:               solution = {a[1] -> 1, a[2] -> 10, a[3] -> 100}      I would like to be able to extract all of the values associated with the rules. Although this problem is simple with a small number of variables, I am not sure how to generalize it. For instance, I can use pattern matching to obtain 1 and 10, respectively:               a[1]/.solution     a[2]/.solution      However, I can't seem to generalize this to extract a[n] values from a list of rules. What is proper pattern to do this?


title: Implementing Bilinear Products

text: Consider a real, vector space $V$ with basis $B=\{v_1,v_2,\dots\}$, and let $\star:V\times V\to\mathbb R$ be a bilinear product on $V$. I would like to implement this product in Mathematica by specifying the action of $\star$ on pairs of basis elements, and by somehow "telling" Mathematica that the product is bilinear. More concretely, I will be specifying elements $v,w$ of $V$ as linear combinations of elements of $B$ \begin{align} v = \sum_i a_iv_i, \qquad w = \sum_i b_iv_i, \end{align} and I would like to tell Mathematica how to deal with products of any two basis elements; \begin{align} v_i\star v_j = \sum_k c_{ijk}v_k \end{align} by telling it how to generate the constants $c_{ijk}$, and then telling it that $\star$ is bilinear so that it can perform the following manipulation: \begin{align} v\star w &= \left(\sum_ia_iv_i\right)\star\left(\sum_j b_jv_j\right) = \sum_{i,j}a_ib_j (v_i\star v_j) = \sum_{ij}a_ib_j\sum_k c_{ijk}v_k\\ &= \sum_{i,j,k}a_ib_jc_{ijk}v_k \end{align} Ideally, I would like to be able to write something like this               Star[5v[3]+7v[6],14v[9]]      and have Mathematica output something like               2v[1]+5v[10]+7v[9]+11v[2234]      depending, of course, on the constants $c_{ijk}$ specified beforehand. I don't really have a sharp idea of how to approach this, any guidance would be greatly appreciated.


title: Labeling points with numbers in a Graphics expression

text: Can I label points with numbers in my Graphics expression, as in this picture ![enter image description here](http://i.stack.imgur.com/ILdjT.png) Here is my code.               Off[InterpolatingFunction::dmval]          {α, γ, ω} = {0.1, 0.05, 1};          T = (2 π)/ω;          a = NDSolve[{x''[t] - γ (1 - x[t]^2) x'[t] + x[t] == α Cos[ω t], x[0] == 0, x'[0] == 0},            {x, x', ω t}, {t, 0, 700}];          ss[n_] := Table[x[t T] /. a, {t, 0, 100 T}][[n, 1]];          ff[n_] := Table[x'[t T] /. a, {t, 0, 100 T}][[n, 1]];          g1 = ParametricPlot[Evaluate[{x[t], x'[t]} /. a], {t, 0, 100 T}];          g2 = Graphics[Table[{PointSize[Large], Red, Point[{ss[n], ff[n]}]}, {n, 1, 20}]];          Show[{g1, g2}]


title: Manipulate keeps updating due to a function

text: Edit: This is apparently only a problem on a mac running OSX. I am trying to use the 'stretchText' function by Jens. But when I use it in manipulate, the output keeps updating without changing anything. This is the simplest example in which the problems occurs:               Manipulate[      choice;           Graphics[{        stretchText["{", {0, 0}, {.1, 1}]        }],           {{choice, "b"}, {"a", "b"}},           Initialization -> {        stretchText[char_, pos_, scale_, angle_ : 0] :=           Module[{g, coords, xMin, xMax, yMin, yMax},            g = First@             First@ImportString[ExportString[char, "PDF"],                "TextOutlines" -> True];            coords =             Apply[Join,              Cases[g, FilledCurve[___, p_] :> Flatten[p, 1],               Infinity]]; {{xMin, xMax}, {yMin, yMax}} =             Map[{Min[#], Max[#]} &[#] &, Transpose[coords]];            Rotate[Inset[             Graphics[g, PlotRange -> {{xMin, xMax}, {yMin, yMax}},               If[ListQ[scale], AspectRatio -> Full,                AspectRatio -> Automatic]], pos, {xMin, yMin}, scale],             angle]];        }]      What can I do to stop the endless updating?


title: Unexpected scaling of graphics when using Show

text: Here is my code:               vslA = RegionPlot[x > 0, {x, 0, 8}, {y, 0, 1},       AspectRatio -> Automatic, PlotStyle -> RGBColor[1, 1, .4]]     fslA = RegionPlot[x > 0, {x, 8, 14}, {y, 0, 1},       AspectRatio -> Automatic, PlotStyle -> RGBColor[0.2, 0.8, .4]]     Show[fslA, vslA, AxesOrigin -> {0, 0}]      But unfortunately, instead of a long rectangle with about 57% area of one color and 43% area of a different color, I am getting this graphic: ![enter image description here](http://i.stack.imgur.com/2NxG0.jpg) Why is this happening and how can I fix this? I plan to create a big graphic by specifying coordinates of every little piece and I have worked out the coordinates just so the shapes and positions come out exactly where I want them but already just the first piece has me stumped.


title: Assignment rule to distribute matrix-multiplication over custom notation

text: I'm trying to write some code to do basic algebraic manipulations in BraKet notation. Thus far I have a function **KetToVec** which will convert any expression of the form _a1 Ket[s1]+ b Ket[s2] +..._ to a column vector, and the inverse function **VecToKet** which does the reverse. One problem I'm having is in assigning matrix multiplication rules to the Ket form of the vectors. Currently I have               Ket:/Dot[M_?MatrixQ,Ket[s__]]:= VecToKet[M.KetToVec[Ket[s]]]      which works for a single Ket. However I can't figure out how to make a similar assignment for multiplication to distribute over a linear combination of Ket's without having to overload one of the internal functions Times, Plus or Dot. What I want is a way for it to evaluate               X.(a*Ket[s]) := a*(X.Ket[s])      and hence in general               X.(a*Ket[s1]+ b*Ket[s2]+..) := a*(X.Ket[s1]) + b*(X.Ket[s2])+...      But if I try something like               Ket:/Dot[M_?MatrixQ,Times[a_,Ket[s__]]]:= a*VecToKet[M.KetToVec[Ket[s]]]      it returns the error message _"Tag Ket in ... is too deep for an assignment rule to be found"_ Is this possible? Cheers!


title: Changing Values in an Association using Map

text: I am trying to change the value of one key in an association based on the value of another key in that association. So if my association starts as:               x=<|"firstValue" -> True, "isFirstValueTrue" -> False|>      I want to change it to:               <|"firstValue" -> True, "isFirstValueTrue" -> True|>      So I wrote the function:               f[x_] := If[x[["firstValue"]], x[["isFirstValueTrue"]] = True, x[["isFirstValueTrue"]] = False]      I got an error, but based on this answer: http://stackoverflow.com/questions/12875913/setsetps-in-the-part-assignment- is-not-a-symbol I was to correct it by using`SetAttributes[f, HoldAll]` But let's say I want to do this to a list of associations:                   x={<|"firstValue" -> True, "isFirstValueTrue" -> False|>,          <|"firstValue" -> True, "isFirstValueTrue" -> True|>,          <|"firstValue" -> False, "isFirstValueTrue" -> False|>,          <|"firstValue" -> False, "isFirstValueTrue" -> True|>}      so I wrote               Map[f[#] &, x]      However, the "in the part assignment is not a symbol." error appears again and you can't `SetAttributes[Map, HoldAll]`. I realize I can make a copy of the list and make changes to that, but the actual list I'm working with is much larger so I do not want to do that. The third solution in the link above is able to be mapped, but it doesn't seem like you can replace in an association. Any suggestions?


title: Roads network visualization by thickness and color intensity by population from GIS files

text: We can have road networks of the countries in GIS shape file.For exmple from here. Normally traffic flows are proportionate to populations of the cities. ![enter image description here](http://i.stack.imgur.com/hLuYQ.jpg) I wonder how we can have the same in Mathematica?Is it possible at all?


title: Keeping axes fixed in an Animate of a 3D graphic

text: I am using the following code to animate a 20 3D `ListPointPlots`:               Dat2={{0.`, 0.`, 0.`}, {0.`, 0.`, 0.`}, {0.`, 5.`*^-8, 1.`*^-7}, {0.`,         5.`*^-8, 1.`*^-7}}[{{0.309017`, 0.077252`, 0.`, 0.`, 0.`, 0.`, 0.`,         0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0,         0}, {0.00041012`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`,         0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0}}, {{0.587785`,         0.262821`, 0.0193124`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`,         0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0, 0}, {0.00108769`,         0.000102527`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`,         0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0}}];          Animate[ListPointPlot3D[{Transpose[{Dat2[[n]][[3]],              Dat2[[n]][[1]]}] /. {x_?NumericQ, y_?NumericQ} :> {x, y, 0},              Transpose[{Dat2[[n]][[4]], Dat2[[n]][[2]]}] /. {x_?NumericQ,              y_?NumericQ} :> {x, 0, y}}, AxesOrigin -> {0, 0, 0}]             /. Point -> Line, {n, 0, 19, 1}, AnimationRunning -> False]      However, each `ListPointPlot3D` has a different x range and y range, such that the axes constantly move in the animated picture, making for a poor comparison of the behaviour. Is there any way to fix the axes in the `Animate` function?


title: Taking inverse powers of an expression to that power

text: I'm finding a curious behavior for Mathematica 8. The code               (x^3)^(1/3)      does not want to Simplify or FullSimplify. I'd prefer not to make a rule for this, because trivial extensions such as               (x^3 y^3 z)^(1/3)      should also be able to simplify (to $xy(z)^{(1/3)}$), which is not so straightforward for a rule. I suspect this may be related to this unanswered question.


title: How to remove a singularity with WhenEvent

text: Bellow I have a differential equation which hits a singularity at low values of t. What I want to do is somehow utilize the `WhenEvent` command in order to replace the last factor of the equation (`2/t a'[t]`) with 0 at low values of t in order to avoid getting errors. Is there a way to do this? Here is an example of the equation and how I attempted to use the `WhenEvent` Command.               q = NDSolve[{a''[t] ==           1/2 a[t]^2 + 1/6 a[t]^6 - 1/4 a[t]^4 - 2/t a'[t], a[0] == 1,          a'[0] == 0, WhenEvent[t < .1, a'[t] -> 0]}, a, {t, 0, 1}];      Any help would be appreciated!


title: Module variable scoping in Scheduled Tasks?

text: I ran across a scoping puzzle while experimenting with ScheduledTasks, and I'd be grateful for an explanation from the sages here. I found a workaround by intuitive horse sense, but was unable to explain to myself adequately what was wrong with my original attempt. First, a straightforward, tail-recursive, synchronous Module               Module[{state = 0, doNextIteration},      doNextIteration = Function[        state = state + 1;        If[state < 4,         (Print[state]; doNextIteration[])]];      doNextIteration[]]     (* 1 2 3 *)      Next, my first attempt to do the same with asynchronous tasks, which I need to tail-chain as one-shot ScheduledTasks. If CreateScheduledTask has a second `List` argument, then it creates a one-shot task delayed by the time in seconds in the list, just what I need for my bigger application. In this simplified sample, the ScheduledTask tail-chains a new one-shot ScheduledTask by a tail-recursive call -- just like the successful synchronous code -- once every tenth of a second until the condition on `state` produces False (ignore cleanup of the task objects for simplicity, here).               Module[{state = 0, runNextTask},      runNextTask = Function[        StartScheduledTask@         CreateScheduledTask[          state = state + 1;          If[state < 4,           (Print[state]; runNextTask[])],          {0.10}]];      runNextTask[]]      OK, the problem is this only Prints once, not the desired three times. I had a **sickening hunch** that the problem has something to do with `runNextTask` being local to the `Module` and somehow not being able to refer to itself recursively -- even though there is only one `Module` -- in the bizzaro-land of asynchrony, so I "fixed" the code as follows:               Module[{state = 0, runNextTask = Unique[]},      runNextTask[] :=       If[state < 3,        StartScheduledTask@         CreateScheduledTask[          Module[{},           state = state + 1;           Print[state];           runNextTask[]],          {0.10}]];      runNextTask[]]      I made `runNextTask` refer to a Unique global symbol, and made my function into a rewrite rule attached to `runNextTask[]`. This works great, but I don't understand well why it does. I hate being as dumb as a horse, even if I can jump the fences. Clues, advice, explanations: all appreciated.


title: Is it possible to colorize brackets in the notebook editor to see matches more easily?

text: I've seen that if I click on a square bracket `[`, I can then use "Check Balance" in the right click menu to see where the matching bracket is. Is there a way to see different levels of brackets in different colors? The closest that I've found is 'Show larger' for bracket matching syntax errors under preferences. If there's no way to colorize bracket nesting, is there a keyboard shortcut for "Check Balance" like `Shift``%` in Vim for C code?


title: How to use SuperLog by loading SMLE.m

text: I am researching a software reliability model that has many parameters that need to be estimated. I want to use a maximum likelihood estimator (MLE) to estimate those parameters. After I searched this site for similar problems, I know that `SuperLog` in SMLE.m package is helpful for MLE. And I find the paper(http://www.tri.org.au/RoseSmithD.pdf), this paper provided code of SMLE.m in Appendix B. I try to copy code from Appendix B and follow instruction in the lower half of page 230, but I still can not get the expected result(See following image). Can anyone help me? My research is suspended for this point.Thanks in advance. **SMLE.m** which I copy from the paper:               (*:Name: SMLE *)     (*:Authors: Colin Rose and Murray D. Smith *)     (*:Version: Mathematica v3, or v4, or later required *)     (*:Legal: Copyright 1999 *)     (*:Summary: Symbolic Maximum Likelihood Estimation *)     BeginPackage["SMLE`"]     SuperLog::usage ="SuperLog[On] activates the enhanced Log operator, so that Log[Product[_ _]] objects get converted into sums of logs. SuperLog[Off] switches the enhancement off."     Begin["`Private`"]     SuperLog[Q_]:=Module[{erk, iii, nnn},     Product[iii,{iii,nnn}]; (* pre-load Product *)     Which[     Q === On,     Unprotect[Log]; Clear[Log];     Log[Product[x_, {k_, a_, b_}]]:=Log[Product[Times[erk, x], {k, a, b}]]/.erk ->1;     Log[Product[HoldPattern[Times[x__]], {k_, a_, b_}]]:=Simplify[Map[Sum[#, {k, a, b}]&, Plus@@Map[Expand[PowerExpand[Log[#]]]&,List[x]]]//.Sum[u_. w_, {kk_, aa_, bb_}] :>u  Sum[w,{kk, aa, bb}] /; FreeQ[u, kk]==True];     Protect[Log]; Print["SuperLog is now On."],     Q === Off,     Unprotect[Log]; Clear[Log]; Protect[Log]; Print["SuperLog is now Off."],     True,     Print["Carumbah! Please use SuperLog[On] or SuperLog[Off]."]     ]]     End[]     Protect[ SuperLog ];      Link of SMLE.m : https://www.dropbox.com/s/e8w8yc15z8t3rw1/SMLE.m ![superlog](http://i.imgur.com/NEgVqYU.jpg?1)


title: Concatenation of lists in a Fibonacci-like pattern

text: I am trying to create a List of elements that follow the general pattern: $$X_{n+1} = X_n X_{n-1}$$ where the operation on the right hand side is concatenation, i.e., joining. I want to achieve the following pattern:   * $X_0 = \{1\}$   * $X_1 = \{1,0\}$   * $X_2 = X_1X_0 = \{1,0,1\}$   * $X_3 = X_2X_1 = \{1,0,1,1,0\}$   * $X_4 = X_3X_2 = \{1,0,1,1,0,1,0,1\}$   * $X_5 = X_4X_3 = \{1,0,1,1,0,1,0,1,1,0,1,1,0\}$ This is much like a Fibonacci sum but is more like a Fibonacci joining. If you notice, the dimension of the $n^\text{th}$ set is the $n^\text{th}$ Fibonacci number. I have gone along the lines of a Do loop but I don't know how to loop the current output with a previous output. My feeble attempts have bee thus far:               X0 = {1};X1 = {1, 0};t = Join[X0, X1];Do[Print[t];t = Join[t, t], {3}]      whose out put is               {1,1,0}     {1,1,0,1,1,0}     {1,1,0,1,1,0,1,1,0,1,1,0}      Now this is just joining the two sets three times. How do I join the set with a previous output one? Is there a tool to use that is easier/more efficient than the Do loop?


title: Rough edges plotting a surface

text: I'm trying to use `SphericalPlot3D` to create some images of a surface but I get some rough edges on the surface around the boundary. However, after rotating the image slightly these anomalies go away. I'd like to find a way to create smooth images without rotating the picture manually. There's also a strange spot at my poles which is also problematic but seems more inevitable. I've tried numerous settings and automatically rotating the image but nothing seems to help with these edge distortions. Here's my code for the top view of this surface:               a = 5;          b = 3;          \[Epsilon] = .75 - .5*Log[a]/Log[10];          freq[n_] = Sqrt[n (n - 1) (n + 2)];          t = \[Pi]/(2*freq[a]);          r1[\[Theta]_, \[Phi]_] = (1 + \[Epsilon]*Sin[t*freq[a]]*          SphericalHarmonicY[a, b, \[Phi], \[Theta]]);          SphericalPlot3D[      Re[r1[\[Theta] + \[Pi], \[Phi]]], {\[Phi], -\[Pi]/2, \[Pi]/        2}, {\[Theta], 0, \[Pi]}, Mesh -> False,       ViewPoint -> {0, 0, Infinity}, Boxed -> False, Axes -> False,       Lighting -> {{"Spot", {Gray,           Specularity[1]}, {{.5, .5, 4}, {.5, .5, 0}}, \[Pi]/          100}, {"Spot", {Gray,           Specularity[1]}, {{.5, .25, 4}, {.5, .25, 0}}, \[Pi]/          150}, {"Spot", {Gray,           Specularity[1]}, {{.25, .5, 4}, {.25, .5, 0}}, \[Pi]/          150}, {"Directional", Gray, {10, 10, 20}}},       PlotStyle -> Specularity[1], PreserveImageOptions -> False]      ![Mathematica graphics](http://i.stack.imgur.com/zxexU.png)


title: DateList coupled with String Operations

text:
Through some webscraping, I have the following list:               dates={{"
January 18, 2001
"}, {"
February 1, 2001
"},     {"
February 2, 2001
"}, {"
February 24, 2001
"},     {"
February 26, 2001
"}, {"
March 1, 2001
"},     {"
March 2, 2001
"}, {"
March 31, 2001
"}, {"
April     5, 2001
"}, {"
April 18, 2001
"}, {"
May 6, 2001
"}};      I am trying to make this into a `DateList[]` list. I can make it human readable in the following fashion:               datelist = StringReplace[       ToString[dates], "<" ~~ Except[">"] .. ~~ ">" -> ""]      > {{January 18, 2001}, {February 1, 2001}, {February 2, 2001}, \ {February 24, > 2001}, {February 26, 2001}, {March 1, 2001}, {March 2, \ 2001}, {March 31, > 2001}, {April 5, 2001}, {April 18, 2001}, {May 6, \ 2001} This brings up a list of nice dates. The only problem is that they are now a string. The list operations that I have tried to use (Cases, Pick, etc.) all deal with the whole part of a list, rather than sub-sets of each part. Is there a quick way to convert what I have in dates to a Mathematica-readable `DateList[]`?


title: how to show value of y-axis value using manipulate to select x-axis value

text: How to add a slider for the x-axis that shows the value of the y-axis based on the position of the slider. Basically providing the result of the probably given a specific lot percent defective, lpd value. I can calculate the value and when I use Column the calculation doesn't respond to changes in the plot's manipulated changes. If I put the calculation within the manipulate plot line - it shows and formatting is pretty hard to read.               Manipulate[      Plot[N[Probability[x<=c, x \[Distributed] PoissonDistribution[SampleSize *lpd]]], {lpd,0,.1},       PlotRange -> {0, 1}, Filling -> Axis],      {SampleSize, 50, 1000, Appearance -> "Labeled"},      {c, 0, 10, 1, Appearance -> "Labeled"}]


title: Why isn't Compile working for me?

text: I cannot get what's the problem with Compile function in my program. If I simply use the Abs function, I get this answer:               Abs[NestWhile[1/(#^2 + 2 #) &,        3 + 4*I, ((Abs[#1] > 0.01) && (#1 != -2 ) && (Abs[#1 - #2] >             0.001)) &, 2]]      > >     1108116250625/(4097 Sqrt[4415238971393]) >   But if I make a function called `PointFunction`, it compiles, and when I try to find its value at the point 3 + 4*I, I get this error message:               PointFunction =        Compile[{{c, _Complex}},          Abs[NestWhile[1/(#^2 + 2 #) &,          c, ((Abs[#1] > 0.01) && (#1 != -2 ) && (Abs[#1 - #2] > 0.001)) &,          2]], {{x, _Complex}}]          PointFunction[3 + 4*I]      > CompiledFunction::cfse: Compiled expression -128.657+3.99803 I should be a > machine-size integer. >>   >  CompiledFunction::cfex: Could not complete external evaluation at > instruction 1; proceeding with uncompiled evaluation. >> >   >   >     1108116250625/(4097 Sqrt[4415238971393]) >   What is the problem? I have tried different options but they didn't work, and I have no idea at all.


title: Manipulating and using result of DSolve

text: I have an unsightly looking equation that nonetheless has an analytical solution. The solution is ugly as hell, but exists; I use the following code with the `DSolve` function to generate it;               a = 5*10^-7;     po = 100;     omega = 3.0318*10^7;     ro = 5*10^-6;     Do2 = 2*10^-9;     ko = 1;          A = (a*omega)/(2*Do2);          k = ((rc - r)^2)*(ko/po);          sol = DSolve[{y'[      r] == (A)*(r  - (rc^2)/         r - (k/r)*(Log[((rc - r)^2 + k)/k]) + ((2*rc*Sqrt[k])/           r)*(ArcTan[(r - rc)/Sqrt[k]])), y[rc] == 0}, y[r], r]      This gives me a solution in terms of the variable $r$ and an as yet unknown constant $r_{c}$ - However, I know that $y(r_{o}) = p_{o} = 100$. I would like to take the result from `DSolve`, set it equal to $p_{o}$ for $r = r_{o}$ and then use this information (perhaps with `FindRoot`) to estimate $r_{c}$, and then graph the function between $r_{o}$ and $r_{c}$ but I keep running into difficulty doing this. Anyone have any idea how I'd set about doing this? I'd be grateful for any help with the syntax!


title: A Bessel & Struve functions related integral

text: I try to numerically compute this integral and I don't figure out why on earth Mathematica is not able   to do it. Is my input correct? Does it possibly have a closed form?               N[Integrate[1/2 (-2 - π BesselI[1, x] StruveL[0, x] +        BesselI[0, x] (2 + π StruveL[1, x]))/(E^x - 1), {x, 0, Infinity}]]      **EDIT:** the correct answer is **0.6076895380471122** OK, here is the infinite series representation of the above integral $$\sum_{k=1}^{\infty} \left(\arcsin\left(\frac{1}{k}\right)-\frac{1}{k}\right)$$