title: Errors in evalauting an expression

text: I have the following: **Constants:**               b3b = 2;     G = (1/eps^2);     a1 = 3;     a3 = 4;     xc = 0.3;      **Functions:**               y[x_] := (x*a1 - x^3*a3)/G     n[x_] := (y[x]^2)      **I want`g[x], gp[x], gpp[x]` as functions of `eps` only and all of these three functions should be evaluated at `x=xc` :**               g[x_] := (G*(-y[x]/eps)*Exp[-n[x]] - (b3b/eps)*          NIntegrate[(y[s])^4*Exp[-n[s]], {s, 0, xc}])      Please note that in the **integrand** above --> both `n[x]` and `y[x]` are functions of `eps` and so I can use `NIntegrate` since I am using `:=` for `g[x]` even though `eps` is not given a numerical value as yet. Everything is perfect till this point as I am able to get a numerical value for `g[xc]` for a `eps` value. The problem happens when I take the following derivatives:                gp[x_] := D[g[x], x]      gpp[x_] := D[gp[x], x]      since when I evaluate `gp[xc]` and `gpp[xc]` for a particular `eps` value, I get errors: `NIntegrate::inumr` and `General::ivar`. Therefore, I need a way to get around this. I must be doing something wrong. Any help would be greatly appreciated. Thanks!


title: Revert Notebook to earlier version using Notebook History

text: Is it possible to revert a notebook to its earlier version via the Mathematica's Notebook History panel? It would be nice if I could select a point in time in the bottom graph and revert back to that version: ![enter image description here](http://i.stack.imgur.com/wyPoB.png) When hovering over the blue dots on the upper graph, you can see the previous and the current contents of the changed cells, so Mathematica must store this somewhere. Maybe this could even be used instead of a better undo implementation.


title: Highlighting text with StringReplacePart but also using Style, Subscript

