Resetting an animation with a custom button

I have the following code, which accepts a function via an `InputField`, and then gradually draws that function in a `Plot` using `Animate`:               Panel[DynamicModule[{f = "x^2-1", dummy = False},      Column[{Row[{InputField[Dynamic[f], String,         ContinuousAction -> True],        Dynamic[Button["Plot!", dummy = Not[dummy]]]}],      Dynamic[Animate[       Plot[If[x < Time, ToExpression[f], Undefined], {x, -5, 5},         PlotRange -> {{-5, 5}, {-5, 5}},         PlotStyle -> {Thick, Blue}], {Time, -5, 5},        LabelStyle -> White, AnimationRunning -> True]]}]]]      The problem is the animation is running constantly; and setting `AnimationRepetitions->1` means that even after updating the function, the plot will stop redrawing. What I'd like to do is have it so that the `Plot` region is only updated when the **Plot!** button is clicked. When it is clicked, the plot is drawn gradually, as above, but _only once_. To do this, I would need to be able to reset the animation from the **Plot!** button itself, and that doesn't seem possible. I thought `Clock[]` might offer an elegant solution, but I think it is also impossible to reset those. So, is there a way to do what I describe? Namely, have a graphics region that is only updated when a certain button is clicked, and when it updates an animation runs exactly once?


Cannot plot a list in ListPlot3D