text: For a Natural Language Processing analysis task it's desirable to highlight a text string programmatically according to XML tags that reference specific words or phrases. The XML tags specify the character ranges in the input string as well as give other information such as identifiers and other codes. Since character ranges are provided in the XML markup, originally I thought `StringReplacePart` would do the job, but it doesn't seem possible to transform the string into more general expressions, eg using Subscript or Style. For example (please excuse I'm showing only a fragment due to Protected Health Information), given the (partial) input text:               In[566]:= StringTake[I2B2[1, text], -500]          Out[566]= " pain and was treated with Percocet . She went for a \     debridement of her left calf lesion on 10/2/93 and was started \     empirically on IV ceftriaxone which was changed to po doxycycline on \     the day of discharge . A follow-up CT scan was done which did not \     show any evidence for splenomegaly or hepatomegaly . The 1 cm cyst \     which was seen in 10/92 was still present . There was a question of a \     cyst in her kidney with a stone right below the cyst , although this \     did not seem to be clinically significant ."      And the XML tag:               In[581]:= Cases[I2B2[1, tags],       XMLElement[       "EVENT", {id_, start_, end_, text_ -> "a stone", modality_,         polarity_, type_}, _]]          Out[581]= {XMLElement[       "EVENT", {"id" -> "E75", "start" -> "2476", "end" -> "2483",         "text" -> "a stone", "modality" -> "POSSIBLE", "polarity" -> "POS",         "type" -> "PROBLEM"}, {}]}      The following `StringReplacePart` works (to ALL CAPS) since the output is still a string:               In[577]:=  StringReplacePart[      StringTake[I2B2[1, text], -500],      "A STONE", {2476,         2483 - 1} - ((I2B2[1, text] // StringLength ) - 500)]          Out[577]= " pain and was treated with Percocet . She went for a \     debridement of her left calf lesion on 10/2/93 and was started \     empirically on IV ceftriaxone which was changed to po doxycycline on \     the day of discharge . A follow-up CT scan was done which did not \     show any evidence for splenomegaly or hepatomegaly . The 1 cm cyst \     which was seen in 10/92 was still present . There was a question of a \     cyst in her kidney with A STONE right below the cyst , although this \     did not seem to be clinically significant ."      But the following does not since I'm trying to highlight in Red using Style:               In[578]:=  StringReplacePart[      StringTake[I2B2[1, text], -500],      Style["a stone",        Red], {2476, 2483 - 1} - ((I2B2[1, text] // StringLength ) - 500)]          Out[578]= StringReplacePart[" pain and was treated with Percocet . \     She went for a debridement of her left calf lesion on 10/2/93 and was \     started empirically on IV ceftriaxone which was changed to po \     doxycycline on the day of discharge . A follow-up CT scan was done \     which did not show any evidence for splenomegaly or hepatomegaly . \     The 1 cm cyst which was seen in 10/92 was still present . There was a \     question of a cyst in her kidney with a stone right below the cyst , \     although this did not seem to be clinically significant .", \!\(\*     StyleBox["\<\"a stone\"\>",     StripOnInput->False,     LineColor->RGBColor[1, 0, 0],     FrontFaceColor->RGBColor[1, 0, 0],     BackFaceColor->RGBColor[1, 0, 0],     GraphicsColor->RGBColor[1, 0, 0],     FontColor->RGBColor[1, 0, 0]]\), {413, 419}]      Are there functions similar to StringReplacePart that can output more general expressions? Or in any case how to perform the desired highlighting with Subscript and Style?


title: How to do the log scale plot for ListContourPlot

text: My current code is:               data = {{0.1, 0.1, 2}, {0.1, 0.2, 1}, {0.2, 0.1, 1}, {0.2, 0.2, 2}};     ListContourPlot[data, Mesh -> None, PlotRange -> All,       InterpolationOrder -> 3,       ColorFunction -> ColorData[{"LakeColors", "Reverse"}]]      It produces the following figure: ![enter image description here](http://i.stack.imgur.com/ju78p.png) I want to scale the linear x and y axes to a log scale without converting to log units. There is a ListLogLogPlot function but no corresponding ListLogLogContourPlot function. I have read several relevant threads:   * How does one set a logarithmic scale in a ContourPlot?: How does one set a logarithmic scale in a ContourPlot?   * Scale ContourPlot axes: http://forums.wolfram.com/mathgroup/archive/2006/Jun/msg00585.html However, they are all for ContourPlot rather than ListContourPlot. I tried to use way suggested by How does one set a logarithmic scale in a ContourPlot?:               data = {{0.1, 0.1, 2}, {0.1, 0.2, 1}, {0.2, 0.1, 1}, {0.2, 0.2, 2}};     pl = Normal@       ListContourPlot[data, Mesh -> None, PlotRange -> All,         InterpolationOrder -> 3,         ColorFunction -> ColorData[{"LakeColors", "Reverse"}]]     ListLogLogPlot[Cases[pl, Line[a_, b___] :> a, Infinity],       Joined -> True, Frame -> True, PlotRange -> All, AspectRatio -> 1,       PlotStyle -> ColorData[1][2]]      However, it only produces the following, in which the density color background is lost, leaving only lines: ![enter image description here](http://i.stack.imgur.com/o7e0U.png) The way suggested by http://forums.wolfram.com/mathgroup/archive/2006/Jun/msg00585.html by using FrameTicks functions seems promising. But, it is for ContourPlot. I do not know how to adopt it to be used in ListContourPlot. Helps are much appreciated.


title: Manipulate inside a function definition slows down when passed a large data set

text: I'm working with large data sets (>1gb) which I'm visualizing with `Manipulate[]`. The following example works fine for me with no additional memory overhead:               data = RandomReal[{0, 1}, {500, 500, 500}];     (* no memory overhead and fast response time *)     Manipulate[Image[data[[All, All, i]]], {i, 1, 500, 1}]      However, if I wrap the above code into a separate function definition, memory usage rises and evaluation does'n complete in a reasonable time:               vizData[dataVar_] := Manipulate[Image[dataVar[[All, All, i]]],{i, 1, 500, 1}]     (* very high memory usag and slow evaluation! *)     vizData[data]      How can I wrap the functionality of `Manipulate` into a function without this high memory utilization? Working with global variables is not an option because I'm dealing with multiple data sets.


title: Storing result from nested Table in a File for further computations

text: Consider the following:                Table[Table[x = 20; y = 30; 2 i x + 3 j y , {i, 10}], {j, 3}]      Suppose I want the result of this nested Table to be stored to an appendable file, I could do something like:               Table[Table[x = 20; y = 30; 2 i x + 3 j y >> test.dat, {i, 10}], {j, 3}]      Where `test.dat` has been previously opened using `OpenAppend["test.dat"]` However, this doesn't work as I would like it to as the answer is stored differently than the actual output shown below and _Mathematica_ returns Null for every element of the output.               {          {130, 170, 210, 250, 290, 330, 370, 410, 450, 490}, {220, 260, 300,           340, 380, 420, 460, 500, 540, 580}, {310, 350, 390, 430, 470, 510,           550, 590, 630, 670}        }      My question is this. How can I save the output of the Nested Table to a file for every iteration of the outer `Table` and prevent any `List` from being returned by _Mathematica_?. That is, I don't want _Mathematica_ to return the following `List` as it currently does:               { {Null, Null, Null, Null, Null, Null, Null, Null, Null, Null}, {Null,        Null, Null, Null, Null, Null, Null, Null, Null, Null}, {Null, Null,        Null, Null, Null, Null, Null, Null, Null, Null} }      I will also like the data stored in the file to be exactly as the output shown above, since I will use it for further calculations in _Mathematica_. This is basically a way to prevent excessive memory usage. If there are better ways to achieve the same thing please feel free to post that as an answer.


title: Write nth line to file

text: I have a code that I am running on a supercomputer. Currently the algorithm must finish before I can export any results from the algorithm. What I would like to do is to have the algorithm write out the results for every nth line of the loop. Could someone help me write this into the algorithm below. I currently use the Reap and Sow construct to store the data and collect it all at the end. Sometimes the code crashes for during the run, in which cases I get nothing out of the run before it stops. If I could also write to a file while the code is running, at least I'd have better starting points to begin the next run. Thanks!                      If[             u[[i]] < v[[i]],(*If u<v always accept that parameter set,             else accept with probability u<v*)                  ka[[i + 1]] = ka[[i]];             kb[[i + 1]] = kb[[i]];             Sow[{True, decayscore[[i]], v[[i]], ka[[i]], kb[[i]], i}],            (* These quantities are written to bestParamSets *)                  ka[[i]] = ka[[i - 1]];             kb[[i]] = kb[[i - 1]];             ],            ka[[i]] = ka[[i - 1]];            kb[[i]] = kb[[i - 1]]            ],


title: Using ANOVA with a "Repeated measures" / "Within-subjects" design

text: Repeated measures designs or "Within-Subjects" designs are very important in live sciences and social sciences. Unfortunately, _Mathematica's_ ANOVA package is not able to analyze those designs. It only handles "Between- Subjects" type of analyses. During my whole research career I haven't been able to use _Mathematica_ to analyze most of the studies I performed, which really is a pity. In an e-mail exchange I had with WRI's Andy Ross in the beginning of this year he confirmed that I wasn't overlooking built-in functionality. The question is: is any one aware of third party packages that handle these types of ANOVAs?


title: Open parent cell groups of selected cell

text: I wrote a small script for a palette, which allows me to highlight a specific cell in a notebook by using `SelectionMove[mycell, All, Cell]`. The cell is selected as expected, but sometimes this cell is part of a cell group (section, subsection etc.) which is currently closed, so the cell itself is hidden, and `SelectionMove` does not reveal it. So far, I didn't find a way to open all parent groups of this cell programatically so that this cell will be shown... Is this possible?


title: How can I make a list plot with bars?

text: Can anyone help me please? I don't want a Histogram; I don't want a BarChart, not even a ListPlot with drop down lines. I want a list plot with drop down columns/bars: please see the link. ![Mathematica graphics](http://i.stack.imgur.com/EQGkc.png) It is basically a histogram but of a different kind. The data structure contains two variables for example in the above figure it was energy and standard deviation. And the frequency distribution was done based on two cut- offs {0.5,2.0} and finally it was plotted along the energy axis. Therefore, it contains overlapping bars/columns. A projection of a 3D histogram in two dimensions.


title: How to bend a logarithmic number line into a circle

text: One way to plot a sequence of numbers on a logarithmic number line is this:               LogLogPlot[0, {t, 8, 16}, Axes -> {True, False},       Ticks -> {{8, 9, 10, 11, 12, 13, 14, 15, 16}}]      ![logarithmic number line values 8 to 16](http://i.stack.imgur.com/xf4bo.png) How can the line be bent into a circle, or how can these values be plotted on a circle? ![logarithmic values 8 to 16 on circle](http://i.stack.imgur.com/7vscl.png) The `ParametricPlot` function plots a circle around the coordinates when using `[{Sin[2 u], Cos[2 u]}, {u, 0, 2 Pi}]` and `Graphics[Circle[]]` draws a circle but I can't figure out how to put `Ticks` on them.


title: Mapping a pure function with multiple slots

text: Here is a pure function with multiple slots:               (#1^2 + #2^2)&[3, 4]      > 25 But how can I map that pure function over lists of values? For example, say I want to map `(#1^2 + #2^2)&` over `x = {1, 2, 4}` and `y = {3, 4, 6}`. I have tried the following expressions, but none of them work:               Map[(#1^2 + #2^2) &, {1, 2, 4}, {3, 4, 6}]     Map[(#1^2 + #2^2) &, {{1, 2, 4}, {3, 4, 6}}]     Map[(#1^2 + #2^2) &, {{1, 3}, {2, 4}, {4, 6}}]      The result I expect is obviously `{10, 20, 52}`. Could some one help me with this?


title: Logical operations on a list

text: > **Possible Duplicate:**   >  Applying And to lists of Booleans I have two lists filled with logicals:               demondata = {True, True, False, True}     numerdata = {True, False, True, True}      I would like to find which corresponding cells positions are both `True`. The only code I could come up with is:               toInclude = MapThread[And, {demondata, numerdata}];      Is there a way to do something like:               demondata && numerdata      Not that there is something wrong with `MapThread`, it just seems more complicated than I thought it would be. In MATLAB, I can do:               list1 & list2  _or_  list1 > 10   etc ...


title: Applying And to lists of Booleans

text: I'd like to take `{True,True,False}` and `{True,False,False}` and apply `And` to get `{True,False,False}`. Right now I'm using               And @@ # & /@ Transpose[{{True, True, False}, {True, False, False}}]      Is that really the best way? I would like `And[{True, True, False}, {True, False, False}]` to work but it does not.


title: Numerical solution of coupled ODEs with boundary conditions

text: I have to solve the following set of ODEs and just can't get good results using Mathematica $$ r\frac{d}{dr}\left(\frac{1}{r}\frac{d}{dr}A(r)\right)-\xi^2F(r)^2\left(A(r)-1\right)=0 $$ $$ \frac{1}{r}\frac{d}{dr}\left(r\frac{d}{dr}F(r)\right)-\frac{n^2}{r^2}F(r)\left(A(r)-1\right)^2-\frac{1}{2}F(r)\left(F(r)^2-1\right)=0 $$ There are two parameters $\xi\in\mathbb{R}^+$ and $n\in\mathbb{Z}$. There also are boundary conditions at $0$ and at $\infty$. $$F(0)=A(0)=0$$ $$F(\infty)=A(\infty)=1$$ These gave me the first puzzle: how to implement boundary conditions at infinity? I solved this by taking a finite number (in my case 5) instead of infinity. Do you think it is a good approach or is there a more elegant way to implement boundary conditions both at zero and infinity?   Next I want to solve these equations numerically. Here is the Mathematica code for $\xi=1$ and $n=1$               paramND = {         r D[1/r D[A[r], r], r] - \[Xi]^2 F[r]^2 (A[r] - 1) == 0,         1/r D[r D[F[r], r], r] - n^2/r^2 F [r] (A[r] - 1)^2 -            1/2 F[r] (F[r]^2 - 1) == 0,         A[5] == 0.99, A[0.01] == 0,         F[5] == 0.99, F[0.01] == 0} /. {\[Xi] -> 1, n -> 1};          numSol = NDSolve[paramND, {A[r], F[r]}, {r, 0.01, 5}] // Flatten;          paramPlot = {A[r], F[r]} //. numSol;          Plot[Evaluate@paramPlot, {r, 0.01, 5}, PlotRange -> {0, 1},       PlotStyle -> {{Black, Thick}, {Red, Thick}},       PlotLegends -> {"A(r)", "F(r)"}]      For $\xi=1$ and $n=1$ this works fine and I get a result that I expect:   ![xi=1,n=1](http://i.stack.imgur.com/cm13c.png)   The problem is that the numerical solution only works if both parameters $\xi$ and $n$ are close to $1$. Changing these parameters to values different from $1$ produces somewhat awkwrd results: $\xi=3$, $n=1$:   ![xi=3,n=1](http://i.stack.imgur.com/xvz79.png) $\xi=1$, $n=5$:   ![xi=1,n=5](http://i.stack.imgur.com/RQJWI.png)   As you can see, the last two plots don't even respect the boundary conditions! Why is this so? All solutions should look more or less like the first plot, which clearly isn't the case.   I suppose that I lack some fundamental knowledge about how to use NDSolve to produce results which I expect. Can you suggest a good strategy in order to obtain good solutions to these ODEs? I've also tried using the "Shooting" algorithm, which, however, didn't give any useful result either. Maybe you can point out to me what the exact reason is, why NDSolve fails here so I know what to cure. Up to now it was rather a try and error procedure.   So, to sum up, my two questions are:   1. How to implement boundary conditions at infinity?   2. How to choose a good strategy for NDSolve to obtain results one expects?


title: Bug in TreeForm: "Plot" formatted as True

text: I believe I have come across a rather curious bug in `TreeForm`:               {"foo", "bar", "Plot"} // TreeForm      ![enter image description here](http://i.stack.imgur.com/tWLuC.png) Note that the string `"Plot"` is formatted as `True`. Unless I have accidentally changed something in my configuration this must be a bug. I am using version 10.0.0 under Windows.


title: Does new MMA9 Time Series support obsolete the old TimeSeries Package?

text: MMA9 includes a fair number of functions and symbols that seem to overlap with the old TimeSeries package. The new features are documented here and the old material is documented here. Some of the names are 'same-only-different:' for example, the old package has `ARMAModel` and the new built-in has `ARMAProcess`. The argument list and meaning appear to be the same. I'd like to know if the old package is obsoleted by the new features, or is there still enough utility in the old package to justify its price (around $300)? I can't find a try-before-buy option on the package, so this question seems difficult to answer on my own.


title: Minimizing a potential using Solve

text: I am having problems minimizing a potential: $\text{V}(h,\eta)=\gamma \left(-h^2\right) \left(\eta ^2 \cos ^2(\theta )+\eta \cos (\delta ) \sqrt{-\eta ^2-h^2+1} \sin (2 \theta )+\left(-\eta ^2-h^2+1\right) \sin ^2(\theta )\right)$ (Input code below)               V = -h^2 γ (η^2 Cos[θ]^2 + (1 - h^2 - η^2) Sin[θ]^2 + η Sqrt[1 - h^2 - η^2] Cos[δ] Sin[2 θ])      I try to minimize simply using:               sol = Solve[{D[V, h] == 0, D[V, η] == 0}, {h, η}]      It seems to solve quickly and with no problems giving me 9 solutions, these solutions depend on the parameters $\theta, \delta, \gamma$. However if for example I try to calculate:               Chop[N[D[V,h] /. sol /. θ -> 1 /. δ -> 1 /. γ -> 1]]      The output it gives is: > >     {0, -0.104069, 0, 0, -0.484451, 0.104069, 0, 0, 0.484451} >   As you can see extrema `2`, `5`, `6` and `9` are not even close to zero! It seems _Mathematica_ is solving this incorrectly, or maybe the solutions are only valid in specific regions (not the full domain)? Does anyone have any ideas? I thought maybe the problem was with the square root in the function (otherwise it's a simple polynomial) but have tried solving it using the Lagrange multiplier method taking a function $V(h,η,s)$ and $s=\sqrt{1-h^2-η^2}$ but it also doesn't seem to give me all zero solutions when I sub it in to the Lagrange equation $\frac{\partial V}{\partial h}+\lambda \frac{\partial g}{\partial g}$, where $g=s-\sqrt{1-h^2-η^2}=0$, the constraint applied to this function. Any ideas what's happening ? Has anyone encountered this problem before?


title: Is there a way to programmatically set global preferences?

text: Can I set global preferences that are accessible via "Edit"->"Preferences" programmatically from within a notebook? As learned from this question, turning off anti-aliasing can make a huge difference in the maximum allowable `ImageSize`. This can be done via menu: ![Mathematica graphics](http://i.stack.imgur.com/jV486.png) The slider is setting the value of `HardwareAntialiasingQuality` that can be found with the option inspector: ![Mathematica graphics](http://i.stack.imgur.com/gmKrK.png) Question: Is there a way to set/reset the value of `HardwareAntialiasing` (and others) programmatically? I´d like to set this with a line only in those notebooks that benefit from this setting and have proper antialiasing for the rest. Footnote: this answer does help with setting the rendering method directly within a `Graphics3D` expression, and as @Sjoerd's answer shows this also works in more global way.


title: EventHandler not working within DateListPlot (?)

text: I have some `{date, value}` data:               data = Transpose[{AbsoluteTime /@ Thread[{2012, Range[12], 15}],         RandomInteger[10, 12]}]      Normally I do initial tests with `DateListPlot` and then implement with `ListPlot` or `ListLinePlot` for efficiency. However I just tried this:               DateListPlot[      Table[With[{i = i},        EventHandler[data[[i]], "MouseClicked" :> {Print["hello"]}]], {i,         12}]      ]      and got this error message `DateListPlot::dtvals: Unable to automatically determine horizontal coordinates for the given data and DataRange.` ![enter image description here](http://i.stack.imgur.com/7jME6.png) Whereas if I switch to `ListPlot` or `ListLinePlot` it works fine:               ListPlot[      Table[With[{i = i},        EventHandler[data[[i]],          "MouseClicked" :> {Print["hello " <> ToString[i]]}]], {i, 12}]      ]      ![enter image description here](http://i.stack.imgur.com/oUxLb.png) Can anyone explain why `EventHandler` would not work within `DateListPlot` (hopefully this is not a RTFM question!)? Problem exists with 8.0.4 and 9.0.1 on Mac 10.6.8


title: Extracting equations from Piecewise expressions

text: Say I have a PDF:               PDF[LogNormalDistribution[1.75, 0.65], x]      Calculating it, Mathematica gives me an expression that looks like this: ![enter image description here](http://i.stack.imgur.com/el6TK.png) I want to extract the equation itself so I can use it in other calculations. On a one off basis, I can do that with `Part[]`:               PDF[LogNormalDistribution[1.75, 0.65], x][[1, 1, 1]]      which gives me the following: ![enter image description here](http://i.stack.imgur.com/uzIdI.png) That's fine, but I need something more universal. For instance, for a different PDF that looks like this: ![enter image description here](http://i.stack.imgur.com/QrZ7u.png) I could get what I need with:               %[[1, 2, 1]]       You see my dilemma. How do I extract the business part of such expressions in a more universal way so I can use them in other calculations and functions that may need to deal with a variety of such expressions?


title: Passing large list by reference

text: I have the following problem: I would like to control evaluation of a variable that points to a list. For example, frequently in the code I have functions of the form that are supposed to work on large lists (modifying them frequently):               updateList[list_, newvalue_, index_]:= (list[[index]] = newvalue)      to be used (many times) as               list = {1, 2, 3};     While[...     updateList[list, -2, 2];     ]      and I should get immediately               list = {1, -2, 3}      The problem is that the list gets evaluated immediately if one is not careful and the assignment statement fails. I have tried to solve this by defining               Attributes[updateList] = {HoldAll}      It works, but I realized that this can get very complicated since I am passing the list quite a bit around in a rather big package. Some function have Hold, some not, on some I would actually like to have the second and the third argument Holding while others not... To tell you the truth, I do not feel I have the control of this behavior; sometimes it evaluates and sometimes it does not, and it is driving me crazy. The reason why I am doing this is to save memory. One could, of course, use the following definition               updateList[list_, newValue_, index_] := (newList = list; newList[[index]] = newvalue)      and use it like               list = updateList[list, -2, 2]      to the same effect, but this will consume quite a bit of memory (my list are huge). So I am trying to control memory usage by updating storage. I guess I am trying to use them as pointers. A more serious example would be               updateList[list_, args__] :=         Block[{indicies, newvalues},            indicies = figureOutIndiciesToChange[args];           newvalues = figureOutValuesToChange[args];           list[[indicies]] = newvalues        ];      or even a more nasty example (actually happens):               updateList[list_, args__] :=         Block[{indicies, newvalues},            indicies = figureOutIndiciesToChange[args];           nestedCallToUpdateTheList[...., list, ...];           newvalues = figureOutValuesToChange[args];           list[[indicies]] = newvalues        ];      where               (* here list can be third argument, or even last *)          nestedCallToUpdateTheList[...., list_, ...] :=                  While[a big loop,           list[[dynamicIndicies] = dynamicValues]];        ]      So I have a principle (open) question: how to update long lists (parts of it) in the most efficient way if such lists are passed through several layers of functional calls? Is there a way to achieve this without using HoldAll? Perhaps using more direct Hold functionality? Anyway, I would like to learn how to be in control... EDIT1: Based on the comments below, I would like to add another requirement; Assume that all this has to be done within the function. Is this possible at all? A bullet-proof way would be               updateLilst[___] := fail["please used Hold on the list argument"];     updateList[...,list_Hold,...] := do the work on the list;      Or...? EDIT2: By the way, how to test whether an argument is evaluated in the function? p.s. I tried with Hold, but it is tricky since it is not make the assignment with a Held variable...


title: How can I scale tick marks without scaling my function?

text: Take this plot for instance: ![enter image description here](http://i.stack.imgur.com/iNYGc.png) It shows power in W, but I'd like to see it in µW, so that I get 200, 400, 600,..., which is much more readable. Is there a way to do this without scaling my function and PlotRange by a factor 10$^6$? **edit** re _szabolcs_ 's comment   I already tried               Ticks -> {Automatic, Table[200 x, {x, 5}]}        but that seems to put those tick marks where they belong, namely at 200 W, 400 W, etc.(which is 240 km up the graph), not at the gridlines.


title: Evaluating Abs'[2 x] gives different results than evaluating D[Abs[2 x], x]

text: I noticed the following difference               Assuming[x ∈ Reals, FullSimplify[D[Abs[2 x], x]]]          (* 2 Sign[x] *)          Assuming[x ∈ Reals, FullSimplify[Abs'[2 x]]]          (* Sign[x] *)      While it is clear that the first line of code above returns the correct result, I wonder why the call of `Derivative` fails? A little further investigation shows that               f[x_] := Abs[2 x]      f'          (* 2 Derivative[1][Abs][#1] & *)      which is correct and implies that the difference might come from with or without `SetDelayed`. But I still do not fully understand why the second code failed.


title: how to improve efficiency when I want to classify a list according to certain laws

text: I have a function that generates lists:               f[n_] := Join @@ Permutations /@ PadLeft@IntegerPartitions[n];      For example               f[3]      > >     {{0, 0, 3}, {0, 3, 0}, {3, 0, 0}, {0, 2, 1}, {0, 1, 2}, >      {2, 0, 1}, {2, 1, 0}, {1, 0, 2}, {1, 2, 0}, {1, 1, 1}} >   `f[3]` returns 10 lists of three elements, which I want to classify this according to certain laws; `{0, 0, 3}, {0, 3, 0}` and `{3, 0, 0}` belong one class with 3 members because `RotateLeft` can transform any one of these into any of the others. Similarly, `{0,1,2}, {1,2,0}` and `{2,0,1}` belong one class with 3 members. `{0, 2, 1}, {2, 1, 0}` and `{1, 0, 2}` belong one class with 3 members. `{1, 1, 1}` belongs to a class of which it is the only member. So the result I want is ![enter image description here](http://i.stack.imgur.com/uHWOG.jpg) I have code that will generate the desired result               m = AbsoluteTime[];     f[n_Integer] := Join @@ Permutations /@ PadLeft@IntegerPartitions[n];     f2[list_] := Module[{n = 1, m = 0},       While[n <= Length[data1],         If[Or @@ (SameQ[data1[[n, 1]], #] & /@             NestList[RotateLeft, list, Length[list] - 1]), data1[[n, 2]]++;          m++; Break[]];        n++];       If[m == 0, AppendTo[data1, {list, 1}]]]     data1 = {{First@f[7], 1}};     f2 /@ Drop[f[7], 1];     Length[f[7]]     data1 // Length     AbsoluteTime[] - m      but it's too slow. When `n = 7`, it takes about 11 seconds, but I want to work with `n` is the range from 14 to 20. how can I improve efficiency the efficiency of my code?


title: How to expand terms within an integral?

text: > **Possible Duplicate:**   >  Why aren’t these additions of integrals and summations equal? I am trying to expand all the terms in a sum in order to apply assignment rules later, but can't figure out how to do it. I've tried pretty much the commands I've seen around here. I have the following integral: $$\iint(x^2+y^2) f(x,y)dxdy$$ and I would like to extend it to $$\iint x^2 f(x,y)dxdy+\iint y^2 f(x,y)dxdy$$ in order to apply rules like $\iint x^2f(x,y)dxdy \to a$ and so on. I would like to do this in a generic way since the integrand would not always look like the one in the example here. Any idea?


title: Sum rule in integration not working

text: I am new to _Mathematica_ and I just tried to play around with some integrals. But the sum rule in integration doesn't work. Here a simple example: Mathematica doesn't recognize that $\int_0^h (1-f(x)) \, dx$ and $h-\int_0^h f(x) \, dx$ are the same. With               Reduce[Integrate[1 - f[x], {x, 0, h}] == h - Integrate[f[x], {x, 0, h}]]       I just get the output of > Reduce::nsmet: This system cannot be solved with the methods available to > Reduce. >> Is that normal? If not, where is the error?


title: Print indexed (by subscript) variable name systematically

text: I have some variables : Subscript[S, 1], Subscript[S, 2]...etc. But they are defined in a for loop like `For[g = 1, g < 4, g++, Subscript[S, g] = g];` Later, I need to print each of the variable name, i.e `Subscript[S, 1], Subscript[S, 2]`...etc. But I can't find a systematic way to do this. `For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]];` doesn't work because it prints `Subscript[S, g]` always. Any idea? Just look at the code:               For[g = 1, g < 4, g++, Subscript[S, g] = g];     Print[Subscript[S, 1]]     Print[Subscript[S, 2]]     Print[Subscript[S, 3]]     For[g = 1, g < 4, g++, Print[Subscript[S, g]]];     Print[HoldForm@Subscript[S, 1]]     Print[HoldForm@Subscript[S, 2]]     Print[HoldForm@Subscript[S, 3]]     For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]];     For[g = 1, g < 4, g++, Subscript[S, g] =.];      And this is the result: ![enter image description here](http://i.stack.imgur.com/jEDSy.png)


title: Can we use letter with a subscript as a variable in Mathematica?

text: I tried                   In[1]:= Subscript[a, 0] = 1         Out[1]= 1              In[2]:= Clear[Subscript[a, 0]]         During evaluation of In[452]:= Clear::ssym: Subscript[a, 0] is not a symbol or a string. >>              In[3]:= Clear[a]              In[4]:= Subscript[a, 0]         Out[4]= 1      Any idea?


title: Clear complains that a subscripted variable is not a symbol or a string?

text: Here's a small listing where I've used `Esc``q``Esc` to typeset `θ` in the notebook:               Clear[ f, θ, Subscript[x, r] ]     Subscript[x, r] := 3     f[θ_] := Subscript[x, r] Cos[θ]          Plot[f[θ], {θ, 0, Pi}]      (in my notebook this looked like $x_r$, not `Subscript[x, r]` for example). This produces a message from `Clear` of the form:               Clear::ssym : x_r is not a symbol or a string      What is curious is that I appear to be able to assign to this variable $x_r$ without any trouble, yet it is apparently treated differently than my other symbols `f` and `θ`. How exactly does Mathematica define a symbol. Why can I use $x_r$ like a variable, yet it does not have this symbol characterization?


title: How to assign (and retrieve) variables with subscripts?

text: I like to give subscripts to my variable names when the variables are related. I.e.,               Subscript[r, i] = 3      > 3 A problem arises when I later assign `r` to a value and want to use `Subscript[r,i]` again.               r = 6      > 6               Subscript[r, i]      > Subscript[6, i] Is there any way for me to get the value I assigned to `Subscript[r,i]`? Is this the wrong way to use Mathematica?


title: How do I clear all variables with subscripts?

text: > **Possible Duplicate:**   >  Clear complains that a variable is not a symbol or a string? `Clear["Global`*"]` Works for most variables, however if i do something like $ \delta_a = \alpha_a \Delta T d $ Then the `Clear` or `ClearAll` will not clear $ \delta_a $, short of `Quit[]` is there anything that can be done to clear variables with subscripts?


title: Solve with v9 (issues with Subscript, Overscript, Superscript etc)

text: The way `Solve` works has changed in v9 ... in essence, to get the answers that one obtained under v8, one now often has to specify a lot more information about all the variables and parameters, in order to get the desired neat solution. In providing this extra detail on Input, across the board, so to speak, I have discovered that, rather unfortunately, the `Solve` function has a poor understanding of notational forms such as Subscript, Superscript, OverBar, OverHat, OverDot, OverTilde etc etc ... causing `Solve[]` to fail on even the simplest examples when such notation is used. As a quick illustration: ![solvebug](http://www.tri.org.au/SolveBug.gif) ... when, of course, Mathematica can trivially solve such examples. Two clarifications on the above:   1. The solution here is certainly _not_ to use the Notation package ... I must confess that the point of the latter has mostly escaped me, because the very beauty of using Subscript etc notation in Mathematica is to be able Thread or Map over the index etc ... essentially getting the best of both worlds: a wonderfully flexible symbolic structure, even if not strictly a Symbol. The Notation package, by contrast, does the opposite ... by symbolising the structure, all flexibility is lost.   2. Some years ago, back in the days of Mathematica 3 or 4, a very similar issue occurred with Integrate when using Subscript notation ... causing it to fail horribly when certain Subscript variables were used on Input. And there were problems with Plot when using Subscript notation too. I recall raising these issue at the time, and if I recall correctly, these issues ... which effect the way thousands of people use Mathematica on a daily basis, were rectified in subsequent revisions of mma. It would be very helpful if a similar fix was adopted for the Solve case, so that Solve was aware that Subscript[y,1] is _not_ the same as say Sin[y] ... That Subscript[y,1] notation does not denote a mathematical function of y ... but rather just denotes a typesetting function of y. Do others have thoughts as to whether this behaviour in Solve is inconsistent? Or as they expect it to be? Or different to the way other Mma functions treat Subscript notation?


title: How to Clear a symbol with subscript in Mathematica?

text: > **Possible Duplicate:**   >  Clear complains that a variable is not a symbol or a string? I want to clear $\lambda_0$ which is assigned to be $\lambda_0=1$. From the reference here, Clear complains that a variable is not a symbol or a string? This could be done by                    << Notation`                Symbolize[NotationBoxTag[\(\[Lambda] \_ 0\)]]      or possibly                     Unset[Subscript[\[Lambda], 0]]      But then when I tried to reassign a value to $\lambda_0$, I got warning "Cannot assign to raw object Subscript[[Lambda], 0]"                     Subscript[\[Lambda], 0]= 1                During evaluation of In[252]:= Set::setraw: Cannot assign to raw object Subscript[\[Lambda], 0]. >>                Out[252]= Subscript[\[Lambda], 0]      When I enter $1$, it output $\lambda_0$                     In[25]:= 1                Out[25]= Subscript[\[Lambda], 0]      No help with following commands:                      Clear[Subscript]                  RemoveSymbolize[NotationBoxTag[\(\[Lambda] \_ 0\)]]      The "DownValues[Subscript]" is empty.                         In[26]:= DownValues[Subscript]                    Out[26]= {}                        In[28]:= Subscript[\[Lambda], 0]=.                    During evaluation of In[28]:= Unset::usraw: Cannot unset raw object Subscript[\[Lambda], 0].                 >> Out[28]= $Failed      **EDIT:** Tried to avoid using the subscript in the Module, but failed with $\lambda[0]$.                        In[119]:= Module[{\[Lambda][0] = 1},\[Lambda][0]]                   During evaluation of In[119]:= Module::lvset: Local variable specification {\[Lambda][0]=1} contains \[Lambda][0]=1, which is an assignment to \[Lambda][0]; only assignments to symbols are allowed. >>                  Out[119]= Module[{\[Lambda][0] = 1}, \[Lambda][0]]`


title: Why the variable cannot use subscript?

text: Today,I use the Lagarange method to deduce the robot 's dynamic equation .I use the mma to help me calculate. I want to use $$x_B,y_B, v_{Bx}, v_{By}, v_B ^2$$ to represent the point B 's displacement ,velocity and square of velocity ,respectively . However ,the mma give the warning information " Set::Tag Plus in the …is Protected" My code               Subscript[x,B][t]=l1 Sin[theta 1[t]]+l2 Sin[theta 1[t]+ theta 2[t] ]      But when I subscribe Subscript[x,B][t] to xB[t],it goes well. So my question is how to wtite variable like the form that we calculate by hand.


title: WinBUGS Interface

text: Has anyone created on WinBUGS (Bayesian inference Using Gibbs Sampling) interface with Mathematica similar to BugsXLA for Excel? I'd like to setup the model, define the evidence in a notebook and then analyze the results of the MCMC (Markov chain Monte Carlo) runs.


title: Security of Mathematica Demonstrations

text: Apologies if this is overly paranoid. I recently discovered the Wolfram Demonstrations Project and intend to play with them to understand some of the power of Mathematica. I have one slight concern: given that Mathematica has all types of system access, what guarantees do I have about these demonstrations (i.e. that they don't maliciously modify my file system, steal ssh keys, install trojans, etc ... ) I would prefer an answer of the form: "option XYZ lets you disable all of that for specific notebooks" rather than an answer of the form "everyone loves each other and would never do that!"


title: How to compare power towers in Mathematica?

text: First I tried it directly, but it overflowed:               In[1]:= 2^3^2^3^5^8 < 3^2^2^7^6^7     During evaluation of In[1]:= General::ovfl: Overflow occurred in computation. >>     During evaluation of In[1]:= General::ovfl: Overflow occurred in computation. >>          Out[1]= Indeterminate < Indeterminate      Using double `Log` did not help either:               In[2]:= Log[Log[2]] + Log[3] 2^3^5^8 < Log[Log[3]] + Log[2] 2^7^6^7       During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >>     During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >>          Out[2]= Overflow[] < Overflow[]      Then I tried to use the `WolframAlpha` function, and it seemed to be able to handle this and even much higher towers:               In[3]:= WolframAlpha["2^3^2^3^5^8 < 3^2^2^7^6^7", "MathematicaForms"][[2, 1]]     Out[3]= True          In[4]:= WolframAlpha["2^2^5^2^7^4^9^3^7^6^9^9^9^9^3^2 < 3^3^6^3^9^4^2^3^2^2^2^2^2^3^3^3", "MathematicaForms"][[2, 1]]     Out[4]= True      But then I discovered that it failed to perform certain comparisons:               In[5]:= WolframAlpha["4^6^8^8^9 < 3^2^3^3^3", "MathematicaForms"]     Out[5]= {}      And sometimes even gave wrong answers, even in seemingly trivial cases:               In[6]:= WolframAlpha["3^3^3^3^3 < 4^4^3^3^3", "MathematicaForms"][[2, 1]]     Out[6]= False      Can anybody suggest a correct and robust method to compare two expressions given in the form `Hold[a^b^...^z]`, where `a,b,...,z` are positive integers?


title: How to separate a vector into two vectors, one having the first half of my original vector and the other having the second half

text: I have a set of `n` vectors with an even length. Let us make an easy example with 3 vectors of length=4:                a={a1,a2,a3,a4}      b={b1,b2,b3,b4}      c={c1,c2,c3,c4}      I want to create the vectors:                d1={a1,a2}      d2={a3,a4}           e1={b1,b2}      e2={b3,b4}           f1={c1,c2}      f2={c3,c4}      I suppose I have to use `GatherBy`, but I have not found the way to get what I want.


title: Plotting a graph

text: Could anyone help me with plotting the following graph?               Integrate (-Inf, Inf) (exp(-i*x*t))/((4*pi)((x-1)^2 +25)(exp(-100x) +1))      It's not a code obviously, but I don't need a code, it's simple enough. Mathematica times out when I try to pot this. Is there a way around it? Could anyone try and plot it? Further info: Plot for t = 0 to 100. And the integration is over x.


title: Is it possible to create a output cell without generating a cell tag from the input cell

text: I give a CellTag to my Input Cell, but the output cell would also inherit the CellTag. Is it possible to control not inherit the CellTag? Sometimes I need the output cell with the CellTag, but sometimes I don't need... * * * ### Application I found another method is use another tags to do the same thing. I want to select some cells with some tags, cells with "Ignore" tag will be omitted, only Input Style Cells with"Ignore1" tag will be omitted, Output Style Cells with "Ignore1" tag will be kept. for example, I select the cells without "Ignore" and "Ignore1" tags.               Select[NotebookRead@Cells[EvaluationNotebook[]],      FreeQ[#, CellTags -> "Ignore"]&&FreeQ[#, CellTags -> "Ignore1"] &]      but this omit the output cells with "Ignore1", how to include these output cells? This is my sub question, if the original question is unsolvable. * * * so the condition could be.               condition=FreeQ[#, CellTags -> "Ignore"] && (#[[2]] === "Output" &&      MemberQ[#, CellTags -> "Ignore1"]) &      * * * ### One method We've add a `CellTags->"Ignore"` in the Input cell, just add a new CellTag, the the Output cell by CellPrint will tagged by new tag `Hello` !               CellPrint@Cell["Test",CellTags->"Hello"]      ![enter image description here](http://i.stack.imgur.com/IQSib.jpg)


title: Perform FindRoots on Function Evaluation Containing RootSearch

text: I am using Ted Ersek's `RootSearch` function in Mathematica 9.0 (http://library.wolfram.com/infocenter/Demos/4482/) to create a function that I am using for graphing. Now, I'd like to use this function inside of a `FindRoot`s call to find specific solutions. To begin, we have a function `f[t_, Rb_, N2_]`:                f[t_, Rb_, N2_] =(4.22153*10^6 (45.5182 + 5.226*10^-6 N2^2 + Rb) (0.106 -                           0.106 E^(-9.43396 t) - Sin[120 \[Pi] t]/(120 \[Pi])))/N2^2      Then we define the `tsat2[Rb_, N2_]` function using Ersek's `RootSearch` function to find the `t` values where `f[t,Rb,N2] = 0.9`4 and return the minimum value.               tsat2[Rb_, N2_] := N[60*Min[t /. RootSearch[f[t, Rb, N2] - 0.94` == 0, {t, 0, 1}]]]      The above `RootSearch` function works great, it's this next step that's the trouble. We play a little trick to turn `tsat2` into a function of only `Rb` to satisfy some other conditions to obtain `tsat2[Rb,97.65*Rb]` Here's the problem: I need to find find `f[Rb,97.65*Rb]==1.5` using numerical methods. Before I go and write my own numerical solver, I'd like to see if I can get `FindRoots` to work:               FindRoots[tsat2[Rb, 97.65*Rb] - 1.5 == 0, {Rb, 10}]      However the problem is Mathematica doesn't even seem to evaluate this ambitious function call and only returns:               FindRoots[-1.5 + 60. (t /. $Failed) == 0, {Rb, 10}]      I suspect that somehow the `tsat2` function is not actually being evaluated inside the `FindRoot` statement, or more specifically, the `RootSearch` function isn't being passed the values from the higher `FindRoots` function call. I have tried this also using the `RootSearch` function (so we essentially have a nested `RootSearch`) and received the same error: > In[203]:= RootSearch[tsat2[Rb, Rb 97.65`] - 1.5` == 0, {Rb, 10}] > > Out[203]= RootSearch[-1.5 + 60. (t /. $Failed) == 0, {Rb, 10}] My question is: How do I get the `tsat2` function to act like any other function evaluation inside the `FindRoots` call? Thanks in advance!


title: Transform list of inequalities into matrix form $A\ x \leq b$

text: I have a list of linear inequalities, and I want to get it into the form $A\ x \leq b$; i.e., find the matrix $A$ and the vector $b$. Is there any function in _Mathematica_ that can that can do this?


title: Goto and Compile

text: Clear[sum];     sum = Compile[{{n0, _Integer}, {s0, _Integer}},        Block[{n = n0, s = s0},         Label["t"];         If[n > 0, s += n; n--; Goto["t"]];         s         ]        ];          sum[10, 0]      It seems that the `Label` is not found. How to make it works?


title: ReadList importing negative times

text: This is probably an easy question to answer, but I need a fresh eye... I'm struggling with processing the following file (extract shown here) It's a list of dates, and positive/negative time durations formatted using "m" and "s".               Apr-09 -1m 47s     Apr-11 -1m 15s     Apr-12 -0m 59s     Apr-13 -0m 44s     Apr-14 -0m 28s     Apr-15 -0m 13s     Apr-16 0m 1s     Apr-17 0m 15s     Apr-18 0m 29s     Apr-19 0m 42s     Apr-20 0m 55s     Apr-21 1m 8s      I'm reading the file in OK:               d = ReadList["/tmp/data.txt",        {Word, Number, Character, Number, Character}];      and assembling the pieces using this:               d /. {s_String, m_Integer, _, n_Integer, _} :> {s,         N@If[m >= 0, (60 m + n)/60, (60 m - n)/60]}        which appears to work:               {"Apr-09", -1.78333},      {"Apr-11", -1.25},     {"Apr-12", 0.983333},      {"Apr-13", 0.733333},      {"Apr-14", 0.466667},      {"Apr-15", 0.216667},       {"Apr-16", 0.0166667},      {"Apr-17", 0.25},      {"Apr-18", 0.483333},       {"Apr-19", 0.7},      {"Apr-20", 0.916667},      {"Apr-21", 1.13333}      but then I noticed that the 0s lost their signs on import, so the conversion is inaccurate:               d      > >     {{"Apr-09", -1, "m", 47, "s"}, >      {"Apr-11", -1, "m", 15, "s"}, >      {"Apr-12", 0, "m", 59, "s"}, >      {"Apr-13", 0, "m", 44, "s"}, >      {"Apr-14", 0, "m", 28, "s"}, >      {"Apr-15", 0, "m", 13, "s"}, >      {"Apr-16", 0, "m", 1, "s"}, >      {"Apr-17", 0, "m", 15, "s"}, >      {"Apr-18", 0, "m", 29, "s"}, >      {"Apr-19", 0, "m", 42, "s"}, >      {"Apr-20", 0, "m", 55, "s"}, >      {"Apr-21", 1, "m", 8, "s"}} >   ![plot](http://i.stack.imgur.com/8Oq0a.png) The problem is that `ReadList`'s `Number` reads "-0" as "0". Is there a better way of reading in data like this? I tried using `Sign` but unfortunately `Sign[-0]` gives 0... :)


title: How to make a code line dynamic in a Module?

text: The code line               If[StreamPosition>0,Read[str,Record]]        should be executed in a Module at first.   The Module consists of a Slider and a Pane.   The Slider positions a StreamPosition in file.   The Module then reads a chunk of records from that file.   The external file is a txt file with variable length string records. The Slider value for the ReadList is just a rough position.   For it is in lack of the knowledge of well defined record start positions.   The unwanted result:   ![enter image description here](http://i.stack.imgur.com/RhBT1.jpg) Therefore the Module has to adjust in a first step to the begin of a   record with Read[str,Record]. The first record displayed in Pane   will be the complete one. Should give this result: ![enter image description here](http://i.stack.imgur.com/Mw539.jpg) Note: The files start position - it's 1. record - is aligned and   does not need that correction. ![enter image description here](http://i.stack.imgur.com/cf1WX.jpg) Where to integrate it and how to bring to life the Read[] in this Module?               infil = "F:\\LargeDataSet\\Entwicklung\\Daten Beispiele\\test 1M \     semicolon key.txt";     panerows = 200;     str = OpenRead[infil, BinaryFormat -> True];     filebytes = FileByteCount[infil];     recbytes = Round[filebytes/anzrecs - 2];     erst = 1;     n1 = (erst - 1)*recbytes;            Module[{},      Column[       {Dynamic[SetStreamPosition[str, n1]],        Slider[Dynamic[n1], {0, maxbyte, recbytes}, ImageSize -> 400,          Appearance -> Small],        Pane[Column /@ Dynamic[ReadList[str, Record, 200 + n1 - n1]],         ImageSize -> {400, 200}, Scrollbars -> True]}       ]      ]


title: How to draw a 3D convex hull of a set of points with styling

text: I´m trying to obtain the convex hull (with transparent faces) of a small number of points. I would like the Plot to have   * the points shown with small spheres   * numbers 1, 2, 3, ... along the axes  Here is what I have tried.               p = {{2, 1, 6}, {4, 3, 0}, {5, 2, 5}, {3, 5, 4}}     ListPointPlot3D[p, PlotStyle -> {Red, "Sphere", Large},        PlotRange -> {{0, 6}, {0, 6}, {0, 6}}, AxesLabel -> Automatic]      Could you help me.


title: Why is NHoldFirst not propagated to symbolic derivatives?

text: I encountered a nasty problem that `N` cannot evaluate expressions containing a symbolic `Derivative` of a multi-parameter function expecting an exact integer as its first argument.               Attributes[StieltjesGamma]     (*        {Listable, NHoldFirst, Protected, ReadProtected}      *)          d = Derivative[0, 1][StieltjesGamma][1, 1]     (*        Derivative[0, 1][StieltjesGamma][1, 1]     *)          N[d, 10]     (*        StieltjesGamma::intnm: Non-negative machine-sized integer expected at position 1        in StieltjesGamma[1.000000000,1.000000000]. >>       Derivative[0, 1][StieltjesGamma][1.000000000, 1.000000000]     *)          The first argument of `StieltjesGamma` only makes sense when it is an integer, and `NHoldFirst` is supposed to take care of this when approximate numeric calculations are performed. But in this case it goes unnoticed by `N` that results in a meaningless expression and an error message. This also blocks some symbolic simplifications that internally rely on arbitrary-precision numeric calculations:               FullSimplify[d > 0]     (*        Derivative[0, 1][StieltjesGamma][1, 1] > 0     *)          FullSimplify[Floor[d]]     (*        Floor[Derivative[0, 1][StieltjesGamma][1, 1]]     *)      There is a workaround: apply `N` directly to the second argument:               MapAt[N[#, 10] &, d, 2]     (*        0.70738627     *)      but, of course, it becomes cumbersome when a derivative occurs deeply nested in a more complex expression. I understand that `NHoldFirst` is formally attached to the symbol `StieltjesGamma` itself, not to a non-symbol head `Derivative[0, 1][StieltjesGamma]`. But the behavior resulting from this seems wrong. Should it be considered as a bug that needs to be reported to _Mathematica_ Tech Support, or there is a valid reason why `NHoldFirst` should not be propagated to derivatives? Do you know any simpler workarounds for this problem?


title: Examine function parameters programmatically

text: I write a lot of scripts in Mathematica and I'd like to eliminate the boilerplate that parses command-line arguments and assigns them to variables of the correct type before doing the real work. I was thinking of accomplishing the following way.   1. Find a function called `main`.   2. Look at the list of its parameters `[a_Integer, b_Real, c_String]`.   3. Attempt to convert the elements of $ScriptCommandLine into those parameters.   4. Call main with those parameters. This way, each script can simply contain a function main that will be called with the appropriate parameters from a bootstrap script. I'm trying to figure out how to accomplish #2. I've been trying to use `Definition`, but I can't figure out how to parse the output. Is there a better way?


title: Question about inequality plot

text: I fed this inequality into _Wolfram/Alpha:_ `Mod[-1 + 2^(1 - IntegerExponent[2 + 2 x, 2]) 3^ IntegerExponent[2 + 2 x, 2] (1 + x), 1 + 2 x] < 1 + 2 x`, and got this plot:   ![enter image description here](http://i.stack.imgur.com/DSPwk.png)   The uploads didn't format properly, so I just have the image. I copied the function for the plot and got: `Plot[{Mod[-1 + 2^(1 - IntegerExponent[2 + 2 x, 2]) 3^ IntegerExponent[2 + 2 x, 2] (1 + x), 1 + 2 x], 1 + 2 x}, {x, -5.01, 5.01}]` This doesn't work. So I have some questions: Q1) How can I get _Mathematica 9_ to replicate the plot? Q2) How can I determine the x-,y-axis ratio? (It looks like 1:2, but I want to be sure.) Q3) If 1:2 is the case, what is there about the formula that would indicate that this is a good ratio?


title: Setting a Row from a Matrix as Variable

text: I'm not advanced in _Mathematica_ but I'm trying to get better. I have a big set of `Data` and I want to `Plot` the first row against the other ones. I tried to set the `Rows` into a list and run a "do loop" over all `Rows`. My Code :               ClearAll["Global`*"]     Data = Import["file", "Table"];     Time = Table[1/60 i, {i, 0, 1430}];     Rows[k_] = Do[List[Transpose[{Time, Data[[All, k]]}]], {k, 1, 16}]     Toplot = Do[Transpose[{Time, Rows[k]}], {k, 1, 16}];     ListPlot[{Toplot}];      I would be grateful for some help and tips.


title: Why does this integral have a complex result

text: I wanted to find the normalization of distribution F2 .               p = 2.2849;     p1 = 0.938/3;     p2 = 0.938/3;     p3 = 1.6;               F2 = Integrate[(s - s0)*(s + 2^2)^-2/(p^2 - s)^2, {s, s0, Infinity}]/. s0 -> (p1^2/(1 - x2 - x3) + p2^2/x2 + p3^2/x3)          nfactor = NIntegrate[F2, {x2, 0, 1}, {x3, 0, 1}];      why is Mathematica producing complex result? while the result have to be real


title: Exiting FindMinimum when a condition is met

text: I want to determine if a function `f[x]` can take negative values. `f` is expensive to compute and `x` may be high-dimensional. I thought to use `FindMinimum` to minimize with respect to `x`. If the minimum is positive I have an answer. But I do not want to proceed with the costly minimization if, en route, an evaluation of `f` produces a negative value. I want to return to the calling program with the information: > `f` can achieve a negative value. How could I do this?


title: Invert 3D objects (shape) to 3D patterns objects (shape)?

text: Is it possible to invert the 3D object (positive model) to 3D pattern objects (negative model) (for example, patterns for casting). For example (positive model):               SphericalPlot3D [1 + 2 Cos [2 \ [Theta]], {\ [Theta], 0, Pi}, {\ [Phi], 0, 2 Pi}]       How to make the pattern object (negative model)?


title: How can I test properties of a symbol without unwanted evaluation

text: ## Problem How to get the **head** , **size** , **dimensions** , etc. of a symbol without evaluating it? Since _Mathematica_ does not allocate fix storage space and type to symbols it is not trivial to query runtime properties of variables. The problem is that one cannot measure e.g. size without evaluating _at least_ a little, though in _Mathematica_ , evaluation could cause all kinds of problems. In certain cases, extra evaluation during query could cause the **loss of the original data** , other **unwanted side effects** or even **hangup** in extreme cases where evaluating the expression is computationally expensive. Let's assume that we are only interested in `OwnValues` and only in accessing the bytesize of the expression. Imagine you want to check your memory to see what is the size of actual symbol values (like Workspace does in Matlab). For lots of symbols, huge values and non-static expressions a complete scan could easily choke your machine. ## Method 1: Sandbox One possible way is to evaluate the expression in a safe environment that does not allow memory leaks. For example, in a local kernel without the possibility of changing state of the original kernel. This has at least three limitations: unnecessary copying of expressions from kernel to sandbox, inconsistency (might yield different results) and the fact that computationally expensive calculations would still be performed. ## Method 2: Evaluate only immutable expressions Another method is to limit size-queries to already calculated, immutable expressions only, leaving those that can potentially cause side effects untouched. This method would be safe in the sense that it would not try to re- evaluate huge expressions that are not static (being set with e.g. `SetDelayed`). Though it would require a test whether `OwnValues` of a symbol would further transform if evaluated or not. As a matter of fact, immutability is not even a necessity: we could measure size for symbols which are:   1. **consistent** : evaluate to the same result;   2. **contained** : without any side effects;   3. **cheap** : possibly without expensive computation. For example, `f:=1+1` could be evaluated to measure size as it is cheap, does not have side effects and does not change the previous value of `f`. But `f:=(x++;RandomReal[])` should not be evaluated for measurement as it has a side effect changing the global state and it would erase any previous value of `f`. ## Simple problem case Evaluating the following two definitions we assign values to `e` and `f`:               e = {1};     f := {Print[0]; 1}     {e == f, e === f}    (* ==> {True, True} *)      It seems that `f` is numerically and structurally identical to `e`, thus having **actual value** `{1}` but it also has the **own value** `{Print[0]; 1}`. How can one measure the memory-requirement of the actual value of `f` without triggering the re-evaluation of `OwnValue`s? A more problematic case is the following:               g := Table[1, {RandomInteger@100000}]     {ByteCount@g, ByteCount@OwnValues@g} (*  ==>  {287984, 336} *)      Clearly, `g` has a certain actual value with a certain size (probably it's different on your machine) that has not much to do with the actual size of its `OwnValues`. Now any such `ByteCount` call would of course re-evaluate `g` which is to be avoided as it might involve unwanted side-effects. The problem with Method 2 is that there is no safe way (at least that I know of) which could test whether an expression is **immutable** (assuming it is more complex than an atom; Mr.Wizard offered a `step` function, but I failed to apply it to this case), **consistent** , has **no side effects** and is **cheap** to evaluate. `OwnValues` unfortunately does not store _how_ a symbol was set (using `Set` or `SetDelayed`) thus one cannot easily exclude symbols that are unsafe to re-evaluate. ## Questions How to measure the bytesize of the value of a "nonstatic" symbol (`g`) that should not be re-evaluated? Is there a method to ascertain whether an expression can be safely evaluated? Is there a method to safely check whether an expression is immutable? Is there a method to safely check whether an expression is consistent, has no side effects and is cheap to evaluate? I found the following posts extremely useful:   * Implementing a safe ValueQ that does not evaluate its argument and Chat about custom valueQ between Mr.Wizard & Leonid The discussion and the post made it clear that there should be at least two approaches to define a sensible new `valueQ`: one to check if there is any value defined for a symbol and the other to check if it will be transformed or not during evaluation. I am certainly interested in the second approach.   * How can I test properties of a symbol from the string name without the symbol completely evaluating It is related, but it stops at the property of whether a symbol has a value or not.


title: Symbolic solution(s) to generalized Heat equation

text: # Symbolic solution(s) to Heat equation? **or more generally,(eventually) Green functions to known PDEs** I am interested in variations of the heat equation: ![Mathematica graphics](http://i.stack.imgur.com/z9UMw.png) or more generally ![Mathematica graphics](http://i.stack.imgur.com/Yp5IY.png) or even more generally (`r` a vector and `Δ(r)` a tensor) ![Mathematica graphics](http://i.stack.imgur.com/15BI6.png) I understand that Mathematica cannot provide a symbolic solution:               DSolve[{eqn =         D[p[x, t], t] == Δ D[p[x, t], x, x],        p[x, 0] == g[x]}, p, {x, t}]      ![Mathematica graphics](http://i.stack.imgur.com/SEDqF.png) > What I do not understand is why not? Indeed I can define a possible solution (wikipedia) as               sol = p -> Function[{x, t}, Exp[-x^2/4/t/Δ]/Sqrt[4 Pi Δ t]];      and check that it satisfies the PDE               eqn /. sol // FullSimplify          (* ==> True *)      I can even build a larger class of solution which satisfy the boundary at t=0               sol2 = p -> Function[{x, t},        Integrate[ g[y] Exp[-(x - y)^2/4/t/Δ]/Sqrt[4 Pi Δ t], {y, -Infinity, Infinity}]];      Which seems to satisfy the PDE as well, (though I don't really understand why it fails to conclude it does!)               eqn2 = eqn /. sol2 // FullSimplify      ![Mathematica graphics](http://i.stack.imgur.com/I9ekW.png) Indeed we can check by taking the limit at t-> 0 which would replace the Gaussian by a Dirac:               p[x, t] /. sol2 /. Exp[-(x - y)^2/4/t/Δ] -> DiracDelta[x - y] Sqrt[4 Pi Δ t]          (* ==> g(x) *)      **Question** Could you please explain to me why no attempt is being made (by WRI or by us) along these lines? I understand that my particular solution corresponds to a specific boundary condition, and that it might be difficult to cover all cases, but it remains surprising that this class of PDE is ignored by mathematica (e.g. those known solutions)? May be as a community we could build up a package which addresses this issue? I truly would like to know if (i) is there indeed no general solution (ii) there is something fundamentally wrong in collecting tools providing useful (if not fully general) classes of solutions. (iii) is there something I miss which would prevent success? > Eventually, it would be great to have a Mathematica function which say would > act as a lookup table and work as follow: GreenFunction[PDE,BCs] would > return the corresponding Green function if it is known in the literature.


title: How to convert \[Formal...] symbols to standard ones in an expression?

text: Mathematica generates an expression sometimes using `\\[Formal]` symbols. This is causing a problem with the `TeXForm` code generated as Latex is not able to process it. **To clarify** The generated `TeXForm` should not include `unicode`. The problem is that these are causing problem. So the solution should be such that, the result of applying `TeXForm` to the expression, should not produce unicode. Is there a way to make these expressions use normal symbols (normal `x` and `y`) so that I can generate Latex code from them that will work in my latex document                f = DifferentialRoot[Function[{y, x}, {y''[x] + y[x] == 0, y[0] == 0, y'[0] == 1}]]      ![Mathematica graphics](http://i.stack.imgur.com/X3YrK.png) If I do `TeXForm[f]` on the above, the latex code generated is not valid with texlive. I just need the expression `f` not to contain those dots above and below the symbols. Just normal symbols. One way is to use               f = DifferentialRoot[Function[{y, x}, {y''[x] + y[x] == 0, y[0] == 0, y'[0] == 1}]] // OutputForm      ![Mathematica graphics](http://i.stack.imgur.com/OY6bk.png) which Latex can handle after `TeXForm` is applied to the above. But it will be nice to have `x` and `y` there instead.


title: Add rational linear expressions

text: I want to set work for my 17 year old calculus students and have access to Mathematica 7. I aim to create a worksheet with rational expressions which they will then decompose into partial fractions. The structure I want to use will rely on some partial fractions appearing on more than one question (i.e. some overlap) So I want to speed the process of adding rational fractions...               1/(2x+7)- 3/(2x-7)      which I was hoping I could resolve in Mathematica into `(-26 - 7 x)/(14 + 11 x + 2 x^2)` without brackets in numerator or denominator. But alas I have work to do in every case, albeit fairly trivial. Instead, using `Together[ ... ]` it yields `(-26 - 7 x)/((2 + x) (7 + 2 x))` `ExpandAll[%]` just splits it up again, though it (horribly) multiplies the brackets in the denominators into `14 + 11 x + 2 x^2`. Surely I can add two or more rational expressions into a fully expanded rational expression in decreasing powers of `x`?


title: Compiling 64bit MathLink code under cygwin on Windows 7

text: I am aware that building MathLink executables is not without its challenges. However, I am trying to compile the MathLink example 'addtwo' from a makefile within cygwin on a 64 bit Windows 7 machine. I'm using cycgwin as I already have a substantial codebase built in this environment, and I have tried the following compilers:   1. The default gcc compiler. This would not compile, as the -mno-cygwin flag has been removed.   2. i686-w64-mingw32-gcc. This compiles but generates undefined references for the MathLink functions.   3. x86_64-w64-mingw32-gcc. This appears to compile and link correctly. In all three cases the command line flags to the compiler are the same for compile and link:               ${CC} -c -mno-cygwin -mwin32 -I${INCS} $<     ${CC} -I${INCS} addtwo.o addtwotm.o -L${LIBS} -lML64i3m -mwindows -o $@      Although the third configuration compiles and links, it won't run correctly. When the prebuilt addtwo.exe is run from the command line, it puts up a dialogue box requesting the link parameters as expected. Mine will very briefly put up a dialogue box that is minimised, and then exit. Unfortunately gdb does not recognise the file format of the executable built with x86_64-w64-mingw32-gcc. Any insights will reduce hair loss, and I can supply whatever additional information is relevant.


title: Is there a way to check whether two notebooks share the same variables?

text: When I code in Mathematica, I often re-use code from old notebooks which fulfilled a specific purpose; for example, one testing for soft matches in strings, or one that identifies outliers on a graph and their index in the list. My code is generally written in a modular fashion using functions, such that I am able to immediately apply the function in my old code to the new data that I have. The trouble with re-using code is that the function names I use in the old code and in the current code that I am processing sometimes overlaps. This most commonly happens with short function names such as `f` within the main function, or function names such as `g` which could double as a physical constant `g=9.81 ms-2`. To avoid this, I try my best to code properly and give my functions names that are unlikely to be re-used. However, I'm wondering whether there's a way to list all the functions/variables used in two separate notebooks and perhaps check the list of functions/variables for those used in both notebooks. These overlaps could then be resolved automatically (perhaps by appending a `notebook1` and `notebook2` at the end of those functions/variables), or, more elegantly in my opinion, by allowing the user to choose the option of replacing all the duplicates in one notebook by another name. In this similar question, separating variables between multiple notebooks is discussed, but this wouldn't really work in my situation since I actually want both codes to run in the same environment. I'm sure that the answers to this question would really help those who are engaged in large coding projects and attempting to re-use old code.


title: Is there a relatively easy way to add the "Cone of Influence" to a waveletscalogram?

text: I am analyzing time series data using the `ContinousWaveletTransform` function and plotting the results with `WaveletScalogram`. I would like to plot the cone of influence on top of the `WaveletScalogram` plot. Is there a relatively simple and general way to calculate and plot the cone of influence? (note - using the default `MexicanHatWavelet`)


title: Compiling ColorFunction for faster complex phase-amplitude plots

text: I have gotten into the habit of plotting complex-valued functions on a plane using a color-function along the lines of               Function[{z}, Hue[Arg[z]/(2 π), 1, Abs[z]]].      For example, the following code generates an interesting image of the sum of 5 spherical wave sources (without 1/r decay included):               i = 130;     ω = 2.0 π i/50;     n = 5;     L1 = 3.0 - δ/2;     L2 = 4.0 - δ/2;     δ = 0.01;     f = Compile[{{x, _Real}, {y, _Real}},      Evaluate[Sum[Exp[ω I Sqrt[(x - 1.0 Cos[θ])^2 + (y -            1.0 Sin[θ])^2]], {θ, 2 π/n, 2 π,        2 π/n}]]];     ArrayPlot[      Table[f[x, y], {x, -L1, L1, δ}, {y, -L2, L2, δ}],       Frame -> False,       ColorFunction -> Function[{z}, Hue[Arg[z]/(2 π), 1, Abs[z/2]]],       ColorFunctionScaling -> False, PixelConstrained -> {1, 1}]      ![enter image description here](http://i.stack.imgur.com/xexdO.png) I have two questions. The second is a little more important than the first.   1. Exchanging `ArrayPlot` with `ListDensityPlot` in the above example either simply yields a blank image or flat-out crashes my MathKernel. I believe this is because `ListDensityPlot` sees the complex-valued array, freaks out because they're not real, and spits out a blank plot even though it has a user-supplied color-function for handling the complex entries of the array. Is there any way of getting `ListDensityPlot` to properly use this color-function?   2. The example I gave above is pretty slow. The construction of the array alone takes 1.26 seconds on my machine, whereas the displaying of the code cited above takes 10.27 seconds (it's just an 800 by 600 pixel plot). Replacing the phase-amplitude `ColorFunction` I used above with the built-in function `GrayLevel` (and applying `Abs` to the array) gives a timing of 2.43 seconds, and using the default `ArrayPlot` scheme by removing the references to `ColorFunction` altogether executes in 1.52 seconds. Subtracting the time to build the array itself, the phase-amplitude color function generates a plot in 9.01 seconds, `GrayLevel` executes in 1.17 seconds, and the default scheme executes in 0.26 seconds. I am attempting to generate a movie, and 10 seconds to generate each frame is a bit on the slow side. Is there a way to compile this color function to make it run as fast as default, or perhaps as fast as `GrayLevel`? For reference purposes, I am running on a 2008 Penryn Dual-Core MacBook and _Mathematica_ 9.0.


title: How to dynamically update Locator[] constraints?

text: I need to visualize Menelaus' theorem for a triangle with moving locators for each of six points. So the vertexes of the triangle can move in any possible way, and the three points on the sides of the triangle can not - they should be fixed on the side. I've tried manipulating stuff, but I cant merge the `Manipulate` with               Locator[Dynamic[pa1, (pa1 = ToTheLine[#, pb, pc]) &]]      So I've come to this:               ToTheLine[p_, lb_, le_] :=       {         p[[1]],          If[le[[1]] == lb[[1]],           p[[2]],           lb[[2]] - (lb[[1]] - p[[1]])*(le[[2]] - lb[[2]])/(le[[1]] - lb[[1]])]       }          DynamicModule[{       pa = {-5, 0}, pb = {5, 0}, pc = {0, 10},       pa1 = (pb + pc)/2, pb1 = (pa + pc)/2, pc1 = (pb + pa)/2},       (* point pa1 is labeled as D and is on side BC of the triangle,           similar definition for the others *)       Graphics[{           Locator[Dynamic[pa]], (* point A *)           Locator[Dynamic[pb]], (* point B *)           Locator[Dynamic[pc]], (* point C *)           Locator[Dynamic[pa1, (pa1 = ToTheLine [#, pb, pc]) &]],           Locator[Dynamic[pb1, (pb1 = ToTheLine [#, pc, pa]) &]],           Locator[Dynamic[pc1, (pc1 = ToTheLine [#, pb, pa]) &]],           Text[Style["A", 20, "Label"], Dynamic[pa + {0, 1}]],           Text[Style["B", 20, "Label"], Dynamic[pb + {0, 1}]],           Text[Style["C", 20, "Label"], Dynamic[pc + {0, 1}]],           Text[Style["D", 10, "Label"], Dynamic[pa1 + {0, 1}]],           Text[Style["E", 10, "Label"], Dynamic[pb1 + {0, 1}]],           Text[Style["F", 10, "Label"], Dynamic[pc1 + {0, 1}]],           Thick, Red,            Line [{Dynamic[pa], Dynamic[pb], Dynamic[pc], Dynamic[pa]}],           Thin, Black,           Line [{Dynamic[pa], Dynamic[pc1]}],           Line [{Dynamic[pb], Dynamic[pa1]}],           Line [{Dynamic[pc], Dynamic[pb1]}],           Line [{Dynamic[pa1], Dynamic[pb1]}],           Line [{Dynamic[pb1], Dynamic[pc1]}]},         PlotRange -> 20.         Axes -> True.         ImageSize -> 600]]      The function `ToTheLine` just gets locator coords and puts the points on a line defined by two other points. When I drag a point on the side and then drag vertex, the point doesnt stay on side anymore. I tried `Locator[Dynamic[pc1, (pc1 = ToTheLine [#, Dynamic[pb], Dynamic[pa]]) &]]`, which uses correct coords for A and B, but there is some error there. How can I solve this problem? Is there a far more elegant solution?


title: A command for outputting a list of parameter values in a Manipulate interface

text: I am looking for a command that will output a list of values that correspond to the current parameter values manually set on a particular `Manipulate` interface. For example, lets say I create an interactive interface using this code:                Manipulate[      Plot[      A*Sin[f*t + p],      {t, 0, 2 Pi},      PlotRange -> {{0, 2 Pi}, {-1, 1}}],      {A, 0, 1}, {f, 1, 10}, {p, 0, 2 Pi}]      Then suppose I use the `Manipulate` interface to set the parameters to some values I like as in the instance shown in the this screen cap: ![enter image description here](http://i.stack.imgur.com/CSetr.png) What I would like to do now is input some command that will output these parameter values that the interface is currently set to (in this case, A = .5, f = 6, p = 1.4). Ideally, I would like a `List` in a new cell of the form               {0.5, 6, 1.4}      Perhaps some kind of `Dynamic` automatic updating feature would be nice too. This will allow me to continue being lazy and not have to enter these values individually when I refer to them in later code. Thanks to anyone who helps!


title: Reference request for logic programming in Mathematica

text: I'm learning _Mathematica_ (v8) to use it to program formal logic. Can anyone recommend a logic-specific tutorial text? A reference list of logic-related functions would also be very appreciated!


title: correct usage of ParallelTable

text: I am trying to parallelize my script. Here is a MWE of how I have done it:               LaunchKernels[2];          container = {};     SetSharedVariable[container];          fun[x_] := 2*x;     container = ParallelTable[{i, fun[i]}, {i, 1, 3}];      I am unsure if this is done correctly. There are mainly two things I am concerned about when using `ParallelTable`:   1. Is it necessary to parallelize the expression to be looped, i.e. `fun`?   2. Is it necessary to make the `container` with the `ParallelTable`-results a shared variable?


title: GridLines in LogPlot or LogLogPlot

text: Suppose I have a plot like               LogLogPlot[2 x^5/3, {x,0.1,10}, GridLines->Automatic]      How can I achieve to get "custom" gridlines to reduce the number of horizontal lines?   I know how to do it with linear scaled plot. # Edit For linear scale I do basicly:               myGrid[{xmin,xmax,xstep}, {ymin,ymax,ystep}]:=     GridLines->{{#&,/@Range[xmin,xmax,xstep},{#&/@Range[ymin,ymax,ystep])}


title: Inverse Z Transform returning complicated expression

text: I want to study how the Z transform changes with the sampling rate T, in a closed loop system. The command I'm using to do this is:               InverseZTransform[(-1 - T + z + E^T (1 + (-1 + T) z))/                       (-T +  E^T (1 + (-2 + T) z + z^2)), z, n]      However, it takes a while to do so, and the result that appears is insanely huge and impractical. For substitutions of T = 1, T = 0, etc, the inverse transform is very very easily found. I was wondering if someone could give any suggestions as to whats going on, because I really don't want to have to solve it by hand. Also, for some reason, Apart[ y[z] , z] Also doesn't work. (y[z] is the function to invert).


title: Interpolation: Unstructured grid error

text: If I try to make a table `SimpleTable` and to interpolate a function of two variables, I encounter a problem. For example:               SimpleTable = Table[{j, i, 2 i - 3 j}, {j, 0, 5}, {i, -5, 5}];      and interpolation:               f := Interpolation[SimpleTable]      and if I try:               f[1, 2]      I get the error messages: > Interpolation::udeg: Interpolation on unstructured grids is currently only > supported for InterpolationOrder->1 or InterpolationOrder->All. Order will > be reduced to 1. >> > > Interpolation::inder: The order-2 derivative of {0,-2,-4} is not a tensor of > rank 2 with dimensions 3. >>*) To me the table `SimpleTable` seems to have a "rectangular domain". What is wrong here? How to tackle this problem, to get an interpolated function from the table? Does the domain have to be changed? Although the unstructured grids have already been mentioned here, I was hoping that somebody could make clear how to interpolate a function from 3-D data, without the unstructured grid warning.


title: trying to speed up sequential use of NDSolve for large system of ODEs

text: I don't have a basic example just yet but I'll describe the problem for now. I have a large system (>100) of coupled first order ODEs. Where the output from one solution becomes the ICs for the next NDSolve. In each case the equations are the same except various coefficients get updated according to a pre-existing list. I then solve this sequence 1000 times or so. What are some tricks I can try to speed this process up? Can I do something with Compile perhaps? Any suggestions would be hugely appreciated.


title: Sublist inside simple list

text: I have a doubt to confirm. Let there is a list                 f = {{l}, {c}, {d}, {e}, {1, 2, 3}, {3, 4, 5}}      And I expect it to be traversed as a normal list which I can do by,               Table[f[[i, k]], {i, Length[f]}, {k, Length[f[[i]]]}]      But if the list is               a = {b, c, d, e, {1, 2, 3}, {3, 4, 5}}      Than I get the following output                  {{}, {}, {}, {}, {1, 2, 3}, {3, 4, 5}}      Is it must that there shall be list of sublists and no single element can be kept without sublist or I am accessing it wrong way. Doesn't Mathematica automatically consider it to be sublist for obvious reason.


title: Solving an ODE numerically

text: I really appreciate it if anyone helps me with this: How can I solve this ODE and plot the answer for $x$ on $[0.6,5]$: $$ \begin{align*} -2xy'[x] = y''[x]+ 47.21 (-.0025 x^6 & + 0.0614 x^5- 0.6087 x^4+ 3.048 x^3-8.0588 x^2 \\ & + 10.586 x - 3.9582)^2\operatorname{Erfc}[x] \end{align*} $$ With the following boundary conditions: $y[0.6]=0$ and $y[\infty]=0$ I used `NDsolve`, but its answer was: > Cannot find starting value for the variable y'[x] * * * Original source of the equation:               -2xy'[x] = y''[x] + 47.21 (-.0025 x^6 + 0.0614 x^5 - 0.6087 x^4 + 3.048 x^3                               - 8.0588 x^2 + 10.586 x - 3.9582)^2 Erfc[x]


title: Make several separate Manipulate controls on a single line?

text: How do I make several different `Manipulate` controls appear on a single line? I currently have both a `Slider` and an `Animator` controlling different variables and they appear one underneath the other. Is there a way to make them appear on the same line? I've read this question, but that deals with control elements of a single variable. How do I do the same for the different control elements of two or more variables?! ![Two variable controls appearing on different lines](http://i.stack.imgur.com/nU73u.png)


title: Alternate parameterization of a line

text: There are several ways to specify a line. In Mathematica's graphics, it is done by specifying two points and then connecting the points with the `Line` command. But it is sometimes desirable to parameterize a line, and the most familiar way is the form $y = m x + b$ where $m$ is the slope and $b$ is the offset. This parameterization is particularly awkward for near-vertical lines (where the slope becomes near infinite and numerically sensitive). An alternative is the $(\rho, \theta)$ parameterization which specifies the line as an angle $\theta$ and a distance $\rho$ from the origin, as shown in the theory section of this wikipedia article. The gist is that the line consists of all points $x$ and $y$ for which $\rho = x \cos(\theta) + y \sin(\theta)$, essentially a conversion to polar coordinates. Here is a function which takes a pair of points `{p1, p2}` as input in the form `{{x1,y1},{x2,y2}}` and outputs the corresponding $\rho$ and $\theta$:               linePolar[{p1_, p2_}] := Module[{},         {rx, ry} = Rationalize[p1]; {sx, sy} = Rationalize[p2];         sol = Solve[{rx Cos[t] + ry Sin[t] == rho,                   sx Cos[t] + sy Sin[t] == rho}, {rho, t}] // N;         First[Select[{rho, t} //. sol //. C[1] -> 0, #[[1]] >= 0 &]]];      For example:               linePolar[{{0, -1}, {-1, 0}}]     {0.707107, -2.35619}      which shows that the line connecting the two points is `Sqrt[2]/2` away from the origin at an angle of -135 degrees. The almost vertical line               linePolar[{{1, -1}, {1.1, 1}}]     {1.04869, -0.0499584}      has slope near zero, and the answer appears to be nicely behaved numerically as the line crosses vertical. I have two questions. First, it bothers me that the function is essentially re-solving the system of equations each time it is called, and this must be inefficient. Is there a nice way to make it only do the solution once? Second, I would like to have an "inverse" for this function -- something that would take a pair of $(\rho, \theta)$ values and allow it to be plotted. This would be useful because many subsequent calculations need to occur in the $(\rho, \theta)$ space, and it would be good to be able to visualize this by plotting.


title: Pattern match with Table for matrix dimension check

text: In Mathematica, often an expression involving matrices will encounter dimension mismatch errors, like we are multiplying a 3x2 matrix to a 3x4 matrix. Below we define a new symbol Dim, which can be passed through your algorithm as a fake parameter to detect errors.               Dim /: Dot[Dim[{x_, y_}], z_] /;        MatrixQ[z] :=       (checkEq[y, Dimensions[z][[1]]];        Dim[{x, Dimensions[z][[2]]}]);      This method can handle most matrix operations, but failed on Table, which seems quite special. In fact, I failed to pattern match with Table by writing:               Dim /: Times[Dim[{x_, y_}], Table[z_]] := Dim[x, y];(*incorrect, just for syntax*)     Dim /: Times[Table[z_], Dim[{x_, y_}]] := Dim[x, y];      The expected result should be:               Dim[{3, 2}] Table[Sin[i + j], {i, 3}, {j, 2}] == Dim[{3, 2}]      But now Dim is multiplied over every element of table and it returns:               {{Dim[{3, 2}] Sin[2], Dim[{3, 2}] Sin[3]}, {Dim[{3, 2}] Sin[3], Dim[{3, 2}] Sin[4]}, {Dim[{3, 2}] Sin[4], Dim[{3, 2}] Sin[5]}} == Dim[{3, 2}]      Full code:               Clear[Dim];     checkEq =       Function[{x, y},        If[x != y, Print[ToString[x] <> "!=" <> ToString[y]]; Abort[]]];     Dim /: Dimensions[Dim[x_]] := x;     Dim /: MatrixQ[Dim[_]] := True;     Dim /: Dot[Dim[{x_, y_}], z_] /;        MatrixQ[z] :=       (checkEq[y, Dimensions[z][[1]]];        Dim[{x, Dimensions[z][[2]]}]);     Dim /: Dot[z_, Dim[{x_, y_}]] /;        MatrixQ[z] :=       (checkEq[Dimensions[z][[2]], x];        Dim[{Dimensions[z][[1]], y}]);     Dim /: Times[z_, Dim[{x_, y_}]] /;        MatrixQ[z] :=       (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);     Dim /: Times[Dim[{x_, y_}], z_] /;        MatrixQ[z] :=       (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);     Dim /: Plus[z_, Dim[{x_, y_}]] /;        MatrixQ[z] :=       (checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);     (*Dim/:Dot[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[y,z];Dim[{x,w}]);     Dim/:Times[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);\     Dim/:Plus[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);*)     Dim /: Times[x_, Dim[{y_, z_}]] /; NumberQ[x] := Dim[{y, z}];          (*Below are tests that should return true.*)     MatrixQ[Dim[{2, 3}]]     Dimensions@Dim[{1, 2}] == {1, 2}     Dim[{3, 2}].Dim[{2, 4}] == Dim[{3, 4}]     Dim[{3, 2}].RandomReal[1, {2, 4}] == Dim[{3, 4}]     RandomReal[1, {2, 4}].Dim[{4, 3}] == Dim[{2, 3}]     Dim[{3, 2}] Dim[{3, 2}] == Dim[{3, 2}]     2 Dim[{3, 2}] == Dim[{3, 2}]     Dim[{3, 2}] - Dim[{3, 2}] == Dim[{3, 2}]          (*Below are tests that should raise errors.*)     Dim[{3, 2}] - Dim[{2, 4}]     Dim[{3, 2}] Dim[{2, 4}]     Dim[{5, 3}].Dim[{2, 4}]


title: How do I change the Head of Graph into List?

text: I am trying to change the Head of b (a NeighborhoodGraph) from Graph into List but Apply seems to fail. I start with a list of connected vertices:               a={1\[UndirectedEdge]1,2\[UndirectedEdge]2,1\[UndirectedEdge]3,3\[UndirectedEdge]3,     4\[UndirectedEdge]4,3\[UndirectedEdge]4,5\[UndirectedEdge]5,6\[UndirectedEdge]6,     6\[UndirectedEdge]2,7\[UndirectedEdge]7,8\[UndirectedEdge]5,8\[UndirectedEdge]8,     9\[UndirectedEdge]9,10\[UndirectedEdge]10,10\[UndirectedEdge]4};      I calculate the neighborhood graph of node 3. Its Head is Graph:               b=NeighborhoodGraph[a//Graph,3]     b//Head     (* ==> Graph *)      I use Apply to change the Head to List:               c=Apply[List,b];      However, the Head of c is still Graph:               c//Head     (* ==> Graph *)      My real question is how to access the list of edges in a NeighborhoodGraph.


title: How to speed up band matrix-matrix multiplication?

text: I have a band matrix               $HistoryLength = 0;     n = 10000;     b = 300;     k = 300;     a = SparseArray[Flatten[#, 1] &@Table[{i, Mod[i + j, n, 1]}, {i, n}, {j, -b, b}] ->          RandomComplex[{-1 - I, 1 + I}, n (2 b + 1)]];      and a dense matrix               u = RandomComplex[{-1 - I, 1 + I}, {n, k}];      I want to multiply them as fast as possible               v = a.u; // AbsoluteTiming      > {6.748518, Null} Visual representation of this multiplication:               draw = ArrayPlot[#[[;; ;; 30, ;; ;; 30]], ImageSize -> {Automatic, 200}] &;     Row@{draw[v], " = ", draw[a].draw[u]}      ![enter image description here](http://i.stack.imgur.com/zKD4l.png) This problem usually comes up when you want to multiply a Hamiltonian by a set of wavefunctions (in a certain basis). Why I expect a possibility of speeding up? When you multiply dense matrices you can use algorithms like Strassen algorithm and use the processor cache to operate with small blocks. The matrix `a` have a dense band. This knowledge can increase performance in contradiction to the sparse matrix of a general form.


title: Missing functions in the Raspberry Pi V10 release

text: There are a few Mathematica users beside myself that are running it on a Raspberry Pi, and we found out it does not always perform the same as the Desktop version [1][2]. During the testing of the prerelease it became obvious that some of the functions are too complex for the not-very-fast [3][4] Pi. So Wolfram decided to omit them from the Pi release branch. Which functions are omitted is not currently documented, so I'd like to find out this on my own.


title: Converting unevaluated lists to strings

text: I have a list like               l = {2 - 3, 12 - 4, Times, aab}      I want to end up with > {"2-3", "12-4", "Times", "aab"} I have tried               lh = Map[ToString, HoldForm[l], {2}]      Which gives the promising result > {ToString[2-3],ToString[12-4],ToString[Times],ToString[aab]} However when I add `ReleaseHold` the numerical values get evaluated ( _then_ converted to strings).               ReleaseHold@lh      > {"-1", "8", "Times", "aab"} How can I achieve the fully unevaluated string form? This question may be a duplicate. If so, I apologise.


title: Phase Unwrap List Of Points: Implementing continuous phase/Arg function for List of Points

text: I am looking for a function to unwrap phase of a list of points as done here for the continuous case. I have the Re/Im data as my input and would like the unwrapped phase as the output. Does anyone know how to do this in Mathematica?


title: Rotating an image along a Möbius strip?

text: I am trying to make a GIF which will be a rotating Möbius strip, with some text printed along its (one!) side. I am trying to (obviously) do this in Mathematica. After some diligent searching and a previous question I asked, I realize it is almost impossible to get text to behave well when it comes to opacity, rotations, etc. So instead I decided to make a rectangular image of the text, and then import it into Mathematica. But I'm getting stuck on putting all the pieces together. Do I want to use this image as a texture on the Möbius strip (which I'm getting from a `ParametricPlot3D`)? Or is there some other way to "wrap" this image exactly once around the Möbius strip? Also, would it be better to use an `Animate` to rotate the image - keeping the Möbius strip fixed - or is it better to simply rotate the whole thing? (I mean "better" as in "easier to do / better-looking"). I would actually prefer to eventually figure all this out on my own, but maybe some hints as to how I might proceed would be awesome. **EDIT** : After Heike's helpful comment, I've come up with the following:               text = Style["Hello!", 200];     ParametricPlot3D[{4 Cos[a] + r Cos[a] Cos[a/2],      4 Sin[a] + r Sin[a] Cos[a/2], r Sin[a/2]}, {a, 0, 2 Pi},     {r, -(3/2), 3/2}, Boxed -> False, Axes -> False,      Mesh -> False, PlotStyle -> {Directive[Texture[text]], Opacity[.5]},      TextureCoordinateFunction -> ({#4, #5} &)]      This of course doesn't rotate. But perhaps something can be done with `ViewVector` or this esoteric `TextureCoordinateFunction`? I don't know, because my Mathematica is having a very hard time drawing this correctly.


title: Averaging an oscillating function

text: I have a function `Ca[t]` that oscillates like a Sine curve, that I used `NDSolve` to obtain. I want to calculate the average value of `Ca[t]` so 1/2(Max+Min) but I have not been able to do this successfully and I don't know what to do.                    Manipulate[                k1 = 0.5; k2 = 0.2;           r1 = -k1 Ca[t]^m;           r2 = -k2 Cb[t]^n;           xa = (Cao[0] -              0.5*(MaxValue[Ca[t], Reals] + MinValue[Ca[t], Reals]))/Cao[0];           Cao[t_] = 5 + A Sin[\[Omega] t];           sol = NDSolve[{              Ca'[t] == r1*\[Tau] + -Ca[t] + Cao[t],              Cb'[t] == r2*\[Tau] - r1*\[Tau] - Cb[t],              Cc'[t] == -r2*\[Tau] - Cc[t],              Ca[0] == 0,              Cb[0] == 0,              Cc[0] == 0},             {Ca, Cb, Cc}, {t, 0, 100}];             {{\[Tau], 5, "residence time/min"}, 2, 10, Appearance -> "Labeled"},        {{\[Omega], 0.6, "frequency"}, 0.2, 2, 0.02,                 Appearance -> "Labeled"},        {{A, 2, "amplitude"}, 0.5, 5, 0.05,                 Appearance -> "Labeled"},        {{m, 1, "m"}, 0, 2, 1, ControlType -> SetterBar},        {{n, 1, "n"}, 0, 2, 1, ControlType -> SetterBar}]      This is as much as I can trim my notebook, my latest attempt at calculating the average of `Ca[t]` inside the expression `xa`.


title: Refering to global variables inside modules

text: How do I refer to global variables inside modules if the same name is used for a local one? In code, I want that               proc[a_] := Module[{b},       b = a;       {"b" -> b}       ]     b /. proc[1]      returns 1. Here "b" is to be replaced by the properly escaped global variable name.


title: How to setup Team Development for a Mathematica project?

text: I am currently working solo on a project that consists of package files, munit tests, notebooks and .xls files. I use Wolfram Workbench as an IDE. I want to collaborate with others on this project. Ideally I would like to do this as I am used to do with Java: dump everything in cvs ( any system will do ) on the net and then check/out, check/in with one person as a repository admin. **Question: How should I do this with a Mathematica project? Do I need Workbench plugins? What are the particular pitfalls, if any?**


title: How can I improve Do loop?

text: I have very large input of time series data (over 30000 observations) that look like as follows:                   data = {{{2011, 1, 2, 0, 0, 0.}, 439.}, {{2011, 1, 3, 0, 0, 0.},        482.}, {{2011, 1, 4, 0, 0, 0.}, 600.}, {{2011, 1, 5, 0, 0, 0.},        540.}, {{2011, 1, 6, 0, 0, 0.}, 448.}, {{2011, 1, 7, 0, 0, 0.},        409.}, {{2011, 1, 8, 0, 0, 0.}, 427.}, {{2011, 1, 9, 0, 0, 0.},        428.}, {{2011, 1, 10, 0, 0, 0.}, 511.}, {{2011, 1, 11, 0, 0, 0.},....}      My purpose is to clean the outliers. Currently, I have to replace the outliers by using a new calculated mean that based on days of week. That is, mean of Monday will replace the outlier of Monday. The following is my code Given that newmean variable is as follows:                newmean =  {{Sunday, 398.231}, {Monday, 495.385}, {Tuesday, 452.}, {Wednesday,                440.308}, {Thursday, 427.692}, {Friday, 434.154}, {Saturday,                439.583}}      I want to replace newmean to the original input data based on day of week. Currently, I am using the following code:               CleanData[data_,newmean_]:=     Module[{result},         result = data;         Do[         result={#[[1]],(#[[2]]/.val_/;DayName@#[[1]]==newmean[[i,1]]&&NumberQ[val]         ->newmean[[i,2]])}&/@result,         {i,Length@newmean}];         result     ]       **My question is how to improve this code ? Are there any better ways to replace data without specifying new variable (result) since the user-defined function (CleanData[data_, newmean_]) does not allow me to replace the input (data) ?**


title: Loop optimization

text: I wrote this to generate a 6D distribution of particles.               Bunch = {};     Do[       Particle = {0, 0, 0, 0, 0, 0};       tempX = { RandomVariate[NormalDistribution[0, Sqrt[EmitX]]],                     RandomVariate[NormalDistribution[0, Sqrt[EmitX]]]};       tempY = { RandomVariate[NormalDistribution[0, Sqrt[EmitY]]],                     RandomVariate[NormalDistribution[0, Sqrt[EmitY]]]};       coordS = {PhiS + \[Pi], BucketHeightP};       While[Abs[coordS[[1]]] >= (PhiS + \[Pi]) ||                     Abs[coordS[[2]]] >= \[Delta][coordS[[1]]],         coordS = {RandomVariate[NormalDistribution[PhiS, BlengthRad]],                     RandomVariate[NormalDistribution[0, MAXDPP ]]};];       coordX = {XCO + Sqrt[BetaX] tempX[[1]] + Dx coordS[[2]],                     XPCO + (-(AlphaX/Sqrt[BetaX]) tempX[[1]] +                     1/Sqrt[BetaX] tempX[[2]]) + Dpx coordS[[2]]};       coordY = {YCO + Sqrt[BetaY] tempY[[1]],                     YPCO - AlphaY/Sqrt[BetaY] tempY[[1]] + 1/Sqrt[BetaY] tempY[[2]]};       Particle = Flatten[{coordX, coordY, coordS}];       Bunch = Append[Bunch, Particle],     {i, 1, 20000}];      I don't think the details are important. I call 6 times `RandomVariate` which I'm afraid is quite inefficient. Would you suggest some major improvement ?