I have this data files:                data1 = {{3.06122, 10000., 0.629892}, {3.06122, 11836.7, 0.590095}, {3.06122,      13673.5, 0.55436}, {3.06122, 15510.2, 0.522086}, {3.06122, 17346.9,      0.492813}, {3.06122, 19183.7, 0.466156}, {3.06122, 21020.4,      0.441802}, {3.06122, 22857.1, 0.419489}, {3.06122, 24693.9,      0.398983}, {3.06122, 26530.6, 0.380088}, {3.06122, 28367.3,      0.362635}, {3.06122, 30204.1, 0.346477}, {3.06122, 32040.8,      0.33148}, {3.06122, 33877.6, 0.317532}, {3.06122, 35714.3,      0.304534}, {3.06122, 37551., 0.292397}, {3.06122, 39387.8,      0.281043}, {3.06122, 41224.5, 0.270404}, {3.06122, 43061.2,      0.260416}, {3.06122, 44898., 0.251027}, {3.06122, 46734.7,      0.242185}, {3.06122, 48571.4, 0.233848}, {3.06122, 50408.2,      0.225977}, {3.06122, 52244.9, 0.218535}, {3.06122, 54081.6,      0.211491}, {3.06122, 55918.4, 0.20481}, {3.06122, 57755.1,      0.198475}, {3.06122, 59591.8, 0.192454}, {3.06122, 61428.6,      0.186732}, {3.06122, 63265.3, 0.181285}, {3.06122, 65102.,      0.176093}, {3.06122, 66938.8, 0.171143}, {3.06122, 68775.5,      0.166419}, {3.06122, 70612.2, 0.161905}, {3.06122, 72449.,      0.157591}, {3.06122, 74285.7, 0.153461}, {3.06122, 76122.4,      0.149508}, {3.06122, 77959.2, 0.14572}, {3.06122, 79795.9,      0.142087}, {3.06122, 81632.7, 0.1386}, {3.06122, 83469.4,      0.135253}, {3.06122, 85306.1, 0.132036}, {3.06122, 87142.9,      0.128947}, {3.06122, 88979.6, 0.125967}, {3.06122, 90816.3,      0.123105}, {3.06122, 92653.1, 0.120346}, {3.06122, 94489.8,      0.117688}, {3.06122, 96326.5, 0.115127}, {3.06122, 98163.3,      0.112655}, {3.06122, 100000., 0.110269}}          data2 = {{1.63265, 10000., 0.629892}, {1.63265, 11836.7, 0.590095}, {1.63265,        13673.5, 0.55436}, {1.63265, 15510.2, 0.522086}, {1.63265, 17346.9,        0.492813}, {1.63265, 19183.7, 0.466156}, {1.63265, 21020.4,        0.441802}, {1.63265, 22857.1, 0.419489}, {1.63265, 24693.9,        0.398983}, {1.63265, 26530.6, 0.380088}, {1.63265, 28367.3,        0.362635}, {1.63265, 30204.1, 0.346477}, {1.63265, 32040.8,        0.33148}, {1.63265, 33877.6, 0.317532}, {1.63265, 35714.3,        0.304534}, {1.63265, 37551., 0.292397}, {1.63265, 39387.8,        0.281043}, {1.63265, 41224.5, 0.270404}, {1.63265, 43061.2,        0.260416}, {1.63265, 44898., 0.251027}, {1.63265, 46734.7,        0.242185}, {1.63265, 48571.4, 0.233848}, {1.63265, 50408.2,        0.225977}, {1.63265, 52244.9, 0.218535}, {1.63265, 54081.6,        0.211491}, {1.63265, 55918.4, 0.20481}, {1.63265, 57755.1,        0.198475}, {1.63265, 59591.8, 0.192454}, {1.63265, 61428.6,        0.186732}, {1.63265, 63265.3, 0.181285}, {1.63265, 65102.,        0.176093}, {1.63265, 66938.8, 0.171143}, {1.63265, 68775.5,        0.166419}, {1.63265, 70612.2, 0.161905}, {1.63265, 72449.,        0.157591}, {1.63265, 74285.7, 0.153461}, {1.63265, 76122.4,        0.149508}, {1.63265, 77959.2, 0.14572}, {1.63265, 79795.9,        0.142087}, {1.63265, 81632.7, 0.1386}, {1.63265, 83469.4,        0.135253}, {1.63265, 85306.1, 0.132036}, {1.63265, 87142.9,        0.128947}, {1.63265, 88979.6, 0.125967}, {1.63265, 90816.3,        0.123105}, {1.63265, 92653.1, 0.120346}, {1.63265, 94489.8,        0.117688}, {1.63265, 96326.5, 0.115127}, {1.63265, 98163.3,        0.112655}, {1.63265, 100000., 0.110269}}      The first entry is the same for all points in `data1`, the same is true for `data2` too. I want to plot it in 3D, so I use:               ListPlot3D[{data1,data2}]      This is the result: ![enter image description here](http://i.stack.imgur.com/EJP1z.jpg) There is nothing!. If I delete the first entry I will get:               ListPlot[Table[Delete[data1[[i, All]], 1], {i, 1, 50}]]      ![enter image description here](http://i.stack.imgur.com/tjYuv.jpg) How can I plot `data1` and `data2` in a 3D form? I have another problem with `ArrayPlot`. I cannot plot `data1` and `data2` by `ArrayPlot` if I use `ColorFunction` option. Suppose I have:               data3 =Flatten[Table[i + j + k, {i, 1, 5}, {j, 1, 10}, {k, 1, 3}], 1]      The dimension is 50 by 3 like `data1` or `data2`. If I use `ColorFunction` option, I get:               ArrayPlot[Flatten[Table[i + j + k, {i, 1, 5}, {j, 1, 10}, {k, 1, 3}], 1],ColorFunction -> "SunsetColors"]      ![enter image description here](http://i.stack.imgur.com/5v337.jpg) If I don't use `ColorFunction` option, I get: ![enter image description here](http://i.stack.imgur.com/O1yni.jpg) I have this problem when I want to plot `data1`and `data2`. How can I resolve that?


Is there an issue tracker for already reported Mathematica bugs?

Since I'm working at least 50% on Linux which is probably the operating system which gets not so much attention from Wolfram, I find _new_ bugs regularly. What bothers me the most is, that tracking a bug down and writing a good bug report takes time but I can never be sure, someone else already reported the same issue which would render my action useless. Especially in Version 9.0.0 the community found some serious issues. Mostly they were propagated through our chat, but neither I can be online all the time nor other users. **Question:** Is there any issue tracker where one can look up open issues of Mathematica? If not, might it be possible to maintain our own tracker, where everyone can insert _confirmed_ bugs? This MathGroup message suggests, that `bugs.wolfram.com` is some webinterface to the bugtracker. Unfortunately the site is down. Let's assume, we set up our own buglist, everyone could insert not only the bug itself, but the information from the support response too. This would be extremely helpful.


Output of mathematica. Quaternion to Matrix

If I have the following instructions: ![enter image description here](http://i.stack.imgur.com/dEft3.png) How will it be the output/how will it appears in Mathematica? something like this: ![enter image description here](http://i.stack.imgur.com/W6Yjf.png) I can't recognize the output in mathematica... How can I do to appear the matrix? because it doesn't appear...


Integers in Range have trailing decimal - how to remove?

I want to create a list like               {0,0.2x,0.4x,0.6x,0.8x,1}      If I try               Range[0, 1, 0.2] x      what I get is               {0., 0.2 x, 0.4 x, 0.6 x, 0.8 x, 1. x}      The main problem is the 1.x. How do I get that to just display as x? (And also to have the 0. display as 0?)


Integrating a periodic function

I have a periodic function ff:               ff := Function[x, Piecewise[{{ff[x - 1], x >= 1}, {2 x, 0 <= x < 1}, {ff[x + 1], x < 0}}]]      Plotting it works fine:               Plot[ff[x], {x, -4, 4}, PlotRange -> {{-4, 4}, {-.5, 3}}]      ![Mathematica graphics](http://i.stack.imgur.com/EyIPM.png) But integrating it like this:               Integrate[ff[t], {t, 0, 5}]      What I get is a few of: > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> and a few of: > $IterationLimit::itlim: Iteration limit of 4096 exceeded. >> And it keeps running until I abort the evaluation. What's the problem? Thanks. * * * EDIT: Thanks for the answers. To avoid any more confusion, this is the signal I actually have to integrate. It's a bit more complex, and I wanted to know if that's the reason why it won't integrate, that's why I went for the sawtooth signal.               s := x \[Function] Piecewise[       {       {s[x + 2 Pi], x < -Pi},       {0, -Pi <= x < -Pi/2},       {Cos[x], -Pi/2 <=  x <= Pi/2},       {0, Pi >= x > Pi/2},       {s[x - 2 Pi], x > Pi}       }      ]      Plot command:               Plot[s[x], {x, -8, 6}, PlotRange -> {{-8, 6}, {-.5, 6}}]      ![Mathematica graphics](http://i.stack.imgur.com/BVcaV.png) EDIT 2: Using this much simpler, "automatically" periodic definition for the signal, there seems to be no problem with integration:               s = Function[x, Piecewise[{{0, Cos[x] < 0}, {Cos[x], Cos[x] >= 0}}]]      Still doesn't answer the question why Mathematica isn't able to integrate the signal when it's defined like above.


Convert a list of rules into 2 lists of integers

If I have a list of n number of rules, what is a concise way of breaking the data into 2 lists of the first and second part of the rule? This works, but seems like an unnecessary amount of code to me:               data = {       1 -> 3, 1 -> 3, 1 -> 3, 2 -> 3, 2 -> 3, 2 -> 1,        3 -> 2, 3 -> 2, 3 -> 3, 4 -> 1, 4 -> 2, 4 -> 2     };          list1 = First[Partition[Flatten[data /. Rule -> List], 2, 2, 1, {}]~Flatten~{2}]      > >     {1,1,1,2,2,2,3,3,3,4,4,4} >                 list2 = Last[Partition[Flatten[data /. Rule -> List], 2, 2, 1, {}]~Flatten~{2}]      > >     {3,3,3,3,3,1,2,2,3,1,2,2} >


how do I plot this surfaces in 2-D?

Let $x_1$ and $x_2$ be two real numbers and define the column vector $\mathbf{x}=[x_1,x_2]$. Let $\mathbf{A}_1$ and $\mathbf{A}_2$ be two $2\times 2$ real symmetric matrices. Then I need to plot the surfaces \begin{align} \mathbf{x}^T\mathbf{A}_1\mathbf{x}+1 &\leq 0 \\\ \mathbf{x}^T\mathbf{A}_2\mathbf{x}+1 &\leq 0 \end{align} How do I do this in _Mathematica_?


How to improve these WASD + mouse look 3D controls?

Insipred by this question and the corresponding answer I've written a code for full-screen exploration of 3D scenes using standard WASD and mouse look controls. Here it is. ![enter image description here](http://i.stack.imgur.com/6QVvd.jpg)               Begin["wasd`"];     prmWORLDWIDTH = 300;     prmVIEWERHEIGHT = 2.5;     prmMOUSESENS = 0.01;     prmKEYSENS = 2;          pos = {-146.2715891902948`, -154.52068004641723`, 2.5`}(*{0.,-200,prmVIEWERHEIGHT}*);     moveDir = {0.6365371822219685`, 0.7712460149971068`, 0.`}(*{0,1,0}*);     viewDir = moveDir;     strafeDir = {0.7712460149971068`, -0.6365371822219685`, 0.`}(*{1,0,0}*);          cube = {Gray, EdgeForm[None],        CapForm[None], Tube[{{-150, -150, 0}, {-50, 0, 0}, {50, 0, 0}}, 20         ],        Blue // Lighter,        Translate[         ExampleData[{"Geometry3D", "SpaceShuttle"}, "PolygonObjects"]~          Scale~3, {0, 0, 6}]        };     floor = {         Texture@ExampleData[{"ColorTexture", "GreenMarble"}],         EdgeForm@None,         Polygon[{{-w, -w, 0}, {-w, w, 0}, {w, w, 0}, {w, -w, 0}},          VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}]         } /. w -> prmWORLDWIDTH;          rotTrans := Function[x, Evaluate[RotationTransform[x, {0., 0., 1.}]]];     mp0 = MousePosition[];     getMouseOffset := (mousePos = MousePosition[];        {mouseDx, mouseDy} = mousePos - mp0;        mp0 = mousePos;        );     processMouse := (getMouseOffset;        viewDir =          RotationTransform[-prmMOUSESENS mouseDy, strafeDir]@viewDir;        {moveDir, strafeDir, viewDir} =          rotTrans[-prmMOUSESENS mouseDx] /@ {moveDir, strafeDir, viewDir};         );          processKeyboard := Switch[CurrentValue["EventKey"],        "w", pos += prmKEYSENS moveDir,        "s", pos -= prmKEYSENS moveDir,        "a", pos -= prmKEYSENS strafeDir,        "d", pos += prmKEYSENS strafeDir        ];          actions = {        "MouseMoved" :> processMouse,        "KeyDown" :> processKeyboard        };          hideMouse[expr_] :=        MouseAppearance[expr, Graphics[{Opacity@.01, Point@{0, 0}}]];          nb = MessageDialog[        Dynamic@EventHandler[          hideMouse@           Style[            Graphics3D[{cube, floor},             ViewVector -> {pos, pos + viewDir},             ViewRange -> {0.1, 300},             Lighting -> "Neutral",             Boxed -> False,             ImageSize -> Full,             Background -> LightBlue,             PlotRangePadding -> 0             ],            Selectable -> False,            Editable -> False            ],          actions          ],        CellMargins -> 0,        ShowCellBracket -> False,        ShowCellLabel -> False,        "TrackCellChangeTimes" -> False,        WindowElements -> {},        WindowFrame -> "Normal",        WindowSize -> Full,        WindowMargins -> Automatic,        WindowTitle -> "WASD"        ];          SetOptions[nb, NotebookEventActions -> actions];     End[];      To implement 'pure' full screen look I used this answer. Though I'm pretty satisfied with the result there are some issues here which require tweaking.   1. Since mouse offset events are implemented using `MousePosition` it is quite easy to get mouse look stucked (e.g. when you try to turn around). This happens when hidden mouse cursor hits screen borders. So, **how to correctly handle mouse offset events?**   2. It is impossible to move diagonally because **`KeyDown` events do not handle simultaneous keystrokes. Can something be done with this?**   3. The duplication of event handlers at the end (`SetOptions[nb, NotebookEventActions -> actions]`) does not seem logical to me, but without it `KeyDown` events do not work. Why?    4. `hideMouse` hack is what I discussed here. Unfortunately the elegant construction `MouseAppearance[expr, Spacer[0]]` proposed by Mike does not work on v. 8.0.4 and WinXP and Win7.   5. And finally **are there any possibilities for speeding this up?**


Join lists in a list of lists

What's the best way to join two consecutive lists in a list of lists ? For example if I have the list               x = {{1}, {2}, {3}, {4}}       and I want to get in x               {{1}, {2, 3}, {4}}.      I want to join arbitrary positions. **Edit** I want to do this using the least amount of extra memory. Imagine that instead of having numbers I have big lists.


"With" as part of the "Dynamic Interactivity Language"

I noticed that in Mathematica's Function Navigator `With` is listed as being part of the "Dynamic Interactivity Language". ![Mathematica graphics](http://i.stack.imgur.com/Ujo0Y.png) It is not the first (or even the fourth, as it seems to be in this case) function that would come to my mind when discussing dynamic interactivity. While I'm well aware of `With`'s main purpose (which to me is injecting evaluated expressions in other, possibly held, expressions) I can't really come up with many examples of its use in a dynamic context. One thing may be the example given on the `Button` doc page:               Table[With[{i = i}, Button[i, Print[i!]]], {i, 10}]      `With` is necessary here because `Button` has attribute `HoldRest` and without it the action of the button would be to print the unevaluated text "i!". Is this sufficient to make `With` be part of the "Dynamic Interactivity Language" or are there better examples of its use that justify its listing in the Function Navigator? Examples which really need `With` and can't be done without?


Why does ImageData need four times more memory?

**Background** We are dealing with very large TIFF image files that are imported, processed and exported using _Mathematica_ 9.0.1. Many of our algorithms only work with an array representation of the images, where pixel values are stored in the form of nested lists. For this, we are currently using the function `ImageData` to directly convert images into an array representation. **Problem** I am struggeling with the increase in memory usage when converting images to the array representation using `ImageData`. What I am wondering about is that when I convert images with `ImageData` the allocated memory is four times higher compared to having only the images in memory. **Example** Consider the following example: I first create a stack of 50 images that is exported to a TIFF file. Then I import the file again with the option `"Data"`. I check the memory before and after `Import`. Compared to importing the file without any option, this takes up four times more memory.               Export["testFile.tif", ConstantArray[Image[ConstantArray[0, {1024, 1024}], "Bit16"], 50]];     FileByteCount["testFile.tif"]      > 104901507               MemoryInUse[]      > 8617736552               imgData = Import["testFile.tif", "Data"];     MemoryInUse[]      > 9037228760               9037228760 - 8617736552      > 419492208 If I import the file without the option, the memory used is about 104905128 bytes. This gives a factor of about 4 (3.99) more memory needed. I repeated this several times and I have to admit I do not have any explanation. **Questions**   1. Is there a simple explanation for the increase of memory usage?   2. How can I reduce the amount of allocated memory when using the array representation? **Attempts** After reading about the function `Developer`ToPackedArray` in What is a Mathematica packed array? I tried to convert the data array hoping that this would give me a decrease in memory usage. Nevertheless, I am not really sure if I am using the function correctly in this case. The code I tried is the following:               packed = Developer`ToPackedArray[Import["testFile.tif", "Data"]];      **System specifictation**   * OS: Windows 7 Professional, Service Pack 1 (64-bit)    * Processor: Intel Xeon CPU E5630 @ 2.53 GHz (2 Processors)   * Installed memory: 96 GB   * _Mathematica_ 9.0.1   * Java version 1.7.0_07 **Additional question** Still one problem remains: Is their a clean way in _Mathematica_ , how I could reduce the number of bits used for Integer to change the amount of memory used for the array representation (`ImageData`) without losing information? Or do I have to stick to `Image` in that case?


How can I highlight a moving bar in an animation of a bar chart?

I wrote the following code, but I don't know how to highlight the moving bar.               bsort[list_] :=       Module[{A = list, tmp},        tmp = Reap[          Do[If[A[[j]] > A[[j + 1]],             Sow[A]; {A[[j + 1]], A[[j]]} = {A[[j]], A[[j + 1]]}], {i,             Length@A}, {j, Length@A - i}]][[2, 1]];       Append[tmp, A]]          d = bsort@RandomSample@Range@10;     ListAnimate[      BarChart[#, ChartLabels -> Placed[Style[#, 15] & /@ #, Above]] & /@ d]      I want it to look like this: ![enter image description here](http://i.stack.imgur.com/5KuMj.gif)


How can I get exactly 5 logarithmic divisions of an interval?

I'd like to get exactly 5 divisions from _x_ to _y_ on a log scale. Can `FindDivisions` do this?


logarithmic distribution of a range in fixed number of elements

I want to distribute a range between 4 to 93 in 50 numbers which are logarithmically distributed. How I can do this in mathematica?


How can I reproduce the MatrixForm, NumberForm, XyzForm behavior?

I wish to write a function like `MatrixForm`, that affect only display but not evaluation, i.e. a function that automatically is stripped away from output. More precisely I wish a `MatrixForm`-variant that collect the LCM of the denominators of the elements of the matrix out of the matrix. Is this possible? I think `Interpretation`, `Defer`, etc. combined with `Row`, `MatrixForm` doesn't fill exactly this need. This is the best I did.               PrettyMatrixForm[       m_ /; VectorQ[m, NumericQ] \[Or] MatrixQ[m, NumericQ]] :=      With[{lcm = LCM @@ (Denominator /@ Flatten[m])},       If[lcm === 1, MatrixForm[m],        With[{mm = m*lcm},         Interpretation[Row[{1/lcm, " \[Times] ", MatrixForm[mm]}], m]]        ]]          PrettyMatrixForm[{{1/2, 1/4}, {2, 1/3}}]      **EDIT.** I wish to be able to write and evaluate something linke this in a cell, as I can do with `MatrixForm`.               {{1/2, 1/4}, {2, 1/3}} //PrettyMatrixForm     % * 2      **EDIT 2** To be even more clear, I wish to reproduce this behavior of Mathematica Kernel.               In[1]:= MatrixForm[{{a,b},{c,d}}]          Out[1]//MatrixForm= a   b                              c   d          In[2]:= Out[1]          Out[2]= {{a, b}, {c, d}}      As you can see the Kernel show `Out[1]//MatrixForm` i.e. `MatrixForm[Out[1]]` but store in `Out[1]` only the list `{{a,b},{c,d}}`. This happens for all `XyzForm`-like symbols, and obviously happens also in the Mathematica Front- End.


Can Reduce *really* not solve for x here?

Sometimes I get the feeling I'm just flailing blindly with Mathematica. Is solving for $x$ in the equation $$ \frac{\cosh (x/2)}{x} = \sqrt{2} $$ really beyond the scope of Mathematica? I try to solve it with the command: `Reduce[(1/x)Cosh[x/2] == Sqrt[2], x]` and am met with `Reduce::nsmet: This system cannot be solved with the methods available to Reduce.` I get a feeling that I'm doing something very silly. Cheers for any assistance!


Why cant Mathematica solve this equation?

> **Possible Duplicate:**   >  Can Reduce *really* not solve for x here? Why cant _Mathematica_ solve this equation?               f[x_] := Exp[Cos[3*x]]     g[x_] := (1/3)*x^3 - x^2 + 2     Solve[f[x] == g[x], x]     (* Solve::nsmet: This system cannot be solved with the methods available to Solve. >> *)


MousePosition Scaling over a cell

I'm trying to have the button follow the mouse while within the output text cell. The scaling does not exactly work as intended (fails to follow mouse correctly).               Dynamic[Overlay[{txtO,         Button[Style["Button", Blue, Italic, 15], Print[1]]}, All, 2,        Alignment ->         Rescale[MousePosition["CellContentsScaled", {0, 0}], {0, 1}, {-1,           1}]]]      Additionally, how would I make the button 1) Snap to 0,0 when the mouse is not over the output text cell anymore; and 2) disappear completely when not within the boundaries of the text cell. The Rescale for {0,1} -> {-1,1} helped a little, but it seems I am not using CellContentsScaled correctly, as the documentation says it should range from 0 to 1 over the cell only (occasional negative numbers pop up, and values are present with the mouse outside the cell)


How to take several values out of a large expression?

Background: Consider the following graphics directive.                   EdgeForm[          Directive[Thickness[Large],           Dashing[{Small, Small}],           Opacity[0.1`],           RGBColor[0, 0, 1]]]      In a Manipulate I want to interactively change Thickness, Dashing, Opacity and Color of the edges of Polygons in a pattern. So, for each of them I will have to create a control. The EdgeForm is stored in Excel =as is=. So I will need to extract the values which will become the starting values for the controls out of the EdgeForm above, i.e.:                   Large,          {Small, Small},          0.1,          RBGColor [0,0,1]      for the four controls respectively. My strategy was to ToString[EdgeForm[ ...everything ] and then do string manipulations on them but that turned out to become a lot of ( messy, still not working ) code. Considering this is Mathematica ( I thought that ) there must be a simple way to get the values out of that EdgeForm. **Question: How to change the EdgeForm above to {Large, {Small, Small}, 0.1, RBGColor [0,0,1] }. Needless to say that the values change per pattern, i.e. Tiny, Large, etc.**


Determining the week of a year from a given date

Consider the following:               AbsoluteTime["17/04/2012",{"Day","/","Month","Year"}];      From my calendar in my office, I know that April 17th is in the 16th week of the year 2012. The `Calendar` package does not provide a function by which I can determine the week of the year. However, is there a way to determine the week of a year based on `AbsoluteTime` figures?


Easy way to export Graphics3D as triangles with VertexNormals?

I would like to export an arbitrary `Graphics3D` object as a text file containing:   * list of vertices    * vertex normals    * triangle faces `Export["foo.obj", g]`, `Export["foo.pov", g]`, and `Export["foo.stl", g]` are all unsatisfactory as they lack the `VertexNormal` data. I started writing my own exporter but it's getting a bit painful as it seems there is no easy way to convert `GraphicsComplex` object containing `Polygon`s of order greater than 3 and converting them to triangles without recreating a triangle tessellation from scratch. Has anyone done this before and would like to share their code? Or is there an undocumented function I could use? Here is an example `Graphics3D`:               g = RegionPlot3D[(x^2 + y^4 + z^4) - (x^3 + y^2 + z) > 1/2, {x, -1, 1}, {y, -1, 1}, {z, -1, 1}]      ![Mathematica graphics](http://i.stack.imgur.com/kOtLQ.png)


automatic processing of numerical results in `Plot`

First I want to solve an equation $F(x,y)=0$ for $y$ by supplying a value of $x$. (suppose obtaining the analytic form of $y(x)$ is too difficult) Then I want to plot root $y$ (numerically calculated) as a function of $x$ by using the following:               Plot[y /. FindRoot[.../.{x->x0},{y, 0.2}],{x0, 0, 1}]      and I got something like the following ![enter image description here](http://i.stack.imgur.com/GsPIh.png) I omit `...` here since it is terribly complicated. **Update** : F(x,y) is of the form $\sum_{n,m}a_{m,n}x^ny^m$ and $m$ and $n$ can be as high as 19, which basically makes `Solve` impractical. The result is satisfying except a small number of points near 1.0. Setting another initial starting value of $y$ in `FindRoot` might be an option but it is very tedious and often I cannot find a value of $y$ that fits the whole range of $x$. My question is: suppose I stick with the initial value of $y$, is there a way to just eliminate that anomaly point after I `Plot` the numerical results? Or is there a better way to deal with this kind of numerical problem in general?


How to find the value of a solution of an ODE at a particular point

I'm trying to find the value of $z(y)$ at a particular time, say $y=0.5$. I've solved the differential equation. I tried using `z3 = z[3] /. sol`, but it's not working:               eqn2[w_, x_, y_, z_] := 3*z'[y]  == 2 (z[y] - 1)  + (1 - y^2 w) x     eqn3 = eqn2[1, 1, y, z]     sol = NDSolve[{eqn3, z[0]  ==  1 }, z[y], {y, 1, 5} ]     Plot[Evaluate[z[y] /. sol], {y, 1, 5}, PlotRange -> All]     z3 = z[y] /. sol /. y -> 3      ![enter image description here](http://i.stack.imgur.com/LgmUX.png)


Simple string pattern crashes kernel

The following code crashes my Mathematica kernel (v9, MacOS):               s = StringJoin[ConstantArray["65 H Isotropic = 27.4022 Anisotropy = 4.3297\n", 400]];     StringCases[s, (Except["\n"]..~~"\n")..];      Is this a known problem? Am I using string patterns in a wrong way?


Option pricing with the Black-Scholes model. Code not running

(*initialisation of variables*)     n = 10;(*expected value greater than 3*)     r = 0.03;     \[Sigma] = 0.2;     sMax = 2;     sMin = -2;          (*define \[CapitalDelta]x.*)     \[CapitalDelta]x = (sMax - sMin)/(n - 1);          (*adding vector matrix... any assignment of v value should be      included here*)     vecMatrix = Array[v, n];          (*reusable internal variables*)     p = 0.5 (\[Sigma]^2)/(\[CapitalDelta]x^2);     q = (2 r - (\[Sigma]^2))/\[CapitalDelta]x;          x = (2 p + r) - 0.75 q;     y = 5 p + q;     a = p - 0.25 q;     b = -2 p - r;     c = p + 0.25 q;          (*introducing matC for one time initialisation*)     matC = SparseArray[{Band[{1, 1}, {n, n}, n - 1] -> x,          Band[{1, 2}, {n, n}, {n - 1, n - 3}] -> y,          Band[{2, 1}, {n - 1, n}] -> a, Band[{2, 2}, {n - 1, n}] -> b,          Band[{2, 3}, {n - 1, n}] -> c}, {n, n}];      MatrixForm [matC]*      MatrixForm[vecMatrix]


Is it possible to recover the style of the previous version(V8,V9) in Windows?

In Wolfram Mathematica 10 (Windows paltform),the menu bar and files are combined together.When I narrow the window，it will become ugly shown as below! ![enter image description here](http://i.stack.imgur.com/Fj5wC.png) So my question is: **Is it possible`recover the style of the previous version(V8,V9)`,** or is it possible to construct a software interface like other software( **All files embedded below the menu bar and the main working windows has the normal size like`Microsoft Word`**). ![enter image description here](http://i.stack.imgur.com/HMA06.png)


How can I connect to a remote machine?

My friend and I are trying to set up remote kernels. He has a server at home running 1 kernel off of a Linux-based server. We're both on 8.0. I manually set `$RemoteCommand` to               "ssh `3`@`1`-l `3` \"math -mathlink -linkmode Connect `4` -linkname \     `2` -subkernel -noinit >& /dev/null &\""`      and manually changed `$RemoteUserName` to the one he set up for me. The problem is, whenever we try and run the code, we get the following error message: `LaunchRemote::rsh: Command ssh [my username]@[his server address]-l [my username] "math -mathlink -linkmode Connect -linkprotocol TCPIP -linkname 51145@[my public IP address],51146@[my public IP address] -subkernel -noinit >& /dev/null &" may have failed (exit code 1).` The problem is, my public IP address is not the same as my private IP address, so I can't connect. How can I get Mathematica to recognize my private IP instead?


Composition with Apply

`Composition` is sometimes useful for clarity of a code. For the same purpose I try to `Apply(@@)` functions as often as it is possible. **My question is how to combine** `Composition` with `Apply`, or, to be more precise, is there any simpler way than one I'm going to show (there is no `Composition` :)):               Fold[#2@@#1&, arg, {f1, f2,...}]      alternatively:               Fold[Apply[#2,#1]&, arg, {f1, f2,...}]      So for **example** :               Fold[#2 @@ #1 &, {1, 2}, {{##} &, {#2, #1} &, {#1, 0, #2} &}]      > >     {2, 0, 1} >


Conditionals slower than operators?

I want to make my application faster. I tried to replace an `If` condition with operators. The `If` condition is               list = Range[4000];     Table[If[list[[i]] == 4000, Print[1], Print[2]],      {i, 4000}]; // AbsoluteTiming      Output is > {7.739443, Null} Using operators:               Table[(list[[i]] == 4000 && (Print[1]; True) || Print[2]), {i,      4000}]; // AbsoluteTiming      Output is > {3.194183, Null} Both give the same output but the execution time using operators is faster than `If` condition. Can you tell me which one is useful that does not have future problems as well?


Numerically solve 2nd order differential equation with singularity

Consider a second order differential equation with a potential that diverges at some generic value in the variable. For example: $$-y^{\prime\prime}(s)+\frac1{\mathrm{cn}{(s\mid k^2)}}y(s)=0$$ where $\mathrm{cn}(s\mid k^2)$ is the `JacobiCN[s, k^2]` function. Now, suppose, the differential equation has to be solved on the interval of a full period, namely $s\in[0,2\mathbb{K}]$, where $\mathbb{K}$ is the complete elliptic integral of the first kind `EllipticK[k^2]`, with the initial conditions $y(0)=0$ and $y^\prime(0)=1$. If I just naïvely start the `NDSolve` function for, say, $k^2=0.7$:               NDSolve[{-y''[s] + y[s]/JacobiCN[s, 0.7] == 0, y[0] == 0, y'[0] == 1},       y[s], {s, 0, 2 EllipticK[0.7]}]      _Mathematica_ rightfully complains that a singularity is detected at half of the evaluation range, namely at the value `s = EllipticK[k^2] = 2.07536`: > NDSolve::ndsz: At s == 2.0753631352632516`, step size is effectively zero; > singularity or stiff system suspected. And also the resulting interpolating function terminates at this value:               {{y[s] -> InterpolatingFunction[{{0., 2.07536}},<>][s]}}      So, evidently, the solution does not overcome the point of singularity and is given only for the half of the required interval. I heard that there are numerical techniques to overcome singularities when solving differential equations. It makes me wonder that _Mathematica_ does not activate these by default. What can I do to solve a differential equation beyond a singularity numerically in _Mathematica_?


Mismatch between Axes -> True and Frame ->True

Using `Axes -> True` of the following........               Plot[(2/Sqrt[6]) Sin[        0.5 ArcSin[Sqrt[(3 R^2)/((2 - R)^2 + 3 R^2)]]], {R, 0.0, 1.3},       PlotRange -> {0.0, .23}, Axes -> True,       FrameLabel -> {d/a, Subscript[Sin\[Theta], 13]},       PlotStyle -> Directive[Red, Thick],       LabelStyle -> Directive[Black, Bold]]      I am getting a plot starting from (0,0) * * * But using `Frame->True` what i am getting throuh               Plot[(2/Sqrt[6]) Sin[        0.5 ArcSin[Sqrt[(3 R^2)/((2 - R)^2 + 3 R^2)]]], {R, 0.0, 1.3},       PlotRange -> {0.0, .23}, Frame -> True,       FrameLabel -> {d/a, Subscript[Sin\[Theta], 13]},       PlotStyle -> Directive[Red, Thick],       LabelStyle -> Directive[Black, Bold]]      is not starting from (0,0). Instead it is starting from (-.05,0) * * * In the second case, y-axis has been shifted from x=0. How to fix it? P.S.- since i don't have 10 reputation , I am unable to post images. * * * ![enter image description here](http://i.stack.imgur.com/UFZrj.jpg) ![enter image description here](http://i.stack.imgur.com/QEF3M.jpg)


Variable number of nested variable-range sums

I would like to express the following nested sum in _Mathematica_ : $$ S(m,j,N) = \sum_{k_1=m+j-1}^{N-1} f(N,k_1) \sum_{k_2=m+j-2}^{k_1-1} f(k_1,k_2) \cdots \sum_{k_m=j}^{k_{m-1}-1} f(k_{m-1},k_m) $$ where $m$, $j$ and $N$ are unspecified and $f(p,q)$ is a complicated function depending on the indices $p$ and $q$. Thus, not only are there a variable number of nested sums, the ranges of the sums are also of variable length, depending on the index of the immediately outer sum. Can anyone please help me? I've searched for solutions to this on this forum and elsewhere, but could only find solutions that treated the ranges of the sums to be variable but equal. I eventually need to place $S(m,j,N)$ inside other expressions and functions, so I need to be able to pass $m$, $j$, $N$ as symbols. For example, one expression I ultimately want to obtain is $$ \sum_{m=1}^{N-1} \frac 1 {m!} \sum_{j=1}^{N-m} S(m,j,N), $$ and I would like the solution as an analytic formula, valid for any $N$. I am hoping (and have reason to believe) that the multiple sum $S(m,j,N)$ will simplify down to an easier expression. If you would like to see my definition for the function $f$, here is my code:               phifn[m_, k_] := \[Piecewise] {     {\[Piecewise] {        {1, k = 1},        {0, 2 <= k <= n}       }, m = 1},     {\[Piecewise] {        {((Gamma[m] Pochhammer[q, m - k])/(         Gamma[m - k + 1] Pochhammer[q + 1, m - 1])), 1 <= k <= m},        {0, m < k <= n}       }, 2 <= m <= n}     };     betafn[m_] := (PolyGamma[q + m] - PolyGamma[q]) q r;     f[m_, k_] := phifn[m, k] betafn[m];      I should also add that I'm rather unexperienced when it comes to _Mathematica_.


Strategies to find curves on messy data using FindCurvePath

I have a set of data points that correspond to roots of a transcendental equation with respect to a parameter (the abscissa) which, by the properties of the system, define continuous curves (might be open or closed). There are many roots and some are very close from one another. Here is the actual data set. A `ListPlot` shows the data set and some of the branches can be seen: ![Roots of transcendental equation](http://i.stack.imgur.com/tuEl0.png) In order to extract some of the branches, I've used `FindCurvePath` to my `dataSet` in the following way:               tmpIdx = Sort[FindCurvePath[dataSet], Length[#1] > Length[#2] &];     ordCrv = Table[dataSet[[tmpIdx[[j]]]], {j, Length@tmpIdx}];      which is, at some measurement, very unsuccessful: ![Data after FindCurvePath](http://i.stack.imgur.com/xpkbe.png) Sorting `tmpIdx` has the purpose to put the largest sets of data at the front of it; then I can construct some of the curves `FindCuvePath` is able to find, eliminate those points from `dataSet` and try again. Of course this works, but it is a lot of hard, manual work and very time consuming, which I wouldn't mind if this were the only data set I had to process. To help `FindCurvePath`, I've been applying it not only to `dataSet`, but also to `{f[#1], g[#2]} &@@@ dataSet`, where `f` and `g` are top of my head chosen (continuous) functions. Again, this works to some extent. The obvious problem is that it involves a lot of manual processing and is not only specific to the data set, but also to the branch in question. I know there is no universal solution, and at some point manual intervention will be in order, but I was wondering if someone knows or has a better strategy to attack the problem. Hope I made myself clear. Any comments or suggestions are very welcome. **EDIT** With some lack of judgement, I've just realized that I excluded some data from my analysis, which can be very useful to do the job. What I have is not a 2d list, but a 3d list. Here it can be found. One can clearly see the separation between curves ![enter image description here](http://i.stack.imgur.com/OuNlz.png) ![enter image description here](http://i.stack.imgur.com/qGYQu.png) Sorry for the omission, it's something I just realized. **EDIT 2** Maybe there is some way to relax the conditions on `FindCurvePath` so it looks for a piecewise linear curve? By taking a closer look to the smaller curves constructed by the function, it seems that its very unsuccessful whenever there are "return" points. I wish the function documentation were more complete.


Is it possible to make v9 ignore case when completing names?

In v8, I could type, say, `fulls` or `texf` to get `FullSimplify` or `TeXForm`from auto-completion. That was quite nice because I didn't need to press the Shift key for capitals. In v9, auto-completion appears only when I type `FullS` or `TeXF`, which is not so handy. Is it possible to make auto- completion ignore case?


How do I tweak the input assistant to use string completion on my own functions?

I would like to be able to use Mathematica's string completion feature for subvalues of my own functions. I tend to go for functions that follow the pattern `f["description"][parameters][variables]` So say I have functions describing models:               modelOfSomething["Linear"][a_, b_][x_]:= a + b x;     modelOfSomething["Logarithmic"][a_, b_][x_]:= a + b Log[x];      Then as time goes on, I define more functions:               modelOfSomething["NonLinear"][a_, b_, c_, n_][x_] :=        modelOfSomething["Linear"][a, b][x] + c x^n;      so as I go along, I may end up with a few different models that I find useful to index with a string especially if they have the same number of parameters. So my question is > if/how can I get Mathematica to give me a drop-down of all the string > subvalues of my function much like it does with `CountryData`: ![enter image description here](http://i.stack.imgur.com/a5cWX.png)


Seek a quick way to bring standard order back to original after Complement

the `Complement` gives result in standard order. But that's not what I want. I want it to keep the original order. say I have a list               list = {8, 3, 6, 4, 2, 5, 7};      and               compli = Complement[list, {3, 6, 2}]      gives               {4, 5, 7, 8}      But I want               {8, 4, 5, 7}      I write the following code to bring it back to the original order               Reap[If[MemberQ[compli, #], Sow[#]] & /@ list][[2, 1]]      I don't know whether it is good or not. Maybe there is more elegant way to do this. Finally, I must say I just don't understand why `Complement` is designed to give standard order. If I want standard order, I can simply use `Sort`. And now things got more complicated than it should be.


How to Delete Elements from List1 appearing in List2?

I'm new to functional programming of Mathematica and trying to remove one list of assorted elements from another. However I only find functions working with the Index rather than the values itself:                list1={b,a,e,f,c,d}        list2={f,e,c}      I can now remove `list2` from `list1`:                result={b,a,d}        I already found out, that you can "abuse"               DeleteCases[list1, a]       to remove 1 specific element from a list, but not a whole assorted list... I would be very grateful for a simple solution to do it.   Thanks a lot for any answer!


Explain a Mathematica winning one-liner

Dynamic[Refresh[       Graphics3D[        Sphere[l -=           MapIndexed[           Plus @@ (Function[                x, (d = # - x)/(d = Sqrt[d.d]) Log@d/2^(2 + 2 d)] /@                Drop[l, #2]) &, l], E^-1]], UpdateInterval -> 1],       l = RandomReal[7, {21, 3}]]      This code is from a past one-liner winner. I'm new to _Mathematica_ and can't understand it. Can some one explain the code in ordinary language terms? I searched all the functions in the help, know `@@`, `/@` do and currently am reading Dynamics Tutorial from Wolfram.


How is the Mathematica kernel structured internally, and how does evaluation work?

There is so much information available for Java--the internal details of (for example) the JVM memory manager are well-documented, and the performance considerations arising from its interaction with user code have been publicly discussed. I am interested to know if there is any comparable documentation for the _Mathematica_ kernel. Specifically:   * What are the major steps involved in evaluation?   * Which of these are the most important from a performance standpoint? Is there any public documentation available about how all of this is implemented? If there is, I wasn't able to find it after searching the Internet: neither the mechanics of the evaluation process, nor the internal workings of particular functions, seem to be known outside of WRI.


Plotting Extended Zone Scheme:

How could I present an extended zone scheme for a delta-function Kronig-Penney model? That is, how can I display only the lowest contour in the region [0, π], the second-lowest contour in the region [π, 2π], etc.? The dispersion relation is $\cos(k) = 5\rm{sinc}(5.12\sqrt{E}) + \cos(5.12\sqrt{E})$. My code for the reduced zone scheme (where all contours are displayed in the region [0, π]) is:               ContourPlot[       Cos[k] == Cos[5.12 Sqrt[e]] + 5*Sinc[5.12 Sqrt[e]], {k, 0, π}, {e, 0.1, 1.52},       FrameLabel -> {"k[\!\(\*SuperscriptBox[\(nm\), \(-1\)]\)]", "Energy[eV]"},        PlotLabel -> Cos[k] == Cos[5.12 Sqrt[e]] + 5*Sinc[5.12 Sqrt[e]]]      which works fine, but I cannot see how to generalize this to the extended zone scheme.


How can text-specific antialiasing be disabled in Rasterize?

While tinkering with the code in the Falling Matrix question, I was hoping to improve the rendering speed by making the rasterizations of the text grayscale. I changed the base color of the text to white and left the background black. However, this did not yield a grayscale raster. The problem seems to be that _Mathematica_ tries to help with the readability of text by using special antialiasing schemes. Consider the following test:               GraphicsRow[      Rasterize[#, Background -> Black, RasterSize -> 15,          ImageSize -> 150] & /@ {Style["\[FilledCircle]", White],         Graphics[{White, Disk[]}]}]      ![Antialiased disk test](http://i.stack.imgur.com/wbpaL.png) Interesting and (I think) undocumented, but the relevant question for me is: How can I control or eliminate this behavior? Adding a `ColorConvert[#,"Grayscale"]` or just taking the `Norm`s of the `ImageData` gives an acceptable result but is pretty slow.


NDSolve and memory usage

After some googling, i've found similar problems around, but didn't find a 100% satisfactory answer, so let me ask here: I'd like to solve a 1+1 problem using the method of lines. In spherical symmetry, I discretize the radial direction and end up with a system of ODEs that I'd like to solve with NDSolve. Problem is, the original 1+1 problem is a system of ~10 first-order PDEs and eventually I need to solve ~10*N first- order ODEs, where N are the radial grid points. To achieve enough resolution, N ranges from O(10^3) to O(10^4). My problem is that NDSolve requires a lot of memory to solve the system. Also, I need the solution at any time, not only at the final time. What I would like to do is having NDSolve storing intermediate values at each time step in a data file, thus leaving the memory free. Is that possible? Is there any other solution to this problem? Frankly, I find this problem quite restrictive, given that a similar odeint in c would require essentially no memory to run, unless i'm doing some silly mistake of course. Here is an example:               $HistoryLength = 0;     Timing[     Nv = 10^4;     tF = 40;     variables = Table[Subscript[\[Phi], i], {i, 1, Nv}];     eqs = Table[     Subscript[\[Phi], i]''[t] + i Subscript[\[Phi], i]'[t]^3 +      1/i Subscript[\[Phi], i][t] == 0, {i, 1, Nv}];     initc = Table[{Subscript[\[Phi], i][0] == 1,      Subscript[\[Phi], i]'[0] == 1}, {i, 1, Nv}] // Flatten;          ruleP = {MaxStepSize -> 0.01, MaxSteps -> 10^5};     sol = NDSolve[Union[eqs, initc], variables, {t, 0, tF}, ruleP];]     MemoryInUse[]/1024^2 // N      In my machine, this takes ~30 seconds and approx. 1 GByte to run! I'm not concerned about the speed, but the memory rapidly increases when the parameters Nv and tF increase and the notebook quickly sucks all machine's memory... Thanks in advance for the help! Paolo


How to restrict the mouse cursor to stay within a box?

I'm trying to use _Mathematica_ to write small games, and I find that it would help to restrict the player's mouse into the game window (just like other games do). Is there any way to achieve this? I've tried to use this `moveMouse` function, but I found it not as efficient as I expected, because what I really want is to restrict the cursor inside the window, not to pull it back. In fact, moving the mouse by this function cannot stop the mouse getting out of the window, it just pulls it back only as the function was executed. So I found it doesn't help much for my purpose. Is there any other method (like another java function?) that can actually restrict the mouse?


Monitor the list for changes

I wrote a function to monitor the list of variable. What it does is if the variable in list change, the changed variable will be separated from others. check the function and output               ListMo[monitorList_, OptionsPattern[]] :=     (      Module[{il = {}},           (         If[             (UnsameQ[monitorList, Global`temp]),             (         il = {Complement[monitorList, Global`temp],          Intersection[monitorList, Global`temp]};         Global`temp = monitorList;         il         )         ]         )      ])      I initialize temp variable separately               temp = {"Value1", "Value2", "Value3", "Value4"};      I call the function               monitorList1 = {"Value1", "Value2", "Value3", "Value4"};     ListMo[monitorList1]      Output will be nothing If I change value in monitorList1 like               monitorList1 = {"Graphs", "Value2", "Value3", "Value4"};      The output should be               {{"Graphs"},{"Value2", "Value3", "Value4"}}      again If I change in monitorList1 like                monitorList1 = {"Graphs", "Value2", "Value3", "computer"};      The output should be               {{"computer"},{"Graphs","Value2", "Value3"}}      Here am getting output, But I want them to be `Dynamic`. If I put `Dynamic` around `ListMo[monitorList1]` like `Dynamic[ListMo[monitorList1]]` the output is keep on executing instead of executing one time. I used `TrackedSymbole` as `Dynamic[ListMo[monitorList1], TrackedSymbols -> monitorList1]` but no use. I used `StartScheduledTask[]` as well like               Module[             {testing = {}},             StartScheduledTask[                CreateScheduledTask[                  With[{testing1 = {}}, testing = ListMo[monitorList1];]                ]             ];             Dynamic[testing]         ]      but it doesn't help. Help me to write better code for same concept.


Adding multiple Complex Numbers in Euler form

Say I have a series of $n$ complex numbers of the form $A_k e^{(I \ \theta_k x)} $ where $A_k$ is a real number and so is $\theta_k$ and $k$ runs from $1$ to $n$. $x$ is an algebraic symbol. Example I have to calculate:- $ 3e^{5Ix}+10e^{7Ix}+2e^{1Ix}$ Now I need to find the summation of the series. I can do this manually because I know all the phase angles (in terms of x) and the lengths of the complex numbers in space, so I will simply add them up like vectors using the parallelogram law and apply the appropriate formulas to successfully reduce the sum of the series to one number say $R e^{I\ F}$ where R and F will be functions in $x$. How do I calculate this number with Mathematica?


Convex hull of a large data set of 3D points

I recently needed to deal with a large data set of 600.000 points in three dimensions. My task was to find a convex hull for this data. I have _Mathematica_ 10, so I could use the function `ConvexHullMesh` and I obtained this: ![enter image description here](http://i.stack.imgur.com/8sq3g.png) ![enter image description here](http://i.stack.imgur.com/CCEZv.png) I was wondering if there is some way to find a smooth convex hull, maybe an ellipsoid, for my data.


Normalize the PlotLegends and z values for two DensityPlot

I'm trying to compare two `DensityPlot`s:               Module[{R1, R2, x, Δ},      R1 = 15;      R2 = 5;           Row @ {        DensityPlot[-((R1 + R2 + R1 x - R2 x - R2 Δ - R1 x Δ + R2 x Δ)/(-2 + Δ)),         {x, 0, 1}, {Δ, 0, 1},          ImageSize -> 700, FrameLabel -> {"% talented", "delta"},          PlotLegends -> Automatic],        DensityPlot[-((          2 R2 + R1 x - R2 x - R2 Δ - R1 x Δ + R2 x Δ)/(-2 + Δ)),          {x, 0, 1}, {Δ, 0, 1},          ImageSize -> 700, FrameLabel -> {"% talented", "delta"},          PlotLegends -> Automatic]        }]      but it would be easier if the colors were coding for the same values in the two graphs. I was able to set the same range of values for the legend with:               PlotLegends -> Placed[BarLegend[{Automatic, {0, 15}}], Right]      but how do I change the command so that the colors of my graphs will represent the whole range of values from 0 to 15?


List Plot 3D the same colour scale

I have a transient problem of pressure disipation. I want to plot severals 3D plot but I have a problem with colours. **Case:** One of my `ListPlot3D` presents pressure at time 200 day and the maximum pressure is about 200 kPa in the center of the plot. The secound plot presents pressure at time 1000 day and the maximum pressure is about 1 kPa in the center of the plot. But in the first and in the second plot the maximum value is red. **Question:** How do I set the coulour scale so that it will be always the same i.e. the range of red colour will be about 200 kPa and purple about 0 kPa. Because now in the first plot red colour is 200 kPa and in the secound plot red is 1 kPa.


Opening a saved notebook in Mathematica 10

I have never had an issue with opening a saved notebook before, but recently installed Mathematica 10 and saved my first notebook with it. It's saved as `.nb` and is a small file with dynamical content. I have tried to open the notebook from both the opening prompt that asks for new notebook or open and File, Open... When I try to open the notebook using either method the file never appears to load. On the contrary I tried saving a notebook that did not contain dynamical content, just a test notebook and that loaded just fine.


How do I craft this constant to a specific accuracy?

An earlier post was migrated to Physics.SE and we determined that if this converged, we would have a constant close to the mass of the proton in kilograms. This constant is constructed by summing the reciprocals of the products of all the numbers between consecutive squares. Per this:               SumConvergence[10^-26/Pochhammer[m^2 + 1, 2 m], m]        (* True *) we have convergence and thus a constant. However, the following:               Sum[10^-26/Pochhammer[m^2 + 1, 2 m], {m, \[Infinity]}]        outruns the precision. My question: Is there a way to use this sum to create the constant to a specified accuracy?


Hiding 3D Axes Blocked by Surface

I want to plot a 3D surface with the axes crossing at (0,0,0), without a bounding box. I'd also like the portions of the axes "hidden" by the surface to not show. For instance,               ContourPlot3D[     x^2 + y^2 + z^2 == 4, {x, -3.1, 3}, {y, -3.1, 3}, {z, -3.1, 3}, AxesOrigin -> {0, 0, 0},     Boxed -> False, Lighting -> "Neutral",Mesh -> 10]      creates a sphere but with the mesh, tick marks, axes, etc., the inside looks rather cluttered. I'd rather the axes disappear inside. How can this be done?


Best practice of passing a large number of parameters to functions

I have a number of functions which all take a large number of parameters. I am wondering which is the best practice of passing these parameters to those functions. I could of course simply specify the parameters outside the functions, like (note that in the actual example there are far more parameters)               mu=1;     sigma=1;     lb=0;     ub=10;     f[x_] := PDF[LogNormalDistribution[mu, sigma],x]      However, I would prefer to explicitly pass the parameters to the functions. In Python, I would use a dictionary. In Mathematica, one possibility would be to use a replacement rule.               par={mu->1,sigma->1,lb->0,ub->10};     f[x_,par_] := PDF[LogNormalDistribution[mu, sigma],x]/.par      However, this can cause warnings if a function only takes numerical arguments, e.g.               Plot[f[x,par],{x,lb,ub}]/.par      > Plot::plln: Limiting value lb in {x,lb,ub} is not a machine-sized real > number. >> The plotting actually, works, though. Also, passing paramters using replacement rules seems to be inefficient, since - if possible - evaluations are done symbolically, and only then are values substituted for variables.


Is there a quick way to find a built-in function by name search?

Is there a quick way to search all built-in Mathematica functions by name? Say I want to find all functions whose name contains "Graph", such as GraphPlot, NeighborhoodGraph, Subgraph, and so forth. When I enter "Graph" into Mathematica's documentation system, I get some, but not all of the functions whose names contain "Graph". I also get a lot of names which are not functions, as well as other material of varying relevance. I just want to search for functions by name or partial name. Also, I don't want to see functions from optional packages -- only the basic ones that load when Mathematica starts up.


Is there a "No Units" (i.e., dimensionless) unit?

I would like to be able to call the `Quantity` function with a null unit so that it returns the original dimensionless value. For example,               Quantity[3.0,"NoUnits"]      would return `3.0`. Is there a dimensionless unit?


Unintended edge extensions in 3D Cube rendering

I have arranged a certain configuration of cubes in 3D using the following code:                Graphics3D[       Table[        {Cuboid[{i, j - i + 1, j + 1}]},        {i, 1, 4, 1}, {j, 1, 4, 1}], Lighting -> {{"Ambient", White}},         Boxed -> False, ViewPoint -> {-1, -1, 1}]      Computing this as it is displays the following graphic: ![cube stack](http://i.stack.imgur.com/3jtEv.jpg) This is fine, but the issue is what happens when you zoom in to this image in Mathematica. Doing so reveals extended edges in some of the corners shown here: ![enter image description here](http://i.stack.imgur.com/dfl5p.jpg) I would like to know why this is happening, and what I need to do to get rid of the extended edges. Is this perhaps happening because Mathematica is not completely updating the graphics upon zooming?


Create an adaptive amount of local variables for error propagation

I intend to write a function which calculates the result and the error for any formula with any amount of variables using the Gauß Error Propagation. The error $\mathrm{d}R$ for a function $R(a,b,c)$ and the corresponding errors $\mathrm{d}a, \mathrm{d}b$, and $\mathrm{d}c$ are calculated with $$R=\left[\left(\partial_{a}A\,\mathrm{d}a\right)^2+\left(\partial_{b}A\,\mathrm{d}b\right)^2+\left(\partial_{c}A\,\mathrm{d}c\right)^2\right]^{1/2}$$ Since there is huge amount of formulas one could wish to use with different amounts of variables, the function has to be adaptive. My first shot is the following function, which already does the job pretty well.               Gaus[φ_, data_?MatrixQ] := (       Do[Evaluate[Symbol["x" <> ToString[i]]] = data[[i, 1]], {i, Length[data]}];       α = Norm[Derivative[##][φ][Sequence @@               Evaluate[Table[Symbol["x" <> ToString[i]], {i, Length[data]}]]] &                 @@@ IdentityMatrix[Length[data]]*data[[All, 2]]];       Α = φ[Sequence @@ Evaluate[Table[Symbol["x" <> ToString[i]], {i, Length[data]}]]];       Print[{N[Α], N[α]}]       )      It accepts a function $\phi$ with a layout like               R[a_, b_, c_] := a*b/c      and a list of {value,error} pairs. Then it creates an corresponding amount of intermediate variables x1,...,xn with n being the number of pairs. These are used to calculate the error $\alpha$ and the value A, which are then printed. And now to my problem. I really want the intermediate variables xi and $\alpha$ and A to be local. Currently they are global, which isn't a problem for the function, as existing variables are overwritten, but proved to be annoying in other calculations. My first try was to use Module similar to this               Module[{Evaluate[Table[Symbol["x" <> ToString[i]], {i, 2}]], a, b}, a + b]          > Module::lvsym : "Local variable specification {Evaluate[Table[Symbol["x" <> > ToString[i]], {i, 2}]], a, b} contains Evaluate[Table[Symbol["x" <> > ToString[i]], {i, 2}]], which is not a symbol or an assignment to a symbol. which produces only the error message above. I could of course define the variables x1 to x10 directly, as I will rarely have more than ten values per formula, but this would be terribly inelegant. Several futile tries later I am running out of possibilities to rephrase my search, since I neither am a native speaker nor have significant programming background. So I would be happy, if someone could provide an idea to create adaptive amount of local variables. **Update:** Thanks to the answer of Jens about the use of downvalues, i could modify my code to the following.               Gaus[\[Phi]_, data_?MatrixQ] := Module[{df, f, x},       Do[x[i] = data[[i, 1]], {i, Length[data]}];       df = Norm[Derivative[##][\[Phi]] [Sequence @@ Array[x, Length[data]]             ] & @@@ IdentityMatrix[Length[data]]*data[[All, 2]]];       f = \[Phi][Sequence @@ Array[x, Length[data]]];       Print[{N[f], N[df]}]       ]      For some reason I had to get rid of the Elavaluate[..] Function, although, from what I understand of it, there no reason for an error. This basically answers my introductory question. The comment of acl and a night of sleep made me realize that the approach is indeed wrong, as the task can be achieved without using intermediate variables just using sequence, which somehow eluded me.               Gauss[\[Phi]_, data_?MatrixQ] := Module[{df, f},       df = Norm[Derivative[##][\[Phi]] [Sequence @@ data[[All, 1]]             ] & @@@ IdentityMatrix[Length[data]]*data[[All, 2]]];       f = \[Phi][Sequence @@ data[[All, 1]]];       Print[{N[f], N[df]}]       ]      This seems to me like much cleaner and easier function.


Fix end point in smooth kernel distribution density

I am using some extreme value fitting method which results in a parametric distribution for values exceeding some threshold, all values $\geq 0$. For smaller values I'd like to use a smooth kernel distribution. Pasting these two together, there is usually a small gap or jump in the distribution. So I looked for the possibility to 'fix' a point in the smoothed distribution, but found no such thing. Is there any way 'force' the smooth kernel distribution density to take a right end value? It doesn't make a big difference, but there is simply no real reason for such a jump in the density. Update: Of course it is possible to shift the empirical smoothed density and then scale the empirical density part to obtain a continuous density, but I am not really convinced. To me, it does not seem like the optimal solution. I'll attach two plots to illustrate the problem. ![enter image description here](http://i.stack.imgur.com/32c09.jpg) ![enter image description here](http://i.stack.imgur.com/YbznC.jpg) Thank you!


Getting output in the same way as most Stat packages

I have been looking at several of the timeseries functions in mathematica, however running a process like ARDL, ARMA, GARCH or ARCH you would be able to get a ANOVA table, with its coefficients and p value, you also in most packages would get R and R^2. I am wondering if there is an easy way to get ANOVA table when running an ARDL model or a ARCH model. I know it is possible with linear model fit, but I am not able to get it when using any other models.


Replace !x with x != 1

I have some logical relationships that I ultimately want to pass to `NMaximize` as constraints: `{x => a, y => a, a => x || y}` `NMaximize` is picky about its input format though, so I'm feeding the expression into `BooleanMinimize` before, which produces something like: `{!x || a, !y || a, ...}`. `NMaximize` can't handle unary negation, but accepts `x! = 1`. I looked at `BooleanConvert`, but most of the forms still use logical negation. What's the best way to deal with this?


LocatorPane and multiple EventHandlers, PassEventsDown option

Consider the following piece of code from Heike as an ( accepted ) answer on LocatorPane, selecting multiple Locators \- Basically the code implements dragging polygons on a LocatorPane.                DynamicModule[{pts, range, gr, drag, pts0},       pts = RandomReal[1, {7, 2}];       range = {1 ;; 4, 5 ;; 7};       gr = {{Red,  Polygon @ Dynamic @ pts[[ range[[1]] ]]},             {Blue, Polygon @ Dynamic @ pts[[ range[[2]] ]]}};       drag = 0;            Panel[LocatorPane[Dynamic[pts],         EventHandler[          Graphics[           EventHandler[gr[[#1]],              {"MouseDown" :>                (drag = #; pts0 = # - MousePosition["Graphics"] & /@ pts[[ range[[#]] ]])}           ] & /@ {1, 2},            PlotRange -> {{0, 2}, {0, 2}}],          {"MouseDragged" :>             If[drag > 0, pts[[range[[drag]]]] = # + MousePosition["Graphics"] & /@ pts0],           "MouseUp" :> (drag = 0)},          PassEventsDown -> True         ]       ]]      ]      If you run this code you'll notice that when a locator's position is on another polygon the locator does not work anymore. **Question: How can the code above be changed so that a click on a locator always works? Why was it necessary to use two two EventHandlers, and what is a good rule to decide on wether to use the PassEventsDown option?**


Obtaining the number in CounterBox

Is there a way of obtaining the current number of a counterbox? Say for instance that in a new notebook you create 3 section cells. Then by evaluating the command:               CellPrint[Cell[TextData[CounterBox["Section"]]]]      You can see now many cells with the style `"Section"` you have created up to the point at which you evaluated the command. ![enter image description here](http://i.stack.imgur.com/ZvTFy.png) Is there a way of obtaining the the number of "Sections" created without having to print a cell displaying a CounterBox? I would like to do something like:               GetCounterNumber["Section"]      and it should return the total number of Sections created. It should behave similarly for subsections and other cells that have counters.


Searching Notebooks for String Patterns using Workbench v2

The Workbench webpage describing new features in version 2 lists the ability to "Search notebook documents with the Mathematica pattern search utility" under the heading **Mathematica Front End Integration**. Does this feature in fact allow the user to search a Mathematica notebook document directly (i.e. interactively from within the front-end) for string pattern expressions, and if so, can anyone provide instructions on how to use this feature? The `NotebookFind` command does not appear to support searching for string pattern expressions which raises the question of whether or not Workbench is using an undocumented Mathematica command and/or option to search for the pattern.


Inline cells and conversion rules

In the following link you can find the following about `ConversionRules` when exporting to HTML: > specifies mappings from Mathematica cell styles to HTML elements, including > both inline and block-level versions of the markup Lets define the following temporary function with the following conversion rules:               TempFunction[expr_] := ExportString[expr, "HTML",         "FullDocument" -> False,         "ConversionRules" -> {             "InlineMath" -> {                 {"<inline>", Convert`TeX`BoxesToTeX[#] &, "</inline>"},                 {"<block>", Convert`TeX`BoxesToTeX[#] &, "</block>"}             },             "Text" -> {                 {"<inlineText>", "</inlineText>"},                 {"<blockText>", "</BlockText>"}             },             "" -> {"", ""}         }     ]      As the quote says, I have specified both the inline and block versions of the mapping. Now lets use it to see if they work as intended. # CASE 1: Here we use a single block cell.               TempFunction[         Cell[BoxData[FormBox[RowBox[{"x", "=", "y"}], TraditionalForm]], "InlineMath"]     ]      The output is:               <block>x=y</block>      # CASE 2: Here we use an inline cell.               TempFunction[         Cell[TextData[{"Let ",          Cell[BoxData[         FormBox[RowBox[{"x", " ", "=", " ", SuperscriptBox["y", "2"]}],         TraditionalForm]], "InlineMath", FormatType -> "TraditionalForm"], "."}], "Text"]     ]                    <blockText>Let <inline>x = y^2</inline>.</BlockText>      # CASE 3:               TempFunction[         Cell[TextData[{"Let ",          Cell[BoxData[         FormBox[RowBox[{"x", " ", "=", " ", "y"}], TraditionalForm]],          "InlineMath", FormatType -> "TraditionalForm"], "."}], "Text"]     ]                    <blockText>Let <inline>x = y</inline>.</BlockText>      I was expecting this:               <blockText>Let <inline>x = y</inline>.</BlockText>      Is this a bug? What style is being surrounded by the tag em? Case 1 and Case 2 make sense, but Case 3 has me scratching my head. Can someone explain this behavior?


Finding solutions of polynomials system

Let $f_1,...,f_n$ be a set of polynomials in $x_1,...,x_n$ with _rational_ coefficients. I need to check whether a system $$f_1=a_1,...,f_n=a_n$$ has a _real_ solution for large enough count of points. To specify, there is 4 polynomials of degree 2 in 4 variables, and 10^4-10^7 values of $a_1,...,a_n$. I tried               Size = 30 (* really 100-300 *)     f[x1_, x2_, y1_, y2_] := x1 + y1 - 1 (* in fact I need polynomial of degree 2, *)     g[x1_, x2_, y1_, y2_] := x2 + y2     (* but it does not work even for degree 1 *)     Equation[a_, b_] := Reduce[f[x1, x2, y1, y2] == 0 && g[x1, x2, y1, y2] == 0 &&          x1^2 + x2^2 == a && y1^2 + y2^2 == b, {x1, x2, y1, y2}, Reals]     CheckPoint[{a_, b_}] := ! (FindInstance[Equation[a, b], {x1, x2, y1, y2}, Reals] == {})     Points = Select[Tuples[Range[-Size, Size], 2], CheckPoint]     Graphics[Point[#] & /@ Points, Frame -> True,          PlotRange -> {{-Size, Size}, {-Size, Size}}]      but it reduces system each time. Is there efficient enough way to do it almost in no time?


Exporting the derivatives from NDsolve

k1 = 1;     k2 = 5;     t0 = 0;     ts = 10000000;     t01 = ts - ts/3;     t02 = 7000;     tfnh = 500;     t0nh01 = tfnh/3;     tf = ts;     bv2 = 0;     bb2 = 0;          fh = 0.99;     b10 = 1.0     h10 = fh*b10*(k2/k1)          h20 = 0     Rm2 = 12000;          soln2dec =       NDSolve[{        h1'[t] == (2/3)*h2[t]*b1[t] - (2/3) (k1/k2)^2*h1[t] - 2*h1[t] (k1/k2)^2/Rm2,         h2'[t] == -(2/3)*h2[t]*b1[t] + (2/3) (k1/k2)^2*h1[t] - 2*h2[t]/Rm2,        b1'[t] == (2/3) h1[t]*h2[t] (k1/k2)^2 - (2/3)*          b1[t] (k1/k2)^2 - (2/Rm2) b1[t] (k1/k2)^2, h1[0] == h10,         b1[0] == b10, h2[0] == h20}, {h1, h2, b1, h1', h2', b1'}, {t, t0, ts},       MaxSteps -> 15000000]          Export["logb1k5Rm12000.dat", Evaluate[{b1[t]} /. soln2dec], "TSV"]          Export["logh2k5Rm12000.dat", Evaluate[{h2[t]} /. soln2dec], "TSV"]          Export["logh1k5Rm12000.dat", Evaluate[{h1[t]} /. soln2dec], "TSV"]          Export["logh1dk5Rm12000.dat", Evaluate[{h1'[t]} /. soln2dec], "TSV"]          Export["logh2dk5Rm12000.dat", Evaluate[{h2'[t]} /. soln2dec], "TSV"]          Export["logb1dk5Rm12000.dat", Evaluate[{b1'[t]} /. soln2dec], "TSV"]      The first three exports rightly retrieve the data. But the last three seem to retrieve the function itself and not the derivatives. Is there a way out ?


Fastest way to check if an expression contains all symbols from a list

I need to execute this function thousands of times, and the faster, the better. I came up with two versions, but wanted to see if you can come up with an even faster way. Is there a better way? I use the list:               symbolsList={r,A,b}      And the function checks if my expression contains all those symbols:               expression=r^2+A*b-3      First version:               ContainsAllSymbols[expression_]:=Block[{containsAllSymbols},         containsAllSymbols=True;         Do[containsAllSymbols=containsAllSymbols&&!FreeQ[expression,symbolsList[[dvi]]];If[!containsAllSymbols,Break[]],{dvi,Length[symbolsList]}];         containsAllSymbols     ]      Second version (faster):               ContainsAllSymbols[expression_]:=Scan[If[FreeQ[expression,#],Return[False]]&,symbolsList]=!=False


replace items in a list with items in a another list

Suppose I have a list `A={x1,x2,x3}`, a list `B={3,4,5}`, and a function `f[x]=x1+x2+x3`. Is there a simple way to create a replacement rule `R` such that I can do a `f[x]/.R` to get `3+4+5`?


How does AutoStyleWords work?

The title says it all. I assume it provides some way of automatically applying a certain style, or a list of options, to certain words written, just like other options of the sort like AutoItalicWords. But I haven't been able to make it work... Thanks!


When importing is it possible to set the delimiter?

When importing a csv file is there a way to set the delimiter. I have a csv that uses ";" as its delimiter. I tried                rd = import["/Users/rolfbosscha/Downloads/rsdata.csv"]


Creating Graph with two or more values in second column

For a social network analysis I have two columns. The second column has one, two or more values. Something like this:               data = {{A, {k, l, m}}, {B, {k, l, m, n, o}}, {C, {m, n, o}}}      I would like to make a relation between te value of the first column and for each value in the second column. So I would like to get:               data1 = {A -> k, A -> l, A -> m, B -> k,  B -> l, B -> m, B -> n,      B -> o, C -> m, C -> n, C -> o}      Anyone a suggestion how to solve this?


Summarize a list of pairs / (Using GatherBy and Tally?)

Given a list of (frencuently repeated and unsorted) pairs `{Mode, SubMode}` I want to form the list `{ {COUNT_mode1, COUNT_mode2,...,COUNT_modeN}, {COUNT_mode1_submode1, COUNT_mode1,submode2, ... , COUNT_mdoe1,submodeM1, ... ,COUNT_modeN_submodeNM}, {mode1,mode2,...}, {submode1,submode2,...} }` Here is an example, given:               l = { {"games","minecraft"},{"games","minecraft"},{"games","WoW"}, {"books","book1"},{"books","book1"},{"books","book1"},{"books","book5"},{"other","something"},{"other","book1"}}          MyFunction[l] -->      {         {3,4,2},         {2,1,3,1,1,1},         {"games","books","other"},         {"minecraft","WoW","book1","book5","something","book1"}     }


Import the "thumbnail" of an internet page

I have a list of internet sites links from which I would like to automatically recover the page image/thumbnail and page title. Let's suppose that one of the links is https://www.google.com/, I would like to retrieve the following: ![enter image description here](http://i.stack.imgur.com/iigaX.gif) Is it possible to do it with _Mathematica_? Or maybe, managed by _Mathematica_?


Google Image Search in Notebook?

How can I use google's image api to custom search for images and import them all?


A regularized hypergeometric function related question

I'm interested in finding a way (if possible) of expressing this specific value of the regularized hypergeometric function in terms of known constants. How might I use _Mathematica_ to check   this possibility?   Here is the value               Derivative[{0, 0, 0, 0}, {0, 0, 1}, 0][HypergeometricPFQRegularized][{1, 1, 1, 1}, {2, 2, 2}, -1]


Conditionally replace rows in lists

I have a sequence of matrices/lists               testlist = {{85, 75, 1}, {84, 74, 2}, {83, 73, 3}, {82, 72, 4},                  {81, 71, 5}, {80, 70, 6}, {79, 69, 7}, {78, 68, 8},                  {77, 67, 9}, {76, 66, 10}, {75, 65, 11}};     Table[list[H1R] = DeleteCases[testlist, a_ /; a[[1]] <= H1R || a[[2]] >= H1R],           {H1R, 80, 78, -1}     ]      namely               list[80] = {{85, 75, 1}, {84, 74, 2}, {83, 73, 3}, {82, 72, 4}, {81, 71, 5}}     list[79] = {{85, 75, 1}, {84, 74, 2}, {83, 73, 3}, {82, 72, 4}, {81, 71, 5},                  {80, 70, 6}}     list[78] = {{85, 75, 1}, {84, 74, 2}, {83, 73, 3}, {82, 72, 4}, {81, 71, 5},                    {80, 70, 6}, {79, 69, 7}}      Now I'd like to be able to, in one shot, using `Table` or something, in all lists replace all records/rows where say the second element is between `74.5` and `72.3` with a replacement row say `{-10,5,0.3}` So at the end of my one shot operation or `Table`, I'll have:               list[80] = {{85, 75, 1}, {-10,5,0.3}, {-10,5,0.3}, {82, 72, 4},                   {81, 71, 5}}     list[79] = {{85, 75, 1}, {-10,5,0.3}, {-10,5,0.3}, {82, 72, 4},                  {81, 71, 5}, {80, 70, 6}}     list[78] = {{85, 75, 1}, {-10,5,0.3}, {-10,5,0.3}, {82, 72, 4},                  {81, 71, 5}, {80, 70, 6},  {79, 69, 7}}      These lists that I have generated for my example are very similar to each other but my actual lists are quite different and are non-integer and basically I would like to be able to scan all of the lists in one shot and replace certain rows by other rows provided the elements of the rows or functions of elements of the said row fall in some interval. **Second Update:** Mimicking what you guys have done, I did this because I didn't want to write { _,_.._} because I have 15 columns now and I might have more later:               Table[list[i]=list[i] /. a_ :> {-10, 5, 0.3} /;Dimensions[a] == {3} && 72.3 < a[[2]] < 74.5, {i, 78, 80}]      This code works. woohoo!!


Is there a good way to map a function over a list to lists exclusively of a certain depth?

Let's say I have some ragged list. If some elements have some depth $n$, then is there a way I can map a function to only those elements? I.e., for some list `foo`,               foo = {1, {2, 3}, {4, 5, {6, 7}}, {8}, {9}}      The result should then be for $n=2$:               {1, {bar[2], bar[3]}, {4, 5, {6, 7}}, {bar[8]}, {bar[9]}}      I want to apply a function bar to all parts of it that are of depth 2, and depth 2 only. So far, I have this attempt:               # /. (p_List /; Depth[p] == 2) :> (bar /@ p) & /@ foo     (* {1, {bar[2], bar[3]}, {4, 5, {bar[6], bar[7]}}, {bar[8]}, {bar[9]}} *)      As you can see, pattern matching looks at ALL lists, so I can't really use what I have. I suspect there could be some better, more functional solution to this (possibly using Scan, Reap, and Sow)?


Transform a Sum into a List

I want to turn a sum like this               sum =a-b+c+d      Into a List like this:               sumToList[sum]={a,-b,c,d}      How can I achieve this?


Using Functions as Arguments to Function

I am trying to make a function like `Norm` but defined like so: `MyNorm[{x_,y_,z_}]=Sqrt[x^2+y^2+z^2]`. Mathematica assumes that x, y, and z are constants, and gives `MyNorm'[{x,y,z}]` to be `0` for any x, y, or z. This would be fine, except that my `x`, `y`, and `z` will be functions of `t`, and I would like `MyNorm'[{x,y,z}]` to be equal to $$\frac{d}{dt} MyNorm(x(t),y(t),z(t))$$ of course I actually mean `MyNorm[{x,y,z}]`. Does anyone know how to do this?


Using an inequality to select elements from a list and then plotting the results

Okay, here is the information that I have.               closingValues =        FinancialData["^GSPC", "Close", {"Jan 1., 2000", "Jan 1., 2012"},         "Value"];     logr = Differences[Log[closingValues]];          x = Tally[Sort[Round[logr, .001]]];      What I want to do is this: (logr >= x) / Length[logr] I want to count all the values in logr that are greater than or equal to x (there are about 110 or so values in x). I also need help on plotting a graph where x is on the x-axis, and the resulting number above is on the y-axis. Any help or advice, or leading me to any direction of solving my problem is greatly appreciated. Thank you.


All curves in plot have the same style. Cannot be fixed with Evaluate[]

Usually, when I plot multiple curves in Mathematica               Plot[{x,x^2,x^3},{x,0,1}]      they are given different colors. However, if I try to construct a list inside the `Plot[]` function,               Plot[Table[x^n, {n, 1, 3}], {x, 0, 1}]      this doesn't work and all the curves come out the same color. The standard advice (e.g. here, here and here), which works but which I don't fully understand, is to wrap the `Table[]` with an `Evaluate[]`:               Plot[Evaluate[Table[x^n, {n, 1, 3}]], {x, 0, 1}]      or equivalently               f[x_,n_]:=x^n;     Plot[Evaluate[Table[f[x,n], {n, 1, 3}]], {x, 0, 1}]      This work in this case, because `f[x_]:=x^n` is a simple function. However, suppose I have a complicated function `g[y]` which uses its argument `y` as an iterator:               g[y_] := Total[Table[1, {z, 1, Round[y + 1]}]]      Mathematica is not smart enough to recognize that this is equivalent to `g[y)]:=Round[y]+1`, and usually such a simplification will not be possible anyways. `g[y]` cannot be evaluated symbolically, because of the iterator, although it's still plenty fast when given a machine number. Then trying to plot various curves using a table constructed with `g[y]` without `Evaluate[]`               Plot[Table[g[x*n], {n, 1, 3}], {x, 0, 1}]      will make all the curves the same color. Adding `Evaluate[]`               Plot[Evaluate[Table[g[x*n], {n, 1, 3}]], {x, 0, 1}]      causes Mathematica to throw an error message about using a bad iterator. (`Table::iterb: "Iterator {z,1,Round[1+x]} does not have appropriate bounds`). **Why, exactly, is`Evaluate[]` necessary in the simple case?** Is it true that `Plot[]` is interpreting the table as a multi-valued function? Why? **How can we achieve the same result in the complicated case where the technique fails?**


Controlling ColorFunctionScaling

Is there a way to control the scaling of `ColorFunction` beside just to turn it off and on with `ColorFunctionScaling`? Two problems with this approach are:   1. Repeating colours if the scaling is small compared to the plot range. ![enter image description here](http://i.stack.imgur.com/90xBU.png)   2. Uniform colour if the scaling is large compared to the plot range. ![enter image description here](http://i.stack.imgur.com/ETpJT.png)


How can I mesh a solid cylinder with triangular or tetrahedral elements

I need to plot triangular mesh on a cylinder. However the function `Cylinder` doesn't have a `mesh` option. By using `ParametricPlot3D[{Cos[phi], Sin[phi], z}, {phi, 0, 2 Pi}, {z, -4, 4}, Mesh->All]`, it gives a hollow cylindrical surface with fine mesh. How can I get a "solid" cylinder with coarse triangular mesh?


Transfer graphics from Mathematica to Word without loss of quality

I want some high-quality 2D graphics produced by _Mathematica_ in my paper. My step-by-step operation as follows: First I make the plot, for example,               Plot[x^3 + 2 x + 3, {x, -2, 3}]      Then I   1. click the right mouse button    2. copy the figure    3. paste in my Word document However, I discover that Word renders my graphic jaggedly. So my question is: how can I extract a graphic from my notebook and transfer it to Word preserving full Mathematica quality? ![enter image description here](http://i.stack.imgur.com/hvgmj.png)


inverting this equation

I'm trying to inverse this equation               Z = X + X^2 / 2      but couldn't wrap up my head around it. If anyone can provide a step by step solution to this it will be really helpful. Thanks in advance!


Differential equation of mass spring system with compliant stoppers

I would like to solve numerically the differential equation for the displacement `x[t]` of a mass `m`-spring `k` system with compliant stoppers. The equation should be something like:               m x"[t] == -k x[t] -F[t]       `F[t]` should be defined so that: -it is `0` when `Abs[x]` is below a certain value `x0` -it is equal to `- k2 (x[t] - x0)` when `Abs[x]` is above `x0`. Which _Mathematica_ function should I use to define `F[t]` so that `NDSolve` can solve the corresponding equation?


Cubic polynomial interpolation with velocities listed rather than some points

I am trying to use the function BSplineFunction[] to create a natural cubic spline. Normally what is done is that you specify "SplineDegree -> 3" and include a list of points and it will carry out the interpolation. I have a slightly different scenario now where my knots are not known, some of the points are variable and some interpolation points are not specified but rather velocities are specified. More specifically, I would like a natural cubic spline satisfying these constraints where the numbers $0 < b < a$ and where $p_{-1}, p_0$ and $p_1$ are fixed: $$ \begin{align}x(-a) & = a(p_{-1} - p_0) & x^{(1)}(-a) & = p_0 - p_{-1} & x^{(2)}(-a) &= 0 \\\ x(a) &= a(p_1 - p_0) & x^{(1)}(a) & = p_1 - p_{0} & x^{(2)}(a) &= 0 \\\ & &x(0) &= p_0\end{align} $$ With the condition $x(t)$ needs $C^2$ at $t = -b$, $t = 0$ and $t=b$. This will give me $4$ separate cubic polynomials on $[-a, -b], [-b, 0], [0, b], [b, a]$. I have a total of $16$ degrees of freedom and $16$ constraints so a unique solution should exist. I could very easily put this into a matrix myself but it seems Mathematica already has it inbuilt, it would be a shame not to use it just because I couldn't figure out how. Is this possible and if so, can you please either let me know how or point me to relevant documentation that I might not have seen yet. Thanks Edit: Additional details regarding the conversation between me and belisarius below. I have done a hand computation for such a problem and here is an example of a function I get: $$ f_1 = -\frac{x^3 (-2 b \text{pC}+b \text{pL}+b \text{pR}-6 \text{pC})}{6 a^2 (a-b)}-\frac{x^2 (-2 b \text{pC}+b \text{pL}+b \text{pR}-6 \text{pC})}{2 a (a-b)}-\frac{x (-2 a \text{pC}+2 a \text{pL}-b \text{pL}+b \text{pR}-6 \text{pC})}{2 (a-b)}+\frac{a (2 b \text{pC}-b \text{pL}-b \text{pR}+6 \text{pC})}{6 (a-b)} $$ where pL = $p_{-1}$, pC = $p_0$ and pR = $p_1$. Here is a picture of $f_1, f_2, f_3, f_4$ for the parameters $b=3, a=6$ and $p_{-1} = 2, p_0 = 3$ and $p_1 = 5$: ![Cubic spline](http://i.stack.imgur.com/Oi2B8.png)


How to efficiently find moments of a multinormal distribution?

I have a multinormal distribution with covariance matrix $\sigma$ and zero mean. I want to find moment $$ E[x_1^{r_1}x_2^{r_2}\cdots x_n^{r_n}] =\,? $$ Of course, there is a build-in function `Moment`, but it is quite slow for big moments               Moment[MultinormalDistribution[{0, 0}, {{σ[1, 1], σ[1, 2]}, {σ[2, 1], σ[2, 2]}}],        {20, 20}]; // AbsoluteTiming // First      > 1.604658 _Is there a more efficient method?_ It is related to this question and my answer there. I think that Isserlis' theorem is helpful. It says $$ E[x_1x_2\cdots x_n] = \sum\prod E[x_ix_j] $$ if $n$ even and $0$ if $n$ odd, by definition $E[x_ix_j]=\sigma_{ij}$. Here the notation $\sum\prod$ means summing over all distinct ways of partitioning $x_1,x_2,\ldots, x_n$ into unordered pairs. For example, $x_1,x_2,x_3,x_4$ can be spitted as $$ (x_1,x_2),(x_3,x_4);\quad (x_1,x_3),(x_2,x_4);\quad (x_1,x_4),(x_2,x_3). $$ Therefore, $$ E[x_1x_2x_3x_4]=\sigma _{1,2} \sigma _{3,4}+\sigma _{1,3} \sigma _{2,4}+\sigma _{1,4} \sigma _{2,3}. $$ If we want to calculate $E[x_1^2x_2x_3]$ then we can put two indexes equal (e.g. $x_4=x_2$) in the previous equation $$ E[x_1^2x_2x_3] = \sigma _{1,1} \sigma _{2,3} + 2 \sigma _{1,2} \sigma _{1,3}. $$ Another examples: $$ E[x_1^2x_2^2] = \sigma _{1,1} \sigma _{2,2} + 2 \sigma _{1,2}^2, $$ $$ E[x_1^3x_2] = 3 \sigma _{1,1} \sigma _{1,2}, $$ $$ E[x_1^4] = 3 \sigma _{1,1}^2. $$ For six variables there is 15 terms: $$ E[x_1x_2x_3x_4x_5x_6]=\sigma _{1,2} \sigma _{3,4} \sigma _{5,6}+\sigma _{1,2} \sigma _{3,5} \sigma _{4,6}+\sigma _{1,2} \sigma _{3,6} \sigma _{4,5}+\sigma _{1,4} \sigma _{2,5} \sigma _{3,6}+\sigma _{1,5} \sigma _{2,4} \sigma _{3,6}+\sigma _{1,4} \sigma _{2,6} \sigma _{3,5}+\sigma _{1,6} \sigma _{2,4} \sigma _{3,5}+\sigma _{1,5} \sigma _{2,6} \sigma _{3,4}+\sigma _{1,6} \sigma _{2,5} \sigma _{3,4}+\sigma _{1,3} \sigma _{2,4} \sigma _{5,6}+\sigma _{1,4} \sigma _{2,3} \sigma _{5,6}+\sigma _{1,3} \sigma _{2,5} \sigma _{4,6}+\sigma _{1,5} \sigma _{2,3} \sigma _{4,6}+\sigma _{1,3} \sigma _{2,6} \sigma _{4,5}+\sigma _{1,6} \sigma _{2,3} \sigma _{4,5}. $$ As you can see, this statistical problem is just a combinatorics problem: find all possibilities to put $r_1$ balls of type $1$, $r_2$ balls of type $2$, ..., and $r_n$ balls of type $n$ to bins. Each bin can take 2 and only 2 balls.


How to always display current section identifier (number, name) in notebook?

Because I find myself relocating frequently within a long notebook divided into sections, subsections, & subsubsections, I would like to display the identifying information for the section, etc. that I'm in at any point in time. I have in mind something similar to a readily visible header or footer that one might display within a word processing document or textbook. For example, if I am working somewhere within a section titled "4.2) Geometry of Matrix Transformations of the Plane", I would like that section identifier displayed conveniently and updated when my further relocating within the notebook takes me into a different section. My aim is not to compose a textbook/article/etc.; it's the far more humble purpose of helping myself as I work my way through an assigned textbook, making notes, computations, plots, and so forth and jumping this way and that throughout the notebook as the semester progresses. Suggestions for someone who is not a programmer? Thx!


Distance between data and curve

I have two datasets:               dataset1 = {{3514147200, 5.83}, {3514233600, 7.48}, {3514320000, 7.86}, {3514406400, 6.74}}     dataset2 = {{2407708800, 131.3}, {2407795200, 131.7}, {2407881600, 130.9}, {2407968000, 131}}      By down sampling to get the datasets to be the same "length", I know that there is a correlation of approximately 0.95 between the two datasets. I have created a **very large** polynomial from `dataset2` to approximate `dataset1`.               polynomial[x_] := -1.19937*10^11 - 16.2653 x - 9.10704*10^-10 x^2 + 4.74474*10^-19 x^3 + ...      When `polynomial` and `dataset1` are plotted together, I can see that the polynomial is close to the data. I am looking for a way to measure the " _distance_ " between the dataset and the polynomial. I tried using `KolmogorovSmirnovTest` but it wasn't much help, any ideas about how to do this?


How to recompute the layout of a Graph?

I asked a question about changing `Graph` properties in a similar way to how `Show` can change `Graphics` properties. The answer was to use `SetProperty`. Unfortunately this does not work for `GraphLayout`. Take the following example:               g1 = RandomGraph[{10, 20}]     g2 = RandomGraph[{10, 20}, GraphLayout -> "SpringEmbedding"]          {PropertyValue[g1, GraphLayout], PropertyValue[g2, GraphLayout]}          (* ==> {Automatic, "SpringEmbedding"} *)          ng1 = SetProperty[g1, GraphLayout -> "CircularEmbedding"]     ng2 = SetProperty[g2, GraphLayout -> "CircularEmbedding"]          {PropertyValue[ng1, GraphLayout], PropertyValue[ng2, GraphLayout]}          (* ==> {Automatic, "SpringEmbedding"} *)      Note that while `GraphLayout` can be queried through the standard property API, it doesn't seem like it can be set. Again, a hack like `HighlightGraph[g, {}, GraphLayout -> "CircularEmbedding"]` will work, but it is just a hack. One could retrieve the vertex and edge lists of the graph and build a new `Graph[...]`, but that is both tedious and it'll discard other property values. **So, what is the best way to re-layout a graph?** Right-clicking the graph and choosing a new layout works, but I'm looking for a programmatic way. Also, right-clicking and choosing a new layout is _terribly slow_ \---much much slower than rebuilding the graph or using `HighlighGraph` (can anyone reproduce this problem, is it slow for you as well?) **Update** Some spelunking reveals that `GraphComputation`CloneGraph[g, GraphLayout -> "CircularEmbedding"]` will do the job, but I'd rather not use internal and undocumented functionality for this.


Solving a system of nonlinear coupled ODEs

I tried using `NDSolve` to solve the following system of equations:               t x'[t] == -x[t] + y[t],      t y'[t] == -5 t^2/x[t]^2 + x[t] - y[t],            x[1] == 4, x[100] == 1      It's weird. The system tells me there is infinity at the boundary $t=1$, so I change the boundary from $t=1$ to $t=2$, and I get the same message again. If I eliminate the nonlinear term `-5 t^2/x[t]^2`, the function can be solved analytically. So I do not know whether these equations are well posed or not with such boundary conditions just for `x[t]` Anyone have a suggestion?


Adding a Sphere onto an existing 3D plot

I have a 3D plot. I need to add a small sphere marking the starting point, `r[t] == 0`. I'm pretty new at _Mathematica_ and would greatly appreciate some help.               r[t_] =        Piecewise[{         {{5 t, 0, 3 (1 + Cos[ t])}, 0 <= t <= π},          {{5 Cos[t - 3 π/2] + 5*π, 5 Sin[t - 3 π/2] + 5, 0}, π < t <= 2 π},          {{5*π + 3*Cos[t - 3 π/2], 2*5 - 3 + 3*Sin[t - 3 π/2], 1/(2 π) (t - 2 π)^2},            2 π < t <= 4 π},          {{-3 (t - 17 π/3), 10, -1/π t^2 + 10 t - 22 π}, 4 π < t <= 5 π},          {{-3 t + 17 π, 10, -972 π + 540 t - (99 t^2)/π + (6 t^3)/π^2}, 5 π < t <= 6 π},          {{-π - 3 Sin[t], 9/40 (1/3 (20 + 18 π) - t)^2, 3 Cos[t] - 3}, 6 π < t <= 8 π},          {{-25 π + 25 t - (19 t^2)/(4 π) + t^3/(4 π^2),            -(25/2) (140 - 132 π + 27 π^2) + (15 (80 - 74 π + 15 π^2) t)/(2 π) -               (3 (180 - 164 π + 33 π^2) t^2)/(8 π^2) -               ((-50 + 45 π - 9 π^2) t^3)/(20 π^3),            1056 - (360 t)/π + (81 t^2)/(2 π^2) - (3 t^3)/(2 π^3)},            8 π < t <= 10 π}}];          s[t_] = Cos[t]          ParametricPlot3D[r[t], {t, 0, 10 π}]


Generate higher dimensional box vectors

I'd like to generate integer vectors in $\\{-M,-M+1,\dots,M\\}^n$, where $M$ and $n$ are parameters. For a fixed $n$, say $n=3$ for instance, I only know I can use               Flatten[Table[{i, j, k}, {i, -M, M}, {j, -M, M}, {k, -M, M}]]      to get the list. But for larger $n$, I would have to add more coordinate ranges manually. Is there an automatic way to do this? I have a similar question on `Sum` and `NSum`; for instance, I want to compute $\sum_x e^{-\|x\|^2}$ for $x$ over $\\{-M,\dots,M\\}^n$. For $n=3$ I could write               NSum[E^(-(i^2 + j^2 + z^2)), {i, -M, M}, {j, -M, M}, {k, -M, M}]      Is there a more automatic way to do this?


Kernel quits on closing notebook

Mathematica quits (exits) when the single notebook I'm working on is closed. How to prevent this? Win7, v10 Mathematica


Setting and changing MetaInformation for arbitrary objects

I work with a lot of dynamic data in `{{date, datum}. . .}` format,               datedatalist={{{2001, 1, 1}, 45.2}, {{2002, 1, 1}, 132.}, {{2003, 1, 2}, 121.1}};      and I have historically attached a header to each object in a format like               datedataObject={{header version, data series name, type (value, % change, etc.)}, datedatalist};      I can see advantages to using Mathematica's TemporalData[] type, and to using MetaInformation[] for recording the header. I would set this up with something like               newObject = TemporalData[datedatalist, MetaInformation -> {"name" -> "whatever", "type" -> "value"}];      and extract header items with, for example               newObject["name"]      But this leaves me with two puzzles,   1. How do I add MetaInformation after the object has been created? and   2. How do I change existing MetaInformation?